diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..b730305 --- /dev/null +++ b/.clang-format @@ -0,0 +1,28 @@ +# Defines the Chromium style for automatic reformatting. +# http://clang.llvm.org/docs/ClangFormatStyleOptions.html +BasedOnStyle: Chromium +# This defaults to 'Auto'. Explicitly set it for a while, so that +# 'vector >' in existing files gets formatted to +# 'vector>'. ('Auto' means that clang-format will only use +# 'int>>' if the file already contains at least one such instance.) +Standard: Cpp11 + +# Make sure code like: +# IPC_BEGIN_MESSAGE_MAP() +# IPC_MESSAGE_HANDLER(WidgetHostViewHost_Update, OnUpdate) +# IPC_END_MESSAGE_MAP() +# gets correctly indented. +MacroBlockBegin: "^\ +BEGIN_COM_MAP|\ +BEGIN_MSG_MAP|\ +BEGIN_OBJECT_MAP|\ +BEGIN_PROP_MAP|\ +BEGIN_REGISTRY_MAP|\ +BEGIN_SERVICE_MAP$" +MacroBlockEnd: "^\ +END_COM_MAP|\ +END_MSG_MAP|\ +END_OBJECT_MAP|\ +END_PROP_MAP|\ +END_REGISTRY_MAP|\ +END_SERVICE_MAP$" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 16ec14d..b9ca4b9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,29 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -.p4config -BRANCH_OWNERS -omaha/common/omaha_customization_proxy_clsid.h -omaha/proxy_clsids.txt -omaha/*.idb -omaha/scons-out/** - -# Ignore compiled Python files. -*.pyc +// Copyright 2003-2009 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ======================================================================== + +*.idb +*.pdb +*.pyc +.vs/ +.vscode/ +omaha/common/omaha_customization_proxy_clsid.h +omaha/proxy_clsids.txt +omaha/scons-out/** +omaha/standalone/* +third_party/breakpad/** +third_party/googletest/** +third_party/libzip/** +third_party/lzma/files/**/obj/ +third_party/zlib/** diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..384f650 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "third_party/googletest"] + path = third_party/googletest + url = https://github.com/google/googletest.git +[submodule "third_party/breakpad"] + path = third_party/breakpad + url = https://chromium.googlesource.com/breakpad/breakpad diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 0000000..6ddbe3c --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,64 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import("//brave/build/config.gni") + +assert(is_win) + +group("omaha") { + deps = [ ":build_omaha_installer" ] +} + +action("build_omaha_installer") { + script="build_omaha.py" + + inputs = [ "build_omaha.py" ] + + sources = [ "$root_out_dir/$brave_installer_exe" ] + + _install_switch = "" + _tag_app_name = "Brave-Release" + if (brave_channel == "beta") { + _install_switch = "--chrome-beta" + _tag_app_name = "Brave-Browser-Beta" + } else if (brave_channel == "dev") { + _install_switch = "--chrome-dev" + _tag_app_name = "Brave-Browser-Dev" + } else if (brave_channel == "nightly") { + _install_switch = "--chrome-sxs" + _tag_app_name = "Brave-Browser-Nightly" + } else { + assert(brave_channel == "", "Unknown channel name") + } + + out_dir = rebase_path(root_out_dir) + + args = [ + "--root_out_dir=$out_dir", + "--brave_installer_exe=$brave_installer_exe", + "--stub_installer_exe=$brave_stub_installer_exe", + "--stub_silent_exe=$brave_silent_stub_installer_exe", + "--stub_untagged_exe=$brave_untagged_stub_installer_exe", + "--standalone_installer_exe=$brave_standalone_installer_exe", + "--silent_installer_exe=$brave_silent_installer_exe", + "--untagged_installer_exe=$brave_untagged_installer_exe", + "--guid=$brave_app_guid", + "--install_switch=$_install_switch", + "--tag_ap=$tag_ap", + "--tag_app_name=$_tag_app_name", + "--brave_full_version=$chrome_version_major.$brave_version_major.$brave_version_minor.$brave_version_build", + ] + + outputs = [ + "$root_out_dir/$brave_stub_installer_exe", + "$root_out_dir/$brave_standalone_installer_exe", + "$root_out_dir/$brave_silent_installer_exe", + "$root_out_dir/$brave_untagged_installer_exe", + ] + + deps = [ + "//brave/build/win:create_signed_installer", + ] +} + diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 286249b..36acb9c 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,256 @@ +# CHANGELOG.txt is not going to be be updated beyond this point +# To see what is being changed, please inspect the git log. + +## 2019-06-05 @247089589,251531419 + +### Changes +-------------------------------------------------------------------------------- +Remove obsolete smartany wrappers. + +Also, remove obsolete #pragmas to disable C4640 +(construction of local static object is not thread-safe). +-------------------------------------------------------------------------------- +Implement the Omaha Cloud Policies Fetcher. + +* The policies are fetched when the UpdateApps (/ua) process runs. UA runs at +5 hour intervals typically. +* The serialized policies are stored locally in separate directories for each +policy_type within the directory "%ProgramFiles(x86)%\Google\Policies". +* Each PolicyFetchResponse is stored into a subdirectory based off the +policy_type, with a fixed file name of "PolicyFetchResponse", where the file +contents are {SerializeToString-PolicyFetchResponse}}. +* Each "PolicyFetchResponse" file is opened in exclusive mode. If we are unable +to open or write to this file, UA will retry at the next UA interval. +* Client applications could use ::FindFirstChangeNotificationW on the +subdirectory corresponding to their respective policy_type to watch for +changes. They can then read and apply the policies within this file. +-------------------------------------------------------------------------------- +Perform best-effort registration with the DMServer during UpdateApps processing. + +This allows post-install registration to take place in the normal /ua scheduled +task in case: +- The network could not be used during installation on account +of NOGOOGLEUPDATEPING. +- Non-mandatory registration failed during installation. +- An enrollment token was provisioned to the machine via Group Policy +after installation. +-------------------------------------------------------------------------------- +Workaround for ICE in service_main.h when building with 16.1.0 +-------------------------------------------------------------------------------- +Cloud policy fetch. +-------------------------------------------------------------------------------- +Enable '/permissive-' as a compiler switch. +-------------------------------------------------------------------------------- +Allow C++17 language features +-------------------------------------------------------------------------------- +Remove weak crypto hash algorithms from Omaha client. +This cl removes MD5 support. +-------------------------------------------------------------------------------- +Produce 3 consecutive versions of some of the Omaha build artifacts. +-------------------------------------------------------------------------------- + +## 2019-05-10 @243143383,247089588 + +### Changes +-------------------------------------------------------------------------------- +Fix broken unit test CommandLineTest.ParseCommandLine_Install. +-------------------------------------------------------------------------------- +App-specific disclaimers for RollbackToTargetVersion policy. + +This change provides a way for apps to inject their own specific disclaimer +text in their RollbackToTargetVersion policy documentation. +New text for Chrome is included. +-------------------------------------------------------------------------------- +Switch Omaha continuous build from VS2017 to VS2019. +-------------------------------------------------------------------------------- +Remove precompiled headers support. +-------------------------------------------------------------------------------- +Fix various test failures. +- RegKey::HasNativeKey has been removed, and callers have been updated to +use HKEY_LOCAL_MACHINE[64] or HKLM[64] as the name of the root key. +- ParseCommandLine_Install had a blatant typo ('%' instead of '&') which +has been fixed. +- DmClientRequestTest.RegisterWithRequest has been updated to reflect the +late change in the request type. +-------------------------------------------------------------------------------- +Fix bug 131367413 Eliminate MFC headers. +-------------------------------------------------------------------------------- +Compliance changes for VS2017. +-------------------------------------------------------------------------------- +Rework the fix for bug 130373054 Build the Protocol Buffer Compiler executable +protoc.exe from source. +-------------------------------------------------------------------------------- +Device Registration in Google Update during install. +-------------------------------------------------------------------------------- + +## 2019-04-11 @239101812,243143382 + +### Changes +-------------------------------------------------------------------------------- +Fix spelling error s/accomodate/accommodate. +-------------------------------------------------------------------------------- +Fix hardcoded Google company name in UtilsTest.AddAllowedAceRegistry. +-------------------------------------------------------------------------------- +Update SaveArguments.exe to fix broken daily unit tests. +-------------------------------------------------------------------------------- +Assorted Google Update policy template fixes. +- Fix a line ending issue preventing all but the first sentence in the +RollbackToTargetVersion .adm documentation from appearing in the policy editor. +- .adm template now calls the TargetVersionPrefix policy "Target version +prefix override" (matches .adml). +- Both templates now call the RollbackToTargetVersion policy "Rollback to +Target version" (rather than "Rollback version override" (.adm) or +"Rollback to Target version override" (.admx)). +- Minor typographical tweaks to the TargetVersionPrefix examples. +- Fix a regression introduced in cl/159509609 whereby part of the per-app +Update policy documentation was accidentally moved to the TargetVersionPrefix +documentation. +-------------------------------------------------------------------------------- +Delete unused file marquee.avi. +-------------------------------------------------------------------------------- + +## 2019-03-19 @226393815,239101811 + +### Changes +-------------------------------------------------------------------------------- +Fix bug 127373943 Omaha fails on Windows XP SP2 due to +GetLogicalProcessorInformation not located in KERNEL32.dll. + +This change uses std::atomic_llong and ::GetCurrentThreadId() as a +replacement for std::thread::id, if GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP is +defined. std::thread does not work on Windows XP SP2 with the latest VC++ +libraries, because it utilizes the Concurrency Runtime that +uses ::GetLogicalProcessorInformation which is only supported on +Windows XP SP3 and above. +-------------------------------------------------------------------------------- +The RollbackToTargetVersion feature is not working as expected because the +client is sending "rollbackallowed" instead of "rollback_allowed". + + +-------------------------------------------------------------------------------- +Fix generated policy templates for Pol_RollbackToTargetVersion. + +The opening element in the ADMX file had an errant "/" before the +closing ">", making it appear to be an empty element. This change also adds +the missing string for "At least Google Update 1.3.34.3" to both the ADM and +ADMX templates. +-------------------------------------------------------------------------------- +Fix bug 127843407 Increase UpdatesSuppressedDurationMin to a max of 16 hours +for Enterprise Scheduling of updates. +-------------------------------------------------------------------------------- +Fix Deadlock in shutdown of UA process. +-------------------------------------------------------------------------------- +Check explicitly for a full match of the command lines to exclude in Omaha +Setup. +-------------------------------------------------------------------------------- +Fix build break: Disable warning C4628 digraphs not supported with -Ze. +-------------------------------------------------------------------------------- +Fix bug 122987550 Implement the RollbackToTargetVersion policy for domain-joined +machines. This policy setting has no effect unless a "Target version override" +is set via the TargetVersionPrefix policy for the app as well. +The RollbackToTargetVersion value will be sent as an attribute of the + element in update checks that the client makes with the +Omaha server. + +Example: + elements that have have it set on a +child of an element. + +This allows the policies to work with Microsoft Intune. +-------------------------------------------------------------------------------- +Replace 1.1.1.1 with 2.2.2.2 in unit tests. + +We need an address where ping times out. +-------------------------------------------------------------------------------- +Change DOS-mitigation header strings (Windows) + +X-GoogleUpdate-Interactivity -> X-Goog-Update-Interactivity +X-GoogleUpdate-AppId -> X-Goog-Update-AppId +X-GoogleUpdate-Updater -> X-Goog-Update-Updater +-------------------------------------------------------------------------------- +Rotate CUP key. +-------------------------------------------------------------------------------- +Send a boolean to indicate whether the machine is domain joined or not. +-------------------------------------------------------------------------------- + ## 2017-11-16 @156858449,176133948 ### Changes @@ -1020,7 +1273,7 @@ non-localized resources over to goopdate.dll to fix this issue. -------------------------------------------------------------------------------- Implement sandbox for omaha crash handler. This adds the plumbing to deal with all the needed files and handles by opening handles ahead of time. It then -creates seperate worker process to perform the crash dump and (after opening all +creates separate worker process to perform the crash dump and (after opening all needed handles) locks down the process by setting the untrusted label on the processes access token. -------------------------------------------------------------------------------- @@ -1095,7 +1348,7 @@ The event log source for Omaha crashes event 2 shows as Update2. -------------------------------------------------------------------------------- Turn on crash analysis for non-system crash handlers. -------------------------------------------------------------------------------- -Adjust the height of the installer state text box to accomodate longer messages +Adjust the height of the installer state text box to accommodate longer messages and product names. Also adjusted a couple of other boxes that are not used currently but may be used in the future. -------------------------------------------------------------------------------- diff --git a/README.md b/README.md index 6dcaf59..c9b9a2e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Omaha ## This is not an official Google product. ## +## How to build ## +See https://github.com/brave/brave-browser/wiki/Brave-omaha Omaha is the open-source version of Google Update, a program to install requested software and keep it up to date. The Google-branded version of Omaha is used to support software patching (both background updating, and on-demand update checks) for Google Chrome, Earth, and a variety of other Google products on Windows. diff --git a/build_omaha.py b/build_omaha.py new file mode 100644 index 0000000..2acaca3 --- /dev/null +++ b/build_omaha.py @@ -0,0 +1,207 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import argparse +import os +import os.path +import shutil +import subprocess as sp +import sys + + +def FetchThirdParties(args, omaha_dir): + os.chdir(omaha_dir) + + command = ['git', 'submodule', 'update', '--init'] + sp.check_call(command, stderr=sp.STDOUT) + +def Build(args, omaha_dir, build_all): + # move to omaha/omaha and start build. + os.chdir(os.path.join(omaha_dir, 'omaha')) + + # set signing environment variables + key_pfx_path = os.environ.get('KEY_PFX_PATH', '') + key_cer_path = os.environ.get('KEY_CER_PATH', '') + authenticode_password = os.environ.get('AUTHENTICODE_PASSWORD', '') + + mode = 'opt-win' + if build_all: + mode = 'all' + command = ['hammer-brave.bat', 'MODE=' + mode, '--all', '--sha2_authenticode_file=' + key_pfx_path, + '--sha2_authenticode_password=' + authenticode_password, '--sha1_authenticode_file=' + key_pfx_path, + '--sha1_authenticode_password=' + authenticode_password, '--patching_certificate=' + key_cer_path, + '--authenticode_file=' + key_pfx_path, '--authenticode_password=' + authenticode_password] + + sp.check_call(command, stderr=sp.STDOUT) + +def Copy_Untagged_Installers(args, omaha_dir, debug): + last_win_dir = 'opt-win' + if debug: + last_win_dir = 'dbg-win' + omaha_out_dir = os.path.join(omaha_dir, 'omaha', 'scons-out', last_win_dir) + + source_untagged_installer = os.path.join(omaha_out_dir, 'Test_Installers', 'UNOFFICIAL_' + args.untagged_installer_exe[0]) + target_untagged_installer_file = args.untagged_installer_exe[0] + if debug: + target_untagged_installer_file = 'Debug' + target_untagged_installer_file + target_untagged_installer = os.path.join(args.root_out_dir[0], target_untagged_installer_file) + + shutil.copyfile(source_untagged_installer, target_untagged_installer) + + source_untagged_stub_installer = os.path.join(omaha_out_dir, 'staging', 'BraveUpdateSetup.exe') + target_untagged_stub_installer_file = args.stub_untagged_exe[0] + if debug: + target_untagged_stub_installer_file = 'Debug' + target_untagged_stub_installer_file + target_untagged_stub_installer = os.path.join(args.root_out_dir[0], target_untagged_stub_installer_file) + + shutil.copyfile(source_untagged_stub_installer, target_untagged_stub_installer) + +def PrepareStandalone(args, omaha_dir): + # copy brave installer to create standalone installer. + installer_file = os.path.join(args.root_out_dir[0], args.brave_installer_exe[0]) + shutil.copyfile(installer_file, os.path.join(omaha_dir, 'omaha', 'standalone', args.brave_installer_exe[0])) + shutil.copyfile(installer_file, os.path.join(omaha_dir, 'omaha', 'standalone', args.untagged_installer_exe[0])) + shutil.copyfile(installer_file, os.path.join(omaha_dir, 'omaha', 'standalone', args.silent_installer_exe[0])) + + # prepare manifset file. + f = open(os.path.join(omaha_dir, 'manifest_template.gup'),'r') + filedata = f.read() + f.close() + + newdata = filedata.replace("APP_GUID", args.guid[0]) + newdata = newdata.replace("BRAVE_INSTALLER_EXE", args.brave_installer_exe[0]) + newdata = newdata.replace("INSTALL_SWITCH", args.install_switch[0]) + + target_manifest_file = args.guid[0] + '.gup' + target_manifest_path = os.path.join(omaha_dir, 'omaha', 'standalone', 'manifests', target_manifest_file) + f = open(target_manifest_path,'w') + f.write(newdata) + f.close() + + # update standalone_installers.txt. + installer_text = "('STANDALONE_FILE_NAME', 'STANDALONE_FILE_NAME', [('BRAVE_VERSION', '$MAIN_DIR/standalone/BRAVE_INSTALLER_EXE', 'APP_GUID')], None, None, None, False, '', '')" + installer_text = installer_text.replace("APP_GUID", args.guid[0]) + installer_text = installer_text.replace("STANDALONE_FILE_NAME", os.path.splitext(args.standalone_installer_exe[0])[0]) + installer_text = installer_text.replace("BRAVE_INSTALLER_EXE", args.brave_installer_exe[0]) + installer_text = installer_text.replace("BRAVE_VERSION", args.brave_full_version[0]) + + # add untagged installer info to standalone_installers.txt. + untagged_installer_text = "('UNTAGGED_FILE_NAME', 'UNTAGGED_FILE_NAME', [('BRAVE_VERSION', '$MAIN_DIR/standalone/UNTAGGED_INSTALLER_EXE', 'APP_GUID')], None, None, None, False, '', '')" + untagged_installer_text = untagged_installer_text.replace("APP_GUID", args.guid[0]) + untagged_installer_text = untagged_installer_text.replace("UNTAGGED_FILE_NAME", os.path.splitext(args.untagged_installer_exe[0])[0]) + untagged_installer_text = untagged_installer_text.replace("UNTAGGED_INSTALLER_EXE", args.untagged_installer_exe[0]) + untagged_installer_text = untagged_installer_text.replace("BRAVE_VERSION", args.brave_full_version[0]) + + # add silent installer info to standalone_installers.txt. + silent_installer_text = "('SILENT_FILE_NAME', 'SILENT_FILE_NAME', [('BRAVE_VERSION', '$MAIN_DIR/standalone/SILENT_INSTALLER_EXE', 'APP_GUID')], None, None, None, False, '', '')" + silent_installer_text = silent_installer_text.replace("APP_GUID", args.guid[0]) + silent_installer_text = silent_installer_text.replace("SILENT_FILE_NAME", os.path.splitext(args.silent_installer_exe[0])[0]) + silent_installer_text = silent_installer_text.replace("SILENT_INSTALLER_EXE", args.silent_installer_exe[0]) + silent_installer_text = silent_installer_text.replace("BRAVE_VERSION", args.brave_full_version[0]) + + target_installer_text_path = os.path.join(omaha_dir, 'omaha', 'standalone', 'standalone_installers.txt') + f = open(target_installer_text_path,'w') + f.write(installer_text + '\n') + f.write(untagged_installer_text + '\n') + f.write(silent_installer_text) + f.close() + +def Tagging(args, omaha_dir, debug): + last_win_dir = 'opt-win' + if debug: + last_win_dir = 'dbg-win' + omaha_out_dir = os.path.join(omaha_dir, 'omaha', 'scons-out', last_win_dir) + apply_tag_exe = os.path.join(omaha_out_dir, 'obj', 'tools', 'ApplyTag', 'ApplyTag.exe') + + tag_admin = os.environ.get('TAG_ADMIN', 'prefers') + tag = 'appguid=APP_GUID&appname=TAG_APP_NAME&needsadmin=TAG_ADMIN&lang=en&ap=TAG_AP' + tag = tag.replace("TAG_ADMIN", tag_admin) + tag = tag.replace("APP_GUID", args.guid[0]) + tag = tag.replace("TAG_APP_NAME", args.tag_app_name[0]) + tag = tag.replace("TAG_AP", args.tag_ap[0]) + + silent_tag = 'appguid=APP_GUID&appname=TAG_APP_NAME&needsadmin=TAG_ADMIN&lang=en&ap=TAG_AP&silent' + silent_tag = silent_tag.replace("TAG_ADMIN", 'False') + silent_tag = silent_tag.replace("APP_GUID", args.guid[0]) + silent_tag = silent_tag.replace("TAG_APP_NAME", args.tag_app_name[0]) + silent_tag = silent_tag.replace("TAG_AP", args.tag_ap[0]) + + source_standalone_installer = os.path.join(omaha_out_dir, 'Test_Installers', 'UNOFFICIAL_' + args.standalone_installer_exe[0]) + target_standalone_installer_file = args.standalone_installer_exe[0] + if debug: + target_standalone_installer_file = 'Debug' + target_standalone_installer_file + target_standalone_installer = os.path.join(args.root_out_dir[0], target_standalone_installer_file) + command = [apply_tag_exe, source_standalone_installer, target_standalone_installer, tag] + sp.check_call(command, stderr=sp.STDOUT) + + source_silent_installer = os.path.join(omaha_out_dir, 'Test_Installers', 'UNOFFICIAL_' + args.silent_installer_exe[0]) + target_silent_installer_file = args.silent_installer_exe[0] + if debug: + target_silent_installer_file = 'Debug' + target_silent_installer_file + target_silent_installer = os.path.join(args.root_out_dir[0], target_silent_installer_file) + command = [apply_tag_exe, source_silent_installer, target_silent_installer, silent_tag] + sp.check_call(command, stderr=sp.STDOUT) + + source_stub_installer = os.path.join(omaha_out_dir, 'staging', 'BraveUpdateSetup.exe') + target_stub_installer_file = args.stub_installer_exe[0] + if debug: + target_stub_installer_file = 'Debug' + target_stub_installer_file + target_stub_installer = os.path.join(args.root_out_dir[0], target_stub_installer_file) + command = [apply_tag_exe, source_stub_installer, target_stub_installer, tag] + sp.check_call(command, stderr=sp.STDOUT) + + source_silent_stub_installer = os.path.join(omaha_out_dir, 'staging', 'BraveUpdateSetup.exe') + target_silent_stub_installer_file = args.stub_silent_exe[0] + if debug: + target_silent_stub_installer_file = 'Debug' + target_silent_stub_installer_file + target_silent_stub_installer = os.path.join(args.root_out_dir[0], target_silent_stub_installer_file) + command = [apply_tag_exe, source_silent_stub_installer, target_silent_stub_installer, silent_tag] + sp.check_call(command, stderr=sp.STDOUT) + return + +def ParseArgs(): + parser = argparse.ArgumentParser(description='build omaha installer') + parser.add_argument('--root_out_dir', + nargs=1) + parser.add_argument('--brave_installer_exe', + nargs=1) + parser.add_argument('--stub_installer_exe', + nargs=1) + parser.add_argument('--stub_untagged_exe', + nargs=1) + parser.add_argument('--stub_silent_exe', + nargs=1) + parser.add_argument('--standalone_installer_exe', + nargs=1) + parser.add_argument('--silent_installer_exe', + nargs=1) + parser.add_argument('--untagged_installer_exe', + nargs=1) + parser.add_argument('--guid', + nargs=1) + parser.add_argument('--install_switch', + nargs=1) + parser.add_argument('--tag_ap', + nargs=1) + parser.add_argument('--tag_app_name', + nargs=1) + parser.add_argument('--brave_full_version', + nargs=1) + return parser.parse_args() + +def Main(args): + args = ParseArgs() + omaha_dir = os.path.join(args.root_out_dir[0], '..', '..', 'brave', 'vendor', 'omaha') + + FetchThirdParties(args, omaha_dir) + PrepareStandalone(args, omaha_dir) + Build(args, omaha_dir, False) + Tagging(args, omaha_dir, False) + Copy_Untagged_Installers(args, omaha_dir, False) + + return 0 + + +if __name__ == '__main__': + sys.exit(Main(sys.argv)) diff --git a/doc/DeveloperSetupGuide.md b/doc/DeveloperSetupGuide.md index fb69926..1e89972 100644 --- a/doc/DeveloperSetupGuide.md +++ b/doc/DeveloperSetupGuide.md @@ -4,15 +4,17 @@ These instructions are intended to assist the would-be Omaha developer with sett We are striving to make the code build with the latest Windows toolchain from Microsoft. Since there is no continuous integration for this project, the code may not build using previous versions of the toolchain. -#### Currently, the supported toolchain is Visual Studio 2015 Update 3 and Windows SDK 10.0.10586.0.#### +#### Currently, the supported toolchain is Visual Studio 2019 Update 16.1.3 and Windows SDK 10.0.18362.0. #### + +Visual Studio 2017 Update 15.9.13 should work too. # Required Downloads/Tools # The following packages are required to build Omaha: * A copy of the Omaha source code. This can be done by cloning this repository. - * Microsoft Visual Studio 2015 Update 3. The free Visual Studion Community edition is sufficient to build. - * The Express Editions are not sufficient - they do not include ATL/MFC headers or libraries, which Omaha requires. - * ATL Server headers + * Microsoft Visual Studio 2017 or 2019. The free Visual Studio Community edition is sufficient to build. + * Download [here](https://visualstudio.microsoft.com/downloads) + * ATL Server headers * Download [here](http://atlserver.codeplex.com). Omaha needs this library for regular expression support. * Windows 10 SDK. * Download Windows 10 SDK [here](https://dev.windows.com/en-us/downloads/windows-10-sdk). @@ -24,21 +26,25 @@ The following packages are required to build Omaha: * Download WTL [here](http://sourceforge.net/projects/wtl/). * The Windows Install XML (WiX) Toolkit, version 3.0 or later. * Download any of the v3 binaries packages [here](http://wix.sourceforge.net/). - * Python 2.4.x (Be sure to use **2.4**, newer versions currently break the build!) - * Download Python [here](http://www.python.org/download/releases/2.4.4/). It can coexist with newer Python installs on a system. - * You'll also need the pywin32 (Python for Windows) extensions for Python 2.4. It can be downloaded [here](http://sourceforge.net/projects/pywin32/files/pywin32/Build216/pywin32-216.win32-py2.4.exe/download). + * Python 2.7.x + * Download Python [here](https://www.python.org/downloads/release/python-2716). It can coexist with newer Python installs on a system. + * You'll also need the pywin32 (Python for Windows) extensions for Python 2.7. + - You can install with pip: `> python -m pip install pywin32` - assuming `python` is added to your `PATH` environmental variable. + - It can also be downloaded [here](https://github.com/mhammond/pywin32/releases/download/b224/pywin32-224.win-amd64-py2.7.exe). * SCons 1.3.x (Be sure to use **1.3**, the 2.0 series is not backwards-compatible!) * Download SCons [here](http://sourceforge.net/projects/scons/files/scons/1.3.1/). * Google Software Construction Toolkit * Get the SCT source [here](http://code.google.com/p/swtoolkit/), either via direct download or via SVN checkout. * The GO programming language * Download [here](https://golang.org/dl/) - * Google Protocol Buffers [here](https://github.com/google/protobuf/releases). + * Google Protocol Buffers (3.6.0 or higher) [here](https://github.com/google/protobuf/releases). * From the [release page](https://github.com/google/protobuf/releases), download the zip file protoc-$VERSION-win32.zip. It contains the protoc binary. Unzip the contents under C:\protobuf. After that, download the zip file protobuf-cpp-$VERSION.zip. Unzip the "src" sub-directory contents to C:\protobuf\src. If other directory is used, please edit the environment variables in the hammer.bat, specifically, OMAHA_PROTOBUF_BIN_DIR and OMAHA_PROTOBUF_SRC_DIR. - * Third-party dependecies: + * Third-party dependencies: * breakpad. Source code [here](https://code.google.com/p/google-breakpad/source/checkout) * googletest. Source code [here](https://github.com/google/googletest). This includes both gtest and gmock frameworks. * Use git clone, git svn clone, or other way to get the source code for these projects into the third_party directory in the root of this repository. + * libzip 1.5.2. Source code [here](https://libzip.org/download/libzip-1.5.2.tar.xz). Unzip the contents of libzip-1.5.2.tar.gz\libzip-1.5.2.tar\libzip-1.5.2\ into the directory googleclient\third_party\libzip. The Omaha repository contains two generated configuration files in `base\libzip`, or one could build the libzip library and generate the files. A change has been made to config.h to disable zip crypto `#undef HAVE_CRYPTO`, or else the zip code won't build because of a compile time bug. + * zlib 1.2.11. Source code [here](https://zlib.net/zlib-1.2.11.tar.gz). Unzip the contents of zlib-1.2.11.tar.gz\zlib-1.2.11.tar\zlib-1.2.11\ into the directory googleclient\third_party\zlib\v1_2_11. To run the unit tests, one more package is needed. Download the Windows Sysinternals PSTools suite [here](https://technet.microsoft.com/en-us/sysinternals/bb897553) and save psexec.exe somewhere. Then, set a system environment variable named OMAHA_PSEXEC_DIR to the directory containing psexec.exe. @@ -58,7 +64,7 @@ To run the unit tests, one more package is needed. Download the Windows Sysinter d---rwx---+ 1 sorin Domain Users 0 Jun 30 17:58 common d---rwx---+ 1 sorin Domain Users 0 Jul 15 11:34 omaha d---rwx---+ 1 sorin Domain Users 0 Jun 30 17:58 third_party - + d:\src\omahaopensource\omaha>ls -l third_party total 16 d---rwx---+ 1 sorin Domain Users 0 Jul 14 12:52 breakpad @@ -75,7 +81,7 @@ Once the tree is in place, a number of environment variables need to be set up i Once the above setup is complete: * Open a fresh cmd.exe window as Administrator. * Navigate to the 'omaha' directory in your source checkout, for example: `D:\src\omahaopensource\omaha\omaha>` - * Run the vsvars.bat file corresponding to the Visual C++ instance you want to use to build. For example: `%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\VC\vcvarsall.bat`. This step sets up the environment variables that the build scripts use. + * Run the vsvars.bat file corresponding to the Visual C++ instance you want to use to build. For example: `%ProgramFiles(x86)%\Microsoft Visual Studio\2019\Professional\VC\Auxiliary\Build\vcvarsamd64_x86.bat`. This step sets up the environment variables that the build scripts use. The 64-bit host toolchain is preferred, otherwise, run `vcvars32.bat` to set up the build environment for the x86 host toolchain. * From the above directory, just type `hammer` to build Omaha! (Note: More advanced build options can be found in [HammerOptions](HammerOptions.md). In particular, if you are building on a multi-core or multi-processor, consider passing the -j# flag to Hammer to enable parallel compilation.) * To build all targets in all modes, type `hammer --all --mode=all`. This builds both debug and opt versions of the binaries, including all unit tests, and standalone installers. @@ -87,7 +93,7 @@ A larger suite of unit tests is also included in the Omaha source. The Omaha build proces includes building an automated unit test suite, based on the [GTest](https://github.com/google/googletest) framework. In order to run it, there are two pieces of preparation you must do: -* Create the following registry key: `HKEY_LOCAL_MACHINE\SOFTWARE\OmahaCompanyName\UpdateDev`. Then, add a string value named `TestSource` with the value `ossdev`. (Note: If you are on 64 bit Windows and are using `regedit` to create the value then you need to place it in `HKEY_LOCAL_MACHINE\Wow6432Node\SOFTWARE\OmahaCompanyName\UpdateDev`. [This allows 32 bit processes to read it.](https://support.microsoft.com/en-us/kb/305097)). +* Create the following registry key: `HKEY_LOCAL_MACHINE\SOFTWARE\OmahaCompanyName\UpdateDev`. Then, add a string value named `TestSource` with the value `ossdev`. (Note: If you are on 64 bit Windows and are using `regedit` to create the value then you need to place it in `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\OmahaCompanyName\UpdateDev`. [This allows 32 bit processes to read it.](https://support.microsoft.com/en-us/kb/305097)). * Download the Windows Sysinternals PSTools suite (available [here](http://technet.microsoft.com/en-us/sysinternals/bb897553)) and save `psexec.exe` somewhere. Then, set an environment variable named `OMAHA_PSEXEC_DIR` to the directory containing `psexec.exe`. When running unit tests: diff --git a/doc/ServerProtocolV3.md b/doc/ServerProtocolV3.md index 9d06bdd..379dfa4 100644 --- a/doc/ServerProtocolV3.md +++ b/doc/ServerProtocolV3.md @@ -167,7 +167,7 @@ Each product that is contained in the request is represented by exactly one `` level. See [#Packages\_&\_Fingerprints](#packages--fingerprints). Default: "". + * `fp`: If there is only one package, the fingerprint for that package may be transmitted at the `` level. See [#Packages\_&\_Fingerprints](#packages--fingerprints). Default: "". * `cohort`: A machine-readable string identifying the release cohort (channel) that the app belongs to. Limited to ASCII characters 32 to 127 (inclusive) and a maximum length of 1024 characters. Default: "". * `cohorthint`: An machine-readable enum indicating that the client has a desire to switch to a different release cohort. The exact legal values are app-specific and should be shared between the server and app implementations. Limited to ASCII characters 32 to 127 (inclusive) and a maximum length of 1024 characters. Default: "". * `cohortname`: A stable non-localized human-readable enum indicating which (if any) set of messages the app should display to the user. For example, an app with a cohortname of "beta" might display beta-specific branding to the user. Limited to ASCII characters 32 to 127 (inclusive) and a maximum length of 1024 characters. Default: "". @@ -219,7 +219,7 @@ None. #### `` (Request) #### A `` tag gives information about an installed package. ##### Attributes ##### - * `fingerprint`: The fingerprint identifying the installed package. See [#Packages\_&\_Fingerprints](#pacakges--fingerprints). Default: "". + * `fp`: The fingerprint identifying the installed package. See [#Packages\_&\_Fingerprints](#pacakges--fingerprints). Default: "". ##### Legal Child Elements ##### None. diff --git a/manifest_template.gup b/manifest_template.gup new file mode 100644 index 0000000..e65287d --- /dev/null +++ b/manifest_template.gup @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/omaha/base/accounts.cc b/omaha/base/accounts.cc deleted file mode 100644 index d196fb1..0000000 --- a/omaha/base/accounts.cc +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Enumeration of the user accounts on the PC. - -#include "omaha/base/accounts.h" - -#include -#include "base/basictypes.h" -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/reg_key.h" - -namespace omaha { - -namespace accounts { - -const wchar_t kActiveProfilesKey[] = - L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList"; - -HRESULT GetAllUserSids(CSimpleArray *sid_array) { - ASSERT(sid_array, (L"")); - - RegKey key_profiles; - HRESULT hr = key_profiles.Open(HKEY_LOCAL_MACHINE, kActiveProfilesKey); - if (FAILED(hr)) { - return hr; - } - - sid_array->RemoveAll(); - - uint32 total_keys = key_profiles.GetSubkeyCount(); - - for (uint32 i = 0 ; i < total_keys ; ++i) { - CString possible_user_sid, name, domain; - SID_NAME_USE user_type; - - if (SUCCEEDED(key_profiles.GetSubkeyNameAt(i, &possible_user_sid))) { - if (SUCCEEDED(GetUserInfo(possible_user_sid, &name, - &domain, &user_type)) && - user_type == SidTypeUser) { - sid_array->Add(possible_user_sid); - } - } - } - - return hr; -} - -HRESULT GetUserInfo(const wchar_t *sid_str, CString *name, - CString *domain, SID_NAME_USE *user_type) { - ASSERT(sid_str, (L"")); - ASSERT(name, (L"")); - ASSERT(domain, (L"")); - ASSERT(user_type, (L"")); - - PSID sid = NULL; - HRESULT ret = E_FAIL; - if (ConvertStringSidToSid(sid_str, &sid)) { - DWORD name_size = 0, domain_size = 0; - if (!LookupAccountSid(NULL, sid, NULL, &name_size, NULL, - &domain_size, user_type) && - ERROR_INSUFFICIENT_BUFFER != GetLastError()) { - ret = GetCurError(); - LocalFree(sid); - return ret; - } - - ASSERT(name_size, (L"")); - ASSERT(domain_size, (L"")); - if (!domain_size || !name_size) { - LocalFree(sid); - return E_UNEXPECTED; - } - - wchar_t* c_name = new wchar_t[name_size]; - ASSERT(c_name, (L"")); - if (!c_name) { - LocalFree(sid); - return E_OUTOFMEMORY; - } - - wchar_t* c_domain = new wchar_t[domain_size]; - ASSERT(c_domain, (L"")); - if (!c_domain) { - delete[] c_name; - LocalFree(sid); - return E_OUTOFMEMORY; - } - - if (LookupAccountSid(NULL, sid, c_name, &name_size, c_domain, - &domain_size, user_type)) { - ret = S_OK; - name->SetString(c_name); - domain->SetString(c_domain); - } else { - ret = GetCurError(); - } - - delete[] c_name; - delete[] c_domain; - LocalFree(sid); - } - - return ret; -} - -} // namespace accounts - -} // namespace omaha - diff --git a/omaha/base/accounts.h b/omaha/base/accounts.h deleted file mode 100644 index 26c713d..0000000 --- a/omaha/base/accounts.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// Enumeration of the user accounts on the PC. - -#ifndef OMAHA_COMMON_ACCOUNTS_H__ -#define OMAHA_COMMON_ACCOUNTS_H__ - -#include -#include -#include - -namespace omaha { - -namespace accounts { - -// Populates sid_array with string SIDs for all users, that have profiles -// on PC. Includes only user SIDs, no groups, computers or aliases. -HRESULT GetAllUserSids(CSimpleArray* sid_array); - -// Looks up account info for given SID. -// sid - SID to look up account info for. -// On success populates: -// name - name on the account -// domain - domain name for account -// user_type - the type of the passed SID, possible values: -// SidTypeUser -// SidTypeGroup -// SidTypeDomain -// SidTypeAlias -// SidTypeWellKnownGroup -// SidTypeDeletedAccount -// SidTypeInvalid -// SidTypeUnknown -// SidTypeComputer -HRESULT GetUserInfo(const wchar_t* sid, - CString* name, - CString* domain, - SID_NAME_USE* user_type); - -} // namespace accounts - -} // namespace omaha - -#endif // OMAHA_COMMON_ACCOUNTS_H__ diff --git a/omaha/base/apply_tag.cc b/omaha/base/apply_tag.cc index 751050b..cc50e3a 100644 --- a/omaha/base/apply_tag.cc +++ b/omaha/base/apply_tag.cc @@ -16,10 +16,12 @@ // Applies a tag to a signed file. #include "omaha/base/apply_tag.h" + #include #include +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/utils.h" #include "omaha/base/extractor.h" diff --git a/omaha/base/apply_tag.h b/omaha/base/apply_tag.h index 45e58b7..be33ba3 100644 --- a/omaha/base/apply_tag.h +++ b/omaha/base/apply_tag.h @@ -22,7 +22,6 @@ #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/error.h" namespace omaha { @@ -86,7 +85,7 @@ class ApplyTag { // data with the tagged information. std::vector buffer_data_; - DISALLOW_EVIL_CONSTRUCTORS(ApplyTag); + DISALLOW_COPY_AND_ASSIGN(ApplyTag); }; } // namespace omaha diff --git a/omaha/base/atl_regexp.cc b/omaha/base/atl_regexp.cc index e712d6b..ac0babb 100644 --- a/omaha/base/atl_regexp.cc +++ b/omaha/base/atl_regexp.cc @@ -14,11 +14,13 @@ // ======================================================================== #include "omaha/base/atl_regexp.h" + +#include #include namespace omaha { -const int kMaxArgs = 16; +constexpr int kMaxArgs = 16; AtlRE::AtlRE(const TCHAR* pattern, bool case_sensitive) { ASSERT(pattern, (L"")); diff --git a/omaha/base/atl_regexp.h b/omaha/base/atl_regexp.h index 7fafc28..1353a16 100644 --- a/omaha/base/atl_regexp.h +++ b/omaha/base/atl_regexp.h @@ -143,7 +143,7 @@ class AtlRE : public RE { private: mutable AtlRegExp re_; - DISALLOW_EVIL_CONSTRUCTORS(AtlRE); + DISALLOW_COPY_AND_ASSIGN(AtlRE); }; } // namespace omaha diff --git a/omaha/base/atlconvfix.h b/omaha/base/atlconvfix.h index 76ffaa4..58f6072 100644 --- a/omaha/base/atlconvfix.h +++ b/omaha/base/atlconvfix.h @@ -21,10 +21,10 @@ #ifndef OMAHA_COMMON_ATLCONVFIX_H_ #define OMAHA_COMMON_ATLCONVFIX_H_ -#ifndef DISALLOW_EVIL_CONSTRUCTORS +#ifndef DISALLOW_COPY_AND_ASSIGN // A macro to disallow the evil copy constructor and operator= functions // This should be used in the private: declarations for a class -#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) \ +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #endif @@ -64,7 +64,7 @@ class DestroyBuffer : public ConversionClass { } private: - DISALLOW_EVIL_CONSTRUCTORS(DestroyBuffer); + DISALLOW_COPY_AND_ASSIGN(DestroyBuffer); }; #define DECLARED_DESTROY_NAME(base_type) DestroyBuffer##base_type @@ -82,7 +82,7 @@ class DestroyBuffer : public ConversionClass { code_page) { \ } \ private: \ - DISALLOW_EVIL_CONSTRUCTORS(DECLARED_DESTROY_NAME(base_type##EX)); \ + DISALLOW_COPY_AND_ASSIGN(DECLARED_DESTROY_NAME(base_type##EX)); \ }; \ typedef DECLARED_DESTROY_NAME(base_type##EX)<> \ DECLARED_DESTROY_NAME(base_type) diff --git a/omaha/base/auto_any.h b/omaha/base/auto_any.h deleted file mode 100644 index 3291614..0000000 --- a/omaha/base/auto_any.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// See the comments in omaha/base/scoped_any.h for details. - -#ifndef OMAHA_COMMON_AUTO_ANY_H__ -#define OMAHA_COMMON_AUTO_ANY_H__ - -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) -#include "omaha/third_party/smartany/scoped_any.h" -#pragma warning(pop) - -#endif // OMAHA_COMMON_AUTO_ANY_H__ - diff --git a/omaha/base/browser_utils.cc b/omaha/base/browser_utils.cc index 6158b2c..7a377a1 100644 --- a/omaha/base/browser_utils.cc +++ b/omaha/base/browser_utils.cc @@ -13,8 +13,12 @@ // limitations under the License. // ======================================================================== -#include #include "omaha/base/browser_utils.h" + +#include + +#include + #include "base/basictypes.h" #include "omaha/base/commands.h" #include "omaha/base/const_utils.h" @@ -27,7 +31,6 @@ #include "omaha/base/proc_utils.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/shell.h" #include "omaha/base/string.h" #include "omaha/base/system.h" @@ -743,10 +746,10 @@ HRESULT GetIeFontSize(uint32* font_size) { return E_UNEXPECTED; } - scoped_array buf; // The font size is a binary registry value. + std::unique_ptr buf; // The font size is a binary registry value. size_t buf_size(0); if (FAILED(RegKey::GetValue(ie_scripts_key, ie_font_size, - address(buf), &buf_size))) { + &buf, &buf_size))) { *font_size = kDefaultFontSize; return S_OK; } diff --git a/omaha/base/browser_utils.h b/omaha/base/browser_utils.h index d6cbf3b..0ddb7d7 100644 --- a/omaha/base/browser_utils.h +++ b/omaha/base/browser_utils.h @@ -13,8 +13,6 @@ // limitations under the License. // ======================================================================== -// TODO(omaha): namespaces - #ifndef OMAHA_BASE_BROWSER_UTILS_H_ #define OMAHA_BASE_BROWSER_UTILS_H_ diff --git a/omaha/base/browser_utils_unittest.cc b/omaha/base/browser_utils_unittest.cc index 03bf06c..de20fdd 100644 --- a/omaha/base/browser_utils_unittest.cc +++ b/omaha/base/browser_utils_unittest.cc @@ -18,6 +18,7 @@ #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" +#include "omaha/base/string.h" #include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" @@ -223,15 +224,13 @@ TEST(BrowserUtilsTest, GetBrowserImagePath_AllSupportedBrowsers) { return; } - CString program_files_path; - EXPECT_SUCCEEDED(GetFolderPath(CSIDL_PROGRAM_FILES | CSIDL_FLAG_DONT_VERIFY, - &program_files_path)); CString path; HRESULT hr = GetBrowserImagePath(BROWSER_IE, &path); if (SUCCEEDED(hr)) { - EXPECT_EQ(0, path.CompareNoCase(program_files_path + - _T("\\Internet Explorer\\iexplore.exe"))) + EXPECT_TRUE(File::Exists(path)); + EXPECT_TRUE( + String_EndsWith(path, _T("\\Internet Explorer\\iexplore.exe"), true)) << _T("Actual path: ") << path.GetString(); } else { EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), hr); @@ -239,13 +238,12 @@ TEST(BrowserUtilsTest, GetBrowserImagePath_AllSupportedBrowsers) { hr = GetBrowserImagePath(BROWSER_FIREFOX, &path); if (SUCCEEDED(hr)) { + EXPECT_TRUE(File::Exists(path)); EXPECT_TRUE( - 0 == path.CompareNoCase(program_files_path + - _T("\\Mozilla Firefox\\firefox.exe")) || + String_EndsWith(path, _T("\\Mozilla Firefox\\firefox.exe"), true) || 0 == path.CompareNoCase( _T("C:\\PROGRA~1\\MOZILL~1\\FIREFOX.EXE")) || - 0 == path.CompareNoCase(program_files_path + - _T("\\Minefield\\FIREFOX.EXE"))) // Trunk build + String_EndsWith(path, _T("\\Minefield\\FIREFOX.EXE"), true)) << _T("Actual path: ") << path.GetString(); } else { EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), hr); @@ -253,12 +251,8 @@ TEST(BrowserUtilsTest, GetBrowserImagePath_AllSupportedBrowsers) { hr = GetBrowserImagePath(BROWSER_CHROME, &path); if (SUCCEEDED(hr)) { - EXPECT_TRUE( - 0 == path.CompareNoCase(program_files_path + - _T("\\Google\\Chrome\\Application\\chrome.exe")) || - 0 == path.CompareNoCase( - GetLocalAppDataPath() + - _T("Google\\Chrome\\Application\\chrome.exe"))) + EXPECT_TRUE(File::Exists(path)); + EXPECT_TRUE(String_EndsWith(path, _T("\\Application\\chrome.exe"), true)) << _T("Actual path: ") << path.GetString(); } else { EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), hr); diff --git a/omaha/base/build.scons b/omaha/base/build.scons index 72311df..8a4503a 100644 --- a/omaha/base/build.scons +++ b/omaha/base/build.scons @@ -15,6 +15,8 @@ Import('env') +import glob +import operator import os import os.path @@ -25,7 +27,6 @@ local_env = env.Clone() inputs = [ 'apply_tag.cc', - 'accounts.cc', 'app_util.cc', 'atl_regexp.cc', 'browser_utils.cc', @@ -35,7 +36,6 @@ inputs = [ 'command_line_validator.cc', 'commands.cc', 'crash_if_specific_error.cc', - 'crc.cc', 'debug.cc', 'disk.cc', 'dynamic_link_kernel32.cc', @@ -49,17 +49,12 @@ inputs = [ 'extractor.cc', 'file.cc', 'file_reader.cc', - 'file_store.cc', 'file_ver.cc', 'firewall_product_detection.cc', 'highres_timer-win32.cc', - 'localization.cc', 'logging.cc', - 'md5.cc', 'omaha_version.cc', 'path.cc', - 'pe_utils.cc', - 'popup_menu.cc', 'process.cc', 'proc_utils.cc', 'program_instance.cc', @@ -67,18 +62,13 @@ inputs = [ 'reactor.cc', 'reg_key.cc', 'regexp.cc', - 'registry_hive.cc', 'registry_monitor_manager.cc', - 'registry_store.cc', 'safe_format.cc', - 'serializable_object.cc', 'service_utils.cc', 'shell.cc', 'shutdown_handler.cc', 'signatures.cc', 'signaturevalidator.cc', - 'single_instance.cc', - 'sta.cc', 'string.cc', 'synchronized.cc', 'system.cc', @@ -101,7 +91,6 @@ inputs = [ '../third_party/chrome/files/src/crypto/rsa_private_key.cc', '../third_party/chrome/files/src/crypto/rsa_private_key_win.cc', '../third_party/chrome/files/src/crypto/signature_creator_win.cc', - '../third_party/smartany/shared_any.cc', ] # Required by the exception barrier code. @@ -110,92 +99,118 @@ local_env.Append(ASFLAGS = ['/safeseh']) # Build these into a library. local_env.ComponentStaticLibraryMultiarch('base', inputs) -""" Build the CRX Verifier libraries.""" +if 'OMAHA_PROTOBUF_BIN_DIR' not in os.environ: + """ Build the Protocol Buffer Compiler executable protoc.exe.""" -Import('env') -local_env = env.Clone() + def GenerateGYPRunAction(source, target, env, for_signature): + """This Generator creates a command line that when executed runs gyp on the + specified source file to generate the specified target file. -crx_file_path = '/third_party/chrome/files/src/components/crx_file/' -proto_input = [ - '$MAIN_DIR' + crx_file_path + 'crx3.proto', -] -proto_target_path = '$TARGET_ROOT/proto_files' + crx_file_path -proto_target = [ - proto_target_path + 'crx3.pb.cc', - proto_target_path + 'crx3.pb.h', -] -proto_output = local_env.CompileProtoBuf(proto_target, proto_input) -default_protobuf_src_dir = '$GOOGLE3/third_party/protobuf/src' -protobuf_src_dir = os.getenv('OMAHA_PROTOBUF_SRC_DIR', default_protobuf_src_dir) + * We explicitly change to the directory of the + source file before running gyp. Not doing this confuses some of the gyp + generators, especially the msvs generator. + * The |--generator-output| option is needed to generate the target in the + target directory. Without |--generator-output|, the target is generated + in the source directory, which is not desirable especially if the source + directory is read-only. Explicitly generating the target in a different + output directory also avoids other warnings. + * |--generator-output| needs to be specified as a + path relative to the source file path to be compatible with the gyp + generators. -local_env.Append( - CCFLAGS=[ - '/wd4100', - '/wd4125', - '/wd4127', - '/wd4146', - '/wd4244', - '/wd4309', - '/wd4577', - '/wd4800', - '/wd4995', - '/wd4996', - ], - CPPPATH=[ - protobuf_src_dir, - '$TARGET_ROOT/proto_files/', - ], -) + Args: + source: A List containing a single .gyp file path. + target: A List containing a single target file path. + env: The Environment in which to build. + for_signature: We ignore this parameter. It indicates to the generator to + just generate the command and not actually run it. -local_inputs = [ - '../third_party/chrome/files/src/components/crx_file/crx_verifier.cc', - '$TARGET_ROOT/proto_files/third_party/chrome/files/src/components/crx_file/crx3.pb.cc', - '../third_party/chrome/files/src/components/crx_file/id_util.cc', - '../third_party/chrome/files/src/crypto/signature_verifier.cc', - '../third_party/chrome/files/src/crypto/secure_util.cc', -] + Returns: + A valid command line that when executed runs gyp on the specified source + file to generate the specified target file. + """ + + # We use the googleclient gyp since the google3 gyp does not work well with + # python 2.7. + gyp_bat_file = '$GOOGLECLIENT\\third_party\\gyp\\files\\gyp.bat' + + # Explicitly using 'cd', since using the chdir option to env.Command() is + # not compatible with parallel builds using the -j option. + gyprun_action = 'cd %s' % source[0].dir.abspath + gyprun_action += ' && ' # Chaining the gyp generation to the 'cd' command. + gyprun_action += '%s %s --generator-output=%s -G msvs_version=2005' % ( + env.File(gyp_bat_file).abspath, + source[0].name, + os.path.relpath(target[0].dir.abspath, source[0].dir.abspath)) -obj_files = [] -for cc_file in local_inputs: - obj_files.append(local_env.Object(cc_file)) -local_env.Depends(obj_files, proto_output) -local_env.ComponentStaticLibrary('crx_file', obj_files, use_pch_default=False) + return gyprun_action -local_env = env.Clone() # SCons pylint: disable=undefined-variable + Import('env') + local_env = env.Clone() + # Use gyp to generate protoc.sln, which in turn is fed to VCBuild to generate + # protoc.exe. + # gyp. + gyprun = Builder(generator = GenerateGYPRunAction) + local_env.Append( BUILDERS = {'GYPRun' : gyprun}) + protoc_sln = local_env.GYPRun( + target='protoc.sln', + source='$GOOGLE3/net/proto2/contrib/portable/gyp/protoc.gyp') + + # VCBuild. + vcbld = Builder(action = + '$GOOGLECLIENT\\third_party\\vc_80\\files\\vc\\vcpackages\\vcbuild.exe' + + ' /useenv $SOURCE "Default|Win32"') + local_env.Append( BUILDERS = {'VCBuild' : vcbld}) + local_env.VCBuild(target='Default/protoc.exe', source=protoc_sln) + +""" Build libprotobuf. """ + +default_protobuf_src_dir = '$GOOGLE3/third_party/protobuf/src' +protobuf_src_dir = os.getenv('OMAHA_PROTOBUF_SRC_DIR', default_protobuf_src_dir) + +proto_env = env.Clone() protobuf_src_path = os.path.join(protobuf_src_dir, 'google/protobuf/') -local_env.FilterOut(CCFLAGS=['/W4']) -local_env.Append( +proto_env.Append( CPPDEFINES=['LIBPROTOBUF_EXPORTS'], CCFLAGS=[ '/wd4005', '/wd4018', '/wd4065', + '/wd4100', + '/wd4125', '/wd4146', + '/wd4242', '/wd4244', - '/wd4251', '/wd4267', - '/wd4305', - '/wd4309', + '/wd4310', '/wd4355', + '/wd4388', + '/wd4389', + '/wd4456', '/wd4506', - '/wd4530', - '/wd4541', - '/wd4577', + '/wd4548', + '/wd4647', + '/wd4701', + '/wd4702', + '/wd4703', + '/wd4798', '/wd4800', - '/wd4996', + '/wd4946', ], CPPPATH=[ + '$GOOGLE3', protobuf_src_dir, protobuf_src_path, ], ) -protobuf_src_path_dir = local_env.Dir(protobuf_src_path) -local_env.Dir('protobuf').addRepository(protobuf_src_path_dir) +protobuf_src_path_dir = proto_env.Dir(protobuf_src_path) +proto_env.Dir('protobuf').addRepository(protobuf_src_path_dir) cc_files = [ 'protobuf/compiler/importer.cc', 'protobuf/compiler/parser.cc', + 'protobuf/any.cc', 'protobuf/descriptor.cc', 'protobuf/descriptor.pb.cc', 'protobuf/descriptor_database.cc', @@ -204,22 +219,24 @@ cc_files = [ 'protobuf/extension_set_heavy.cc', 'protobuf/generated_message_reflection.cc', 'protobuf/generated_message_util.cc', + 'protobuf/implicit_weak_message.cc', 'protobuf/io/coded_stream.cc', 'protobuf/io/printer.cc', + 'protobuf/io/strtod.cc', 'protobuf/io/tokenizer.cc', + 'protobuf/io/strtod.cc', 'protobuf/io/zero_copy_stream.cc', 'protobuf/io/zero_copy_stream_impl.cc', 'protobuf/io/zero_copy_stream_impl_lite.cc', 'protobuf/arena.cc', + 'protobuf/map_field.cc', 'protobuf/message.cc', 'protobuf/message_lite.cc', 'protobuf/reflection_ops.cc', 'protobuf/repeated_field.cc', 'protobuf/service.cc', - 'protobuf/stubs/atomicops_internals_x86_msvc.cc', 'protobuf/stubs/common.cc', 'protobuf/stubs/int128.cc', - 'protobuf/stubs/once.cc', 'protobuf/stubs/status.cc', 'protobuf/stubs/stringprintf.cc', 'protobuf/stubs/stringpiece.cc', @@ -232,9 +249,96 @@ cc_files = [ 'protobuf/wire_format_lite.cc', ] -obj_files = [] -for cc_file in cc_files: - obj_files.append(local_env.Object(cc_file)) +proto_env.ComponentStaticLibraryMultiarch( + 'libprotobuf', cc_files, COMPONENT_STATIC=True) -local_env.ComponentLibrary('libprotobuf', obj_files, COMPONENT_STATIC=True) +""" Build the CRX Verifier libraries.""" + +Import('env') +local_env = env.Clone() + +crx_file_path = '/third_party/chrome/files/src/components/crx_file/' +local_env.Append(PROTO_PATH = '$MAIN_DIR' + crx_file_path) +local_env.Append(CPP_OUT = '$TARGET_ROOT/proto_files' + crx_file_path) +proto_sources = [ + '$MAIN_DIR' + crx_file_path + 'crx3.proto' +] +cc_files = local_env.CompileProtoBuf(proto_sources) +local_env.Append( + CPPPATH=[ + '$GOOGLE3', + protobuf_src_dir, + '$TARGET_ROOT/proto_files/', + ], +) + +cc_files += [ + '../third_party/chrome/files/src/components/crx_file/crx_verifier.cc', + '../third_party/chrome/files/src/components/crx_file/id_util.cc', + '../third_party/chrome/files/src/crypto/signature_verifier.cc', + '../third_party/chrome/files/src/crypto/signature_verifier_win.cc', + '../third_party/chrome/files/src/crypto/secure_util.cc', +] + +""" Add zlib library files.""" +zlib_src_path = '$THIRD_PARTY/zlib/v1_2_11/' +zlib_src_path_dir = local_env.Dir(zlib_src_path) +local_env.Dir('zlib').addRepository(zlib_src_path_dir) +cc_files += ['zlib/' + + os.path.basename(x) for x in + glob.glob(zlib_src_path_dir.path + os.sep + '*.c')] + +""" Add libzip library files.""" + +libzip_src_path = '$THIRD_PARTY/libzip/lib/' +libzip_src_path_dir = local_env.Dir(libzip_src_path) +local_env.Dir('libzip').addRepository(libzip_src_path_dir) +libzip_gladman_src_path = '$THIRD_PARTY/libzip/lib/gladman-fcrypt' + +local_env.Append( + CPPDEFINES=[ + 'HAVE_CONFIG_H', + ], + CPPPATH=[ + 'libzip/', + libzip_gladman_src_path, + libzip_src_path, + zlib_src_path, + ], + CCFLAGS=[ + '/wd4005', + '/wd4100', + '/wd4013', + '/wd4047', + '/wd4131', + '/wd4132', + '/wd4242', + '/wd4244', + '/wd4245', + '/wd4255', + '/wd4267', + '/wd4310', + '/wd4312', + '/wd4388', + '/wd4389', + '/wd4647', + '/wd4548', + ], +) + +cc_files_exclusions = [ + '*unix*.c', + 'zip_crypto_[cgmo]*.c', + 'zip_source_file.c', + 'zip_random_uwp.c', + 'zip_winzip_aes.c', + '*bzip2.c', + 'zip_source_winzip_aes_*.c' +] +cc_files += ['libzip/' + os.path.basename(x) for x in list( + set(glob.glob(os.sep.join([libzip_src_path_dir.path, '*.c']))) - + set(reduce(operator.concat, map (lambda x : glob.glob( + os.sep.join([libzip_src_path_dir.path, x])), cc_files_exclusions))))] +local_env.ComponentStaticLibraryMultiarch( + 'crx_file', cc_files, COMPONENT_STATIC=True) diff --git a/omaha/base/cgi_unittest.cc b/omaha/base/cgi_unittest.cc index 0aec8c4..679c8de 100644 --- a/omaha/base/cgi_unittest.cc +++ b/omaha/base/cgi_unittest.cc @@ -15,8 +15,10 @@ // // Unit test for the CGI escape/unescape string.. -#include "base/scoped_ptr.h" #include "omaha/base/cgi.h" + +#include + #include "omaha/base/string.h" #include "omaha/testing/unit_test.h" @@ -25,12 +27,12 @@ namespace omaha { void TestEscapeUnescape(const TCHAR* origin, const TCHAR* escaped) { int origin_len = lstrlen(origin); int buffer_len = origin_len * CGI::kEscapeFactor + 1; - scoped_array escaped_buffer(new TCHAR[buffer_len]); + std::unique_ptr escaped_buffer(new TCHAR[buffer_len]); ASSERT_TRUE(CGI::EscapeString(origin, origin_len, escaped_buffer.get(), buffer_len)); ASSERT_STREQ(escaped_buffer.get(), escaped); - scoped_array origin_buffer(new TCHAR[buffer_len]); + std::unique_ptr origin_buffer(new TCHAR[buffer_len]); ASSERT_TRUE(CGI::UnescapeString(escaped_buffer.get(), lstrlen(escaped_buffer.get()), origin_buffer.get(), buffer_len)); diff --git a/omaha/base/command_line_parser.h b/omaha/base/command_line_parser.h index 9cbdeef..999514a 100644 --- a/omaha/base/command_line_parser.h +++ b/omaha/base/command_line_parser.h @@ -19,9 +19,10 @@ #include #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" namespace omaha { @@ -102,10 +103,10 @@ class CommandLineParser { HRESULT AddOptionalSwitchArgument(const CString& switch_name, const CString& argument_value); - scoped_ptr required_args_; - scoped_ptr optional_args_; + std::unique_ptr required_args_; + std::unique_ptr optional_args_; - DISALLOW_EVIL_CONSTRUCTORS(CommandLineParser); + DISALLOW_COPY_AND_ASSIGN(CommandLineParser); }; } // namespace omaha diff --git a/omaha/base/command_line_parser_internal.h b/omaha/base/command_line_parser_internal.h index 59c43a2..7dce7fd 100644 --- a/omaha/base/command_line_parser_internal.h +++ b/omaha/base/command_line_parser_internal.h @@ -67,7 +67,7 @@ class CommandLineParserArgs { private: SwitchAndArgumentsMap switch_arguments_; - DISALLOW_EVIL_CONSTRUCTORS(CommandLineParserArgs); + DISALLOW_COPY_AND_ASSIGN(CommandLineParserArgs); }; } // namespace internal diff --git a/omaha/base/command_line_validator.h b/omaha/base/command_line_validator.h index f289b2d..1e57a3d 100644 --- a/omaha/base/command_line_validator.h +++ b/omaha/base/command_line_validator.h @@ -44,7 +44,7 @@ class CommandLineValidator { size_t num_required_parameters_; private: - DISALLOW_EVIL_CONSTRUCTORS(ScenarioParameter); + DISALLOW_COPY_AND_ASSIGN(ScenarioParameter); }; typedef std::vector ScenarioParameterVector; @@ -97,7 +97,7 @@ class CommandLineValidator { size_t scenario_sequence_number_; MapScenarios scenarios_; - DISALLOW_EVIL_CONSTRUCTORS(CommandLineValidator); + DISALLOW_COPY_AND_ASSIGN(CommandLineValidator); }; } // namespace omaha diff --git a/omaha/base/commands.cc b/omaha/base/commands.cc index 71cd847..573c6f5 100644 --- a/omaha/base/commands.cc +++ b/omaha/base/commands.cc @@ -16,8 +16,10 @@ // Parse command-line options #include "omaha/base/commands.h" + #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/cgi.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" @@ -28,12 +30,11 @@ namespace omaha { -#define kNameValueChar _T('=') -#define kTrueValue _T("true") -#define kFalseValue _T("false") -#define kOnValue _T("on") -#define kOffValue _T("off") - +constexpr TCHAR kNameValueChar = L'='; +constexpr TCHAR kTrueValue[] = L"true"; +constexpr TCHAR kFalseValue[] = L"false"; +constexpr TCHAR kOnValue[] = L"on"; +constexpr TCHAR kOffValue[] = L"off"; // // Helper functions @@ -117,7 +118,7 @@ HRESULT ConvertValue(const TCHAR* str_value, CString* value, bool to_unescape) { if (to_unescape) { int length = value->GetLength(); - scoped_array unescaped_value(new TCHAR[length + 1]); + std::unique_ptr unescaped_value(new TCHAR[length + 1]); RET_IF_FALSE(CGI::UnescapeString(*value, length, unescaped_value.get(), length + 1), CI_E_INVALID_ARG); *value = unescaped_value.get(); diff --git a/omaha/base/commands.h b/omaha/base/commands.h index 78d8b1b..fad19b7 100644 --- a/omaha/base/commands.h +++ b/omaha/base/commands.h @@ -72,7 +72,7 @@ class CommandParsingSimple { // in quotes. For instance, earlier versions of Google Desktop // used to have an "Uninstall" string of the form: // C:\Program Files\Google\Google Toolbar\GoogleToolbarSetup.exe -uninstall - // This function is meant to accomodate such cases. + // This function is meant to accommodate such cases. static HRESULT SplitExeAndArgsGuess(const TCHAR* cmd_line, CString* exe, CString* args); @@ -105,7 +105,7 @@ class CommandParsingSimple { private: - DISALLOW_EVIL_CONSTRUCTORS(CommandParsingSimple); + DISALLOW_COPY_AND_ASSIGN(CommandParsingSimple); }; @@ -151,7 +151,7 @@ class CommandParsing : public CommandParsingSimple { int options_count_; // Count of command-line options bool as_name_value_pair_; // Parse as name-value-pair - DISALLOW_EVIL_CONSTRUCTORS(CommandParsing); + DISALLOW_COPY_AND_ASSIGN(CommandParsing); }; } // namespace omaha diff --git a/omaha/base/const_addresses.h b/omaha/base/const_addresses.h index cd67a7b..99aaf80 100644 --- a/omaha/base/const_addresses.h +++ b/omaha/base/const_addresses.h @@ -58,30 +58,38 @@ const TCHAR* const kGoopdateServer = _T("tools.") COMPANY_DOMAIN; // The channel for update checks is secured by using CUP to sign the messages. // It does not depend solely on https security in any case. const TCHAR* const kUrlUpdateCheck = - _T("https://update.") COMPANY_DOMAIN_BASE _T("apis.com/service/update2"); + _T("https://updates.bravesoftware.com/service/update2"); // Pings. const TCHAR* const kUrlPing = - _T("https://update.") COMPANY_DOMAIN_BASE _T("apis.com/service/update2"); + _T("https://updates.bravesoftware.com/service/update2"); // The urls below never fall back to http. // // Crash reports. const TCHAR* const kUrlCrashReport = - _T("https://clients2.") COMPANY_DOMAIN _T("/cr/report"); + _T("https://updates.bravesoftware.com/cr/report"); // More information url. // Must allow query parameters to be appended to it. const TCHAR* const kUrlMoreInfo = - _T("https://www.") COMPANY_DOMAIN _T("/support/installer/?"); + _T("https://updates.bravesoftware.com/support/installer/?"); // Code Red check url. const TCHAR* const kUrlCodeRedCheck = - _T("https://clients2.") COMPANY_DOMAIN _T("/service/check2"); + _T("https://updates.bravesoftware.com/service/check2"); // Usage stats url. const TCHAR* const kUrlUsageStatsReport = - _T("https://clients5.") COMPANY_DOMAIN _T("/tbproxy/usagestats"); + _T("https://updates.bravesoftware.com/tbproxy/usagestats"); + +#if defined(HAS_DEVICE_MANAGEMENT) + +// Device Management API url. +const TCHAR* const kUrlDeviceManagement = + _T("https://m.") COMPANY_DOMAIN _T("/devicemanagement/data/api"); + +#endif // defined(HAS_DEVICE_MANAGEMENT) } // namespace omaha diff --git a/omaha/base/const_code_signing.h b/omaha/base/const_code_signing.h index c5a62f5..cff2aab 100644 --- a/omaha/base/const_code_signing.h +++ b/omaha/base/const_code_signing.h @@ -30,19 +30,19 @@ namespace omaha { // The company and organization names expected in the code // signing certificates which are trusted. const TCHAR* const kCertificateSubjectName = _T("Google Inc"); -const TCHAR* const kSha256CertificateSubjectName = _T("Google Inc"); +const TCHAR* const kSha256CertificateSubjectName = _T("Google LLC"); // The Omaha certificate thumbprint. Used by unit tests. const TCHAR* const kCertificateThumbprint = _T("1a6ac0549a4a44264deb6ff003391da2f285b19f"); const TCHAR* const kSha256CertificateThumbprint = - _T("5a9272ce76a9415a4a3a5002a2589a049312aa40"); + _T("cb7e84887f3c6015fe7edfb4f8f36df7dc10590e"); // The SHA256 hash of the Omaha certificate RSA public key. const TCHAR* const kCertificatePublicKeyHash = _T("d49de35a2e9fdbed09e2b9a6c1243df414d6aac13690ab221b0017a5cbe1351f"); const TCHAR* const kSha256CertificatePublicKeyHash = - _T("cd623b2bf2c06940bd480b6bcf4a5c9e1cbe94626fbfa127d001bf19ae5ba9fe"); + _T("03e27c19d222043a8f0c64181c23c9339cc84a7ec4ebff8a19adb7caefb0c709"); // The hash of public keys that we pin the code signing certificates to. // For quick identification, the date and thumbprint of the certificates are @@ -71,16 +71,22 @@ _T("4365c47f17727f2da65892b1f34c0cf418b0138b519b6864dd17300f21aa3144"), // SHA1 Fingerprint=26:4E:38:57:0F:88:2E:5A:02:72:42:37:57:74:12:33:A6:61:B5:53 _T("309bae1b466c4235e1daea9fe0e373b3415807ac667202f704d030ef33b519d6"), +// Omaha and Chrome certificate: sha256 (12/15/2015 to 12/16/2018). +// thumbprint=5a9272ce76a9415a4a3a5002a2589a049312aa40 +// serial=2a9c21acaaa63a3c58a7b9322bee948d +// SHA1 Fingerprint=5A:92:72:CE:76:A9:41:5A:4A:3A:50:02:A2:58:9A:04:93:12:AA:40 +_T("cd623b2bf2c06940bd480b6bcf4a5c9e1cbe94626fbfa127d001bf19ae5ba9fe"), + // Omaha and Chrome certificate: sha1 (11/28/2016 to 11/21/2019). // thumbprint=1a6ac0549a4a44264deb6ff003391da2f285b19f // serial=14F8FDD167F92402B1570B5DC495C815 // SHA1 Fingerprint=1A:6A:C0:54:9A:4A:44:26:4D:EB:6F:F0:03:39:1D:A2:F2:85:B1:9F kCertificatePublicKeyHash, -// Omaha and Chrome certificate: sha256 (12/15/2015 to 12/16/2018). -// thumbprint=5a9272ce76a9415a4a3a5002a2589a049312aa40 -// serial=2a9c21acaaa63a3c58a7b9322bee948d -// SHA1 Fingerprint=5A:92:72:CE:76:A9:41:5A:4A:3A:50:02:A2:58:9A:04:93:12:AA:40 +// Omaha and Chrome certificate: sha256 (11/06/2018 to 11/17/2021). +// thumbprint=cb7e84887f3c6015fe7edfb4f8f36df7dc10590e +// serial=0c15be4a15bb0903c901b1d6c265302f +// SHA1 Fingerprint=CB:7E:84:88:7F:3C:60:15:FE:7E:DF:B4:F8:F3:6D:F7:DC:10:59:0E kSha256CertificatePublicKeyHash, }; diff --git a/omaha/base/const_object_names.h b/omaha/base/const_object_names.h index a9822a7..76e4ba9 100644 --- a/omaha/base/const_object_names.h +++ b/omaha/base/const_object_names.h @@ -24,7 +24,7 @@ namespace omaha { // The prefix to use for global names in the win32 API's. -const TCHAR* const kGlobalPrefix = _T("Global\\Omaha"); +const TCHAR* const kGlobalPrefix = _T("Global\\BraveSoftware"); const TCHAR* const kObjectName64Suffix = _T("-x64"); @@ -33,7 +33,7 @@ const TCHAR* const kCrashPipeNamePrefix = // Ensures that only one instance of machine or user Omaha is trying to setup at // a time. -const TCHAR* const kSetupMutex = _T("{A9A86B93-B54E-4570-BE89-42418507707B}"); +const TCHAR* const kSetupMutex = _T("{C50974A0-5616-4DC6-AC6D-D4EFF6F5FAC3}"); // TODO(omaha3): Update this comment. // Signals the process to exit. Currently the core and the worker listen to @@ -41,7 +41,7 @@ const TCHAR* const kSetupMutex = _T("{A9A86B93-B54E-4570-BE89-42418507707B}"); // TODO(omaha): Consider making all our processes listen to it. Maybe not the // service, since the SCM controls the life time of the service. const TCHAR* const kShutdownEvent = - _T("{A0C1F415-D2CE-4ddc-9B48-14E56FD55162}"); + _T("{4613C8D6-D26E-4F10-B494-72CFF6F0BF0B}"); // This is for Omaha2 backwards compatibility. // The installed Omaha3 handoff process sets an event to tell an Omaha2 setup @@ -54,27 +54,32 @@ const TCHAR* const kLegacyUiDisplayedEventEnvironmentVariableName = // Ensures the Core only runs one instance per machine and one instance per // each user session. const TCHAR* const kCoreSingleInstance = - _T("{B5665124-2B19-40e2-A7BC-B44321E72C4B}"); + _T("{EC98B00C-9557-4627-ADCF-5832C3B09AA3}"); // Ensures the Crash Handler only runs one instance per machine and one // instance per each user session. const TCHAR* const kCrashHandlerSingleInstance = - _T("{C4F406E5-F024-4e3f-89A7-D5AB7663C3CD}"); + _T("{08DA086F-9FC4-4B2E-954C-6D7D5ACD5167}"); // Ensures the /ua process only runs one instance per machine and one // instance per each user session. const TCHAR* const kUpdateAppsSingleInstance = - _T("{D0BB2EF1-C183-4cdb-B218-040922092869}"); + _T("{0EADE80E-E9B8-4A5D-AF64-6D2A918F597C}"); // Ensures only one installer for an app is running in a session. // The %s is replaced with the application ID. const TCHAR* const kInstallAppSingleInstance = - _T("%s-{F707E94F-D66B-4525-AD84-B1DA87D6A971}"); + _T("%s-{0684C3E2-4EFA-4D1C-AE8D-A61945B94687}"); // Ensures the GoogleUpdate3 server only runs one instance per machine and one // instance per each user session. const TCHAR* const kGoogleUpdate3SingleInstance = - _T("{6885AE8E-C070-458d-9711-37B9BEAB65F6}"); + _T("{BD1D9A71-3C5B-436B-BAD8-D337E3226819}"); + +// Ensures the recovery probe only runs one instance per machine and one +// instance per each user session. +const TCHAR* const kRecoveryProbeSingleInstance = + _T("{5E36ECFE-B623-49F6-B9EB-9657264F3782}"); // TODO(omaha): Delete Job Object code. @@ -82,36 +87,36 @@ const TCHAR* const kGoogleUpdate3SingleInstance = // These may not be running as Local System for machine installs like // self-updates do. const TCHAR* const kSetupPhase1NonSelfUpdateJobObject = - _T("{5A913EF1-4160-48bc-B688-4D67EAEB698A}"); + _T("{4748B871-BD66-46D8-AAA1-BB61817AFF8F}"); // Base name of job object for interactive install processes except /install. const TCHAR* const kAppInstallJobObject = - _T("{8AD051DB-4FE6-458b-B103-7DCC78D56013}"); + _T("{0495DC7E-EA56-4677-9F0B-3B1535DF0E1A}"); // Base name of job object for silent processes that are okay to kill. const TCHAR* const kSilentJobObject = - _T("{A2300FD6-CBED-48a6-A3CB-B35C38A42F8E}"); + _T("{FB4AA39D-3174-43A2-838C-2DA4523D8B55}"); // Base name of job object for silent processes that should not be killed. const TCHAR* const kSilentDoNotKillJobObject = - _T("{D33A8A53-F57D-4fd9-A32D-238FD69B4BC4}"); + _T("{9D178053-EB3B-4183-B258-385F139CC1E8}"); // The global lock to ensure that a single app is being installed for this // user/machine at a given time. const TCHAR* const kInstallManagerSerializer = - _T("{0A175FBE-AEEC-4fea-855A-2AA549A88846}"); + _T("{FE0E7F6B-B8BD-4EEE-A8F1-8CE625AEF520}"); // Serializes access to metrics stores, machine and user, respectively. const TCHAR* const kMetricsSerializer = - _T("{C68009EA-1163-4498-8E93-D5C4E317D8CE}"); + _T("{D6025E95-A77B-4ADB-B46F-65CC31BB40E7}"); // Serializes access to the registry for application state. const TCHAR* const kRegistryAccessMutex = - _T("{66CC0160-ABB3-4066-AE47-1CA6AD5065C8}"); + _T("{4E15433F-5E08-47A1-AA4F-B1D1657EE725}"); // Serializes opt user id generation. const TCHAR* const kOptUserIdLock = - _T("{D19BAF17-7C87-467E-8D63-6C4B1C836373}"); + _T("{BC6A0F04-AE75-459F-B879-2C961515B78A}"); // Prefix used for programs with external (in-process) updaters to signal to // Omaha that they are currently doing an update check, and that Omaha should diff --git a/omaha/base/const_utils.h b/omaha/base/const_utils.h index be8ccfd..ae007f1 100644 --- a/omaha/base/const_utils.h +++ b/omaha/base/const_utils.h @@ -70,10 +70,6 @@ const TCHAR* const kRegValueIEAutoConfigURL = _T("AutoConfigURL"); #define kRegKeyFirefox \ _T("HKCR\\Applications\\FIREFOX.EXE\\shell\\open\\command") #define kRegValueFirefox _T("") -#define kFullRegKeyFirefox _T("HKLM\\SOFTWARE\\Mozilla\\Mozilla Firefox") -#define kRegKeyFirefoxPlugins _T("plugins") -#define kFirefoxCurrentVersion _T("CurrentVersion") -#define kFirefoxInstallDir _T("Install Directory") // Chrome. #define kRegKeyChrome _T("HKCR\\Applications\\chrome.exe\\shell\\open\\command") @@ -91,6 +87,15 @@ const TCHAR* const kRegKeyNetworkCards = _T("HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards"); const TCHAR* const kRegValueAdapterServiceName = _T("ServiceName"); +#if defined(HAS_DEVICE_MANAGEMENT) + +// Windows machine GUID (found in the 64-bit view of the registry). +const TCHAR* const kRegKeyCryptography = + _T("HKLM[64]\\SOFTWARE\\Microsoft\\Cryptography\\"); +const TCHAR* const kRegValueMachineGuid = _T("MachineGuid"); + +#endif // defined(HAS_DEVICE_MANAGEMENT) + } // namespace omaha #endif // OMAHA_BASE_CONST_UTILS_H_ diff --git a/omaha/base/constants.h b/omaha/base/constants.h index 0719cfe..e5ff505 100644 --- a/omaha/base/constants.h +++ b/omaha/base/constants.h @@ -45,7 +45,7 @@ namespace omaha { // not build values in other source files by concatenating preprocessor defines. // Full company name. -// FULL_COMPANY_NAME == "Google Inc." +// FULL_COMPANY_NAME == "Google LLC" const TCHAR* const kFullCompanyName = _T(FULL_COMPANY_NAME_ANSI); // Short company name (for use in paths and messages and to combine with product @@ -155,31 +155,48 @@ const TCHAR* const kTemporaryFilenamePrefix = _T("gup"); // Omaha's app ID // // TODO(omaha): Rename all of these "Omaha". -#define GOOPDATE_APP_ID _T("{430FD4D0-B729-4F61-AA34-91526481799D}") +#define GOOPDATE_APP_ID _T("{B131C935-9BE6-41DA-9599-1F776BEB8019}") const TCHAR* const kGoogleUpdateAppId = GOOPDATE_APP_ID; -const GUID kGoopdateGuid = {0x430FD4D0, 0xB729, 0x4F61, - {0xAA, 0x34, 0x91, 0x52, 0x64, 0x81, 0x79, 0x9D}}; +const GUID kGoopdateGuid = {0xB131C935, 0x9BE6, 0x41DA, + {0x95, 0x99, 0x1F, 0x77, 0x6B, 0xEB, 0x80, 0x19}}; // Chrome AppIDs #define CHROME_APP_ID _T("{8A69D345-D564-463C-AFF1-A69D9E530F96}") const TCHAR* const kChromeAppId = CHROME_APP_ID; +#if defined(HAS_DEVICE_MANAGEMENT) && defined(HAS_LEGACY_DM_CLIENT) + +// +// Cloud-based device management +// + +// The name of the legacy client application. +#define LEGACY_DM_CLIENT_APP _T("Chrome") + +#endif // defined(HAS_DEVICE_MANAGEMENT) && defined(HAS_LEGACY_DM_CLIENT) + // // Directory names // -#define OFFLINE_DIR_NAME _T("Offline") +#define OFFLINE_DIR_NAME _T("Offline") +#define DOWNLOAD_DIR_NAME _T("Download") +#define INSTALL_WORKING_DIR_NAME _T("Install") +// Directories relative to \Google #define OMAHA_REL_COMPANY_DIR SHORT_COMPANY_NAME #define OMAHA_REL_CRASH_DIR OMAHA_REL_COMPANY_DIR _T("\\CrashReports") +#define OMAHA_REL_POLICY_RESPONSES_DIR OMAHA_REL_COMPANY_DIR _T("\\Policies") + +// Directories relative to \Google\Update #define OMAHA_REL_GOOPDATE_INSTALL_DIR \ OMAHA_REL_COMPANY_DIR _T("\\") PRODUCT_NAME #define OMAHA_REL_LOG_DIR OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\Log") #define OMAHA_REL_OFFLINE_STORAGE_DIR \ OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\") OFFLINE_DIR_NAME #define OMAHA_REL_DOWNLOAD_STORAGE_DIR \ - OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\Download") + OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\") DOWNLOAD_DIR_NAME #define OMAHA_REL_INSTALL_WORKING_DIR \ - OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\Install") + OMAHA_REL_GOOPDATE_INSTALL_DIR _T("\\") INSTALL_WORKING_DIR_NAME // This directory is relative to the user profile app data local. #define LOCAL_APPDATA_REL_TEMP_DIR _T("\\Temp") @@ -189,6 +206,7 @@ const TCHAR* const kChromeAppId = CHROME_APP_ID; // #define MACHINE_KEY_NAME _T("HKLM") #define MACHINE_KEY MACHINE_KEY_NAME _T("\\") +#define MACHINE_KEY_64 MACHINE_KEY_NAME _T("[64]\\") #define USER_KEY_NAME _T("HKCU") #define USER_KEY USER_KEY_NAME _T("\\") #define USERS_KEY _T("HKU\\") @@ -202,6 +220,8 @@ const TCHAR* const kChromeAppId = CHROME_APP_ID; _T("Software\\Policies\\") SHORT_COMPANY_NAME _T("\\") #define GOOPDATE_POLICIES_RELATIVE COMPANY_POLICIES_MAIN_KEY \ PRODUCT_NAME _T("\\") +#define CLOUD_MANAGEMENT_POLICIES_RELATIVE COMPANY_POLICIES_MAIN_KEY \ + _T("CloudManagement\\") #define USER_LOCAL USER_KEY _T("Software\\Classes\\Local Settings\\") #define USER_LOCAL_REG_UPDATE USER_LOCAL GOOPDATE_MAIN_KEY @@ -280,6 +300,10 @@ const TCHAR* const kRegValueProxyHost = _T("ProxyHost"); const TCHAR* const kRegValueProxyPort = _T("ProxyPort"); const TCHAR* const kRegValueMID = _T("mid"); +#if defined(HAS_DEVICE_MANAGEMENT) +const TCHAR* const kRegValueNameDeviceManagementUrl = _T("DeviceManagementUrl"); +#endif + // The values below can be overriden in unofficial builds. const TCHAR* const kRegValueNameWindowsInstalling = _T("WindowsInstalling"); @@ -391,6 +415,13 @@ const TCHAR* const kDefaultCountryCode = _T("us"); // the max length of the extra info we can store inside the install stubs. const int kExtraMaxLength = 64 * 1024; // 64 KB +#if defined(HAS_DEVICE_MANAGEMENT) + +// The maximum length of an enrollment token. +const int kEnrollmentTokenMaxLength = 1024; + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // Default brand code value when one is not specified. // This has been specifically assigned to Omaha. const TCHAR* const kDefaultGoogleUpdateBrandCode = _T("GGLS"); @@ -487,7 +518,7 @@ const TCHAR* const kCustomClientInfoGroup = _T("ClientCustomData"); const COLORREF kTextColor = RGB(0x29, 0x29, 0x29); const COLORREF kBkColor = RGB(0XFB, 0XFB, 0XFB); -const COLORREF kCaptionForegroundColor = RGB(0x82, 0x82, 0x82); +const COLORREF kCaptionForegroundColor = RGB(0x00, 0x00, 0x00); const COLORREF kCaptionBkHover = RGB(0xE9, 0xE9, 0xE9); const COLORREF kCaptionFrameColor = RGB(0xC1, 0xC1, 0xC1); @@ -497,11 +528,11 @@ const COLORREF kProgressInnerFrameLight = RGB(0x6e, 0xc2, 0xfe); const COLORREF kProgressInnerFrameDark = RGB(0x44, 0x90, 0xfc); const COLORREF kProgressBarLightColor = RGB(0x4d, 0xa4, 0xfd); const COLORREF kProgressBarDarkColor = RGB(0x40, 0x86, 0xfd); -const COLORREF kProgressEmptyFillColor = RGB(230, 230, 230); -const COLORREF kProgressEmptyFrameColor = RGB(0xdd, 0xdd, 0xdd); -const COLORREF kProgressShadowLightColor = RGB(0xed, 0xed, 0xed); -const COLORREF kProgressShadowDarkColor = RGB(0xd5, 0xd5, 0xd5); -const COLORREF kProgressLeftHighlightColor = RGB(0xed, 0xed, 0xed); +const COLORREF kProgressEmptyFillColor = RGB(0xb6, 0xb6, 0xb6); +const COLORREF kProgressEmptyFrameColor = RGB(0xad, 0xad, 0xad); +const COLORREF kProgressShadowLightColor = RGB(0xbd, 0xbd, 0xbd); +const COLORREF kProgressShadowDarkColor = RGB(0xa5, 0xa5, 0xa5); +const COLORREF kProgressLeftHighlightColor = RGB(0xbd, 0xbd, 0xbd); // *** *** // *** Custom HTTP request headers sent by the Omaha Client. *** @@ -537,21 +568,21 @@ const TCHAR kHeaderXHTTPAttempts[] = _T("X-HTTP-Attempts"); // previous UID. const TCHAR kHeaderXOldUserId[] = _T("X-Old-UID"); -// The client sends a X-GoogleUpdate-Interactivity header to indicate whether +// The client sends a X-Goog-Update-Interactivity header to indicate whether // the current request is foreground or background. // A value of "fg" ("foreground") indicates foreground install or on-demand // updates. "bg" ("background") indicates silent update traffic. -const TCHAR kHeaderXInteractive[] = _T("X-GoogleUpdate-Interactivity"); +const TCHAR kHeaderXInteractive[] = _T("X-Goog-Update-Interactivity"); -// The client sends a X-GoogleUpdate-AppId header to indicate the apps +// The client sends a X-Goog-Update-AppId header to indicate the apps // associated with the request. When updating multiple apps, the client // specifies a comma-separated list of app ids. -const TCHAR kHeaderXAppId[] = _T("X-GoogleUpdate-AppId"); +const TCHAR kHeaderXAppId[] = _T("X-Goog-Update-AppId"); -// The client sends a X-GoogleUpdate-Updater header to indicate the identity of +// The client sends a X-Goog-Update-Updater header to indicate the identity of // the updater. This is the "updater" version string also present in the // request. In the case of Omaha, prepend "Omaha-" to the version string. -const TCHAR kHeaderXUpdater[] = _T("X-GoogleUpdate-Updater"); +const TCHAR kHeaderXUpdater[] = _T("X-Goog-Update-Updater"); // *** *** // *** Custom HTTP request headers that may be in an Omaha server response. *** diff --git a/omaha/base/crash_if_specific_error.h b/omaha/base/crash_if_specific_error.h index 6321a47..fded3bb 100644 --- a/omaha/base/crash_if_specific_error.h +++ b/omaha/base/crash_if_specific_error.h @@ -15,7 +15,9 @@ #ifndef OMAHA_BASE_CRASH_IF_SPECIFIC_ERROR_H_ #define OMAHA_BASE_CRASH_IF_SPECIFIC_ERROR_H_ + #include +#include #if defined __cplusplus diff --git a/omaha/base/crc.cc b/omaha/base/crc.cc deleted file mode 100644 index 729162c..0000000 --- a/omaha/base/crc.cc +++ /dev/null @@ -1,899 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Implemetation of CRCs (aka Rabin Fingerprints). -// Treats the input as a polynomial with coefficients in Z(2), -// and finds the remainder when divided by an irreducible polynomial -// of the appropriate length. -// It handles all CRC sizes from 8 to 128 bits. -// It's somewhat complicated by having separate implementations optimized for -// CRC's <=32 bits, <= 64 bits, and <= 128 bits. -// The input string is prefixed with a "1" bit, and has "degree" "0" bits -// appended to it before the remainder is found. This ensures that -// short strings are scrambled somewhat and that strings consisting -// of all nulls have a non-zero CRC. - -#include -#include "omaha/base/crc.h" -#include "omaha/base/debug.h" -#include "omaha/base/commontypes.h" - -namespace omaha { - -static const int SMALL_BITS = 8; - // When extending an input with a string of zeroes, - // if the number of zeroes is less than 2**SMALL_BITS, - // a normal Extend is done, rather than a polynomial - // multiplication. -static const char zeroes[1 << SMALL_BITS] = { 0 }; // an array of zeroes - -static const uint8 *zero_ptr = 0; // The 0 pointer---used for alignment - -// These are used to index a 2-entry array of words that together -// for a longer integer. LO indexes the low-order half. -#define LO 0 -#define HI (1-LO) - -// Constructor and destructor for baseclase CRC. -CRC::~CRC() {} -CRC::CRC() {} - -struct CRC_pair { // Used to represent a 128-bit value - uint64 lo; - uint64 hi; -}; - -class CRCImpl : public CRC { // Implemention of the abstract class CRC - public: - CRCImpl() {} - virtual ~CRCImpl() {} - - // The internal version of CRC::New(). - static CRCImpl *NewInternal(uint64 lo, uint64 hi, - int degree, size_t roll_length); - - virtual void Empty(uint64 *lo, uint64 *hi) const; - - size_t roll_length_; // length of window in rolling CRC - int degree_; // bits in the CRC - uint64 poly_lo_; // The CRC of the empty string, low part - uint64 poly_hi_; // The CRC of the empty string, high part - - private: - DISALLOW_EVIL_CONSTRUCTORS(CRCImpl); -}; - -// This is the 32-bit implementation. It handles all sizes from 8 to 32. -class CRC32 : public CRCImpl { - public: - CRC32() {} - virtual ~CRC32() {} - - virtual void Extend(uint64 *lo, uint64 *hi, - const void *bytes, size_t length) const; - virtual void ExtendByZeroes(uint64 *lo, uint64 *hi, size_t length) const; - virtual void Roll(uint64 *lo, uint64 *hi, uint8 o_byte, uint8 i_byte) const; - - uint32 table0_[256]; // table of byte extensions - uint32 table1_[256]; // table of byte extensions, shifted by 1 byte - uint32 table2_[256]; // table of byte extensions, shifted by 2 bytes - uint32 table3_[256]; // table of byte extensions, shifted by 3 bytes - uint32 roll_[256]; // table of byte roll values - uint32 zeroes_[256]; // table of zero extensions - - private: - DISALLOW_EVIL_CONSTRUCTORS(CRC32); -}; - -static const uint64 UINT64_ZERO = 0; // a 64-bit zero -static const uint64 UINT64_ONE = 1; // a 64-bit 1 - -// The B() macro sets the bit corresponding to X**(_x) in the polynomial -#define B(_x) (UINT64_ONE << ((_x) < 64?(63-(_x)):(127-(_x)))) - -// Used to initialize polynomials. -// The redundant tests on _len are to avoid warnings from the -// compiler about inappropriate shift lengths. These shifts -// occur on not-taken branch of the ?: in some cases. -#define kDefPoly(_h,_l,_len) \ - { ((_len) <= 64 ? (_l) >> ((_len) <= 64? 64 - (_len): 0) : \ - (_len) == 128 ? (_h) : \ - ((_h) >> ((_len) > 64? 128 - (_len): 0)) | \ - ((_l) << ((_len) > 64 && (_len) < 128? (_len)-64: 0))), \ - ((_len) <= 64 ? 0 : \ - (_len) == 128 ? (_l) : \ - (_l) >> ((_len) > 64? 128 - (_len): 0)), \ - (_len) } - -// A table of irreducible polynomials suitable for use with the implementation. -// Indexes 0...1 have degree 32 polynomials. -// Indexes 2...3 have degree 64 polynomials. -// Indexes 4...5 have degree 96 polynomials. -// Indexes 6...7 have degree 128 polynomials. -// Index i=8...128 has a degree i polynomial. -// All polynomials in the table are guaranteed distinct. -// lint -save -e572 -e648 -e778 Excessive shift value, expression evaluates to 0 -static const struct CRC::Poly poly_list[] = { - kDefPoly(UINT64_ZERO, B(30)+B(27)+B(26)+B(25)+B(23)+B(20)+B(17)+B(15)+B(14)+ - B(12)+B(6)+B(5)+B(2)+B(0), 32), - kDefPoly(UINT64_ZERO, B(31)+B(28)+B(27)+B(26)+B(24)+B(22)+B(19)+B(18)+B(16)+ - B(13)+B(11)+B(10)+B(9)+B(4)+B(2)+B(0), 32), - kDefPoly(UINT64_ZERO, B(60)+B(59)+B(58)+B(56)+B(55)+B(54)+B(51)+B(50)+B(49)+ - B(48)+B(47)+B(45)+B(44)+B(42)+B(40)+B(39)+B(38)+B(36)+B(34)+B(33)+ - B(32)+B(31)+B(30)+B(27)+B(25)+B(23)+B(22)+B(21)+B(20)+B(19)+ - B(17)+B(16)+B(15)+B(8)+B(7)+B(6)+B(5)+B(0), 64), - kDefPoly(UINT64_ZERO, B(63)+B(62)+B(60)+B(58)+B(57)+B(56)+B(54)+B(52)+B(46)+ - B(45)+B(43)+B(40)+B(37)+B(36)+B(34)+B(33)+B(32)+B(31)+B(30)+B(29)+ - B(28)+B(27)+B(26)+B(23)+B(19)+B(18)+B(15)+B(14)+B(13)+B(9)+B(8)+ - B(0), 64), - kDefPoly(B(95)+B(94)+B(91)+B(90)+B(89)+B(88)+B(87)+B(86)+B(79)+B(78)+ - B(77)+B(76)+B(75)+B(74)+B(73)+B(69)+B(68)+B(66), B(63)+B(61)+ - B(59)+B(57)+B(53)+B(51)+B(50)+B(47)+B(40)+B(39)+B(38)+B(36)+ - B(35)+B(33)+B(29)+B(28)+B(27)+B(25)+B(24)+B(23)+B(21)+B(19)+ - B(18)+B(17)+B(16)+B(13)+B(12)+B(10)+B(9)+B(7)+B(4)+B(2)+B(1)+ - B(0), 96), - kDefPoly(B(95)+B(92)+B(89)+B(88)+B(87)+B(85)+B(84)+B(82)+B(81)+B(80)+ - B(79)+B(78)+B(76)+B(75)+B(70)+B(69)+B(66)+B(65), B(60)+B(56)+ - B(55)+B(52)+B(51)+B(49)+B(48)+B(46)+B(44)+B(42)+B(41)+B(39)+ - B(38)+B(37)+B(35)+B(33)+B(32)+B(30)+B(28)+B(27)+B(25)+B(22)+ - B(19)+B(17)+B(14)+B(12)+B(10)+B(0), 96), - kDefPoly(B(122)+B(121)+B(120)+B(119)+B(117)+B(116)+B(114)+B(113)+B(112)+ - B(111)+B(109)+B(107)+B(104)+B(102)+B(100)+B(98)+B(96)+B(94)+ - B(93)+B(92)+B(91)+B(90)+B(88)+B(87)+B(86)+B(84)+B(82)+B(80)+ - B(75)+B(74)+B(73)+B(69), B(62)+B(61)+B(58)+B(52)+B(48)+B(47)+ - B(46)+B(45)+B(42)+B(41)+B(38)+B(37)+B(35)+B(33)+B(32)+B(31)+ - B(30)+B(28)+B(26)+B(24)+B(22)+B(21)+B(20)+B(19)+B(18)+B(17)+ - B(10)+B(9)+B(8)+B(7)+B(5)+B(2)+B(1)+B(0), 128), - kDefPoly(B(127)+B(126)+B(124)+B(121)+B(117)+B(116)+B(115)+B(113)+B(112)+ - B(111)+B(108)+B(105)+B(104)+B(103)+B(100)+B(98)+B(96)+B(93)+ - B(92)+B(90)+B(89)+B(88)+B(86)+B(85)+B(80)+B(77)+B(76)+B(72)+ - B(70)+B(69)+B(68)+B(65)+B(64), B(62)+B(61)+B(59)+B(58)+B(56)+ - B(53)+B(52)+B(51)+B(50)+B(48)+B(46)+B(39)+B(35)+B(34)+B(33)+ - B(32)+B(30)+B(29)+B(28)+B(22)+B(21)+B(19)+B(18)+B(17)+B(14)+ - B(10)+B(9)+B(7)+B(5)+B(4)+B(3)+B(2)+B(0), 128), - kDefPoly(UINT64_ZERO, B(7)+B(6)+B(5)+B(4)+B(2)+B(0), 8), - kDefPoly(UINT64_ZERO, B(8)+B(4)+B(3)+B(2)+B(1)+B(0), 9), - kDefPoly(UINT64_ZERO, B(8)+B(6)+B(5)+B(3)+B(1)+B(0), 10), - kDefPoly(UINT64_ZERO, B(10)+B(9)+B(7)+B(5)+B(1)+B(0), 11), - kDefPoly(UINT64_ZERO, B(11)+B(10)+B(5)+B(2)+B(1)+B(0), 12), - kDefPoly(UINT64_ZERO, B(12)+B(11)+B(10)+B(8)+B(5)+B(3)+B(2)+B(0), 13), - kDefPoly(UINT64_ZERO, B(11)+B(10)+B(9)+B(8)+B(7)+B(5)+B(4)+B(2)+B(1)+ - B(0), 14), - kDefPoly(UINT64_ZERO, B(14)+B(12)+B(11)+B(10)+B(9)+B(5)+B(3)+B(2)+B(1)+ - B(0), 15), - kDefPoly(UINT64_ZERO, B(12)+B(11)+B(7)+B(6)+B(5)+B(4)+B(3)+B(0), 16), - kDefPoly(UINT64_ZERO, B(16)+B(14)+B(11)+B(10)+B(8)+B(3)+B(1)+B(0), 17), - kDefPoly(UINT64_ZERO, B(12)+B(11)+B(9)+B(8)+B(7)+B(4)+B(3)+B(0), 18), - kDefPoly(UINT64_ZERO, B(12)+B(11)+B(8)+B(7)+B(6)+B(5)+B(2)+B(0), 19), - kDefPoly(UINT64_ZERO, B(18)+B(15)+B(14)+B(12)+B(9)+B(6)+B(3)+B(0), 20), - kDefPoly(UINT64_ZERO, B(20)+B(19)+B(14)+B(13)+B(12)+B(11)+B(8)+B(7)+B(6)+ - B(5)+B(2)+B(0), 21), - kDefPoly(UINT64_ZERO, B(21)+B(20)+B(18)+B(16)+B(15)+B(14)+B(12)+B(9)+B(7)+ - B(2)+B(1)+B(0), 22), - kDefPoly(UINT64_ZERO, B(22)+B(21)+B(17)+B(16)+B(15)+B(14)+B(12)+B(10)+B(7)+ - B(4)+B(1)+B(0), 23), - kDefPoly(UINT64_ZERO, B(23)+B(22)+B(21)+B(18)+B(17)+B(15)+B(14)+B(12)+B(4)+ - B(0), 24), - kDefPoly(UINT64_ZERO, B(24)+B(23)+B(22)+B(20)+B(18)+B(17)+B(14)+B(13)+B(9)+ - B(0), 25), - kDefPoly(UINT64_ZERO, B(25)+B(22)+B(21)+B(19)+B(17)+B(15)+B(14)+B(12)+B(11)+ - B(10)+B(6)+B(4)+B(3)+B(0), 26), - kDefPoly(UINT64_ZERO, B(26)+B(25)+B(19)+B(17)+B(16)+B(13)+B(5)+B(4)+B(1)+ - B(0), 27), - kDefPoly(UINT64_ZERO, B(23)+B(22)+B(21)+B(20)+B(19)+B(18)+B(13)+B(12)+B(10)+ - B(9)+B(8)+B(6)+B(5)+B(3)+B(1)+B(0), 28), - kDefPoly(UINT64_ZERO, B(27)+B(26)+B(25)+B(23)+B(22)+B(20)+B(19)+B(15)+B(14)+ - B(11)+B(10)+B(8)+B(7)+B(6)+B(4)+B(0), 29), - kDefPoly(UINT64_ZERO, B(29)+B(27)+B(25)+B(23)+B(20)+B(19)+B(18)+B(17)+B(16)+ - B(14)+B(11)+B(10)+B(9)+B(7)+B(6)+B(5)+B(4)+B(0), 30), - kDefPoly(UINT64_ZERO, B(30)+B(29)+B(28)+B(27)+B(25)+B(23)+B(22)+B(21)+B(20)+ - B(19)+B(18)+B(16)+B(15)+B(10)+B(9)+B(8)+B(4)+B(3)+B(1)+B(0), 31), - kDefPoly(UINT64_ZERO, B(31)+B(29)+B(28)+B(27)+B(21)+B(20)+B(15)+B(13)+B(10)+ - B(9)+B(8)+B(7)+B(4)+B(3)+B(2)+B(0), 32), - kDefPoly(UINT64_ZERO, B(32)+B(31)+B(30)+B(29)+B(27)+B(25)+B(24)+B(22)+B(21)+ - B(19)+B(15)+B(10)+B(4)+B(3)+B(2)+B(0), 33), - kDefPoly(UINT64_ZERO, B(30)+B(27)+B(26)+B(25)+B(24)+B(20)+B(19)+B(18)+B(16)+ - B(15)+B(14)+B(12)+B(9)+B(8)+B(7)+B(5)+B(1)+B(0), 34), - kDefPoly(UINT64_ZERO, B(34)+B(32)+B(28)+B(27)+B(26)+B(22)+B(21)+B(20)+B(19)+ - B(14)+B(13)+B(12)+B(10)+B(6)+B(5)+B(4)+B(3)+B(0), 35), - kDefPoly(UINT64_ZERO, B(35)+B(34)+B(33)+B(32)+B(31)+B(28)+B(26)+B(24)+B(22)+ - B(21)+B(20)+B(19)+B(18)+B(14)+B(13)+B(12)+B(10)+B(9)+B(8)+B(6)+B(5)+ - B(4)+B(3)+B(0), 36), - kDefPoly(UINT64_ZERO, B(36)+B(35)+B(31)+B(30)+B(28)+B(26)+B(25)+B(23)+B(22)+ - B(20)+B(19)+B(18)+B(16)+B(13)+B(12)+B(7)+B(6)+B(4)+B(3)+B(0), 37), - kDefPoly(UINT64_ZERO, B(37)+B(34)+B(33)+B(32)+B(31)+B(30)+B(29)+B(28)+B(27)+ - B(26)+B(25)+B(23)+B(18)+B(16)+B(15)+B(13)+B(12)+B(11)+B(10)+B(9)+ - B(8)+B(7)+B(6)+B(2)+B(1)+B(0), 38), - kDefPoly(UINT64_ZERO, B(38)+B(37)+B(33)+B(32)+B(31)+B(27)+B(25)+B(24)+B(21)+ - B(20)+B(19)+B(18)+B(17)+B(15)+B(14)+B(8)+B(7)+B(6)+B(3)+B(2)+B(1)+ - B(0), 39), - kDefPoly(UINT64_ZERO, B(38)+B(37)+B(35)+B(34)+B(32)+B(31)+B(30)+B(27)+B(24)+ - B(21)+B(20)+B(14)+B(13)+B(11)+B(8)+B(4)+B(2)+B(0), 40), - kDefPoly(UINT64_ZERO, B(38)+B(36)+B(35)+B(34)+B(33)+B(31)+B(30)+B(29)+B(28)+ - B(27)+B(23)+B(22)+B(20)+B(19)+B(18)+B(17)+B(15)+B(14)+B(11)+B(5)+ - B(4)+B(0), 41), - kDefPoly(UINT64_ZERO, B(41)+B(37)+B(36)+B(35)+B(32)+B(31)+B(30)+B(29)+B(28)+ - B(25)+B(19)+B(18)+B(14)+B(13)+B(12)+B(7)+B(6)+B(4)+B(2)+B(0), 42), - kDefPoly(UINT64_ZERO, B(42)+B(40)+B(38)+B(37)+B(36)+B(35)+B(34)+B(33)+B(31)+ - B(29)+B(27)+B(26)+B(25)+B(23)+B(21)+B(20)+B(19)+B(15)+B(11)+B(10)+ - B(9)+B(8)+B(6)+B(5)+B(3)+B(0), 43), - kDefPoly(UINT64_ZERO, B(43)+B(42)+B(40)+B(39)+B(37)+B(35)+B(32)+B(30)+B(26)+ - B(25)+B(24)+B(20)+B(16)+B(13)+B(12)+B(11)+B(8)+B(6)+B(5)+B(4)+B(1)+ - B(0), 44), - kDefPoly(UINT64_ZERO, B(43)+B(42)+B(41)+B(40)+B(39)+B(38)+B(33)+B(32)+B(27)+ - B(26)+B(25)+B(23)+B(20)+B(18)+B(17)+B(16)+B(14)+B(11)+B(10)+B(9)+ - B(6)+B(5)+B(1)+B(0), 45), - kDefPoly(UINT64_ZERO, B(45)+B(43)+B(42)+B(41)+B(40)+B(39)+B(32)+B(31)+B(30)+ - B(29)+B(27)+B(25)+B(23)+B(18)+B(17)+B(16)+B(10)+B(9)+B(7)+B(6)+B(4)+ - B(3)+B(2)+B(0), 46), - kDefPoly(UINT64_ZERO, B(45)+B(44)+B(43)+B(41)+B(40)+B(39)+B(38)+B(37)+B(32)+ - B(30)+B(23)+B(21)+B(20)+B(17)+B(15)+B(13)+B(11)+B(10)+B(7)+B(5)+ - B(3)+B(0), 47), - kDefPoly(UINT64_ZERO, B(46)+B(42)+B(41)+B(39)+B(37)+B(36)+B(35)+B(29)+B(28)+ - B(25)+B(24)+B(21)+B(20)+B(18)+B(17)+B(13)+B(12)+B(11)+B(10)+B(9)+ - B(8)+B(5)+B(1)+B(0), 48), - kDefPoly(UINT64_ZERO, B(48)+B(44)+B(41)+B(40)+B(39)+B(38)+B(37)+B(36)+B(35)+ - B(34)+B(30)+B(28)+B(27)+B(24)+B(21)+B(18)+B(17)+B(8)+B(3)+B(0), 49), - kDefPoly(UINT64_ZERO, B(48)+B(47)+B(46)+B(45)+B(44)+B(43)+B(42)+B(35)+B(33)+ - B(29)+B(26)+B(24)+B(23)+B(21)+B(18)+B(16)+B(14)+B(13)+B(12)+B(9)+ - B(7)+B(6)+B(5)+B(4)+B(3)+B(0), 50), - kDefPoly(UINT64_ZERO, B(47)+B(46)+B(45)+B(44)+B(43)+B(40)+B(39)+B(38)+B(36)+ - B(35)+B(30)+B(29)+B(28)+B(26)+B(25)+B(24)+B(23)+B(22)+B(20)+B(19)+ - B(18)+B(17)+B(15)+B(11)+B(7)+B(4)+B(3)+B(0), 51), - kDefPoly(UINT64_ZERO, B(51)+B(46)+B(43)+B(38)+B(37)+B(36)+B(34)+B(31)+B(27)+ - B(26)+B(20)+B(17)+B(16)+B(15)+B(13)+B(12)+B(11)+B(9)+B(7)+B(5)+B(1)+ - B(0), 52), - kDefPoly(UINT64_ZERO, B(50)+B(49)+B(47)+B(46)+B(44)+B(42)+B(41)+B(37)+B(36)+ - B(35)+B(33)+B(29)+B(28)+B(26)+B(24)+B(23)+B(21)+B(20)+B(14)+B(13)+ - B(12)+B(11)+B(10)+B(9)+B(8)+B(6)+B(3)+B(2)+B(1)+B(0), 53), - kDefPoly(UINT64_ZERO, B(52)+B(47)+B(46)+B(44)+B(43)+B(42)+B(40)+B(36)+B(32)+ - B(31)+B(30)+B(29)+B(28)+B(26)+B(25)+B(24)+B(23)+B(22)+B(20)+B(19)+ - B(17)+B(16)+B(15)+B(14)+B(13)+B(12)+B(11)+B(10)+B(7)+B(4)+B(2)+ - B(0), 54), - kDefPoly(UINT64_ZERO, B(53)+B(50)+B(48)+B(47)+B(37)+B(35)+B(31)+B(30)+B(25)+ - B(22)+B(21)+B(20)+B(19)+B(18)+B(15)+B(10)+B(8)+B(6)+B(3)+B(2)+B(1)+ - B(0), 55), - kDefPoly(UINT64_ZERO, B(54)+B(52)+B(51)+B(49)+B(48)+B(42)+B(38)+B(37)+B(31)+ - B(30)+B(27)+B(26)+B(24)+B(23)+B(22)+B(19)+B(16)+B(12)+B(11)+B(8)+ - B(6)+B(4)+B(3)+B(0), 56), - kDefPoly(UINT64_ZERO, B(55)+B(54)+B(51)+B(49)+B(48)+B(47)+B(46)+B(44)+B(43)+ - B(42)+B(41)+B(40)+B(39)+B(38)+B(32)+B(29)+B(27)+B(26)+B(23)+B(21)+ - B(20)+B(15)+B(12)+B(7)+B(6)+B(5)+B(3)+B(0), 57), - kDefPoly(UINT64_ZERO, B(57)+B(54)+B(52)+B(47)+B(45)+B(42)+B(41)+B(40)+B(39)+ - B(36)+B(34)+B(33)+B(31)+B(28)+B(26)+B(21)+B(20)+B(18)+B(17)+B(16)+ - B(13)+B(11)+B(8)+B(7)+B(4)+B(2)+B(1)+B(0), 58), - kDefPoly(UINT64_ZERO, B(58)+B(56)+B(54)+B(49)+B(47)+B(46)+B(43)+B(40)+B(38)+ - B(36)+B(35)+B(33)+B(32)+B(31)+B(30)+B(27)+B(24)+B(22)+B(21)+B(19)+ - B(17)+B(16)+B(11)+B(10)+B(9)+B(8)+B(7)+B(4)+B(3)+B(2)+B(1)+B(0), - 59), - kDefPoly(UINT64_ZERO, B(56)+B(54)+B(51)+B(46)+B(43)+B(42)+B(40)+B(39)+B(37)+ - B(35)+B(34)+B(33)+B(32)+B(31)+B(30)+B(29)+B(27)+B(25)+B(22)+B(21)+ - B(20)+B(19)+B(17)+B(16)+B(15)+B(14)+B(13)+B(12)+B(9)+B(7)+B(4)+ - B(3)+B(1)+B(0), 60), - kDefPoly(UINT64_ZERO, B(59)+B(58)+B(57)+B(56)+B(54)+B(53)+B(50)+B(49)+B(47)+ - B(44)+B(42)+B(41)+B(40)+B(37)+B(35)+B(34)+B(32)+B(30)+B(29)+B(27)+ - B(26)+B(22)+B(21)+B(20)+B(17)+B(14)+B(13)+B(12)+B(8)+B(5)+B(4)+ - B(0), 61), - kDefPoly(UINT64_ZERO, B(61)+B(59)+B(57)+B(55)+B(54)+B(53)+B(52)+B(51)+B(50)+ - B(49)+B(48)+B(45)+B(44)+B(40)+B(37)+B(35)+B(32)+B(31)+B(29)+B(25)+ - B(24)+B(23)+B(20)+B(17)+B(16)+B(15)+B(13)+B(12)+B(11)+B(10)+B(6)+ - B(5)+B(2)+B(0), 62), - kDefPoly(UINT64_ZERO, B(62)+B(57)+B(56)+B(53)+B(52)+B(51)+B(50)+B(46)+B(41)+ - B(38)+B(35)+B(34)+B(33)+B(31)+B(27)+B(25)+B(23)+B(21)+B(19)+B(18)+ - B(17)+B(16)+B(13)+B(11)+B(7)+B(5)+B(1)+B(0), 63), - kDefPoly(UINT64_ZERO, B(62)+B(61)+B(60)+B(57)+B(55)+B(54)+B(53)+B(49)+B(48)+ - B(46)+B(44)+B(42)+B(40)+B(39)+B(37)+B(36)+B(28)+B(27)+B(25)+B(23)+ - B(22)+B(21)+B(17)+B(15)+B(13)+B(7)+B(6)+B(4)+B(2)+B(0), 64), - kDefPoly(UINT64_ZERO, B(63)+B(62)+B(59)+B(57)+B(54)+B(53)+B(51)+B(48)+ - B(47)+B(46)+B(45)+B(44)+B(41)+B(40)+B(38)+B(36)+B(35)+B(28)+ - B(25)+B(24)+B(21)+B(20)+B(18)+B(16)+B(15)+B(13)+B(11)+B(8)+B(7)+ - B(3)+B(1)+B(0), 65), - kDefPoly(UINT64_ZERO, B(63)+B(58)+B(57)+B(56)+B(52)+B(51)+B(50)+B(44)+ - B(41)+B(40)+B(36)+B(34)+B(32)+B(31)+B(27)+B(25)+B(23)+B(21)+ - B(20)+B(19)+B(18)+B(17)+B(15)+B(14)+B(12)+B(11)+B(10)+B(8)+B(5)+ - B(4)+B(3)+B(0), 66), - kDefPoly(B(66), B(62)+B(60)+B(59)+B(58)+B(57)+B(56)+B(55)+B(54)+B(52)+ - B(50)+B(47)+B(46)+B(45)+B(43)+B(42)+B(41)+B(38)+B(37)+B(36)+ - B(33)+B(32)+B(31)+B(30)+B(28)+B(27)+B(26)+B(24)+B(21)+B(18)+ - B(17)+B(14)+B(13)+B(12)+B(11)+B(10)+B(7)+B(4)+B(3)+B(0), 67), - kDefPoly(B(67)+B(66), B(63)+B(61)+B(57)+B(55)+B(51)+B(47)+B(45)+B(43)+ - B(42)+B(41)+B(40)+B(39)+B(32)+B(31)+B(30)+B(28)+B(27)+B(25)+ - B(19)+B(18)+B(17)+B(15)+B(11)+B(9)+B(8)+B(7)+B(6)+B(5)+B(4)+B(3)+ - B(1)+B(0), 68), - kDefPoly(B(68), B(60)+B(57)+B(55)+B(54)+B(52)+B(50)+B(49)+B(48)+B(44)+ - B(40)+B(38)+B(37)+B(33)+B(31)+B(28)+B(25)+B(22)+B(21)+B(20)+ - B(19)+B(18)+B(17)+B(13)+B(12)+B(9)+B(8)+B(6)+B(5)+B(4)+B(1)+ - B(0), 69), - kDefPoly(B(69)+B(68)+B(67)+B(66), B(63)+B(62)+B(61)+B(59)+B(51)+B(49)+ - B(48)+B(46)+B(45)+B(42)+B(40)+B(38)+B(36)+B(35)+B(33)+B(32)+ - B(30)+B(29)+B(27)+B(23)+B(22)+B(21)+B(16)+B(12)+B(5)+B(4)+B(1)+ - B(0), 70), - kDefPoly(B(70)+B(69)+B(68)+B(64), B(63)+B(62)+B(61)+B(60)+B(59)+B(57)+ - B(56)+B(55)+B(54)+B(53)+B(51)+B(50)+B(47)+B(44)+B(43)+B(41)+ - B(39)+B(37)+B(36)+B(33)+B(32)+B(26)+B(25)+B(24)+B(23)+B(21)+ - B(20)+B(19)+B(17)+B(12)+B(11)+B(10)+B(8)+B(6)+B(5)+B(4)+B(2)+ - B(0), 71), - kDefPoly(B(71)+B(69)+B(68)+B(65)+B(64), B(62)+B(61)+B(59)+B(58)+B(55)+ - B(53)+B(51)+B(49)+B(48)+B(47)+B(43)+B(40)+B(38)+B(37)+B(36)+ - B(35)+B(33)+B(32)+B(31)+B(30)+B(29)+B(26)+B(24)+B(19)+B(18)+ - B(15)+B(13)+B(9)+B(7)+B(6)+B(3)+B(1)+B(0), 72), - kDefPoly(B(71)+B(70)+B(69)+B(67)+B(65), B(63)+B(62)+B(61)+B(58)+B(57)+ - B(56)+B(55)+B(52)+B(51)+B(50)+B(49)+B(46)+B(45)+B(44)+B(43)+ - B(41)+B(37)+B(36)+B(34)+B(33)+B(27)+B(26)+B(25)+B(21)+B(19)+ - B(18)+B(16)+B(15)+B(14)+B(13)+B(9)+B(8)+B(6)+B(5)+B(2)+B(1)+ - B(0), 73), - kDefPoly(B(73)+B(71)+B(70)+B(65)+B(64), B(62)+B(60)+B(55)+B(54)+B(52)+ - B(50)+B(48)+B(47)+B(46)+B(44)+B(41)+B(40)+B(31)+B(29)+B(28)+ - B(27)+B(26)+B(24)+B(23)+B(22)+B(20)+B(16)+B(12)+B(9)+B(6)+B(5)+ - B(4)+B(2)+B(0), 74), - kDefPoly(B(74)+B(73)+B(72)+B(67)+B(64), B(63)+B(61)+B(60)+B(58)+B(57)+ - B(56)+B(54)+B(52)+B(51)+B(50)+B(44)+B(43)+B(42)+B(41)+B(40)+ - B(39)+B(38)+B(36)+B(35)+B(33)+B(32)+B(31)+B(29)+B(28)+B(26)+ - B(23)+B(21)+B(19)+B(18)+B(16)+B(15)+B(13)+B(12)+B(11)+B(7)+B(6)+ - B(5)+B(4)+B(3)+B(2)+B(0), 75), - kDefPoly(B(75)+B(74)+B(71)+B(70)+B(66), B(63)+B(61)+B(59)+B(57)+B(53)+ - B(50)+B(49)+B(48)+B(44)+B(43)+B(42)+B(37)+B(33)+B(30)+B(27)+ - B(24)+B(23)+B(20)+B(18)+B(15)+B(12)+B(11)+B(9)+B(7)+B(6)+B(4)+ - B(3)+B(2)+B(0), 76), - kDefPoly(B(73)+B(71)+B(70)+B(68)+B(67)+B(66)+B(65), B(63)+B(60)+B(59)+ - B(58)+B(57)+B(54)+B(49)+B(47)+B(46)+B(45)+B(43)+B(41)+B(38)+ - B(34)+B(33)+B(31)+B(30)+B(29)+B(27)+B(25)+B(24)+B(21)+B(20)+ - B(19)+B(16)+B(15)+B(14)+B(13)+B(10)+B(8)+B(6)+B(5)+B(4)+B(2)+ - B(0), 77), - kDefPoly(B(77)+B(76)+B(75)+B(74)+B(70)+B(66)+B(65)+B(64), B(63)+B(62)+ - B(60)+B(58)+B(57)+B(55)+B(52)+B(51)+B(44)+B(41)+B(39)+B(38)+ - B(35)+B(31)+B(30)+B(29)+B(26)+B(22)+B(21)+B(20)+B(19)+B(15)+ - B(13)+B(11)+B(6)+B(4)+B(1)+B(0), 78), - kDefPoly(B(78)+B(76)+B(75)+B(71)+B(68)+B(67)+B(65), B(63)+B(61)+B(60)+ - B(55)+B(54)+B(51)+B(50)+B(48)+B(44)+B(42)+B(41)+B(40)+B(38)+ - B(35)+B(34)+B(32)+B(28)+B(26)+B(23)+B(22)+B(19)+B(15)+B(13)+ - B(12)+B(8)+B(7)+B(5)+B(2)+B(0), 79), - kDefPoly(B(77)+B(76)+B(75)+B(73)+B(70)+B(66), B(63)+B(61)+B(60)+B(59)+ - B(56)+B(54)+B(53)+B(52)+B(50)+B(44)+B(43)+B(40)+B(39)+B(38)+ - B(35)+B(34)+B(33)+B(29)+B(28)+B(27)+B(26)+B(25)+B(24)+B(23)+ - B(22)+B(21)+B(20)+B(18)+B(16)+B(13)+B(12)+B(11)+B(10)+B(8)+B(7)+ - B(6)+B(3)+B(2)+B(1)+B(0), 80), - kDefPoly(B(78)+B(77)+B(76)+B(75)+B(73)+B(71)+B(67)+B(66)+B(65)+ - B(64), B(61)+B(54)+B(53)+B(52)+B(49)+B(47)+B(44)+B(41)+B(40)+ - B(35)+B(33)+B(31)+B(30)+B(28)+B(27)+B(26)+B(25)+B(22)+B(21)+ - B(20)+B(16)+B(15)+B(13)+B(12)+B(11)+B(0), 81), - kDefPoly(B(81)+B(80)+B(79)+B(77)+B(76)+B(74)+B(73)+B(72)+B(68)+B(67)+ - B(66)+B(64), B(62)+B(51)+B(50)+B(49)+B(47)+B(46)+B(45)+B(43)+ - B(41)+B(38)+B(37)+B(34)+B(32)+B(30)+B(27)+B(26)+B(25)+B(24)+ - B(23)+B(22)+B(20)+B(19)+B(16)+B(15)+B(13)+B(12)+B(9)+B(7)+B(5)+ - B(4)+B(1)+B(0), 82), - kDefPoly(B(82)+B(81)+B(79)+B(78)+B(77)+B(75)+B(72)+B(71)+B(69)+B(68)+ - B(67)+B(66)+B(65)+B(64), B(60)+B(58)+B(57)+B(56)+B(53)+B(52)+ - B(51)+B(49)+B(48)+B(45)+B(43)+B(41)+B(40)+B(39)+B(38)+B(37)+ - B(36)+B(35)+B(33)+B(26)+B(24)+B(21)+B(19)+B(16)+B(13)+B(12)+ - B(11)+B(9)+B(7)+B(5)+B(4)+B(3)+B(1)+B(0), 83), - kDefPoly(B(79)+B(77)+B(73)+B(72)+B(71)+B(66)+B(64), B(62)+B(61)+B(59)+ - B(58)+B(57)+B(56)+B(53)+B(52)+B(51)+B(48)+B(47)+B(46)+B(45)+ - B(43)+B(42)+B(41)+B(38)+B(37)+B(35)+B(33)+B(32)+B(29)+B(24)+ - B(22)+B(17)+B(16)+B(15)+B(13)+B(11)+B(10)+B(9)+B(7)+B(6)+B(5)+ - B(0), 84), - kDefPoly(B(83)+B(78)+B(76)+B(73)+B(70)+B(69)+B(68)+B(67)+B(66)+ - B(64), B(62)+B(61)+B(60)+B(59)+B(54)+B(51)+B(50)+B(48)+B(47)+ - B(42)+B(41)+B(40)+B(38)+B(37)+B(36)+B(34)+B(31)+B(30)+B(28)+ - B(27)+B(26)+B(24)+B(22)+B(21)+B(20)+B(19)+B(18)+B(16)+B(15)+ - B(14)+B(13)+B(12)+B(10)+B(6)+B(4)+B(0), 85), - kDefPoly(B(84)+B(77)+B(76)+B(75)+B(71)+B(70)+B(69)+B(67)+B(65), B(63)+ - B(62)+B(59)+B(58)+B(57)+B(55)+B(53)+B(52)+B(51)+B(48)+B(47)+ - B(45)+B(43)+B(40)+B(38)+B(36)+B(34)+B(33)+B(31)+B(27)+B(25)+ - B(24)+B(23)+B(22)+B(19)+B(15)+B(13)+B(12)+B(11)+B(8)+B(6)+B(4)+ - B(0), 86), - kDefPoly(B(85)+B(84)+B(83)+B(81)+B(80)+B(78)+B(73)+B(72)+B(70)+B(68)+ - B(67)+B(64), B(61)+B(60)+B(58)+B(57)+B(55)+B(52)+B(50)+B(49)+ - B(47)+B(44)+B(37)+B(36)+B(35)+B(34)+B(32)+B(31)+B(30)+B(25)+ - B(24)+B(23)+B(20)+B(13)+B(12)+B(11)+B(10)+B(9)+B(7)+B(6)+B(4)+ - B(3)+B(2)+B(0), 87), - kDefPoly(B(86)+B(85)+B(84)+B(83)+B(82)+B(80)+B(77)+B(74)+B(70)+B(69)+ - B(65), B(63)+B(60)+B(59)+B(57)+B(56)+B(55)+B(53)+B(50)+B(49)+ - B(48)+B(45)+B(42)+B(41)+B(40)+B(39)+B(38)+B(37)+B(36)+B(25)+ - B(21)+B(19)+B(13)+B(11)+B(8)+B(5)+B(4)+B(2)+B(1)+B(0), 88), - kDefPoly(B(86)+B(85)+B(83)+B(82)+B(81)+B(78)+B(77)+B(74)+B(73)+B(72)+ - B(70)+B(69)+B(68)+B(65)+B(64), B(59)+B(57)+B(55)+B(54)+B(51)+ - B(50)+B(46)+B(45)+B(44)+B(43)+B(42)+B(40)+B(38)+B(37)+B(33)+ - B(31)+B(30)+B(29)+B(28)+B(27)+B(23)+B(22)+B(21)+B(20)+B(18)+ - B(17)+B(16)+B(15)+B(10)+B(9)+B(3)+B(1)+B(0), 89), - kDefPoly(B(86)+B(83)+B(82)+B(80)+B(79)+B(73)+B(70)+B(69)+B(67)+ - B(64), B(63)+B(62)+B(61)+B(57)+B(56)+B(54)+B(51)+B(49)+B(47)+ - B(46)+B(45)+B(40)+B(39)+B(37)+B(35)+B(33)+B(32)+B(29)+B(28)+ - B(27)+B(25)+B(24)+B(23)+B(22)+B(21)+B(20)+B(19)+B(18)+B(17)+ - B(15)+B(9)+B(8)+B(7)+B(3)+B(2)+B(0), 90), - kDefPoly(B(90)+B(89)+B(84)+B(81)+B(80)+B(78)+B(74)+B(73)+B(71)+B(68)+ - B(64), B(60)+B(59)+B(58)+B(57)+B(55)+B(54)+B(52)+B(50)+B(49)+ - B(47)+B(45)+B(42)+B(41)+B(39)+B(38)+B(36)+B(32)+B(28)+B(25)+ - B(21)+B(20)+B(19)+B(15)+B(12)+B(11)+B(9)+B(8)+B(3)+ - B(0), 91), - kDefPoly(B(91)+B(89)+B(88)+B(87)+B(86)+B(85)+B(84)+B(83)+B(80)+B(78)+ - B(76)+B(72)+B(70)+B(68), B(63)+B(62)+B(61)+B(59)+B(57)+B(56)+ - B(52)+B(51)+B(50)+B(49)+B(43)+B(40)+B(39)+B(37)+B(36)+B(35)+ - B(34)+B(33)+B(32)+B(26)+B(25)+B(24)+B(23)+B(22)+B(18)+B(15)+ - B(12)+B(11)+B(9)+B(7)+B(6)+B(3)+B(1)+B(0), 92), - kDefPoly(B(86)+B(85)+B(83)+B(82)+B(79)+B(78)+B(77)+B(75)+B(74)+B(73)+ - B(66)+B(64), B(59)+B(57)+B(56)+B(55)+B(54)+B(52)+B(51)+B(40)+ - B(38)+B(36)+B(34)+B(33)+B(28)+B(27)+B(26)+B(25)+B(23)+B(22)+ - B(21)+B(20)+B(19)+B(18)+B(16)+B(15)+B(14)+B(13)+B(12)+B(11)+B(8)+ - B(7)+B(6)+B(5)+B(4)+B(0), 93), - kDefPoly(B(93)+B(92)+B(91)+B(89)+B(88)+B(87)+B(86)+B(81)+B(80)+B(75)+ - B(66)+B(64), B(62)+B(61)+B(60)+B(59)+B(58)+B(57)+B(56)+B(54)+ - B(48)+B(47)+B(46)+B(45)+B(44)+B(42)+B(41)+B(38)+B(37)+B(36)+ - B(34)+B(33)+B(31)+B(30)+B(27)+B(26)+B(25)+B(22)+B(13)+B(12)+ - B(11)+B(10)+B(8)+B(7)+B(4)+B(0), 94), - kDefPoly(B(94)+B(88)+B(87)+B(82)+B(79)+B(78)+B(76)+B(73)+B(65)+ - B(64), B(62)+B(61)+B(60)+B(59)+B(58)+B(57)+B(53)+B(51)+B(50)+ - B(49)+B(48)+B(47)+B(46)+B(44)+B(40)+B(36)+B(34)+B(33)+B(30)+ - B(28)+B(27)+B(25)+B(22)+B(19)+B(18)+B(17)+B(16)+B(14)+B(7)+B(5)+ - B(3)+B(2)+B(1)+B(0), 95), - kDefPoly(B(92)+B(89)+B(88)+B(86)+B(83)+B(79)+B(78)+B(76)+B(75)+B(74)+ - B(72)+B(70)+B(67)+B(66), B(63)+B(60)+B(57)+B(55)+B(53)+B(51)+ - B(47)+B(46)+B(44)+B(43)+B(42)+B(39)+B(38)+B(36)+B(34)+B(32)+ - B(31)+B(30)+B(27)+B(26)+B(25)+B(22)+B(21)+B(19)+B(17)+B(13)+ - B(11)+B(10)+B(9)+B(8)+B(7)+B(4)+B(1)+B(0), 96), - kDefPoly(B(96)+B(94)+B(93)+B(91)+B(89)+B(87)+B(85)+B(83)+B(81)+B(78)+ - B(76)+B(74)+B(73)+B(68)+B(67)+B(64), B(62)+B(61)+B(57)+B(55)+ - B(54)+B(53)+B(49)+B(47)+B(41)+B(38)+B(35)+B(33)+B(28)+B(27)+ - B(24)+B(23)+B(21)+B(19)+B(18)+B(17)+B(15)+B(13)+B(12)+B(11)+B(8)+ - B(6)+B(4)+B(3)+B(1)+B(0), 97), - kDefPoly(B(97)+B(93)+B(92)+B(91)+B(90)+B(87)+B(83)+B(82)+B(80)+B(77)+ - B(76)+B(75)+B(74)+B(73)+B(72)+B(70)+B(69)+B(68)+B(66)+B(65)+ - B(64), B(63)+B(62)+B(61)+B(60)+B(59)+B(57)+B(55)+B(53)+B(50)+ - B(49)+B(48)+B(45)+B(44)+B(43)+B(42)+B(40)+B(38)+B(36)+B(35)+ - B(34)+B(28)+B(27)+B(24)+B(22)+B(21)+B(18)+B(17)+B(16)+B(15)+ - B(14)+B(12)+B(11)+B(9)+B(8)+B(2)+B(1)+B(0), 98), - kDefPoly(B(96)+B(94)+B(92)+B(86)+B(85)+B(84)+B(78)+B(77)+B(76)+B(75)+ - B(73)+B(71)+B(69)+B(68)+B(65), B(61)+B(59)+B(57)+B(56)+B(54)+ - B(50)+B(47)+B(46)+B(44)+B(41)+B(38)+B(36)+B(35)+B(34)+B(33)+ - B(32)+B(29)+B(27)+B(26)+B(25)+B(23)+B(22)+B(21)+B(19)+B(17)+ - B(16)+B(11)+B(9)+B(7)+B(6)+B(3)+B(2)+B(0), 99), - kDefPoly(B(99)+B(96)+B(95)+B(93)+B(92)+B(88)+B(87)+B(83)+B(78)+B(77)+ - B(76)+B(75)+B(74)+B(73)+B(70)+B(66)+B(64), B(63)+B(62)+B(60)+ - B(59)+B(57)+B(56)+B(53)+B(50)+B(47)+B(41)+B(39)+B(38)+B(37)+ - B(34)+B(25)+B(23)+B(21)+B(20)+B(19)+B(18)+B(17)+B(16)+B(13)+B(9)+ - B(8)+B(6)+B(5)+B(1)+B(0), 100), - kDefPoly(B(100)+B(98)+B(97)+B(95)+B(93)+B(92)+B(91)+B(89)+B(87)+B(85)+ - B(84)+B(82)+B(81)+B(80)+B(79)+B(76)+B(68)+B(66)+B(65), B(63)+ - B(62)+B(59)+B(57)+B(52)+B(51)+B(50)+B(47)+B(46)+B(45)+B(42)+ - B(41)+B(40)+B(39)+B(38)+B(37)+B(36)+B(34)+B(32)+B(31)+B(30)+ - B(24)+B(22)+B(21)+B(20)+B(18)+B(17)+B(16)+B(14)+B(12)+B(11)+ - B(10)+B(8)+B(7)+B(5)+B(4)+B(2)+B(1)+B(0), 101), - kDefPoly(B(101)+B(99)+B(97)+B(96)+B(92)+B(89)+B(88)+B(87)+B(86)+B(84)+ - B(82)+B(81)+B(80)+B(78)+B(77)+B(76)+B(75)+B(74)+B(73)+ - B(69), B(60)+B(59)+B(57)+B(56)+B(55)+B(54)+B(53)+B(51)+B(50)+ - B(49)+B(47)+B(45)+B(43)+B(41)+B(35)+B(34)+B(32)+B(31)+B(29)+ - B(27)+B(26)+B(25)+B(24)+B(21)+B(13)+B(12)+B(9)+B(8)+B(6)+B(5)+ - B(3)+B(0), 102), - kDefPoly(B(101)+B(98)+B(97)+B(96)+B(94)+B(93)+B(92)+B(90)+B(89)+B(88)+ - B(87)+B(85)+B(83)+B(81)+B(80)+B(79)+B(76)+B(75)+B(71)+B(70)+ - B(69)+B(66), B(63)+B(62)+B(60)+B(59)+B(58)+B(56)+B(54)+B(53)+ - B(48)+B(45)+B(43)+B(42)+B(41)+B(37)+B(36)+B(32)+B(31)+B(30)+ - B(27)+B(25)+B(23)+B(22)+B(19)+B(16)+B(15)+B(11)+B(9)+B(5)+B(3)+ - B(0), 103), - kDefPoly(B(98)+B(97)+B(95)+B(94)+B(91)+B(89)+B(88)+B(86)+B(85)+B(84)+ - B(81)+B(79)+B(78)+B(76)+B(74)+B(73)+B(70)+B(69)+B(68)+B(67)+ - B(66)+B(64), B(59)+B(53)+B(52)+B(51)+B(48)+B(46)+B(45)+B(43)+ - B(37)+B(34)+B(33)+B(31)+B(30)+B(28)+B(25)+B(22)+B(21)+B(20)+ - B(19)+B(14)+B(10)+B(8)+B(4)+B(2)+B(1)+B(0), 104), - kDefPoly(B(103)+B(100)+B(99)+B(98)+B(94)+B(90)+B(89)+B(86)+B(84)+B(82)+ - B(79)+B(76)+B(74)+B(73)+B(72)+B(71)+B(70)+B(69)+B(67)+ - B(66), B(63)+B(62)+B(59)+B(58)+B(57)+B(55)+B(51)+B(49)+B(48)+ - B(47)+B(46)+B(43)+B(42)+B(38)+B(36)+B(34)+B(33)+B(31)+B(30)+ - B(29)+B(28)+B(27)+B(24)+B(21)+B(20)+B(18)+B(17)+B(16)+B(14)+ - B(13)+B(11)+B(9)+B(7)+B(6)+B(5)+B(0), 105), - kDefPoly(B(105)+B(104)+B(103)+B(102)+B(100)+B(98)+B(94)+B(93)+B(92)+B(91)+ - B(90)+B(89)+B(87)+B(86)+B(85)+B(83)+B(82)+B(81)+B(79)+B(77)+ - B(69)+B(68)+B(67)+B(64), B(61)+B(60)+B(59)+B(58)+B(56)+B(55)+ - B(53)+B(50)+B(48)+B(44)+B(40)+B(38)+B(37)+B(36)+B(35)+B(34)+ - B(33)+B(30)+B(29)+B(26)+B(22)+B(20)+B(13)+B(10)+B(8)+B(7)+B(5)+ - B(0), 106), - kDefPoly(B(105)+B(101)+B(100)+B(98)+B(97)+B(96)+B(93)+B(92)+B(91)+B(90)+ - B(87)+B(86)+B(81)+B(79)+B(77)+B(75)+B(74)+B(72)+B(68)+B(67)+ - B(64), B(63)+B(62)+B(61)+B(60)+B(59)+B(58)+B(54)+B(53)+B(52)+ - B(50)+B(48)+B(47)+B(45)+B(42)+B(41)+B(38)+B(32)+B(29)+B(27)+ - B(26)+B(24)+B(21)+B(19)+B(18)+B(16)+B(15)+B(14)+B(13)+B(12)+ - B(10)+B(7)+B(6)+B(4)+B(1)+B(0), 107), - kDefPoly(B(106)+B(105)+B(102)+B(100)+B(97)+B(95)+B(90)+B(89)+B(88)+B(86)+ - B(83)+B(82)+B(81)+B(79)+B(78)+B(75)+B(72)+B(66)+B(64), B(63)+ - B(62)+B(59)+B(58)+B(56)+B(54)+B(52)+B(51)+B(50)+B(48)+B(46)+ - B(45)+B(44)+B(42)+B(40)+B(37)+B(36)+B(35)+B(33)+B(29)+B(27)+ - B(22)+B(19)+B(17)+B(14)+B(12)+B(11)+B(10)+B(9)+B(8)+B(7)+B(6)+ - B(5)+B(3)+B(0), 108), - kDefPoly(B(108)+B(102)+B(101)+B(100)+B(99)+B(98)+B(96)+B(95)+B(94)+B(90)+ - B(89)+B(88)+B(87)+B(84)+B(83)+B(81)+B(80)+B(77)+B(76)+B(75)+ - B(71)+B(67)+B(65), B(63)+B(61)+B(60)+B(54)+B(50)+B(49)+B(48)+ - B(43)+B(40)+B(39)+B(38)+B(36)+B(34)+B(29)+B(28)+B(27)+B(22)+ - B(21)+B(19)+B(16)+B(14)+B(13)+B(12)+B(10)+B(9)+B(7)+B(6)+B(5)+ - B(3)+B(2)+B(0), 109), - kDefPoly(B(109)+B(108)+B(107)+B(102)+B(101)+B(98)+B(97)+B(96)+B(94)+B(92)+ - B(91)+B(90)+B(88)+B(87)+B(85)+B(84)+B(83)+B(82)+B(81)+B(80)+ - B(79)+B(78)+B(74)+B(73)+B(71)+B(70)+B(69)+B(66)+B(64), B(61)+ - B(58)+B(57)+B(56)+B(50)+B(49)+B(46)+B(44)+B(43)+B(41)+B(36)+ - B(35)+B(34)+B(30)+B(29)+B(26)+B(25)+B(24)+B(22)+B(21)+B(17)+ - B(13)+B(11)+B(9)+B(4)+B(1)+B(0), 110), - kDefPoly(B(110)+B(109)+B(105)+B(98)+B(97)+B(95)+B(94)+B(93)+B(92)+B(90)+ - B(88)+B(84)+B(83)+B(82)+B(80)+B(77)+B(75)+B(72)+B(71)+B(70)+ - B(69)+B(66), B(63)+B(61)+B(60)+B(59)+B(57)+B(56)+B(55)+B(52)+ - B(51)+B(50)+B(49)+B(47)+B(43)+B(40)+B(36)+B(35)+B(34)+B(33)+ - B(31)+B(27)+B(26)+B(21)+B(20)+B(19)+B(17)+B(16)+B(12)+B(8)+B(6)+ - B(4)+B(3)+B(2)+B(1)+B(0), 111), - kDefPoly(B(109)+B(107)+B(106)+B(104)+B(100)+B(98)+B(96)+B(95)+B(94)+B(92)+ - B(91)+B(90)+B(89)+B(88)+B(86)+B(84)+B(81)+B(79)+B(78)+B(77)+ - B(75)+B(73)+B(71)+B(70)+B(69)+B(67)+B(64), B(63)+B(62)+B(61)+ - B(60)+B(58)+B(56)+B(54)+B(52)+B(51)+B(49)+B(48)+B(45)+B(44)+ - B(39)+B(38)+B(37)+B(36)+B(35)+B(34)+B(32)+B(30)+B(26)+B(25)+ - B(24)+B(23)+B(22)+B(21)+B(19)+B(16)+B(15)+B(11)+B(10)+B(9)+B(8)+ - B(3)+B(1)+B(0), 112), - kDefPoly(B(111)+B(107)+B(102)+B(100)+B(99)+B(98)+B(97)+B(96)+B(95)+B(94)+ - B(93)+B(92)+B(87)+B(86)+B(82)+B(81)+B(80)+B(79)+B(77)+B(76)+ - B(75)+B(72)+B(69)+B(64), B(61)+B(58)+B(56)+B(54)+B(53)+B(52)+ - B(51)+B(49)+B(46)+B(43)+B(40)+B(39)+B(37)+B(36)+B(35)+B(34)+ - B(33)+B(31)+B(29)+B(24)+B(22)+B(21)+B(20)+B(15)+B(14)+B(12)+ - B(10)+B(6)+B(1)+B(0), 113), - kDefPoly(B(112)+B(111)+B(110)+B(104)+B(102)+B(101)+B(100)+B(92)+B(89)+ - B(87)+B(83)+B(82)+B(80)+B(79)+B(75)+B(74)+B(73)+B(72)+B(71)+ - B(70)+B(68)+B(67)+B(65), B(60)+B(59)+B(57)+B(56)+B(55)+B(52)+ - B(50)+B(47)+B(44)+B(41)+B(36)+B(35)+B(30)+B(29)+B(26)+B(25)+ - B(24)+B(21)+B(18)+B(17)+B(16)+B(14)+B(12)+B(10)+B(7)+B(6)+ - B(0), 114), - kDefPoly(B(114)+B(112)+B(111)+B(110)+B(108)+B(107)+B(103)+B(102)+B(98)+ - B(97)+B(96)+B(90)+B(88)+B(87)+B(86)+B(83)+B(82)+B(80)+B(79)+ - B(77)+B(75)+B(70)+B(66)+B(65)+B(64), B(61)+B(60)+B(59)+B(58)+ - B(57)+B(53)+B(52)+B(51)+B(50)+B(47)+B(45)+B(43)+B(39)+B(38)+ - B(33)+B(32)+B(31)+B(29)+B(27)+B(21)+B(17)+B(14)+B(12)+B(10)+B(7)+ - B(4)+B(2)+B(1)+B(0), 115), - kDefPoly(B(113)+B(110)+B(108)+B(106)+B(105)+B(102)+B(101)+B(100)+B(98)+ - B(96)+B(92)+B(89)+B(87)+B(86)+B(84)+B(81)+B(79)+B(78)+B(76)+ - B(75)+B(73)+B(72)+B(71)+B(70)+B(67)+B(64), B(63)+B(62)+B(61)+ - B(52)+B(47)+B(45)+B(44)+B(42)+B(40)+B(39)+B(35)+B(34)+B(33)+ - B(31)+B(29)+B(25)+B(18)+B(15)+B(14)+B(10)+B(8)+B(6)+B(1)+ - B(0), 116), - kDefPoly(B(113)+B(111)+B(110)+B(109)+B(107)+B(106)+B(103)+B(102)+B(100)+ - B(96)+B(95)+B(94)+B(91)+B(90)+B(89)+B(86)+B(82)+B(81)+B(78)+ - B(77)+B(76)+B(75)+B(74)+B(73)+B(70)+B(67)+B(66), B(63)+B(61)+ - B(59)+B(57)+B(56)+B(55)+B(53)+B(52)+B(51)+B(50)+B(47)+B(45)+ - B(42)+B(40)+B(37)+B(35)+B(32)+B(30)+B(29)+B(25)+B(22)+B(21)+ - B(20)+B(19)+B(16)+B(15)+B(14)+B(12)+B(8)+B(5)+B(0), 117), - kDefPoly(B(117)+B(113)+B(110)+B(108)+B(105)+B(104)+B(103)+B(102)+B(99)+ - B(98)+B(97)+B(94)+B(93)+B(91)+B(90)+B(89)+B(85)+B(84)+B(82)+ - B(81)+B(79)+B(78)+B(77)+B(74)+B(73)+B(69)+B(67)+B(64), B(63)+ - B(62)+B(61)+B(57)+B(55)+B(51)+B(50)+B(46)+B(45)+B(43)+B(42)+ - B(41)+B(37)+B(33)+B(32)+B(30)+B(27)+B(26)+B(21)+B(19)+B(18)+ - B(17)+B(15)+B(14)+B(12)+B(10)+B(8)+B(7)+B(3)+B(2)+B(1)+ - B(0), 118), - kDefPoly(B(118)+B(111)+B(109)+B(107)+B(106)+B(105)+B(104)+B(101)+B(99)+ - B(98)+B(97)+B(94)+B(92)+B(91)+B(89)+B(83)+B(82)+B(80)+B(79)+ - B(67)+B(66), B(62)+B(61)+B(60)+B(58)+B(57)+B(52)+B(48)+B(46)+ - B(44)+B(42)+B(40)+B(39)+B(38)+B(36)+B(34)+B(33)+B(32)+B(29)+ - B(23)+B(22)+B(20)+B(19)+B(18)+B(15)+B(13)+B(12)+B(11)+B(6)+B(5)+ - B(4)+B(3)+B(1)+B(0), 119), - kDefPoly(B(116)+B(115)+B(113)+B(112)+B(110)+B(107)+B(106)+B(104)+B(103)+ - B(101)+B(100)+B(99)+B(98)+B(90)+B(89)+B(88)+B(87)+B(82)+B(80)+ - B(79)+B(77)+B(76)+B(75)+B(74)+B(73)+B(71)+B(70)+B(68)+B(65)+ - B(64), B(63)+B(62)+B(59)+B(55)+B(54)+B(48)+B(47)+B(45)+B(44)+ - B(40)+B(39)+B(38)+B(35)+B(33)+B(29)+B(27)+B(26)+B(25)+B(24)+ - B(23)+B(22)+B(21)+B(18)+B(17)+B(15)+B(13)+B(12)+B(10)+B(8)+B(3)+ - B(2)+B(0), 120), - kDefPoly(B(118)+B(117)+B(114)+B(113)+B(112)+B(110)+B(109)+B(104)+B(103)+ - B(101)+B(99)+B(97)+B(96)+B(95)+B(93)+B(92)+B(91)+B(90)+B(89)+ - B(87)+B(85)+B(84)+B(82)+B(81)+B(79)+B(73)+B(72)+B(68)+B(67)+ - B(66)+B(64), B(60)+B(58)+B(57)+B(56)+B(54)+B(53)+B(52)+B(51)+ - B(49)+B(48)+B(47)+B(45)+B(44)+B(38)+B(37)+B(36)+B(35)+B(33)+ - B(32)+B(31)+B(30)+B(27)+B(26)+B(24)+B(23)+B(22)+B(20)+B(19)+ - B(18)+B(16)+B(15)+B(12)+B(6)+B(5)+B(4)+B(2)+B(0), 121), - kDefPoly(B(121)+B(118)+B(114)+B(112)+B(109)+B(106)+B(103)+B(102)+B(101)+ - B(100)+B(97)+B(95)+B(90)+B(89)+B(87)+B(83)+B(81)+B(80)+B(79)+ - B(78)+B(77)+B(76)+B(75)+B(74)+B(72)+B(71)+B(70)+B(69)+B(68)+ - B(66)+B(64), B(61)+B(57)+B(51)+B(50)+B(47)+B(46)+B(43)+B(39)+ - B(38)+B(37)+B(36)+B(34)+B(33)+B(32)+B(30)+B(28)+B(27)+B(24)+ - B(22)+B(20)+B(18)+B(17)+B(14)+B(12)+B(11)+B(9)+B(7)+B(2)+ - B(0), 122), - kDefPoly(B(122)+B(121)+B(120)+B(119)+B(118)+B(117)+B(116)+B(113)+B(112)+ - B(111)+B(109)+B(106)+B(105)+B(103)+B(100)+B(98)+B(97)+B(95)+ - B(93)+B(92)+B(90)+B(87)+B(86)+B(85)+B(83)+B(81)+B(78)+B(77)+ - B(75)+B(74)+B(73)+B(72)+B(71)+B(70)+B(69)+B(68)+B(67)+B(65)+ - B(64), B(63)+B(62)+B(60)+B(55)+B(52)+B(51)+B(49)+B(47)+B(45)+ - B(43)+B(42)+B(41)+B(37)+B(36)+B(35)+B(34)+B(32)+B(28)+B(27)+ - B(26)+B(24)+B(23)+B(21)+B(20)+B(16)+B(13)+B(10)+B(9)+B(8)+B(7)+ - B(5)+B(2)+B(0), 123), - kDefPoly(B(123)+B(121)+B(120)+B(118)+B(117)+B(116)+B(115)+B(112)+B(111)+ - B(110)+B(109)+B(107)+B(104)+B(102)+B(101)+B(100)+B(99)+B(98)+ - B(97)+B(94)+B(90)+B(87)+B(86)+B(84)+B(83)+B(82)+B(79)+B(75)+ - B(72)+B(71)+B(70)+B(64), B(63)+B(56)+B(54)+B(51)+B(50)+B(47)+ - B(45)+B(44)+B(42)+B(39)+B(38)+B(36)+B(34)+B(33)+B(29)+B(26)+ - B(24)+B(20)+B(16)+B(14)+B(11)+B(10)+B(8)+B(7)+B(6)+B(4)+B(2)+ - B(0), 124), - kDefPoly(B(124)+B(123)+B(121)+B(119)+B(118)+B(116)+B(115)+B(114)+B(107)+ - B(105)+B(104)+B(103)+B(102)+B(99)+B(98)+B(96)+B(94)+B(93)+B(89)+ - B(83)+B(82)+B(81)+B(80)+B(79)+B(78)+B(75)+B(74)+B(73)+B(72)+ - B(70)+B(69)+B(68)+B(64), B(63)+B(59)+B(56)+B(55)+B(52)+B(51)+ - B(50)+B(49)+B(48)+B(44)+B(42)+B(38)+B(37)+B(36)+B(33)+B(31)+ - B(29)+B(27)+B(26)+B(25)+B(23)+B(21)+B(19)+B(18)+B(16)+B(14)+ - B(11)+B(8)+B(7)+B(6)+B(4)+B(1)+B(0), 125), - kDefPoly(B(124)+B(122)+B(121)+B(120)+B(119)+B(117)+B(113)+B(110)+B(108)+ - B(105)+B(103)+B(102)+B(101)+B(97)+B(93)+B(91)+B(90)+B(88)+B(86)+ - B(84)+B(82)+B(81)+B(79)+B(77)+B(76)+B(75)+B(73)+B(72)+B(71)+ - B(69)+B(67)+B(64), B(63)+B(62)+B(61)+B(60)+B(58)+B(56)+B(55)+ - B(52)+B(51)+B(48)+B(47)+B(45)+B(44)+B(42)+B(41)+B(40)+B(39)+ - B(37)+B(33)+B(32)+B(30)+B(29)+B(28)+B(27)+B(26)+B(25)+B(24)+ - B(23)+B(19)+B(18)+B(17)+B(16)+B(14)+B(13)+B(11)+B(9)+B(8)+B(7)+ - B(4)+B(2)+B(1)+B(0), 126), - kDefPoly(B(125)+B(124)+B(121)+B(116)+B(115)+B(105)+B(103)+B(101)+B(94)+ - B(93)+B(91)+B(90)+B(88)+B(87)+B(86)+B(85)+B(77)+B(73)+B(72)+ - B(70)+B(68)+B(67), B(63)+B(62)+B(61)+B(59)+B(57)+B(53)+B(52)+ - B(51)+B(49)+B(48)+B(46)+B(44)+B(41)+B(39)+B(38)+B(36)+B(35)+ - B(30)+B(27)+B(25)+B(23)+B(20)+B(19)+B(13)+B(12)+B(11)+B(10)+B(8)+ - B(7)+B(5)+B(4)+B(3)+B(2)+B(0), 127), - kDefPoly(B(127)+B(122)+B(121)+B(118)+B(117)+B(116)+B(109)+B(108)+B(107)+ - B(106)+B(104)+B(103)+B(102)+B(101)+B(96)+B(93)+B(92)+B(91)+B(89)+ - B(86)+B(85)+B(80)+B(78)+B(77)+B(76)+B(75)+B(74)+B(73)+B(72)+ - B(71)+B(66), B(60)+B(56)+B(53)+B(52)+B(50)+B(47)+B(45)+B(41)+ - B(39)+B(38)+B(37)+B(35)+B(34)+B(33)+B(30)+B(28)+B(25)+B(24)+ - B(23)+B(21)+B(20)+B(19)+B(14)+B(13)+B(10)+B(8)+B(5)+B(4)+B(2)+ - B(1)+B(0), 128), -}; -// lint -restore - -// The number of polynomials in POLYS[]. -SELECTANY const int CRC::N_POLYS = sizeof (poly_list) / sizeof (poly_list[0]); - -// The externally visible name of poly_list. -// This guarantees that the size of poly_list is opaque. -SELECTANY const struct CRC::Poly *const CRC::POLYS = poly_list; - -// The "constructor" for a CRC with an default polynomial. -CRC *CRC::Default(int degree, size_t roll_length) { - ASSERT1(32 == degree); - - CRC *crc = CRCImpl::NewInternal(CRC::POLYS[degree].lo, CRC::POLYS[degree].hi, - degree, roll_length); // Build the table - return crc; -} - -// The "constructor" for a CRC with an arbitrary polynomial. -CRC *CRC::New(uint64 lo, uint64 hi, int degree, size_t roll_length) { - return CRCImpl::NewInternal(lo, hi, degree, roll_length); -} - -// Internal version of the "constructor". -CRCImpl *CRCImpl::NewInternal(uint64 lo, uint64 hi, - int degree, size_t roll_length) { - ASSERT1(8 <= degree && degree <= 64); // precondition - ASSERT1(lo != 0 || hi != 0); // precondition - // Generate the tables for extending a CRC by 4 bytes at a time. - // Why 4 and not 8? Because Pentium 4 has such small caches. - struct CRC_pair t[4][256]; - for (int j = 0; j != 4; j++) { // for each byte of extension.... - t[j][0].lo = 0; // a zero has no effect - t[j][0].hi = 0; - for (int i = 128; i != 0; i >>= 1) { // fill in entries for powers of 2 - if (j == 0 && i == 128) { - t[j][i].lo = lo; // top bit in first byte is easy---it's the polynomial - t[j][i].hi = hi; - } else { - // each successive power of two is derive from the previous - // one, either in this table, or the last table - struct CRC_pair pred; - if (i == 128) { - pred = t[j-1][1]; - } else { - pred = t[j][i << 1]; - } - // Advance the CRC by one bit (multiply by X, and take remainder - // through one step of polynomial long division) - if (pred.lo & 1) { - t[j][i].lo = (pred.lo >> 1) ^ (pred.hi << 63) ^ lo; - t[j][i].hi = (pred.hi >> 1) ^ hi; - } else { - t[j][i].lo = (pred.lo >> 1) ^ (pred.hi << 63); - t[j][i].hi = pred.hi >> 1; - } - } - } - // CRCs have the property that CRC(a xor b) == CRC(a) xor CRC(b) - // so we can make all the tables for non-powers of two by - // xoring previously created entries. - for (int i = 2; i != 256; i <<= 1) { - for (int k = i+1; k != (i << 1); k++) { - t[j][k].lo = t[j][i].lo ^ t[j][k-i].lo; - t[j][k].hi = t[j][i].hi ^ t[j][k-i].hi; - } - } - } - - // Copy the newly built tables in t[] into an appropriate - // CRC implenentation object. - CRCImpl *result = 0; - CRC32 *crc32 = 0; - crc32 = new CRC32(); - for (int i = 0; i != 256; i++) { - crc32->table0_[i] = static_cast(t[0][i].lo); - crc32->table1_[i] = static_cast(t[1][i].lo); - crc32->table2_[i] = static_cast(t[2][i].lo); - crc32->table3_[i] = static_cast(t[3][i].lo); - } - result = crc32; - - // "result" is now a CRC object of the right type to handle - // the polynomial of the right degree. - - result->roll_length_ = roll_length; - result->degree_ = degree; - result->poly_lo_ = lo; - result->poly_hi_ = hi; - - // Build the table for extending by zeroes. - // Entry i=a-1+3*b (a in {1, 2, 3}, b in {0, 1, 2, 3, ...} - // contains a polynomial Pi such that multiplying - // a CRC by Pi mod P, where P is the CRC polynomial, is equivalent to - // appending a*2**(2*b+SMALL_BITS) zero bytes to the original string. - // Entry is generated by calling ExtendByZeroes() twice using - // half the length from the previous entry. - int pos = 0; - for (uint64 inc_len = (1 << SMALL_BITS); inc_len != 0; inc_len <<= 2) { - result->Empty(&lo, &hi); - for (int k = 0; k != 3; k++) { - result->ExtendByZeroes(&lo, &hi, (size_t) (inc_len >> 1)); - result->ExtendByZeroes(&lo, &hi, (size_t) (inc_len >> 1)); - crc32->zeroes_[pos] = static_cast(lo); - pos++; - } - } - - // Calculate the entries in the roll table, used for rolling checksums - // of a fixed length. - // Extend the powers of two in the one-byte extension table by the roll - // length. - int bit = 256; - do { - bit >>= 1; - result->ExtendByZeroes(&t[0][bit].lo, &t[0][bit].hi, roll_length); - } while (bit != 0); - // Calculate the non-powers of two using CRC(a xor b) == CRC(a) xor CRC(b) - for (int i = 2; i != 256; i <<= 1) { - for (int j = i+1; j != (i << 1); j++) { - t[0][j].lo = t[0][i].lo ^ t[0][j-i].lo; - t[0][j].hi = t[0][i].hi ^ t[0][j-i].hi; - } - } - // Now xor the CRC of (binary) 100000001 followed by - // the roll length of zeroes. This will be xored into every - // entry. This will simultaneously roll out the CRC - // of the empty string that's been pushed one byte too far, - // and roll in the CRC of the empty string in the correct place again. - result->Empty(&lo, &hi); - const uint8 x = 0x80; - result->Extend(&lo, &hi, &x, 1); - result->ExtendByZeroes(&lo, &hi, roll_length); - for (int i = 0; i != 256; i++) { - t[0][i].lo ^= lo; - t[0][i].hi ^= hi; - } - - // Put the roll table into the object. - for (int i = 0; i != 256; i++) { - crc32->roll_[i] = static_cast(t[0][i].lo); - } - - return result; -} - -// The CRC of the empty string is always the CRC polynomial itself. -void CRCImpl::Empty(uint64 *lo, uint64 *hi) const { - ASSERT1(hi); - ASSERT1(lo); - - *lo = this->poly_lo_; - *hi = this->poly_hi_; -} - -// The 32-bit implementation - -void CRC32::Extend(uint64 *lo, uint64 *hi, const void *bytes, size_t length) - const { - ASSERT1(hi); - ASSERT1(lo); - - hi; // unreferenced formal parameter - - const uint8 *p = static_cast(bytes); - const uint8 *e = p + length; - uint32 l = static_cast(*lo); - // point x at MIN(first 4-byte aligned byte in string, end of string) - const uint8 *x = p + ((zero_ptr - p) & 3); - if (x > e) { - x = e; - } - // Process bytes until finished or p is 4-byte aligned - while (p != x) { - int c = (l & 0xff) ^ *p++; - l = this->table0_[c] ^ (l >> 8); - } - // point x at MIN(last 4-byte aligned byte in string, end of string) - x = e - ((e - zero_ptr) & 3); - // Process bytes 4 at a time - while (p < x) { - uint32 c = l ^ *reinterpret_cast(p); - p += 4; - l = this->table3_[c & 0xff] ^ - this->table2_[(c >> 8) & 0xff] ^ - this->table1_[(c >> 16) & 0xff] ^ - this->table0_[c >> 24]; - } - - // Process the last few bytes - while (p != e) { - int c = (l & 0xff) ^ *p++; - l = this->table0_[c] ^ (l >> 8); - } - *lo = l; -} - -void CRC32::ExtendByZeroes(uint64 *lo, uint64 *hi, size_t length) const { - ASSERT1(hi); - ASSERT1(lo); - - // Process the low order SMALL_BITS of the length by simply - // using Extend() on an array of bytes that are zero. - size_t small_part = (length & ((1 << SMALL_BITS)-1)); - if (small_part != 0) { - this->Extend(lo, hi, zeroes, small_part); - } - length >>= SMALL_BITS; - if (length != 0) { // if the length was at least 2**SMALL_BITS - uint32 l = static_cast(*lo); - uint32 onebit = 1; - onebit <<= this->degree_ - 1; - // For each pair of bits in length - // (after the low-oder bits have been removed) - // we lookup the appropriate polynomial in the zeroes_ array - // and do a polynomial long multiplication (mod the CRC polynomial) - // to extend the CRC by the appropriate number of bits. - for (size_t i = 0; length != 0; i += 3, length >>= 2) { - size_t c = length & 3; // pick next two bits - if (c != 0) { // if they are not zero, - // multiply by entry in table - uint32 m = this->zeroes_[c+i-1]; - uint32 result = 0; - for (uint32 one = onebit; one != 0; one >>= 1) { - if ((l & one) != 0) { - result ^= m; - } - if (m & 1) { - m = (m >> 1) ^ static_cast(poly_lo_); - } else { - m = (m >> 1); - } - } - l = result; - } - } - *lo = l; - } -} - -void CRC32::Roll(uint64 *lo, uint64 *hi, uint8 o_byte, uint8 i_byte) const { - ASSERT1(hi); - ASSERT1(lo); - - hi; // unreferenced formal parameter - - uint32 l = static_cast(*lo); - // Roll in i_byte and out o_byte - *lo = this->table0_[(l & 0xff) ^ i_byte] ^ (l >> 8) ^ this->roll_[o_byte]; -} - -} // namespace omaha - diff --git a/omaha/base/crc.h b/omaha/base/crc.h deleted file mode 100644 index 26abe59..0000000 --- a/omaha/base/crc.h +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef _CRC_H_ -#define _CRC_H_ - -#include "base/basictypes.h" - -namespace omaha { - -// This class implements CRCs (aka Rabin Fingerprints). -// Treats the input as a polynomial with coefficients in Z(2), -// and finds the remainder when divided by an irreducible polynomial -// of the appropriate length. -// It handles all CRC sizes from 8 to 128 bits. -// The input string is prefixed with a "1" bit, and has "degree" "0" bits -// appended to it before the remainder is found. This ensures that -// short strings are scrambled somewhat. - -// A polynomial is represented by the bit pattern formed by its coefficients, -// but with the highest order bit not stored. -// The highest degree coefficient is stored in the lowest numbered bit -// in the the lowest adderessed byte. Thus, in what follows, -// the highest degree coeficient that is stored is in the low order bit -// of "lo" or "*lo". - -// Typical usage: -// -// // prepare to do 32-bit CRCs using the default polynomial. No rolling hash. -// scoped_ptr crc(CRC::Default(32, 0)); -// ... -// uint64 lo; // declare a lo,hi pair to hold the CRC -// uint64 hi; -// crc->Empty(&lo, &hi); // Initialize to CRC of empty string -// crc->Extend(&lo, &hi, "hello", 5); // Get CRC of "hello" -// ... -// -// // prepare to use a 32-bit rolling hash over 6 bytes -// scoped_ptr crc(CRC::Default(32, 6)); -// ... -// uint64 lo; // declare a lo,hi pair to hold the CRC -// uint64 hi; -// crc->Empty(&lo, &hi); // Initialize to CRC of empty string -// crc->Extend(&lo, &hi, data, 6); // Get CRC of first 6 bytes -// for (int i = 6; i != sizeof (data); i++) { -// crc->Roll(&lo, &hi, data[i-6], data[i]); // Move window by one byte -// // lo,hi is CRC of bytes data[i-5...i] -// } -// ... -// - -class CRC { -public: - // Initialize all the tables for CRC's of a given bit length "degree" - // using a default polynomial of the given length. - // - // The argument "roll_length" is used by subsequent calls to - // Roll(). - // Returns a handle that MUST NOT be destroyed with delete. - // The default polynomials are those in POLYS[8...128]. - // Handles returned by Default() MUST NOT be deleted. - // Identical calls to Default() yield identical handles. - static CRC *Default(int degree, size_t roll_length); - - // Initialize all the tables for CRC's of a given bit length "degree" - // using an arbitrary CRC polynomial. - // Normally, you would use Default() instead of New()---see above. - // - // Requires that "lo,hi" contain an irreducible polynomial of degree "degree" - // Requires 8 <= degree && degree <= 128 - // Any irreducible polynomial of the correct degree will work. - // See the POLYS array for suitable irredicible polynomials. - // - // The argument "roll_length" is used by subsequent calls to - // Roll(). - // Each call to New() yeilds a pointer to a new object - // that may be deallocated with delete. - static CRC *New(uint64 lo, uint64 hi, int degree, size_t roll_length); - - virtual ~CRC(); - - // Place the CRC of the empty string in "*lo,*hi" - virtual void Empty(uint64 *lo, uint64 *hi) const = 0; - - // If "*lo,*hi" is the CRC of bytestring A, place the CRC of - // the bytestring formed from the concatenation of A and the "length" - // bytes at "bytes" into "*lo,*hi". - virtual void Extend(/*INOUT*/ uint64 *lo, /*INOUT*/ uint64 *hi, - const void *bytes, size_t length) const = 0; - - // Equivalent to Extend(lo, hi, bytes, length) where "bytes" - // points to an array of "length" zero bytes. - virtual void ExtendByZeroes(/*INOUT*/ uint64 *lo, /*INOUT*/ uint64 *hi, - size_t length) const = 0; - - // If "*lo,*hi" is the CRC of a byte string of length "roll_length" - // (which is an argument to New() and Default()) that consists of - // byte "o_byte" followed by string S, set "*lo,*hi" to the CRC of - // the string that consists of S followed by the byte "i_byte". - virtual void Roll(/*INOUT*/ uint64 *lo, /*INOUT*/ uint64 *hi, - uint8 o_byte, uint8 i_byte) const = 0; - - // POLYS[] is an array of valid triples that may be given to New() - static const struct Poly { - uint64 lo; // first half suitable CRC polynomial - uint64 hi; // second half of suitable CRC polynomial - int degree; // degree of suitable CRC polynomial - } *const POLYS; - // It is guaranteed that no two entries in POLYS[] are identical, - // that POLYS[i] cnotains a polynomial of degree i for 8 <= i <= 128, - // that POLYS[0] and POLYS[1] contains polynomials of degree 32, - // that POLYS[2] and POLYS[3] contains polynomials of degree 64, - // that POLYS[4] and POLYS[5] contains polynomials of degree 96, and - // that POLYS[6] and POLYS[7] contains polynomials of degree 128. - - static const int N_POLYS; // Number of elements in POLYS array. - -protected: - CRC(); // Clients may not call constructor; - // use Default() or New() instead. - -private: - DISALLOW_EVIL_CONSTRUCTORS(CRC); -}; - -} // namespace omaha - -#endif diff --git a/omaha/base/debug.cc b/omaha/base/debug.cc index 754d19a..c6e095d 100644 --- a/omaha/base/debug.cc +++ b/omaha/base/debug.cc @@ -27,8 +27,9 @@ #endif #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/clipboard.h" #include "omaha/base/commontypes.h" @@ -43,7 +44,6 @@ #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/system_info.h" @@ -267,22 +267,19 @@ TCHAR *ReportSummaryGenerator::GetReportSummary() { if (s) { s[0] = 0; if (g_total_reports) { - SafeStrCat(s, L"REPORT SUMMARY:\r\n\r\n", kMaxReportSummaryLen); - SafeStrCat(s, - SPRINTF(L"%d total reports\r\n\r\n", g_total_reports), - kMaxReportSummaryLen); - SafeStrCat(s, + wcscat_s(s, kMaxReportSummaryLen, L"REPORT SUMMARY:\r\n\r\n"); + wcscat_s(s, kMaxReportSummaryLen, + SPRINTF(L"%d total reports\r\n\r\n", g_total_reports)); + wcscat_s(s, kMaxReportSummaryLen, g_report_summary. - Left(kMaxReportSummaryLen - lstrlen(s) - 1).GetString(), - kMaxReportSummaryLen); + Left(kMaxReportSummaryLen - lstrlen(s) - 1).GetString()); CString report_string = g_report_ids.DebugReportString(); ReplaceCString(report_string, L"&", L"\r\n"); - SafeStrCat(s, + wcscat_s(s, kMaxReportSummaryLen, report_string. - Left(kMaxReportSummaryLen - lstrlen(s) - 1).GetString(), - kMaxReportSummaryLen); + Left(kMaxReportSummaryLen - lstrlen(s) - 1).GetString()); } else { - SafeStrCat(s, L"NO REPORTS!!\r\n", kMaxReportSummaryLen); + wcscat_s(s, kMaxReportSummaryLen, L"NO REPORTS!!\r\n"); } } @@ -587,7 +584,7 @@ bool DebugReport(unsigned int id, arraysize(clipboard_string)); stack_trace = stack_trace.Left( arraysize(clipboard_string) - lstrlen(clipboard_string) - 1); - SafeStrCat(clipboard_string, stack_trace, arraysize(clipboard_string)); + wcscat_s(clipboard_string, arraysize(clipboard_string), stack_trace); SetClipboard(clipboard_string); stack_trace = stack_trace.Left(kMaxStackTraceDialogLen); @@ -927,9 +924,9 @@ TCHAR * __cdecl SPRINTF(const TCHAR * format, ...) { va_end(argptr); // copy to fixed return buffers - SafeStrCat(sprintf_buf, - out.GetBufferSetLength(kSprintfMaxLen), - g_current_sprintf_buffer); + wcscat_s(sprintf_buf, + g_current_sprintf_buffer, + out.GetBufferSetLength(kSprintfMaxLen)); sprintf_buf[kSprintfMaxLen] = '\0'; return sprintf_buf; @@ -958,7 +955,7 @@ class SprintfCleaner { } private: - DISALLOW_EVIL_CONSTRUCTORS(SprintfCleaner); + DISALLOW_COPY_AND_ASSIGN(SprintfCleaner); }; static SprintfCleaner cleaner; @@ -1000,10 +997,9 @@ bool ReleaseAssert(const char *expr, filename, linenumber, VER_TIMESTAMP_STR_FILE); - SafeStrCat(error_string, msg, arraysize(error_string)); - SafeStrCat(error_string, - L"\r\n\r\n*** This message has been copied to the clipboard. ***", - arraysize(error_string)); + wcscat_s(error_string, arraysize(error_string), msg); + wcscat_s(error_string, arraysize(error_string), + L"\r\n\r\n*** This message has been copied to the clipboard. ***"); SetClipboard(error_string); TCHAR title_string[1024]; @@ -1049,10 +1045,9 @@ void ReleaseAbort(const TCHAR *msg, filename, linenumber, omaha::GetVersionString()); - SafeStrCat(error_string, msg, arraysize(error_string)); - SafeStrCat(error_string, - L"\r\n\r\n*** This message has been copied to the clipboard. ***", - arraysize(error_string)); + wcscat_s(error_string, arraysize(error_string), msg); + wcscat_s(error_string, arraysize(error_string), + L"\r\n\r\n*** This message has been copied to the clipboard. ***"); SetClipboard(error_string); TCHAR title_string[1024]; @@ -1117,9 +1112,9 @@ void DumpInterface(IUnknown* unknown) { // RegKey sub_key; if (sub_key.Open(key.Key(), name, KEY_READ) == S_OK) { - scoped_array display; + std::unique_ptr display; // If this fails, we should still have the IID - if (sub_key.GetValue(NULL, address(display)) == S_OK) + if (sub_key.GetValue(NULL, &display) == S_OK) lstrcpyn(name, display.get(), _MAX_PATH); } diff --git a/omaha/base/debug.h b/omaha/base/debug.h index 2427ee2..3b5b5e3 100644 --- a/omaha/base/debug.h +++ b/omaha/base/debug.h @@ -134,7 +134,7 @@ class ReportIds : public GLock { bool LoadReportData(ReportData **data); void SaveReportData(ReportData *data); - DISALLOW_EVIL_CONSTRUCTORS(ReportIds); + DISALLOW_COPY_AND_ASSIGN(ReportIds); }; #if defined(_DEBUG) || defined(ASSERT_IN_RELEASE) @@ -257,7 +257,7 @@ class ReportSummaryGenerator { // get text summary of reports // caller is responsible for deleting the string returned TCHAR *GetReportSummary(); - DISALLOW_EVIL_CONSTRUCTORS(ReportSummaryGenerator); + DISALLOW_COPY_AND_ASSIGN(ReportSummaryGenerator); }; extern ReportSummaryGenerator g_report_summary_generator; diff --git a/omaha/base/disk.cc b/omaha/base/disk.cc index 0f3d372..d1a11a2 100644 --- a/omaha/base/disk.cc +++ b/omaha/base/disk.cc @@ -17,341 +17,21 @@ #include "omaha/base/disk.h" -#include +#include + #include "omaha/base/commontypes.h" #include "omaha/base/const_config.h" -#include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/file.h" -#include "omaha/base/localization.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" #include "omaha/base/shell.h" #include "omaha/base/string.h" -#include "omaha/base/synchronized.h" #include "omaha/base/system.h" -#include "omaha/base/timer.h" #include "omaha/base/utils.h" namespace omaha { -#define kNetdiskVendorId "netdisk" - -// see also: http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q264203 - -#if _MSC_VER < 1400 -// Not defined in the headers we have; from MSDN: -#define IOCTL_STORAGE_QUERY_PROPERTY \ - CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct _STORAGE_DEVICE_DESCRIPTOR { - ULONG Version; - ULONG Size; - UCHAR DeviceType; - UCHAR DeviceTypeModifier; - BOOLEAN RemovableMedia; - BOOLEAN CommandQueueing; - ULONG VendorIdOffset; - ULONG ProductIdOffset; - ULONG ProductRevisionOffset; - ULONG SerialNumberOffset; - STORAGE_BUS_TYPE BusType; - ULONG RawPropertiesLength; - UCHAR RawDeviceProperties[1]; -} STORAGE_DEVICE_DESCRIPTOR, *PSTORAGE_DEVICE_DESCRIPTOR; - -typedef enum _STORAGE_QUERY_TYPE { - PropertyStandardQuery = 0, - PropertyExistsQuery, - PropertyMaskQuery, - PropertyQueryMaxDefined -} STORAGE_QUERY_TYPE, *PSTORAGE_QUERY_TYPE; - -typedef enum _STORAGE_PROPERTY_ID { - StorageDeviceProperty = 0, - StorageAdapterProperty, - StorageDeviceIdProperty -} STORAGE_PROPERTY_ID, *PSTORAGE_PROPERTY_ID; - -typedef struct _STORAGE_PROPERTY_QUERY { - STORAGE_PROPERTY_ID PropertyId; - STORAGE_QUERY_TYPE QueryType; - UCHAR AdditionalParameters[1]; -} STORAGE_PROPERTY_QUERY, *PSTORAGE_PROPERTY_QUERY; - -// ------- -#endif - -#define kIoctlBufferSize 1024 - -#define kMaxDrivesCached 3 -#define kMaxDriveLen 20 -static TCHAR g_cache_drive[kMaxDrivesCached][kMaxDriveLen+1]; -static bool g_cache_external[kMaxDrivesCached]; -static int g_cache_pos; -static LLock g_cache_lock; - -bool IsDiskExternal(const TCHAR *drive) { - ASSERT(drive, (L"")); - ASSERT(lstrlen(drive) < kMaxDriveLen, (L"")); - - DisableThreadErrorUI disable_error_dialog_box; - - { - __mutexScope(g_cache_lock); - for (int i = 0; i < kMaxDrivesCached; i++) - if (!lstrcmp(drive, g_cache_drive[i])) { - UTIL_LOG(L1, (L"cached disk ext %s %d", drive, g_cache_external[i])); - return g_cache_external[i]; - } - } - -#ifdef _DEBUG - Timer timer(true); -#endif - - byte buffer[kIoctlBufferSize+1]; - - bool external = false; - HANDLE device = ::CreateFile(drive, - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - OPEN_EXISTING, - NULL, - NULL); - if (device == INVALID_HANDLE_VALUE) { - UTIL_LOG(L1, (L"disk external could not open drive %s", drive)); - goto done; - } - STORAGE_DEVICE_DESCRIPTOR *device_desc; - STORAGE_PROPERTY_QUERY query; - DWORD out_bytes; - query.PropertyId = StorageDeviceProperty; - query.QueryType = PropertyStandardQuery; - *(query.AdditionalParameters) = 0; - - device_desc = reinterpret_cast(buffer); - // should not be needed, but just to be safer - ZeroMemory(buffer, kIoctlBufferSize); - - BOOL ok = ::DeviceIoControl(device, - IOCTL_STORAGE_QUERY_PROPERTY, - &query, - sizeof(STORAGE_PROPERTY_QUERY), - buffer, - kIoctlBufferSize, - &out_bytes, - (LPOVERLAPPED)NULL); - - if (ok && - device_desc->VendorIdOffset && - stristr(reinterpret_cast(buffer + device_desc->VendorIdOffset), - kNetdiskVendorId)) { - external = true; - UTIL_LOG(L1, (L"ximeta netdisk %s", drive)); - } - - if (ok && - (device_desc->BusType == BusTypeUsb || - device_desc->BusType == BusType1394)) { - external = true; - } - if (!ok) { - UTIL_LOG(L1, (L"disk external ioctl failed %s", drive)); - } - CloseHandle(device); - done: - UTIL_LOG(L1, (L"disk external %s %d time %s", - drive, external, String_DoubleToString(timer.GetMilliseconds(), 3))); - - { - __mutexScope(g_cache_lock); - lstrcpyn(g_cache_drive[g_cache_pos], drive, kMaxDriveLen+1); - g_cache_external[g_cache_pos] = external; - if (++g_cache_pos >= kMaxDrivesCached) g_cache_pos = 0; - } - - return external; -} - -// find the first fixed local disk with at least the space requested -// confirms that we can create a directory on the drive -// returns the drive in the drive parameter -// returns E_FAIL if no drive with enough space could be found -HRESULT FindFirstLocalDriveWithEnoughSpace(const uint64 space_required, - CString *drive) { - ASSERT1(drive); - - DisableThreadErrorUI disable_error_dialog_box; - - const int kMaxNumDrives = 26; - static const size_t kBufLen = (STR_SIZE("c:\\\0") * kMaxNumDrives) + 1; - - // obtain the fixed system drives - TCHAR buf[kBufLen]; - DWORD str_len = ::GetLogicalDriveStrings(kBufLen, buf); - if (str_len > 0 && str_len < kBufLen) { - for (TCHAR* ptr = buf; *ptr != L'\0'; ptr += (lstrlen(ptr) + 1)) { - UINT drive_type = GetDriveType(ptr); - if (drive_type == DRIVE_FIXED) { - CString test_drive(ptr); - if (!IsDiskExternal(CString(L"\\\\?\\") + test_drive.Left(2))) { - uint64 free_disk_space = 0; - HRESULT hr = GetFreeDiskSpace(test_drive, &free_disk_space); - - if (SUCCEEDED(hr) && space_required <= free_disk_space) { - CString temp_dir; - // confirm that we can create a directory on this drive - bool found = false; - while (!found) { - temp_dir = test_drive + - NOTRANSL(L"test") + - itostr(static_cast(::GetTickCount())); - if (!File::Exists (temp_dir)) found = true; - } - - if (SUCCEEDED(CreateDir(temp_dir, NULL))) { - VERIFY1(SUCCEEDED(DeleteDirectory(temp_dir))); - *drive = test_drive; - UTIL_LOG(L1, (L"drive %s enough space %d", test_drive.GetString(), - free_disk_space)); - return S_OK; - } - } - } - } - } - } - - return E_FAIL; -} - -// Get free disk space of a drive containing the specified folder -HRESULT GetFreeDiskSpace(uint32 csidl, uint64* free_disk_space) { - ASSERT1(free_disk_space); - - CString path; - RET_IF_FAILED(Shell::GetSpecialFolder(csidl, false, &path)); - - return GetFreeDiskSpace(path, free_disk_space); -} - -// Get free disk space of a drive containing the specified folder -HRESULT GetFreeDiskSpace(const TCHAR* folder, uint64* free_disk_space) { - ASSERT1(folder && *folder); - ASSERT1(free_disk_space); - - DisableThreadErrorUI disable_error_dialog_box; - - CString drive(folder); - - // (Stupid API used by System::GetDiskStatistics will work with any folder - - // as long as it EXISTS. Since the data storage folder might not exist yet - // (e.g., on a clean install) we'll just truncate it down to a drive letter.) - drive = drive.Left(3); // "X:\" - ASSERT1(String_EndsWith(drive, _T(":\\"), false)); - - // Get the free disk space available to this user on this drive - uint64 free_bytes_current_user = 0LL; - uint64 total_bytes_current_user = 0LL; - uint64 free_bytes_all_users = 0LL; - RET_IF_FAILED(System::GetDiskStatistics(drive, - &free_bytes_current_user, - &total_bytes_current_user, - &free_bytes_all_users)); - - *free_disk_space = std::min(free_bytes_current_user, free_bytes_all_users); - - return S_OK; -} - -// Has enough free disk space on a drive containing the specified folder -HRESULT HasEnoughFreeDiskSpace(uint32 csidl, uint64 disk_space_needed) { - uint64 free_disk_space = 0; - if (SUCCEEDED(GetFreeDiskSpace(csidl, &free_disk_space))) { - return (disk_space_needed <= free_disk_space) ? - S_OK : CI_E_NOT_ENOUGH_DISK_SPACE; - } - return S_OK; -} - -// Has enough free disk space on a drive containing the specified folder -HRESULT HasEnoughFreeDiskSpace(const TCHAR* folder, uint64 disk_space_needed) { - uint64 free_disk_space = 0; - if (SUCCEEDED(GetFreeDiskSpace(folder, &free_disk_space))) { - return (disk_space_needed <= free_disk_space) ? - S_OK : CI_E_NOT_ENOUGH_DISK_SPACE; - } - return S_OK; -} - -// The ::CreateFile() call will fail for mapped local drives (subst). -bool IsHotPluggable(const TCHAR* drive) { - ASSERT(drive, (L"")); - - // Disable potential error dialogs during this check - DisableThreadErrorUI disable_error_dialog_box; - - // - // We set the default return value to true so that - // we treat the disk as hot-pluggable in case we - // don't know. - // - bool ret = true; - - if (drive && lstrlen(drive) >= 2) { - CString volume_path(_T("\\\\.\\")); - // We don't want the trailing backslash. - volume_path.Append(drive, 2); - - CHandle volume(::CreateFile(volume_path, GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, NULL)); - - if (volume != INVALID_HANDLE_VALUE) { - STORAGE_HOTPLUG_INFO shi = {0}; - shi.Size = sizeof(shi); - DWORD bytes_returned = 0; - if (::DeviceIoControl(volume, IOCTL_STORAGE_GET_HOTPLUG_INFO, NULL, 0, - &shi, sizeof(STORAGE_HOTPLUG_INFO), &bytes_returned, - NULL)) { - ret = (shi.DeviceHotplug != false); - } else { - UTIL_LOG(LW, (_T("[::DeviceIoControl failed][%u]"), ::GetLastError())); - } - } else { - UTIL_LOG(LW, (_T("[::CreateFile failed][%u]"), ::GetLastError())); - } - } else { - ASSERT(false, (L"Invalid path")); - } - - return ret; -} - -bool IsLargeDrive(const TCHAR* drive) { - ASSERT1(drive && *drive); - - DisableThreadErrorUI disable_error_dialog_box; - - ULARGE_INTEGER caller_free_bytes = {0}; - ULARGE_INTEGER total_bytes = {0}; - ULARGE_INTEGER total_free_bytes = {0}; - - if (!::GetDiskFreeSpaceEx(drive, - &caller_free_bytes, - &total_bytes, - &total_free_bytes)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, - (_T("[IsLargeDrive - failed to GetDiskFreeSpaceEx][0x%x]"), hr)); - return false; - } - - return (total_bytes.QuadPart > kLargeDriveSize); -} - HRESULT DevicePathToDosPath(const TCHAR* device_path, CString* dos_path) { ASSERT1(device_path); ASSERT1(dos_path); diff --git a/omaha/base/disk.h b/omaha/base/disk.h index dd59006..59cf9d9 100644 --- a/omaha/base/disk.h +++ b/omaha/base/disk.h @@ -23,86 +23,10 @@ namespace omaha { -// A constant we use to determine a large drive. -// Although today this isn't really really large, -// it is enough to distinguish small, removable -// drives that are not continually connected to -// a computer, from the drives that are. -// In addition to using this constant, we -// also check if the drive is hot-pluggable. -const uint64 kLargeDriveSize = 0x00000000ffffffff; - -// returns true if the device is an external disk -// drive typically is something like: \\?\C: -bool IsDiskExternal(const TCHAR *drive); - -// -// Determines if a drive can be unplugged without manually disabling -// the drive first. By default, USB drives are initialized with -// "surprise removal" enabled, which means they are hot-pluggable. -// -// @param drive The root of the drive, as returned from GetLogicalDriveStrings -// e.g. "E:\\". -// -// @returns true if the drive is optimized for quick/surprise removal. -// If the function returns false, then caching (lazy write) is enabled for -// the drive, otherwise it is not. -// If an error occurs during this call, the return value will be 'true' since -// we always want to treat a drive as hot-pluggable if we're not sure. -// -bool IsHotPluggable(const TCHAR* drive); - -// -// @returns true if the specified drive is larger than kLargeDriveSize. -// -// @param drive The root of the drive, as returned from GetLogicalDriveStrings -// e.g. "E:\\". -// -bool IsLargeDrive(const TCHAR* drive); - -// find the first fixed local disk with at least the space requested -// returns the drive in the drive parameter -// returns E_FAIL if no drive with enough space could be found -HRESULT FindFirstLocalDriveWithEnoughSpace(const uint64 space_required, - CString *drive); - -// Get free disk space of a drive containing the specified folder -HRESULT GetFreeDiskSpace(uint32 csidl, uint64* free_disk_space); - -// Get free disk space of a drive containing the specified folder -HRESULT GetFreeDiskSpace(const TCHAR* folder, uint64* free_disk_space); - -// Has enough free disk space on a drive containing the specified folder -HRESULT HasEnoughFreeDiskSpace(uint32 csidl, uint64 disk_space_needed); - -// Has enough free disk space on a drive containing the specified folder -HRESULT HasEnoughFreeDiskSpace(const TCHAR* folder, uint64 disk_space_needed); - // Convert from "\Device\Harddisk0\Partition1\WINNT\System32\ntdll.dll" to // "C:\WINNT\System32\ntdll.dll" HRESULT DevicePathToDosPath(const TCHAR* device_path, CString* dos_path); -// -// Disables critical error dialogs on the current thread. -// The system does not display the critical-error-handler message box. -// Instead, the system returns the error to the calling process. -// -class DisableThreadErrorUI { - public: - DisableThreadErrorUI() { - // Set the error mode - prev_mode_ = SetErrorMode(SEM_FAILCRITICALERRORS); - } - - ~DisableThreadErrorUI() { - // Restore the error mode - SetErrorMode(prev_mode_); - } - - protected: - UINT prev_mode_; -}; - } // namespace omaha #endif // OMAHA_COMMON_DISK_H__ diff --git a/omaha/base/disk_unittest.cc b/omaha/base/disk_unittest.cc index ae7a1d2..12c5590 100644 --- a/omaha/base/disk_unittest.cc +++ b/omaha/base/disk_unittest.cc @@ -13,50 +13,17 @@ // limitations under the License. // ======================================================================== -#include +#include "omaha/base/disk.h" + +#include #include #include "omaha/base/app_util.h" -#include "omaha/base/const_utils.h" -#include "omaha/base/disk.h" #include "omaha/base/file.h" -#include "omaha/base/vistautil.h" #include "omaha/testing/unit_test.h" namespace omaha { -TEST(DiskTest, GetFreeDiskSpace) { - uint64 bytes_available = 0; - EXPECT_SUCCEEDED(GetFreeDiskSpace(_T("C:\\"), &bytes_available)); - - bytes_available = 0; - EXPECT_SUCCEEDED(GetFreeDiskSpace(CSIDL_PROGRAM_FILES, &bytes_available)); -} - -TEST(DiskTest, Disk_SystemDrive) { - TCHAR system_drive[MAX_PATH] = _T("%SystemDrive%"); - EXPECT_TRUE(::ExpandEnvironmentStrings(system_drive, system_drive, MAX_PATH)); - EXPECT_TRUE(::PathAddBackslash(system_drive)); - - if (vista_util::IsUserAdmin()) { - // System drive should not be hot-pluggable - EXPECT_FALSE(IsHotPluggable(system_drive)); - } - - // System drive is expected to be > 4GB. - EXPECT_TRUE(IsLargeDrive(system_drive)); -} - -TEST(DiskTest, Disk_FirstLargeLocalDrive) { - // Preferred amount of disk space for data (choose first location if found). - // Ideally this would be 1 GB, but some test VMs have little free space. - const int kDesiredSpace = 100 * 1000 * 1000; // 100 MB - - CString drive; - EXPECT_SUCCEEDED(FindFirstLocalDriveWithEnoughSpace(kDesiredSpace, &drive)); - EXPECT_TRUE(IsLargeDrive(drive)); -} - // TODO(omaha): Make this work on mapped drives. See http://b/1076675. TEST(DiskTest, DISABLED_DevicePathToDosPath) { TCHAR image_name[MAX_PATH] = _T(""); diff --git a/omaha/base/dual_interface_switch.h b/omaha/base/dual_interface_switch.h deleted file mode 100644 index 72dd933..0000000 --- a/omaha/base/dual_interface_switch.h +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// This class allows for implementing two dual interfaces, ReadOnly being a -// read-only dual interface, and ReadWrite being a read-write dual interface. -// Based on the value returned from is_read_only(), the ReadOnly or the -// ReadWrite dual interface is exposed at runtime. -// -// An ATL class needs to -// (a) derive from DualInterfaceSwitch -// -// (b) implement the is_read_only() method. For instance: -// bool is_read_only() { return is_read_only_; } -// -// (c) add entries similar to below for the dual interfaces as well as IDispatch -// to the COM map: -// BEGIN_COM_MAP(AppData) -// COM_INTERFACE_ENTRY2(IUnknown, IAppData) -// COM_INTERFACE_ENTRY_FUNC(__uuidof(IAppDataReadOnly), 0, DualInterfaceQI) -// COM_INTERFACE_ENTRY_FUNC(__uuidof(IAppData), 0, DualInterfaceQI) -// COM_INTERFACE_ENTRY_FUNC(__uuidof(IDispatch), 0, DualInterfaceQI) -// END_COM_MAP() - -#ifndef OMAHA_BASE_DUAL_INTERFACE_SWITCH_H_ -#define OMAHA_BASE_DUAL_INTERFACE_SWITCH_H_ - -#include -#include -#include "base/basictypes.h" -#include "omaha/base/debug.h" - -namespace omaha { - -template -class ATL_NO_VTABLE DualInterfaceSwitch : public ReadOnly, - public ReadWrite { - protected: - // DualInterfaceQI gives out either the ReadOnly or ReadWrite interface - // pointer, based on the value of is_read_only() that class T implements. - // The signature of this function has to be - // HRESULT WINAPI func(void* pv, REFIID riid, LPVOID* ppv, DWORD dw); - // for it to work with COM_INTERFACE_ENTRY_FUNC. - static HRESULT WINAPI DualInterfaceQI(void* p, - REFIID riid, - LPVOID* v, - DWORD) { - // Ensure that ReadOnly and ReadWrite are derived from IDispatch. - ASSERT1(static_cast(reinterpret_cast(1))); - ASSERT1(static_cast(reinterpret_cast(1))); - - if (riid != iid_read_only && - riid != iid_read_write && - riid != __uuidof(IDispatch)) { - // Returning S_FALSE allows COM map processing to continue. Another entry - // in the COM map might match the interface requested. - return S_FALSE; - } - - T* t = reinterpret_cast(p); - if (t->is_read_only() && riid == iid_read_write) { - return S_FALSE; - } - - t->AddRef(); - if (t->is_read_only() || riid == iid_read_only) { - *v = static_cast(t); - return S_OK; - } - - *v = static_cast(t); - return S_OK; - } -}; - -} // namespace omaha - -#endif // OMAHA_BASE_DUAL_INTERFACE_SWITCH_H_ diff --git a/omaha/base/dynamic_link_kernel32.h b/omaha/base/dynamic_link_kernel32.h index b8542f8..0aba0b1 100644 --- a/omaha/base/dynamic_link_kernel32.h +++ b/omaha/base/dynamic_link_kernel32.h @@ -38,7 +38,7 @@ class Kernel32 { static BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process); private: - DISALLOW_EVIL_CONSTRUCTORS(Kernel32); + DISALLOW_COPY_AND_ASSIGN(Kernel32); }; } // namespace omaha diff --git a/omaha/base/environment_block_modifier.cc b/omaha/base/environment_block_modifier.cc index 855891b..98b3917 100644 --- a/omaha/base/environment_block_modifier.cc +++ b/omaha/base/environment_block_modifier.cc @@ -15,6 +15,8 @@ #include "omaha/base/environment_block_modifier.h" +#include + #include "omaha/base/debug.h" #include "omaha/base/environment_utils.h" diff --git a/omaha/base/environment_block_modifier.h b/omaha/base/environment_block_modifier.h index db2ff48..98891ca 100644 --- a/omaha/base/environment_block_modifier.h +++ b/omaha/base/environment_block_modifier.h @@ -24,6 +24,7 @@ #include #include #include +#include "base/basictypes.h" namespace omaha { diff --git a/omaha/base/environment_block_modifier_unittest.cc b/omaha/base/environment_block_modifier_unittest.cc index 78c30ef..ea2bb21 100644 --- a/omaha/base/environment_block_modifier_unittest.cc +++ b/omaha/base/environment_block_modifier_unittest.cc @@ -13,10 +13,11 @@ // limitations under the License. // ======================================================================== +#include "omaha/base/environment_block_modifier.h" + +#include #include -#include "base/scoped_ptr.h" -#include "omaha/base/environment_block_modifier.h" #include "omaha/base/environment_utils.h" #include "omaha/base/error.h" #include "omaha/testing/unit_test.h" diff --git a/omaha/base/error.h b/omaha/base/error.h index d54887d..71c7b78 100644 --- a/omaha/base/error.h +++ b/omaha/base/error.h @@ -209,6 +209,8 @@ const ULONG kFacilityOmaha = 67; MAKE_OMAHA_HRESULT(SEVERITY_ERROR, 0x606) #define GOOPDATE_E_SHUTDOWN_SIGNALED \ MAKE_OMAHA_HRESULT(SEVERITY_ERROR, 0x607) +#define GOOPDATE_E_PROBE_ALREADY_RUNNING \ + MAKE_OMAHA_HRESULT(SEVERITY_ERROR, 0x608) // Setup and metainstaller custom error codes. #define GOOPDATE_E_NONADMIN_INSTALL_ADMIN_APP \ diff --git a/omaha/base/event_trace_provider.h b/omaha/base/event_trace_provider.h index 7fedeae..3ff1315 100644 --- a/omaha/base/event_trace_provider.h +++ b/omaha/base/event_trace_provider.h @@ -19,10 +19,12 @@ #define BASE_EVENT_TRACE_PROVIDER_H_ #include -#include #include -#include "omaha/base/debug.h" +#include +#include +#include #include "base/basictypes.h" +#include "omaha/base/debug.h" namespace omaha { @@ -50,33 +52,33 @@ template class EtwMofEvent: public EtwMofEventBase { EtwMofEvent(const EtwEventClass& event_class, EtwEventType type, EtwEventLevel level) { memset(static_cast(this), 0, sizeof(Super)); - header.Size = sizeof(Super); - header.Guid = event_class; - header.Class.Type = type; - header.Class.Level = level; - header.Flags = WNODE_FLAG_TRACED_GUID | WNODE_FLAG_USE_MOF_PTR; + this->header.Size = sizeof(Super); + this->header.Guid = event_class; + this->header.Class.Type = type; + this->header.Class.Level = level; + this->header.Flags = WNODE_FLAG_TRACED_GUID | WNODE_FLAG_USE_MOF_PTR; } EtwMofEvent(const EtwEventClass& event_class, EtwEventType type, EtwEventVersion version, EtwEventLevel level) { memset(static_cast(this), 0, sizeof(Super)); - header.Size = sizeof(Super); - header.Guid = event_class; - header.Class.Type = type; - header.Class.Version = version; - header.Class.Level = level; - header.Flags = WNODE_FLAG_TRACED_GUID | WNODE_FLAG_USE_MOF_PTR; + this->header.Size = sizeof(Super); + this->header.Guid = event_class; + this->header.Class.Type = type; + this->header.Class.Version = version; + this->header.Class.Level = level; + this->header.Flags = WNODE_FLAG_TRACED_GUID | WNODE_FLAG_USE_MOF_PTR; } void SetField(int field, size_t size, const void *data) { ASSERT1(field < N); - if ((field < N) && (size <= kuint32max)) { - fields[field].DataPtr = reinterpret_cast(data); - fields[field].Length = static_cast(size); + if ((field < N) && (size <= std::numeric_limits::max())) { + this->fields[field].DataPtr = reinterpret_cast(data); + this->fields[field].Length = static_cast(size); } } - EVENT_TRACE_HEADER* get() { return& header; } + EVENT_TRACE_HEADER* get() { return &this->header; } private: DISALLOW_COPY_AND_ASSIGN(EtwMofEvent); diff --git a/omaha/base/extractor_unittest.cc b/omaha/base/extractor_unittest.cc index 8ea0d00..44b3e26 100644 --- a/omaha/base/extractor_unittest.cc +++ b/omaha/base/extractor_unittest.cc @@ -18,11 +18,13 @@ // TODO(omaha): eliminate the dependency on the hardcoded "GoogleUpdate.exe" // program name. +#include "omaha/base/extractor.h" + #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/app_util.h" #include "omaha/base/apply_tag.h" -#include "omaha/base/extractor.h" #include "omaha/base/scope_guard.h" #include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" @@ -146,7 +148,7 @@ TEST(ExtractorTest, EmbedAppendExtract) { ASSERT_TRUE(extractor.ExtractTag(NULL, &tag_buffer_size)); ASSERT_EQ(tag_buffer_size, expected_tag_string_len); - scoped_array tag_buffer(new char[expected_tag_string_len]); + std::unique_ptr tag_buffer(new char[expected_tag_string_len]); ASSERT_TRUE(extractor.ExtractTag(tag_buffer.get(), &tag_buffer_size)); ASSERT_EQ(tag_buffer_size, expected_tag_string_len); ASSERT_EQ(memcmp(tag_buffer.get(), diff --git a/omaha/base/file.cc b/omaha/base/file.cc index 3d4c045..eff3cee 100644 --- a/omaha/base/file.cc +++ b/omaha/base/file.cc @@ -56,8 +56,10 @@ // call some cleanup routine #include "omaha/base/file.h" + #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/app_util.h" #include "omaha/base/const_config.h" #include "omaha/base/debug.h" @@ -66,8 +68,6 @@ #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/timer.h" @@ -481,27 +481,27 @@ HRESULT File::MoveAfterReboot(const TCHAR* from, const TCHAR* to) { // NOTE: If the only values found were our own keys, the whole // PendingFileRenameOperations MULTISZ needs to be deleted. // This is signified by a returned *value_size_chars_ptr of 0. -HRESULT File::GetPendingRenamesValueMinusDir(const TCHAR* in_directory, - bool prefix_match, - TCHAR** value_multisz_ptr, - size_t* value_size_chars_ptr, - bool* found_ptr) { +HRESULT File::GetPendingRenamesValueMinusDir( + const TCHAR* in_directory, + bool prefix_match, + std::unique_ptr* value_multisz_ptr, + size_t* value_size_chars_ptr, + bool* found_ptr) { ASSERT1(in_directory && *in_directory); // Convert to references for easier-to-read-code: - TCHAR*& value_multisz = *value_multisz_ptr; size_t& value_size_chars = *value_size_chars_ptr; bool& found = *found_ptr; // Initialize [out] parameters - value_multisz = NULL; + value_multisz_ptr->reset(); value_size_chars = 0; found = false; // Locals mirroring the [out] parameters. // We will only set the corresponding [out] parameters when we have something // meaningful to return to the caller - scoped_array value_multisz_local; + std::unique_ptr value_multisz_bytes; size_t value_size_chars_local = 0; size_t value_size_bytes = 0; @@ -511,10 +511,13 @@ HRESULT File::GetPendingRenamesValueMinusDir(const TCHAR* in_directory, RegKey::HasValue(kSessionManagerKey, kPendingFileRenameOps) && SUCCEEDED(RegKey::GetValue(kSessionManagerKey, kPendingFileRenameOps, - reinterpret_cast(&value_multisz_local), + &value_multisz_bytes, &value_size_bytes)), S_OK); + std::unique_ptr value_multisz_local( + reinterpret_cast(value_multisz_bytes.release())); + ASSERT1(value_multisz_local.get() || value_size_bytes == 0); UTIL_LOG(L5, (_T("[File::GetPendingRenamesValueMinusDir]") _T("[read multisz %d bytes]"), @@ -611,7 +614,7 @@ HRESULT File::GetPendingRenamesValueMinusDir(const TCHAR* in_directory, // value needs to be deleted. We do not populate // value_size_chars or value_multisz in this case. ASSERT1(!value_size_chars); - ASSERT1(!value_multisz); + ASSERT1(!*value_multisz_ptr); } else { // The last string should have a NULL terminator: ASSERT1(str_write[-1] == '\0'); @@ -622,8 +625,8 @@ HRESULT File::GetPendingRenamesValueMinusDir(const TCHAR* in_directory, ++str_write; // Populate value_size_chars and value_multisz in this case. - value_multisz = value_multisz_local.release(); - value_size_chars = str_write - value_multisz; + value_multisz_ptr->reset(value_multisz_local.release()); + value_size_chars = str_write - value_multisz_ptr->get(); } } @@ -639,12 +642,12 @@ HRESULT File::RemoveFromMovesPendingReboot(const TCHAR* in_directory, ASSERT1(in_directory && *in_directory); bool found = false; - // scoped_array will free the value_multisz buffer on stack unwind: - scoped_array value_multisz; + // unique_ptr will free the value_multisz buffer on stack unwind: + std::unique_ptr value_multisz; size_t value_size_chars = 0; HRESULT hr = GetPendingRenamesValueMinusDir(in_directory, prefix_match, - address(value_multisz), + &value_multisz, &value_size_chars, &found); if (SUCCEEDED(hr) && found) { @@ -684,13 +687,13 @@ bool File::AreMovesPendingReboot(const TCHAR* in_directory, bool prefix_match) { ASSERT1(in_directory && *in_directory); bool found = false; - // scoped_array will free the value_multisz buffer on stack unwind: - scoped_array value_multisz; + // unique_ptr will free the value_multisz buffer on stack unwind: + std::unique_ptr value_multisz; size_t value_size_chars = 0; if (SUCCEEDED(GetPendingRenamesValueMinusDir(in_directory, prefix_match, - address(value_multisz), + &value_multisz, &value_size_chars, &found)) && found) { return true; @@ -955,7 +958,7 @@ HRESULT File::WriteN(const byte* buf, byte* temp_buf = const_cast(buf); - scoped_array encrypt_buf; + std::unique_ptr encrypt_buf; uint32 to_go = n; while (to_go) { @@ -987,7 +990,7 @@ HRESULT File::Write(const byte* buf, const uint32 len, uint32* bytes_written) { byte* b = const_cast(buf); - scoped_array encrypt_buf; + std::unique_ptr encrypt_buf; DWORD wrote = 0; if (!::WriteFile(handle_, b, len, &wrote, NULL)) { diff --git a/omaha/base/file.h b/omaha/base/file.h index 6ea90e9..b9fa5e9 100644 --- a/omaha/base/file.h +++ b/omaha/base/file.h @@ -19,11 +19,15 @@ #ifndef OMAHA_BASE_FILE_H_ #define OMAHA_BASE_FILE_H_ +#include #include +#include +#include #include + #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/store_watcher.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -171,11 +175,12 @@ class File { // NOTE: If the only values found were our own keys, the whole // PendingFileRenameOperations MULTISZ needs to be deleted. This is // signified by a returned *value_size_chars_ptr of 0. - static HRESULT GetPendingRenamesValueMinusDir(const TCHAR* in_directory, - bool prefix_match, - TCHAR** value_multisz_ptr, - size_t* value_size_chars_ptr, - bool* found_ptr); + static HRESULT GetPendingRenamesValueMinusDir( + const TCHAR* in_directory, + bool prefix_match, + std::unique_ptr* value_multisz_ptr, + size_t* value_size_chars_ptr, + bool* found_ptr); HANDLE handle_; CString file_name_; @@ -185,9 +190,9 @@ class File { uint32 encryption_seed_; uint32 sequence_id_; - static const int kMaxFileSize = kint32max; + static const int kMaxFileSize = std::numeric_limits::max(); - DISALLOW_EVIL_CONSTRUCTORS(File); + DISALLOW_COPY_AND_ASSIGN(File); }; // File lock @@ -211,7 +216,7 @@ class FileLock { private: std::vector handles_; - DISALLOW_EVIL_CONSTRUCTORS(FileLock); + DISALLOW_COPY_AND_ASSIGN(FileLock); }; @@ -241,7 +246,7 @@ class FileWatcher : public StoreWatcher { bool watch_subtree_; DWORD notify_filter_; - DISALLOW_EVIL_CONSTRUCTORS(FileWatcher); + DISALLOW_COPY_AND_ASSIGN(FileWatcher); }; } // namespace omaha diff --git a/omaha/base/file_reader.h b/omaha/base/file_reader.h index ebfac7b..5431db1 100644 --- a/omaha/base/file_reader.h +++ b/omaha/base/file_reader.h @@ -16,10 +16,11 @@ #ifndef OMAHA_COMMON_FILE_READER_H_ #define OMAHA_COMMON_FILE_READER_H_ -#include #include +#include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/file.h" namespace omaha { @@ -47,12 +48,12 @@ class FileReader { bool file_is_open_; uint32 buffered_byte_count_; // How many bytes are in the buffer. uint32 current_position_; // An index into the buffer. - scoped_array file_buffer_; // A buffer (cache) of the file. + std::unique_ptr file_buffer_; // A buffer (cache) of the file. uint32 file_buffer_size_; // How much of the file to slurp // in on each read. bool is_unicode_; - DISALLOW_EVIL_CONSTRUCTORS(FileReader); + DISALLOW_COPY_AND_ASSIGN(FileReader); }; } // namespace omaha diff --git a/omaha/base/file_reader_unittest.cc b/omaha/base/file_reader_unittest.cc index fa07d25..1fd1f3d 100644 --- a/omaha/base/file_reader_unittest.cc +++ b/omaha/base/file_reader_unittest.cc @@ -16,9 +16,11 @@ // TODO(omaha): improve unit test. For example, test we are handling correctly // different types of line termination. -#include -#include "base/scoped_ptr.h" #include "omaha/base/file_reader.h" + +#include +#include + #include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" @@ -29,13 +31,13 @@ class ReadingFilesTest : public testing::Test { ReadingFilesTest() { } - virtual void SetUp() { + void SetUp() override { // create a temporary file temp_file_ = GetTempFilename(_T("ut_")); ASSERT_FALSE(temp_file_.IsEmpty()); } - virtual void TearDown() { + void TearDown() override { // remove the temporary file if (!temp_file_.IsEmpty()) { ASSERT_SUCCEEDED(File::Remove(temp_file_)); @@ -135,7 +137,7 @@ class ReadingFilesTest : public testing::Test { CString temp_file_; - DISALLOW_EVIL_CONSTRUCTORS(ReadingFilesTest); + DISALLOW_COPY_AND_ASSIGN(ReadingFilesTest); }; @@ -162,7 +164,7 @@ TEST_F(ReadingFilesTest, ReadFile1) { ASSERT_SUCCEEDED(file_read1.Open(temp_file_, false, false)); while (true) { uint32 bytes_read; - scoped_array line(new char[256]); + std::unique_ptr line(new char[256]); if (FAILED(file_read1.ReadLineAnsi(256, line.get(), &bytes_read))) { break; } @@ -177,7 +179,7 @@ TEST_F(ReadingFilesTest, ReadFile1) { uint32 buffer_size = 512; ASSERT_SUCCEEDED(file_read2.Init(temp_file_, buffer_size)); while (true) { - scoped_array line(new char[256]); + std::unique_ptr line(new char[256]); if (FAILED(file_read2.ReadLineAnsi(256, line.get()))) { break; } diff --git a/omaha/base/file_store.cc b/omaha/base/file_store.cc deleted file mode 100644 index 0a7ac4a..0000000 --- a/omaha/base/file_store.cc +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2006-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Defines class FileStore - -#include -#include "omaha/base/debug.h" -#include "omaha/base/file.h" -#include "omaha/base/file_store.h" -#include "omaha/base/string.h" -#include "omaha/base/utils.h" - -namespace omaha { - -// Open the store -bool FileStore::Open(const TCHAR* file_path) { - file_path_ = String_MakeEndWith(file_path, _T("\\"), false); - return true; -} - -// Close the store -bool FileStore::Close() { - file_path_.Empty(); - return true; -} - -// Clear the store -bool FileStore::Clear() { - if (File::Exists(file_path_) && File::IsDirectory(file_path_)) { - return SUCCEEDED(DeleteDirectoryFiles(file_path_)); - } else { - return true; - } -} - -// Read a value from the store -bool FileStore::Read(const TCHAR* name, std::vector* data) const { - ASSERT1(name); - ASSERT1(data); - - return Exists(name) && SUCCEEDED(ReadEntireFile(file_path_ + name, 0, data)); -} - -// Write a value to the store -bool FileStore::Write(const TCHAR* name, byte* data, int data_size) { - ASSERT1(name); - ASSERT1(data); - ASSERT1(data_size); - - std::vector buffer(data_size); - memcpy(&buffer.front(), data, data_size); - - return SUCCEEDED(WriteEntireFile(file_path_ + name, buffer)); -} - -// Check to see a named value exists in the store -bool FileStore::Exists(const TCHAR* name) const { - ASSERT1(name); - - return File::Exists(file_path_ + name); -} - -// Remove a value from the store -bool FileStore::Remove(const TCHAR* name) { - ASSERT1(name); - - return SUCCEEDED(File::Remove(file_path_ + name)); -} - -// Get the number of values for this store -bool FileStore::GetValueCount(size_t* value_count) { - ASSERT1(value_count); - - std::vector matching_paths; - - if (FAILED(File::GetWildcards(file_path_, _T("*"), &matching_paths))) { - return false; - } - - *value_count = matching_paths.size(); - - return true; -} - -// Get the value name for the given value name index -bool FileStore::GetValueNameAt(size_t index, CString* value_name) { - ASSERT1(value_name); - - std::vector matching_paths; - - if (FAILED(File::GetWildcards(file_path_, _T("*"), &matching_paths))) { - return false; - } - if (index >= matching_paths.size()) { - return false; - } - - *value_name = matching_paths[index].Mid(file_path_.GetLength()); - - return true; -} - -} // namespace omaha - diff --git a/omaha/base/file_store.h b/omaha/base/file_store.h deleted file mode 100644 index ecfb3bd..0000000 --- a/omaha/base/file_store.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2006-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Defines class FileStore - -#ifndef OMAHA_COMMON_FILE_STORE_H__ -#define OMAHA_COMMON_FILE_STORE_H__ - -#include -#include -#include "base/basictypes.h" - -namespace omaha { - -class FileStore { - public: - // Open the store - bool Open(const TCHAR* file_path); - - // Close the store - bool Close(); - - // Clear the store - bool Clear(); - - // Read a value from the store - bool Read(const TCHAR* name, std::vector* data) const; - - // Write a value to the store - bool Write(const TCHAR* name, byte* data, int data_size); - - // Check to see a named value exists in the store - bool Exists(const TCHAR* name) const; - - // Remove a value from the store - bool Remove(const TCHAR* name); - - // Get the number of values for this store - bool GetValueCount(size_t* value_count); - - // Get the value name for the given value name index - bool GetValueNameAt(size_t index, CString* value_name); - - private: - CString file_path_; // Full path to the file store -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_FILE_STORE_H__ diff --git a/omaha/base/file_store_unittest.cc b/omaha/base/file_store_unittest.cc deleted file mode 100644 index 7d50131..0000000 --- a/omaha/base/file_store_unittest.cc +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2006-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Unit test for the file_store. - - - -#include -#include "base/basictypes.h" -#include "omaha/base/app_util.h" -#include "omaha/base/file_store.h" -#include "omaha/base/scope_guard.h" -#include "omaha/base/utils.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -const TCHAR kFilePathPrefix[] = _T("unittest"); -const TCHAR kFileName1[] = _T("fname1"); -const TCHAR kFileName2[] = _T("fname2"); -char kFileContent[] = "1234567890abcdefg"; - -TEST(FileStoreTest, FileStore) { - // Create a temp dir - CString temp_path = app_util::GetTempDir(); - ASSERT_FALSE(temp_path.IsEmpty()); - - CString temp_dir; - temp_dir.Format(_T("%s%s%x"), temp_path, kFilePathPrefix, ::GetTickCount()); - ASSERT_EQ(::SHCreateDirectoryEx(0, temp_dir, 0), ERROR_SUCCESS); - ON_SCOPE_EXIT(DeleteDirectory, temp_dir); - - // Test the file store - FileStore file_store; - ASSERT_TRUE(file_store.Open(temp_dir)); - - // Make sure the folder is empty - size_t value_count(0); - ASSERT_TRUE(file_store.GetValueCount(&value_count)); - ASSERT_EQ(value_count, 0); - CString value_name; - ASSERT_FALSE(file_store.GetValueNameAt(0, &value_name)); - - // Write 2 files - std::vector buffer; - ASSERT_TRUE(file_store.Write(kFileName1, - reinterpret_cast(kFileContent), - arraysize(kFileContent))); - ASSERT_TRUE(file_store.Exists(kFileName1)); - ASSERT_TRUE(file_store.GetValueCount(&value_count)); - ASSERT_EQ(value_count, 1); - ASSERT_TRUE(file_store.GetValueNameAt(0, &value_name)); - ASSERT_TRUE(value_name == kFileName1); - ASSERT_TRUE(file_store.Read(kFileName1, &buffer)); - ASSERT_TRUE(memcmp(kFileContent, - &buffer.front(), - arraysize(kFileContent)) == 0); - - ASSERT_TRUE(file_store.Write(kFileName2, - reinterpret_cast(kFileContent), - arraysize(kFileContent))); - ASSERT_TRUE(file_store.Exists(kFileName2)); - ASSERT_TRUE(file_store.GetValueCount(&value_count)); - ASSERT_EQ(value_count, 2); - ASSERT_TRUE(file_store.GetValueNameAt(1, &value_name)); - ASSERT_TRUE(value_name == kFileName2); - ASSERT_TRUE(file_store.Read(kFileName2, &buffer)); - ASSERT_TRUE(memcmp(kFileContent, - &buffer.front(), - arraysize(kFileContent)) == 0); - - // Remove files - ASSERT_TRUE(file_store.Remove(kFileName1)); - ASSERT_FALSE(file_store.Exists(kFileName1)); - ASSERT_TRUE(file_store.GetValueCount(&value_count)); - ASSERT_EQ(value_count, 1); - ASSERT_TRUE(file_store.Remove(kFileName2)); - ASSERT_FALSE(file_store.Exists(kFileName2)); - ASSERT_TRUE(file_store.GetValueCount(&value_count)); - ASSERT_EQ(value_count, 0); - - ASSERT_TRUE(file_store.Close()); -} - -} // namespace omaha - diff --git a/omaha/base/file_ver.h b/omaha/base/file_ver.h index 6ba29f0..6724407 100644 --- a/omaha/base/file_ver.h +++ b/omaha/base/file_ver.h @@ -65,7 +65,7 @@ class FileVer { // language charset DWORD lang_charset_; - DISALLOW_EVIL_CONSTRUCTORS(FileVer); + DISALLOW_COPY_AND_ASSIGN(FileVer); }; } // namespace omaha diff --git a/omaha/base/has_exception_namespace_fix.h b/omaha/base/has_exception_namespace_fix.h deleted file mode 100644 index e4f6367..0000000 --- a/omaha/base/has_exception_namespace_fix.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#if !_HAS_EXCEPTIONS -// Fixes a problem with using the standard library with exceptions turned off. -// See discussion at http://tiny.cc/byLhe -#include -using std::exception; -#endif diff --git a/omaha/base/lang_enc.h b/omaha/base/lang_enc.h deleted file mode 100644 index 9da8c03..0000000 --- a/omaha/base/lang_enc.h +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// This file is for i18n. It contains two enums, namely Language and -// Encoding, where Language is the linguistic convention, and Encoding -// contains information on both language encoding and character set. -// -// The language and encoding are both based on Teragram's conventions, -// except for some common ISO-8859 encodings that are not detected by -// Teragram but might be in the future. -// -// This file also includes functions that do mappings among -// Language/Encoding enums, language/encoding string names (typically -// the output from Language Encoding identifier), and language codes -// (iso 639), and two-letter country codes (iso 3166) -// -// NOTE: Both Language and Encoding enums should always start from -// zero value. This assumption has been made and used. - -#ifndef OMAHA_BASE_LANG_ENC_H_ -#define OMAHA_BASE_LANG_ENC_H_ - -#include - -// some of the popular encoding aliases -#define LATIN1 ISO_8859_1 -#define LATIN2 ISO_8859_2 -#define LATIN3 ISO_8859_3 -#define LATIN4 ISO_8859_4 -#define CYRILLIC ISO_8859_5 -#define ARABIC_ENCODING ISO_8859_6 // avoiding the same name as language -#define GREEK_ENCODING ISO_8859_7 // avoiding the same name as language -#define HEBREW_ENCODING ISO_8859_8 // avoiding the same name as language -#define LATIN5 ISO_8859_9 -#define LATIN6 ISO_8859_10 -#define KOREAN_HANGUL KOREAN_EUC_KR - -// NOTE: Only add new languages to the end of this list (but before -// NUM_LANGUAGES). -enum Language { - ENGLISH = 0, /* 0 */ - DANISH, /* 1 */ - DUTCH, /* 2 */ - FINNISH, /* 3 */ - FRENCH, /* 4 */ - GERMAN, /* 5 */ - HEBREW, /* 6 */ - ITALIAN, /* 7 */ - JAPANESE, /* 8 */ - KOREAN, /* 9 */ - NORWEGIAN, /* 10 */ - POLISH, /* 11 */ - PORTUGUESE, /* 12 */ - RUSSIAN, /* 13 */ - SPANISH, /* 14 */ - SWEDISH, /* 15 */ - CHINESE, /* 16 */ - CZECH, /* 17 */ - GREEK, /* 18 */ - ICELANDIC, /* 19 */ - LATVIAN, /* 20 */ - LITHUANIAN, /* 21 */ - ROMANIAN, /* 22 */ - HUNGARIAN, /* 23 */ - ESTONIAN, /* 24 */ - TG_UNKNOWN_LANGUAGE, /* 25 */ - UNKNOWN_LANGUAGE, /* 26 */ - BULGARIAN, /* 27 */ - CROATIAN, /* 28 */ - SERBIAN, /* 29 */ - IRISH, /* 30 */ - GALICIAN, /* 31 */ - TAGALOG, /* 32 */ - TURKISH, /* 33 */ - UKRAINIAN, /* 34 */ - HINDI, /* 35 */ - MACEDONIAN, /* 36 */ - BENGALI, /* 37 */ - INDONESIAN, /* 38 */ - LATIN, /* 39 */ - MALAY, /* 40 */ - MALAYALAM, /* 41 */ - WELSH, /* 42 */ - NEPALI, /* 43 */ - TELUGU, /* 44 */ - ALBANIAN, /* 45 */ - TAMIL, /* 46 */ - BELARUSIAN, /* 47 */ - JAVANESE, /* 48 */ - OCCITAN, /* 49 */ - URDU, /* 50 */ - BIHARI, /* 51 */ - GUJARATI, /* 52 */ - THAI, /* 53 */ - ARABIC, /* 54 */ - CATALAN, /* 55 */ - ESPERANTO, /* 56 */ - BASQUE, /* 57 */ - INTERLINGUA, /* 58 */ - KANNADA, /* 59 */ - PUNJABI, /* 60 */ - SCOTS_GAELIC, /* 61 */ - SWAHILI, /* 62 */ - SLOVENIAN, /* 63 */ - MARATHI, /* 64 */ - MALTESE, /* 65 */ - VIETNAMESE, /* 66 */ - FRISIAN, /* 67 */ - SLOVAK, /* 68 */ - CHINESE_T, /* 69 */ // This is added to solve the problem of - // distinguishing Traditional and Simplified - // Chinese when the encoding is UTF8. - FAROESE, /* 70 */ - SUNDANESE, /* 71 */ - UZBEK, /* 72 */ - AMHARIC, /* 73 */ - AZERBAIJANI, /* 74 */ - GEORGIAN, /* 75 */ - TIGRINYA, /* 76 */ - PERSIAN, /* 77 */ - BOSNIAN, /* 78 */ - SINHALESE, /* 79 */ - NORWEGIAN_N, /* 80 */ - PORTUGUESE_P, /* 81 */ - PORTUGUESE_B, /* 82 */ - XHOSA, /* 83 */ - ZULU, /* 84 */ - GUARANI, /* 85 */ - SESOTHO, /* 86 */ - TURKMEN, /* 87 */ - KYRGYZ, /* 88 */ - BRETON, /* 89 */ - TWI, /* 90 */ - YIDDISH, /* 91 */ - ORIYA, /* 92 */ - SERBO_CROATIAN, /* 93 */ - SOMALI, /* 94 */ - UIGHUR, /* 95 */ - KURDISH, /* 96 */ - MONGOLIAN, /* 97 */ - ARMENIAN, /* 98 */ - LAOTHIAN, /* 99 */ - SINDHI, /* 100! */ - RHAETO_ROMANCE, /* 101 */ - CHINESE_JAPANESE_KOREAN, /* 103 */ // Not really a language - PSEUDOTRANSLATION, /* 104 */ // Not really a language - NUM_LANGUAGES, // Always keep this at the end. It is not a - // valid Language enum, it is only used to - // indicate the total number of Languages. -}; - - -// Language codes for those languages we support, used to map to IDs from -// the Language enumeration. We could have used the Rfc1766ToLcid from the -// Win32 system's mlang.dll to map these to LCIDs, but a) we don't want to -// have to load mlang.dll and b) we are using our own language IDs. -const TCHAR* const kLangCodeChinesePrc = _T("zh_cn"); -const TCHAR* const kLangCodeChineseTaiwan = _T("zh_tw"); -const TCHAR* const kLangCodeCjk = _T("cjk"); -const TCHAR* const kLangCodeDutch = _T("nl"); -const TCHAR* const kLangCodeEnglish = _T("en"); -const TCHAR* const kLangCodeFrench = _T("fr"); -const TCHAR* const kLangCodeGerman = _T("de"); -const TCHAR* const kLangCodeItalian = _T("it"); -const TCHAR* const kLangCodeJapanese = _T("ja"); -const TCHAR* const kLangCodeKorean = _T("ko"); -const TCHAR* const kLangCodePseudo = _T("x"); -const TCHAR* const kLangCodeSpanish = _T("es"); - - -// Maps language codes to languages. Terminated by a { NULL, UNKNOWN_LANGUAGE } -// item. -struct CodeToLanguage { - const TCHAR* code; - Language language; -}; - -SELECTANY CodeToLanguage codes_to_languages[] = { - { kLangCodeChinesePrc, CHINESE }, - { kLangCodeChineseTaiwan, CHINESE_T }, - { kLangCodeCjk, CHINESE_JAPANESE_KOREAN }, - { kLangCodeDutch, DUTCH }, - { kLangCodeEnglish, ENGLISH }, - { kLangCodeFrench, FRENCH }, - { kLangCodeGerman, GERMAN }, - { kLangCodeItalian, ITALIAN }, - { kLangCodeJapanese, JAPANESE }, - { kLangCodeKorean, KOREAN }, - { kLangCodePseudo, PSEUDOTRANSLATION }, - { kLangCodeSpanish, SPANISH }, - { NULL, UNKNOWN_LANGUAGE } -}; - - - -// Macro to wrap the notion of "unknown language". -#define IS_LANGUAGE_UNKNOWN(l) \ - ((l) == TG_UNKNOWN_LANGUAGE || (l) == UNKNOWN_LANGUAGE) - -// NOTE: Only add new encodings to the end of this list (but before -// NUM_ENCODINGS). -// NOTE: If you add an encoding here, you must also modify basistech_encoding() -// and google2/com/google/i18n/Encoding.java -enum Encoding { - ISO_8859_1 = 0, // 0: Teragram ASCII - ISO_8859_2, // 1: Teragram Latin2 - ISO_8859_3, // 2: in BasisTech but not in Teragram - ISO_8859_4, // 3: Teragram Latin4 - ISO_8859_5, // 4: Teragram ISO-8859-5 - ISO_8859_6, // 5: Teragram Arabic - ISO_8859_7, // 6: Teragram Greek - ISO_8859_8, // 7: Teragram Hebrew - ISO_8859_9, // 8: in BasisTech but not in Teragram - ISO_8859_10, // 9: in BasisTech but not in Teragram - JAPANESE_EUC_JP, // 10: Teragram EUC_JP - JAPANESE_SHIFT_JIS, // 11: Teragram SJS - JAPANESE_JIS, // 12: Teragram JIS - CHINESE_BIG5, // 13: Teragram BIG5 - CHINESE_GB, // 14: Teragram GB - CHINESE_EUC_CN, // 15: Teragram EUC-CN - KOREAN_EUC_KR, // 16: Teragram KSC - UNICODE_ENCODING, // 17: Teragram Unicode, changed to UNICODE_ENCODING - // from UNICODE, which is predefined by WINDOW - CHINESE_EUC_DEC, // 18: Teragram EUC - CHINESE_CNS, // 19: Teragram CNS - CHINESE_BIG5_CP950, // 20: Teragram BIG5_CP950 - JAPANESE_CP932, // 21: Teragram CP932 - UTF8, // 22 - UNKNOWN_ENCODING, // 23 - ASCII_7BIT, // 24: ISO_8859_1 with all characters <= 127. - // Should be present only in the crawler - // and in the repository, - // *never* as a result of Document::encoding(). - RUSSIAN_KOI8_R, // 25: Teragram KOI8R - RUSSIAN_CP1251, // 26: Teragram CP1251 - - //---------------------------------------------------------- - // These are _not_ output from teragram. Instead, they are as - // detected in the headers of usenet articles. - MSFT_CP1252, // 27: CP1252 aka MSFT euro ascii - RUSSIAN_KOI8_RU, // 28: CP21866 aka KOI8_RU, used for Ukrainian - MSFT_CP1250, // 29: CP1250 aka MSFT eastern european - ISO_8859_15, // 30: aka ISO_8859_0 aka ISO_8859_1 euroized - //---------------------------------------------------------- - - //---------------------------------------------------------- - // These are in BasisTech but not in Teragram. They are - // needed for new interface languages. Now detected by - // research langid - MSFT_CP1254, // 31: used for Turkish - MSFT_CP1257, // 32: used in Baltic countries - //---------------------------------------------------------- - - //---------------------------------------------------------- - //---------------------------------------------------------- - // New encodings detected by Teragram - ISO_8859_11, // 33: aka TIS-620, used for Thai - MSFT_CP874, // 34: used for Thai - MSFT_CP1256, // 35: used for Arabic - - //---------------------------------------------------------- - // Detected as ISO_8859_8 by Teragram, but can be found in META tags - MSFT_CP1255, // 36: Logical Hebrew Microsoft - ISO_8859_8_I, // 37: Iso Hebrew Logical - HEBREW_VISUAL, // 38: Iso Hebrew Visual - //---------------------------------------------------------- - - //---------------------------------------------------------- - // Detected by research langid - CZECH_CP852, // 39 - CZECH_CSN_369103, // 40: aka ISO_IR_139 aka KOI8_CS - MSFT_CP1253, // 41: used for Greek - RUSSIAN_CP866, // 42 - //---------------------------------------------------------- - HZ_ENCODING, - ISO2022_CN, - ISO2022_KR, - - NUM_ENCODINGS // Always keep this at the end. It is not a - // valid Encoding enum, it is only used to - // indicate the total number of Encodings. -}; - -const int kNumLanguages = NUM_LANGUAGES; -const int kNumEncodings = NUM_ENCODINGS; - -#endif // OMAHA_BASE_LANG_ENC_H_ diff --git a/omaha/base/libzip/config.h b/omaha/base/libzip/config.h new file mode 100644 index 0000000..d83abe3 --- /dev/null +++ b/omaha/base/libzip/config.h @@ -0,0 +1,92 @@ +#ifndef HAD_CONFIG_H +#define HAD_CONFIG_H +#ifndef _HAD_ZIPCONF_H +#include "zipconf.h" +#endif +/* BEGIN DEFINES */ +/* #undef HAVE___PROGNAME */ +#define HAVE__CHMOD +#define HAVE__CLOSE +#define HAVE__DUP +#define HAVE__FDOPEN +#define HAVE__FILENO +#define HAVE__OPEN +#define HAVE__SETMODE +/* #undef HAVE__SNPRINTF */ +#define HAVE__STRDUP +#define HAVE__STRICMP +#define HAVE__STRTOI64 +#define HAVE__STRTOUI64 +#define HAVE__UMASK +#define HAVE__UNLINK +/* #undef HAVE_CLONEFILE */ +/* #undef HAVE_COMMONCRYPTO */ +/* #undef HAVE_CRYPTO */ +/* #undef HAVE_FICLONERANGE */ +#define HAVE_FILENO +/* #undef HAVE_FSEEKO */ +/* #undef HAVE_FTELLO */ +/* #undef HAVE_GETPROGNAME */ +/* #undef HAVE_GNUTLS */ +/* #undef HAVE_LIBBZ2 */ +/* #undef HAVE_MBEDTLS */ +/* #undef HAVE_MKSTEMP */ +/* #undef HAVE_NULLABLE */ +#define HAVE_OPEN +/* #undef HAVE_OPENSSL */ +#define HAVE_SETMODE +/* #undef HAVE_SNPRINTF */ +/* #undef HAVE_SSIZE_T_LIBZIP */ +/* #undef HAVE_STRCASECMP */ +#define HAVE_STRDUP +#define HAVE_STRICMP +#define HAVE_STRTOLL +#define HAVE_STRTOULL +/* #undef HAVE_STRUCT_TM_TM_ZONE */ +#define HAVE_STDBOOL_H +/* #undef HAVE_STRINGS_H */ +/* #undef HAVE_UNISTD_H */ +#define HAVE_WINDOWS_CRYPTO +#define __INT8_LIBZIP 1 +#define INT8_T_LIBZIP 1 +#define UINT8_T_LIBZIP 1 +#define __INT16_LIBZIP 2 +#define INT16_T_LIBZIP 2 +#define UINT16_T_LIBZIP 2 +#define __INT32_LIBZIP 4 +#define INT32_T_LIBZIP 4 +#define UINT32_T_LIBZIP 4 +#define __INT64_LIBZIP 8 +#define INT64_T_LIBZIP 8 +#define UINT64_T_LIBZIP 8 +#define SHORT_LIBZIP 2 +#define INT_LIBZIP 4 +#define LONG_LIBZIP 4 +#define LONG_LONG_LIBZIP 8 +#define SIZEOF_OFF_T 4 +#define SIZE_T_LIBZIP 4 +/* #undef SSIZE_T_LIBZIP */ +/* #undef HAVE_DIRENT_H */ +/* #undef HAVE_FTS_H */ +/* #undef HAVE_NDIR_H */ +/* #undef HAVE_SYS_DIR_H */ +/* #undef HAVE_SYS_NDIR_H */ +/* #undef WORDS_BIGENDIAN */ +#define HAVE_SHARED +/* END DEFINES */ +#define PACKAGE "libzip" +#define VERSION "1.5.2" + +#ifndef HAVE_SSIZE_T_LIBZIP +# if SIZE_T_LIBZIP == INT_LIBZIP +typedef int ssize_t; +# elif SIZE_T_LIBZIP == LONG_LIBZIP +typedef long ssize_t; +# elif SIZE_T_LIBZIP == LONG_LONG_LIBZIP +typedef long long ssize_t; +# else +#error no suitable type for ssize_t found +# endif +#endif + +#endif /* HAD_CONFIG_H */ diff --git a/omaha/base/libzip/zipconf.h b/omaha/base/libzip/zipconf.h new file mode 100644 index 0000000..cd8ea20 --- /dev/null +++ b/omaha/base/libzip/zipconf.h @@ -0,0 +1,48 @@ +#ifndef _HAD_ZIPCONF_H +#define _HAD_ZIPCONF_H + +/* + zipconf.h -- platform specific include file + + This file was generated automatically by CMake + based on ../cmake-zipconf.h.in. + */ + +#define LIBZIP_VERSION "1.5.2" +#define LIBZIP_VERSION_MAJOR 1 +#define LIBZIP_VERSION_MINOR 5 +#define LIBZIP_VERSION_MICRO 2 + +/* #undef ZIP_STATIC */ + +#define _Nullable +#define _Nonnull + +#include + +typedef int8_t zip_int8_t; +typedef uint8_t zip_uint8_t; +typedef int16_t zip_int16_t; +typedef uint16_t zip_uint16_t; +typedef int32_t zip_int32_t; +typedef uint32_t zip_uint32_t; +typedef int64_t zip_int64_t; +typedef uint64_t zip_uint64_t; + +#define ZIP_INT8_MIN (-ZIP_INT8_MAX-1) +#define ZIP_INT8_MAX 0x7f +#define ZIP_UINT8_MAX 0xff + +#define ZIP_INT16_MIN (-ZIP_INT16_MAX-1) +#define ZIP_INT16_MAX 0x7fff +#define ZIP_UINT16_MAX 0xffff + +#define ZIP_INT32_MIN (-ZIP_INT32_MAX-1L) +#define ZIP_INT32_MAX 0x7fffffffL +#define ZIP_UINT32_MAX 0xffffffffLU + +#define ZIP_INT64_MIN (-ZIP_INT64_MAX-1LL) +#define ZIP_INT64_MAX 0x7fffffffffffffffLL +#define ZIP_UINT64_MAX 0xffffffffffffffffULL + +#endif /* zipconf.h */ diff --git a/omaha/base/localization.cc b/omaha/base/localization.cc deleted file mode 100644 index 5c1ffed..0000000 --- a/omaha/base/localization.cc +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// localization.cpp -// -// Localization functions for date-time, strings, locales, and numbers - -#include "omaha/base/localization.h" - -#include // SetThreadLocale -#include -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" -#include "omaha/base/string.h" -#include "omaha/base/time.h" -#include "omaha/base/utils.h" - -namespace omaha { - -// The maximum length for a date -#define kDateLengthMax 200 - -// The maximum length for chracter seperators -#define kDecimalSeparatorMaxLen 5 - -// Allow the unittest to override. -static LCID lcid_override = MAKELCID(-1, -1); - -void SetLcidOverride(const LCID & lcid_new) { - lcid_override = lcid_new; -} - -// We should call this, it allows for our override -LCID GetLiveLcid() { - if (lcid_override != MAKELCID(-1, -1)) - return lcid_override; - - return GetUserDefaultLCID(); -} - - -CString ShowDateInternal(const time64 & t, const LCID & lcid, - // Either type needs to be 0 or format needs to be - // NULL; both cannot be set simultaneously: - const DWORD type, const TCHAR * format ) { - SYSTEMTIME time = Time64ToLocalTime(t); - TCHAR buf[kDateLengthMax] = {_T('\0')}; - int num = ::GetDateFormat(lcid, type, &time, format, buf, kDateLengthMax); - ASSERT(num > 0, (_T("[localization::ShowDateInternal] - GetDateFormat ") - _T("failed"))); - - return CString(buf); -} - -CString ShowDateForLocale(const time64 & t, const LCID & lcid) { - return ShowDateInternal(t, lcid, DATE_SHORTDATE, NULL); -} - -CString ShowFormattedDateForLocale(const time64 & t, const LCID & lcid, - const TCHAR * format) { - return ShowDateInternal(t, lcid, 0, format); -} - - -CString ShowTimeInternal(const time64 & t, const LCID & lcid, - // Either type needs to be 0 or format needs to be - // NULL; both cannot be set simultaneously: - const DWORD type, const TCHAR * format) { - ASSERT(IsValidTime(t), (_T("[localization::ShowTimeInternal - Invalid ") - _T("time %llu"), t)); - - SYSTEMTIME time = Time64ToLocalTime(t); - TCHAR buf[kDateLengthMax] = {_T('\0')}; - int num = ::GetTimeFormat(lcid, type, &time, format, buf, kDateLengthMax); - ASSERT(num > 0, (_T("[localization::ShowTimeInternal - GetTimeFormat ") - _T("failed"))); - - return CString(buf); -} - -CString ShowTimeForLocale(const time64 & t, const LCID & lcid) { - return ShowTimeInternal(t, lcid, TIME_NOSECONDS, NULL); -} - -CString ShowFormattedTimeForLocale(const time64 & t, const LCID & lcid, - const TCHAR * format) { - return ShowTimeInternal(t, lcid, 0, format); -} - -// Show the long date and time [ie - Tuesday, March 20, 2004 5:15pm] -CString ShowDateTimeForLocale(const time64 & t, const LCID & lcid) { - return ShowDateForLocale(t, lcid) + _T(" ") + ShowTimeForLocale(t, lcid); -} - -// Get the long data and time in a (US English) format for logging -CString ShowDateTimeForLogging(const time64 & t) { - if (t == 0) { - return CString(); - } - const LCID lcid = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); - return ShowDateTimeForLocale(t, lcid); -} - -// Convert a number in string format to formatted string -static CString Show(const CString & in, const int decimal_places) { - NUMBERFMT nf = {0}; - TCHAR decimal_seperator[8] = {_T('\0')}; - TCHAR thousands_seperator[8] = {_T('\0')}; - GetNumberFormatForLCID(GetLiveLcid(), &nf, - decimal_seperator, arraysize(decimal_seperator), - thousands_seperator, arraysize(thousands_seperator)); - nf.NumDigits = decimal_places; - - TCHAR buf[kDateLengthMax] = {_T('\0')}; - int num = GetNumberFormat(GetLiveLcid(), // locale (current user locale) - 0, // options - in, // input string (see MSDN for chars) - &nf, // formatting information - buf, // formatted string buffer - kDateLengthMax); // size of buffer - - ASSERT(num > 0, (_T("GetNumberFormat failed: %s?"), in.GetString())); - - return CString(buf); -} - -// If we have a formatted number containing a decimal, and we want it to be -// an int -CString TrimDecimal(const CString & in) { - // Get the decimal seperator -- cache it as this is very slow - static LCID last_user_default_lcid = MAKELCID(-1, -1); - static TCHAR buf[kDecimalSeparatorMaxLen] = {_T('\0')}; - - LCID current_lcid = GetLiveLcid(); - if (last_user_default_lcid != current_lcid) { - int num = GetLocaleInfo(GetLiveLcid(), - LOCALE_SDECIMAL, - buf, - kDecimalSeparatorMaxLen); - ASSERT(num > 0, (L"GetLocaleInfo(.., LOCALE_SDECIMAL, ..) failed?")); - last_user_default_lcid = current_lcid; - } - - CString sep(buf); - - // Trim it if necessary - int pos = String_FindString(in, sep); - if (pos != -1) - return in.Left(pos); - - return in; -} - -// Number Functions -// Changes the number into a user viewable format for the current locale - -// TODO(omaha): Rename these functions into ShowNumberForLocale. -CString Show(const int i) { - return TrimDecimal(Show(itostr(i), 0)); -} - -CString Show(const uint32 u) { - return TrimDecimal(Show(itostr(u), 0)); -} - -CString Show(const double & d, const int decimal_places) { - return Show(String_DoubleToString(d, decimal_places), decimal_places); -} - -HRESULT SetLocaleToRfc1766(const TCHAR * rfc1766_locale) { - ASSERT1(rfc1766_locale != NULL); - - // Convert the RFC 1766 locale (eg, "fr-CA" for Canadian French to a - // Windows LCID (eg, 0x0c0c for Canadian French) - CComPtr pIM; - RET_IF_FAILED(pIM.CoCreateInstance(__uuidof(CMultiLanguage))); - - LCID lcid = 0; - CComBSTR rfc1766_locale_bstr(rfc1766_locale); - RET_IF_FAILED(pIM->GetLcidFromRfc1766(&lcid, (BSTR)rfc1766_locale_bstr)); - - return SetLocaleToLCID(lcid); -} - -HRESULT SetLocaleToLCID(const LCID & lcid) { - // Initialize the locales - // (in an attempt to cut down on our memory footprint, don't call - // the libc version of setlocale) - if (!::SetThreadLocale(lcid)) { - UTIL_LOG(LEVEL_ERROR, (_T("Unable to SetThreadLocale to lcid 0x%x"), - lcid)); - return E_FAIL; - } - - return S_OK; -} - -HRESULT GetLocaleAsLCID(LCID * lcid) { - ASSERT1(lcid != NULL); - - *lcid = GetThreadLocale(); - return S_OK; -} - -HRESULT GetLocaleAsRfc1766(CString * rfc1766_locale) { - ASSERT1(rfc1766_locale != NULL); - - LCID lcid = 0; - HRESULT hr = GetLocaleAsLCID(&lcid); - if (FAILED(hr)) { - return hr; - } - - CComPtr pIM; - RET_IF_FAILED(pIM.CoCreateInstance(__uuidof(CMultiLanguage))); - - CComBSTR bstr; - RET_IF_FAILED(pIM->GetRfc1766FromLcid(lcid, &bstr)); - - *rfc1766_locale = bstr; - return hr; -} - -HRESULT GetNumberFormatForLCID(const LCID & lcid, NUMBERFMT * fmt, - TCHAR * fmt_decimal_buf, - size_t decimal_buf_len, // including null char - TCHAR * fmt_thousand_buf, - size_t thousand_buf_len) { // including null - ASSERT1(fmt); - - if (decimal_buf_len > INT_MAX || thousand_buf_len > INT_MAX) { - return E_INVALIDARG; - } - - TCHAR buf[64] = {_T('\0')}; - const int buf_len = arraysize(buf); - - HRESULT hr = S_OK; - int retval = GetLocaleInfo(lcid, LOCALE_IDIGITS, buf, buf_len); - - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[localization::GetNumberFormatForLCID - ") - _T("Failed to load LOCALE_IDIGITS]"))); - hr = E_FAIL; - } else { - fmt->NumDigits = String_StringToInt(buf); - } - - retval = GetLocaleInfo(lcid, LOCALE_ILZERO, buf, buf_len); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_ILZERO]"))); - hr = E_FAIL; - } else { - fmt->LeadingZero = String_StringToInt(buf); - } - - retval = GetLocaleInfo(lcid, LOCALE_INEGNUMBER, buf, buf_len); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_INEGNUMBER]"))); - hr = E_FAIL; - } else { - fmt->NegativeOrder = String_StringToInt(buf); - } - - retval = GetLocaleInfo(lcid, LOCALE_SGROUPING, buf, buf_len); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_SGROUPING]"))); - hr = E_FAIL; - } else { - // A string terminated in ';0' is equivalent to the substring without - // the ';0', so just truncate the ';0' from the string - int semicolon_idx = String_ReverseFindChar(buf, _T(';')); - if (retval > semicolon_idx && buf[semicolon_idx + 1] == _T('0')) { - buf[semicolon_idx] = _T('\0'); - } - - if (String_FindChar(buf, _T(';')) != -1) { - // NUMBERFMT only allows values 0-9 or 32 for number grouping. If - // this locale has variable-length grouping rules (as indicated by - // the presence of ';[1-9]'), pass in the only variable-length - // grouping rule NUMBERFMT understands: 32. Note that '3;0' is - // considered a fixed-length grouping rule and handled above. - // This is a HACK. - fmt->Grouping = 32; - } else { - fmt->Grouping = String_StringToInt(buf); - } - } - - // GetLocaleInfo doesn't write more than 4 chars for this field (per MSDN) - retval = GetLocaleInfo(lcid, LOCALE_SDECIMAL, fmt_decimal_buf, - static_cast(decimal_buf_len)); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_SDECIMAL]"))); - hr = E_FAIL; - } else { - fmt->lpDecimalSep = fmt_decimal_buf; - } - - // GetLocaleInfo doesn't write more than 4 chars for this field (per MSDN) - retval = GetLocaleInfo(lcid, LOCALE_STHOUSAND, fmt_thousand_buf, - static_cast(thousand_buf_len)); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_STHOUSAND]"))); - hr = E_FAIL; - } else { - fmt->lpThousandSep = fmt_thousand_buf; - } - - retval = GetLocaleInfo(lcid, LOCALE_INEGNUMBER, buf, buf_len); - if (!retval) { - CORE_LOG(LEVEL_WARNING, (_T("[App::Impl::InitializeLocaleSettings - ") - _T("Failed to load LOCALE_INEGNUMBER]"))); - hr = E_FAIL; - } else { - fmt->NegativeOrder = String_StringToInt(buf); - } - - return hr; -} - -} // namespace omaha - diff --git a/omaha/base/localization.h b/omaha/base/localization.h deleted file mode 100644 index 87c8b14..0000000 --- a/omaha/base/localization.h +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// -// localization.h -// -// Localization functions for date-time, strings, locales, and numbers - -#ifndef OMAHA_BASE_LOCALIZATION_H_ -#define OMAHA_BASE_LOCALIZATION_H_ - -#include -#include "base/basictypes.h" -#include "omaha/base/time.h" - -namespace omaha { - -// Allows us to override LCIDs for unittests -void SetLcidOverride(const LCID & lcid_new); - - -// -// Date-time Functions -// - -// Show the time in the specified locale's default format. -// If you want to use the user's default format, use LOCALE_USER_DEFAULT -// for the locale [eg - "5:15:34 pm" is the US default] -CString ShowDateForLocale(const time64 & t, const LCID & lcid); - -// Show the time in the specified format for the specified locale. -// If you want to use the user's default format, use LOCALE_USER_DEFAULT -// for the locale [eg - "5:15:34 pm" is the US default] -CString ShowFormattedDateForLocale(const time64 & t, const LCID & lcid, - const TCHAR * format); - - -// Show the time in the specified locale's default format. -// If you want to use the user's default format, use LOCALE_USER_DEFAULT -// for the locale [eg - "5:15:34 pm" is the US default] -CString ShowTimeForLocale(const time64 & t, const LCID & lcid); - -// Show the time in the specified format for the specified locale. -// If you want to use the user's default format, use LOCALE_USER_DEFAULT -// for the locale [eg - "5:15:34 pm" is the US default] -CString ShowFormattedTimeForLocale(const time64 & t, const LCID & lcid, - const TCHAR * format); - -// Show the long date and time [ie - Tuesday, March 20, 2004 5:15pm] -CString ShowDateTimeForLocale(const time64 & t, const LCID & lcid); - -// Get the long data and time in a (US English) format for logging -CString ShowDateTimeForLogging(const time64 & t); - -// -// Number Functions -// - -// Changes the number into a user viewable format for the current locale -CString Show(const int i); -CString Show(const uint32 u); -CString Show(const double & d, const int decimal_places); - - -// -// Locale Name / LCID / RFC 1766 conversions -// -HRESULT SetLocaleToRfc1766(const TCHAR * rfc1766_locale); -HRESULT SetLocaleToLCID(const LCID & lcid); - -HRESULT GetLocaleAsLCID(LCID * lcid); -HRESULT GetLocaleAsRfc1766(CString * rfc1766_locale); - -HRESULT GetNumberFormatForLCID(const LCID & lcid, NUMBERFMT * fmt, - TCHAR * fmt_decimal_buf, - size_t decimal_buf_len, - TCHAR * fmt_thousand_buf, - size_t thousand_buf_len); - -} // namespace omaha - -#endif // OMAHA_BASE_LOCALIZATION_H_ diff --git a/omaha/base/localization_unittest.cc b/omaha/base/localization_unittest.cc deleted file mode 100644 index 253c279..0000000 --- a/omaha/base/localization_unittest.cc +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// localization_unittest.cpp -// -// Unit test functions for Localization - -#include "omaha/base/localization.h" -#include "omaha/base/string.h" -#include "omaha/base/time.h" -#include "omaha/testing/unit_test.h" - -using testing::Message; - -namespace omaha { - -// Test out the time display functions -void LocalizationTimeTest() { - CString time_str; - - // Lets process this a bit to give ourselves a known time. - SYSTEMTIME temp_time; - temp_time.wYear = 2004; - temp_time.wMonth = 4; - temp_time.wDayOfWeek = 1; - temp_time.wDay = 19; - temp_time.wHour = 19; - temp_time.wMinute = 18; - temp_time.wSecond = 17; - temp_time.wMilliseconds = 16; - - time64 override_time = SystemTimeToTime64(&temp_time); - - // Useful when debugging to confirm that this worked - SYSTEMTIME confirm = Time64ToSystemTime(override_time); - - // the need to check two different times below is because: - - // FileTimeToLocalFileTime uses the current settings for the time - // zone and daylight saving time. Therefore, if it is daylight - // saving time, this function will take daylight saving time into - // account, even if the time you are converting is in standard - // time. - // TODO(omaha): we may want to fix this. - - // Show just the time [ie -12:19pm] - time_str = ShowTimeForLocale(override_time, 1033 /* US english */); - ASSERT_TRUE(time_str == _T("12:18 PM") || time_str == _T("11:18 AM")) - << _T("Returned time string was ") << time_str.GetString(); - - // Show just the time [ie - 12:19:18pm] - time_str = ShowFormattedTimeForLocale(override_time, 1033, - _T("hh:mm:ss tt")); - ASSERT_TRUE(time_str == _T("12:18:17 PM") || time_str == _T("11:18:17 AM")) - << _T("Returned time string was ") << time_str.GetString(); - - // Try it out with a some different values to test out single digit - // minutes and such - temp_time.wHour = 15; - temp_time.wMinute = 4; - temp_time.wSecond = 3; - temp_time.wMilliseconds = 2; - override_time = SystemTimeToTime64(&temp_time); - - time_str = ShowTimeForLocale(override_time, 1033); - ASSERT_TRUE(time_str == _T("8:04 AM") || time_str == _T("7:04 AM")) - << _T("Returned time string was ") << time_str.GetString(); - - time_str = ShowFormattedTimeForLocale(override_time, 1033, - _T("hh:mm:ss tt")); - ASSERT_TRUE(time_str == _T("08:04:03 AM") || time_str == _T("07:04:03 AM")) - << _T("Returned time string was ") << time_str.GetString(); - - - // - // Check the date functionality - // - - temp_time.wYear = 2004; - temp_time.wMonth = 4; - temp_time.wDayOfWeek = 1; - temp_time.wDay = 19; - - // Show the short date - time_str = ShowDateForLocale(override_time, 1033); -// CHKM(time_str == _T("Monday, April 19, 2004"), - ASSERT_STREQ(time_str, _T("4/19/2004")); - - // Show the customized date - time_str = ShowFormattedDateForLocale(override_time, 1033, - _T("MMM d, yyyy")); - ASSERT_STREQ(time_str, _T("Apr 19, 2004")); - - // Try it out with a some different values to test out single dates and such - temp_time.wDay = 1; - override_time = SystemTimeToTime64(&temp_time); - - time_str = ShowFormattedDateForLocale(override_time, 1033, - _T("ddd, MMM dd")); - ASSERT_STREQ(time_str, _T("Thu, Apr 01")); - - time_str = ShowFormattedDateForLocale(override_time, 1033, _T("MM/dd/yyyy")); - ASSERT_STREQ(time_str, _T("04/01/2004")); -} - -// Test out the numbers and display functions -void LocalizationNumberTest() { - // Make sure we are using the normal american version - SetLcidOverride(1033); // the codepage for american english - - // Try some basics - ASSERT_STREQ(Show(1), _T("1")); - ASSERT_STREQ(Show(2), _T("2")); - - // Try some extremes - ASSERT_STREQ(Show(0), _T("0")); - ASSERT_STREQ(Show(kint32max), _T("2,147,483,647")); - ASSERT_STREQ(Show(-kint32max), _T("-2,147,483,647")); - ASSERT_STREQ(Show(kuint32max), _T("4,294,967,295")); - - // Try some doubles - ASSERT_STREQ(Show(0.3, 0), _T("0")); - ASSERT_STREQ(Show(0.3, 1), _T("0.3")); - ASSERT_STREQ(Show(0.3, 2), _T("0.30")); - ASSERT_STREQ(Show(0.3, 5), _T("0.30000")); - - // Try some with interesting rounding - ASSERT_STREQ(Show(0.159, 0), _T("0")); - ASSERT_STREQ(Show(0.159, 1), _T("0.1")); - ASSERT_STREQ(Show(0.159, 2), _T("0.15")); - ASSERT_STREQ(Show(0.159, 5), _T("0.15900")); - - // Try a nice whole number - ASSERT_STREQ(Show(12.0, 0), _T("12")); - ASSERT_STREQ(Show(12.0, 1), _T("12.0")); - ASSERT_STREQ(Show(12.0, 2), _T("12.00")); - ASSERT_STREQ(Show(12.0, 5), _T("12.00000")); -} - -TEST(LocalizationTest, Localization) { - LocalizationTimeTest(); - LocalizationNumberTest(); -} - -} // namespace omaha - diff --git a/omaha/base/lock_ptr.h b/omaha/base/lock_ptr.h deleted file mode 100644 index 74c424a..0000000 --- a/omaha/base/lock_ptr.h +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// lock_ptr.h -// -// A smart pointer to manage synchronized access to a shared resource. -// -// LockPtr provides a simple and concise syntax for accessing a -// shared resource. The LockPtr is a smart pointer and provides -// pointer operators -> and *. LockPtr does not have copy semantics and it is -// not intended to be stored in containers. Instead, instances of LockPtr are -// usually unamed or short-lived named variables. -// -// LockPtr uses an external lock, it acquires the lock in the constructor, and -// it guarantees the lock is released in the destructor. -// -// Since different types of locks have different method names, such as -// Enter/Exit or Lock/Unlock, etc, LockPtr uses an external customizable policy -// to bind to different operations. The external policy is a set of template -// functions that can be specialized for different types of locks, if needed. -// Think of this policy as an adapter between the lock type and the LockPtr. -// -// Usage: let's assume that we have the type below: -// -// class X { -// public: -// X() : i_(0) {} -// void f() {} -// -// private: -// int i_; -// -// friend int LockPtrTest(int, int); -// }; -// -// We have an instance of this type and an external lock instance to serialize -// the access to the X instance. -// -// Using LockPtr, the code is: -// -// X x; -// LLock local_lock; -// -// LockPtr(x, local_lock)->f(); -// -// For more example, please see the unit test of the module. - - - -#ifndef OMAHA_COMMON_LOCK_PTR_H_ -#define OMAHA_COMMON_LOCK_PTR_H_ - -#include "omaha/base/debug.h" - -namespace omaha { - -template -class LockPtr { - public: - template - LockPtr(T& obj, U& lock) - : pobj_(&obj), - plock_(&lock), - punlock_method_(&LockPtr::Unlock) { - AcquireLock(lock); - } - - ~LockPtr() { - ASSERT1(punlock_method_); - (this->*punlock_method_)(); - } - - // Pointer behavior - T& operator*() { - ASSERT1(pobj_); - return *pobj_; - } - - T* operator->() { - return pobj_; - } - - private: - // template method to restore the type of the lock and to call the - // release policy for the lock - template - void Unlock() { - ASSERT1(plock_); - U& lock = *(static_cast(plock_)); - ReleaseLock(lock); - } - - T* pobj_; // managed shared object - void* plock_; // type-less lock to control access to pobj_ - - void (LockPtr::*punlock_method_)(); // the address of the method to Unlock - - DISALLOW_EVIL_CONSTRUCTORS(LockPtr); -}; - -// template functions to define the policy of acquiring and releasing -// the locks. -template inline void AcquireLock(Lock& lock) { lock.Lock(); } -template inline void ReleaseLock(Lock& lock) { lock.Unlock(); } - -// specialization of policy for diferent types of locks. -#include "omaha/base/synchronized.h" -template <> void inline AcquireLock(CriticalSection& cs) { cs.Enter(); } -template <> void inline ReleaseLock(CriticalSection& cs) { cs.Exit(); } - -// Add more policy specializations below, if needed. - -} // namespace omaha - -#endif // OMAHA_COMMON_LOCK_PTR_H_ - diff --git a/omaha/base/lock_ptr_unittest.cc b/omaha/base/lock_ptr_unittest.cc deleted file mode 100644 index d1cce8b..0000000 --- a/omaha/base/lock_ptr_unittest.cc +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// lock_ptr_unittest.cpp - -#include "omaha/base/lock_ptr.h" -#include "omaha/base/synchronized.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -// Test type. -class X { - public: - X() : i_(0) {} - void f() { i_ = 10; } - - private: - int i_; - - friend class LockTest; - FRIEND_TEST(LockTest, X); -}; - -// A dummy lock just to test that locking and unlocking methods get called. -class DummyLock { - public: - DummyLock() : cnt_(0) {} - - void FakeLock() { ++cnt_; } - void FakeUnlock() { --cnt_; } - - private: - int cnt_; - - friend class LockTest; - FRIEND_TEST(LockTest, DummyLock); -}; - -// Specialization of the policy for the DummyLock. -template<> void AcquireLock(DummyLock& lock) { lock.FakeLock(); } -template<> void ReleaseLock(DummyLock& lock) { lock.FakeUnlock(); } - -// Empty test fixture. -class LockTest : public testing::Test {}; - -TEST_F(LockTest, X) { - // Create a few synchronization objects. - CriticalSection cs_lock; - LLock local_lock; - GLock global_lock; - ASSERT_TRUE(global_lock.Initialize(_T("test"))); - - // The instance to lock. - X x; - - // Lock the instance and call a method. - LockPtr(x, local_lock)->f(); - ASSERT_EQ((*LockPtr(x, cs_lock)).i_, 10); - - // Lock the instance and access a data member. - LockPtr(x, cs_lock)->i_ = 0; - ASSERT_EQ((*LockPtr(x, cs_lock)).i_, 0); - - // Lock the instance and call a method. - LockPtr(x, global_lock)->f(); - ASSERT_EQ((*LockPtr(x, cs_lock)).i_, 10); -} - -TEST_F(LockTest, DummyLock) { - DummyLock dummy_lock; - ASSERT_EQ(dummy_lock.cnt_, 0); - - // The instance to lock. - X x; - - { - LockPtr p(x, dummy_lock); - ASSERT_EQ(dummy_lock.cnt_, 1); - } - - ASSERT_EQ(dummy_lock.cnt_, 0); -} - -} // namespace omaha - diff --git a/omaha/base/logging.cc b/omaha/base/logging.cc index 2025622..a0d3420 100644 --- a/omaha/base/logging.cc +++ b/omaha/base/logging.cc @@ -52,6 +52,8 @@ #include #include #include +#include + #include "base/basictypes.h" #include "omaha/base/app_util.h" #include "omaha/base/const_debug.h" @@ -91,7 +93,7 @@ static bool history_buffer_full = false; // #define LC_ENTRY(lc_value) (L#lc_value), (lc_value) struct { - wchar_t* category_name; + const wchar_t* category_name; LogCategory category; } static LogCategoryNames[] = { LC_ENTRY(LC_UTIL), @@ -176,20 +178,20 @@ Logging* GetLogging() { Logging::Logging() : logging_initialized_(false), + is_initializing_(false), logging_enabled_(true), force_show_time_(false), show_time_(true), log_to_file_(true), + log_file_name_(kDefaultLogFileName), log_to_debug_out_(true), append_to_file_(true), logging_shutdown_(false), + config_file_path_(GetConfigurationFilePath()), num_writers_(0), file_log_writer_(NULL), debug_out_writer_(NULL), - etw_log_writer_(NULL), - is_initializing_(false), - log_file_name_(kDefaultLogFileName), - config_file_path_(GetConfigurationFilePath()) { + etw_log_writer_(NULL) { g_last_category_check_time = 0; for (int i = 0; i < max_writers; ++i) { writers_[i] = NULL; @@ -954,14 +956,14 @@ FileLogWriter* FileLogWriter::Create(const wchar_t* file_name, bool append) { } FileLogWriter::FileLogWriter(const wchar_t* file_name, bool append) - : initialized_(false), + : max_file_size_(kDefaultMaxLogFileSize), + initialized_(false), valid_(false), - file_name_(file_name), - log_file_mutex_(NULL), - log_file_(NULL), append_(append), - max_file_size_(kDefaultMaxLogFileSize), - log_file_wide_(kDefaultLogFileWide) { + log_file_wide_(kDefaultLogFileWide), + log_file_mutex_(NULL), + file_name_(file_name), + log_file_(NULL) { Logging* logger = GetLogging(); if (logger) { CString config_file_path = logger->GetCurrentConfigurationFilePath(); @@ -1171,7 +1173,7 @@ bool FileLogWriter::IsArchivePending() { if (!(res == ERROR_SUCCESS && type == REG_MULTI_SZ)) { return false; } - scoped_array buf(new byte[bytes]); + std::unique_ptr buf(new byte[bytes]); memset(buf.get(), 0, bytes); res = ::RegQueryValueEx(key, L"PendingFileRenameOperations", diff --git a/omaha/base/logging.h b/omaha/base/logging.h index e4f0cf1..2a6d714 100644 --- a/omaha/base/logging.h +++ b/omaha/base/logging.h @@ -236,7 +236,7 @@ class LogWriter { bool Unregister(); private: - DISALLOW_EVIL_CONSTRUCTORS(LogWriter); + DISALLOW_COPY_AND_ASSIGN(LogWriter); }; // A LogWriter that writes to a named file. @@ -281,7 +281,7 @@ class FileLogWriter : public LogWriter { friend class FileLogWriterTest; - DISALLOW_EVIL_CONSTRUCTORS(FileLogWriter); + DISALLOW_COPY_AND_ASSIGN(FileLogWriter); }; // A LogWriter that uses OutputDebugString() to write messages. @@ -293,7 +293,7 @@ class OutputDebugStringLogWriter : public LogWriter { static OutputDebugStringLogWriter* Create(); virtual void OutputMessage(const OutputInfo* info); private: - DISALLOW_EVIL_CONSTRUCTORS(OutputDebugStringLogWriter); + DISALLOW_COPY_AND_ASSIGN(OutputDebugStringLogWriter); }; // A LogWriter that overrides the settings in trconfig.ini and sends messages @@ -314,7 +314,7 @@ class OverrideConfigLogWriter : public LogWriter { LogLevel level_; LogWriter* log_writer_; bool force_logging_enabled_; - DISALLOW_EVIL_CONSTRUCTORS(OverrideConfigLogWriter); + DISALLOW_COPY_AND_ASSIGN(OverrideConfigLogWriter); }; // This log writer outputs to Event Tracing for Windows. @@ -478,7 +478,7 @@ class Logging { friend class HistoryTest; - DISALLOW_EVIL_CONSTRUCTORS(Logging); + DISALLOW_COPY_AND_ASSIGN(Logging); }; // In order to make the logging macro LC_LOG work out we need to pass a @@ -511,11 +511,11 @@ class LoggingHelper { private: Logging* logger_; - DWORD writer_mask_; - LogLevel level_; LogCategory category_; + LogLevel level_; + DWORD writer_mask_; - DISALLOW_EVIL_CONSTRUCTORS(LoggingHelper); + DISALLOW_COPY_AND_ASSIGN(LoggingHelper); }; // Getter for the Logging singleton class. diff --git a/omaha/base/logging/logging.cc b/omaha/base/logging/logging.cc index 77864ae..330a270 100644 --- a/omaha/base/logging/logging.cc +++ b/omaha/base/logging/logging.cc @@ -16,17 +16,19 @@ // This is code that defines the backend for the new LogMessage definition // and the functions that the client application can call to control logging. -#include -#include +#include "omaha/base/logging/logging.h" + #include -#include +#include #include +#include #include -#include "omaha/base/logging/logging.h" +#include +#include namespace logging { -const char* const log_severity_names[LOG_NUM_SEVERITIES] = { +constexpr const char* const log_severity_names[LOG_NUM_SEVERITIES] = { "INFO", "WARNING", "ERROR", "FATAL" }; int min_log_level = 0; @@ -178,7 +180,7 @@ void DisplayDebugMessage(const std::string& str) { int charcount = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); if (!charcount) return; - scoped_array cmdline(new wchar_t[charcount]); + std::unique_ptr cmdline(new wchar_t[charcount]); if (!MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, cmdline.get(), charcount)) return; @@ -351,7 +353,7 @@ std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) { return out; // convert - scoped_array buf(new char[charcount]); + std::unique_ptr buf(new char[charcount]); WideCharToMultiByte(CP_UTF8, 0, wstr, -1, buf.get(), charcount, NULL, NULL); return out << buf.get(); } diff --git a/omaha/base/logging/logging.h b/omaha/base/logging/logging.h index bec0dbe..f02918f 100644 --- a/omaha/base/logging/logging.h +++ b/omaha/base/logging/logging.h @@ -18,15 +18,10 @@ #include #include -#pragma warning(push) -// C4365: conversion from 'type_1' to 'type_2', signed/unsigned mismatch -#pragma warning(disable : 4365) #include -#pragma warning(pop) #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" // This file provides logging facility for Windows client apps. // @@ -462,7 +457,7 @@ class LogMessage { LogSeverity severity_; std::ostrstream stream_; - DISALLOW_EVIL_CONSTRUCTORS(LogMessage); + DISALLOW_COPY_AND_ASSIGN(LogMessage); }; // A non-macro interface to the log facility; (useful diff --git a/omaha/base/md5.cc b/omaha/base/md5.cc deleted file mode 100644 index dfd6068..0000000 --- a/omaha/base/md5.cc +++ /dev/null @@ -1,455 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -/* - * md5_opt.c V1.0 - optimized md5c.c from RFC1321 reference implementation - * - * Copyright (c) 1995 University of Southern California. - * All rights reserved. - * - * Redistribution and use in source and binary forms are permitted - * provided that the above copyright notice and this paragraph are - * duplicated in all such forms and that any documentation, advertising - * materials, and other materials related to such distribution and use - * acknowledge that the software was developed by the University of - * Southern California, Information Sciences Institute. The name of the - * University may not be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - J. Touch / touch@isi.edu - 5/1/95 - -*/ -/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm - */ - -/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. -*/ - -#include "omaha/base/md5.h" -#include "omaha/base/debug.h" - -namespace omaha { - -#if (defined(i386) || defined (__i386__) || defined (_M_IX86) || defined(__alpha)) // little-endian -#undef REORDER -#else -#define REORDER 1 -#endif - -// Constants for MD5Transform routine -#define kS11 7 -#define kS12 12 -#define kS13 17 -#define kS14 22 -#define kS21 5 -#define kS22 9 -#define kS23 14 -#define kS24 20 -#define kS31 4 -#define kS32 11 -#define kS33 16 -#define kS34 23 -#define kS41 6 -#define kS42 10 -#define kS43 15 -#define kS44 21 - -static void MD5Transform (uint32 [4], unsigned char [64]); -static void Encode (unsigned char *, uint32 *, unsigned int); -#ifdef REORDER -static void Decode (uint32 *, unsigned char *, unsigned int); -#endif - -// SELECTANY static unsigned char PADDING[64] = { -static unsigned char PADDING[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -// F, G, H and I are basic MD5 functions. -#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) -#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define I(x, y, z) ((y) ^ ((x) | (~z))) - -// ROTATE_LEFT rotates x left n bits. -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) - -// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. -// Rotation is separate from addition to prevent recomputation. -#define FF(a, b, c, d, x, s, ac) { \ - (a) += F ((b), (c), (d)) + (x) + (uint32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define GG(a, b, c, d, x, s, ac) { \ - (a) += G ((b), (c), (d)) + (x) + (uint32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define HH(a, b, c, d, x, s, ac) { \ - (a) += H ((b), (c), (d)) + (x) + (uint32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } -#define II(a, b, c, d, x, s, ac) { \ - (a) += I ((b), (c), (d)) + (x) + (uint32)(ac); \ - (a) = ROTATE_LEFT ((a), (s)); \ - (a) += (b); \ - } - -// MD5 initialization. Begins an MD5 operation, writing a new context. -void MD5Init (MD5_CTX *context) { - ASSERT(context, (L"")); - - context->count[0] = context->count[1] = 0; - // Load magic initialization constants. - context->state[0] = 0x67452301; - context->state[1] = 0xefcdab89; - context->state[2] = 0x98badcfe; - context->state[3] = 0x10325476; -} - -// MD5 block update operation. Continues an MD5 message-digest -// operation, processing another message block, and updating the context. -void MD5Update (MD5_CTX *context, unsigned char *input, unsigned int inputLen) { - ASSERT(input, (L"")); - ASSERT(context, (L"")); - - unsigned int i, index, partLen; - - // Compute number of bytes mod 64 - index = (unsigned int)((context->count[0] >> 3) & 0x3F); - - // Update number of bits - if ((context->count[0] += ((uint32)inputLen << 3)) < ((uint32)inputLen << 3)) - context->count[1]++; - - context->count[1] += ((uint32)inputLen >> 29); - partLen = 64 - index; - - // Transform as many times as possible - if (inputLen >= partLen) { - memcpy ((POINTER)&context->buffer[index], (POINTER)input, partLen); - MD5Transform (context->state, context->buffer); - - for (i = partLen; i + 63 < inputLen; i += 64) MD5Transform (context->state, &input[i]); - index = 0; - } - else - i = 0; - - // Buffer remaining input - memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i); -} - -// MD5 finalization. Ends an MD5 message-digest operation, writing the -// the message digest and zeroizing the context. -void MD5Final (unsigned char digest[16], MD5_CTX *context) { - ASSERT(context, (L"")); - - unsigned char bits[8]; - unsigned int index, padLen; - - // Save number of bits - Encode (bits, context->count, 8); - - // Pad out to 56 mod 64. - index = (unsigned int)((context->count[0] >> 3) & 0x3f); - padLen = (index < 56) ? (56 - index) : (120 - index); - MD5Update (context, PADDING, padLen); - - // Append length (before padding) - MD5Update (context, bits, 8); - // Store state in digest - Encode (digest, context->state, 16); - - // Zeroize sensitive information. - memset ((POINTER)context, 0, sizeof (*context)); -} - -// MD5 basic transformation. Transforms state based on block. -void MD5Transform (uint32 state[4], unsigned char block[64]) { - // USC/ISI J. Touch - encourage pushing state variables into registers - register uint32 a = state[0], b = state[1], c = state[2], d = state[3]; - - /* USC/ISI J. Touch - decode and using copied data vs. direct use of input buffer - depends on whether reordering is required, which is a combination - of the byte order of the architecture and the command-line option - override - */ - -#ifdef REORDER - uint32 x[16]; - - Decode (x, block, 64); - - /* Round 1 */ - FF (a, b, c, d, x[ 0], kS11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], kS12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], kS13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], kS14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], kS11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], kS12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], kS13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], kS14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], kS11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], kS12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], kS13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], kS14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], kS11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], kS12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], kS13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], kS14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, x[ 1], kS21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], kS22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], kS23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], kS24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], kS21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], kS22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], kS23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], kS24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], kS21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], kS22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], kS23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], kS24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], kS21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], kS22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], kS23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], kS24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, x[ 5], kS31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], kS32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], kS33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], kS34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], kS31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], kS32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], kS33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], kS34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], kS31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], kS32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], kS33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], kS34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], kS31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], kS32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], kS33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], kS34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, x[ 0], kS41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], kS42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], kS43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], kS44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], kS41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], kS42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], kS43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], kS44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], kS41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], kS42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], kS43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], kS44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], kS41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], kS42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], kS43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], kS44, 0xeb86d391); /* 64 */ - -#else - // USC/ISI J. Touch - // omit reordering, and use the input block as source data - /* Round 1 */ - FF (a, b, c, d, ((uint32 *)block)[ 0], kS11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, ((uint32 *)block)[ 1], kS12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, ((uint32 *)block)[ 2], kS13, 0x242070db); /* 3 */ - FF (b, c, d, a, ((uint32 *)block)[ 3], kS14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, ((uint32 *)block)[ 4], kS11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, ((uint32 *)block)[ 5], kS12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, ((uint32 *)block)[ 6], kS13, 0xa8304613); /* 7 */ - FF (b, c, d, a, ((uint32 *)block)[ 7], kS14, 0xfd469501); /* 8 */ - FF (a, b, c, d, ((uint32 *)block)[ 8], kS11, 0x698098d8); /* 9 */ - FF (d, a, b, c, ((uint32 *)block)[ 9], kS12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, ((uint32 *)block)[10], kS13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, ((uint32 *)block)[11], kS14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, ((uint32 *)block)[12], kS11, 0x6b901122); /* 13 */ - FF (d, a, b, c, ((uint32 *)block)[13], kS12, 0xfd987193); /* 14 */ - FF (c, d, a, b, ((uint32 *)block)[14], kS13, 0xa679438e); /* 15 */ - FF (b, c, d, a, ((uint32 *)block)[15], kS14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG (a, b, c, d, ((uint32 *)block)[ 1], kS21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, ((uint32 *)block)[ 6], kS22, 0xc040b340); /* 18 */ - GG (c, d, a, b, ((uint32 *)block)[11], kS23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, ((uint32 *)block)[ 0], kS24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, ((uint32 *)block)[ 5], kS21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, ((uint32 *)block)[10], kS22, 0x2441453); /* 22 */ - GG (c, d, a, b, ((uint32 *)block)[15], kS23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, ((uint32 *)block)[ 4], kS24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, ((uint32 *)block)[ 9], kS21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, ((uint32 *)block)[14], kS22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, ((uint32 *)block)[ 3], kS23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, ((uint32 *)block)[ 8], kS24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, ((uint32 *)block)[13], kS21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, ((uint32 *)block)[ 2], kS22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, ((uint32 *)block)[ 7], kS23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, ((uint32 *)block)[12], kS24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH (a, b, c, d, ((uint32 *)block)[ 5], kS31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, ((uint32 *)block)[ 8], kS32, 0x8771f681); /* 34 */ - HH (c, d, a, b, ((uint32 *)block)[11], kS33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, ((uint32 *)block)[14], kS34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, ((uint32 *)block)[ 1], kS31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, ((uint32 *)block)[ 4], kS32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, ((uint32 *)block)[ 7], kS33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, ((uint32 *)block)[10], kS34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, ((uint32 *)block)[13], kS31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, ((uint32 *)block)[ 0], kS32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, ((uint32 *)block)[ 3], kS33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, ((uint32 *)block)[ 6], kS34, 0x4881d05); /* 44 */ - HH (a, b, c, d, ((uint32 *)block)[ 9], kS31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, ((uint32 *)block)[12], kS32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, ((uint32 *)block)[15], kS33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, ((uint32 *)block)[ 2], kS34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II (a, b, c, d, ((uint32 *)block)[ 0], kS41, 0xf4292244); /* 49 */ - II (d, a, b, c, ((uint32 *)block)[ 7], kS42, 0x432aff97); /* 50 */ - II (c, d, a, b, ((uint32 *)block)[14], kS43, 0xab9423a7); /* 51 */ - II (b, c, d, a, ((uint32 *)block)[ 5], kS44, 0xfc93a039); /* 52 */ - II (a, b, c, d, ((uint32 *)block)[12], kS41, 0x655b59c3); /* 53 */ - II (d, a, b, c, ((uint32 *)block)[ 3], kS42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, ((uint32 *)block)[10], kS43, 0xffeff47d); /* 55 */ - II (b, c, d, a, ((uint32 *)block)[ 1], kS44, 0x85845dd1); /* 56 */ - II (a, b, c, d, ((uint32 *)block)[ 8], kS41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, ((uint32 *)block)[15], kS42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, ((uint32 *)block)[ 6], kS43, 0xa3014314); /* 59 */ - II (b, c, d, a, ((uint32 *)block)[13], kS44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, ((uint32 *)block)[ 4], kS41, 0xf7537e82); /* 61 */ - II (d, a, b, c, ((uint32 *)block)[11], kS42, 0xbd3af235); /* 62 */ - II (c, d, a, b, ((uint32 *)block)[ 2], kS43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, ((uint32 *)block)[ 9], kS44, 0xeb86d391); /* 64 */ -#endif // REORDER - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - -#ifdef REORDER - memset ((POINTER)x, 0, sizeof (x)); // zero sensitive information -#endif -} - -// Encodes input (uint32) into output (unsigned char). Assumes len is a multiple of 4. -void Encode (unsigned char *output, uint32 *input, unsigned int len) { - ASSERT(input, (L"")); - ASSERT(output, (L"")); - - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) { - output[j] = (unsigned char)(input[i] & 0xff); - output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); - output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); - output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); - } -} - -#ifdef REORDER - -// Decodes input (unsigned char) into output (uint32). Assumes len is a multiple of 4. -void Decode (uint32 *output, unsigned char *input, unsigned int len) { - ASSERT(input, (L"")); - ASSERT(output, (L"")); - - UNREFERENCED_PARAMETER(len); - - register uint32 out,other; - - // for (i = 0, j = 0; j < len; i++, j += 4) - // output[i] = ((uint32)input[j]) | (((uint32)input[j+1]) << 8) | - // (((uint32)input[j+2]) << 16) | (((uint32)input[j+3]) << 24); - - // USC/ISI J. Touch - // these are optimized swap routines, in C code they cost more in "computation" operations, but less in - // "loads" than the above code, and run substantially faster as a result -#if (!defined(hpux)) -#define swapbyte(src,dst) { \ - out = ROTATE_LEFT((src),16); \ - other = out >> 8; \ - other &= 0x00ff00ff; \ - out &= 0x00ff00ff; \ - out <<= 8; \ - (dst) = out | other; \ - } -#else -#define swapbyte(src,dst) { \ - (dst) = (ROTATE_LEFT((src),8) & 0x00ff00ff) | ROTATE_LEFT((src) & 0x00ff00ff,24); \ - } -#endif - - // USC/ISI J. Touch - // unroll the loop above, because the code runs faster with constants for indices than even with variable indices - // as conventional (automatic) unrolling would perform (!) - swapbyte(((uint32 *)input)[0],output[0]); - swapbyte(((uint32 *)input)[1],output[1]); - swapbyte(((uint32 *)input)[2],output[2]); - swapbyte(((uint32 *)input)[3],output[3]); - swapbyte(((uint32 *)input)[4],output[4]); - swapbyte(((uint32 *)input)[5],output[5]); - swapbyte(((uint32 *)input)[6],output[6]); - swapbyte(((uint32 *)input)[7],output[7]); - swapbyte(((uint32 *)input)[8],output[8]); - swapbyte(((uint32 *)input)[9],output[9]); - swapbyte(((uint32 *)input)[10],output[10]); - swapbyte(((uint32 *)input)[11],output[11]); - swapbyte(((uint32 *)input)[12],output[12]); - swapbyte(((uint32 *)input)[13],output[13]); - swapbyte(((uint32 *)input)[14],output[14]); - swapbyte(((uint32 *)input)[15],output[15]); -} - -#endif // #ifdef REORDER - -} // namespace omaha - diff --git a/omaha/base/md5.h b/omaha/base/md5.h deleted file mode 100644 index a688c3d..0000000 --- a/omaha/base/md5.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -/* MD5.H - header file for MD5C.C -*/ - -/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. -*/ - -/* GLOBAL.H - RSAREF types and constants -*/ - -#ifndef TR_COMMON_MD5_H_ -#define TR_COMMON_MD5_H_ - -#include "base/basictypes.h" - -namespace omaha { - -/* POINTER defines a generic pointer type */ -typedef unsigned char *POINTER; - -/* MD5 context */ -typedef struct { - uint32 state[4]; /* state (ABCD) */ - uint32 count[2]; /* number of bits, modulo 2^64 (lsb first) */ - unsigned char buffer[64]; /* input buffer */ -} MD5_CTX; - -void MD5Init (MD5_CTX *); -void MD5Update (MD5_CTX *, unsigned char *, unsigned int); -void MD5Final (unsigned char [16], MD5_CTX *); - -} // namespace omaha - -#endif // TR_COMMON_MD5_H_ diff --git a/omaha/base/md5_unittest.cc b/omaha/base/md5_unittest.cc deleted file mode 100644 index 8102eb3..0000000 --- a/omaha/base/md5_unittest.cc +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include -#include "omaha/base/debug.h" -#include "omaha/base/md5.h" -#include "omaha/base/string.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -void CheckMD5(char* string, TCHAR* correct_digest) { - ASSERT_TRUE(correct_digest); - ASSERT_TRUE(string); - - MD5_CTX context; - MD5Init(&context); - MD5Update(&context, - reinterpret_cast(string), - static_cast(strlen (string))); - unsigned char digest[16] = {0}; - MD5Final(digest, &context); - - const DWORD digest_len = 32 + 1; - TCHAR digest_string[digest_len] = {0}; - - for(int i = 0; i < 16; i++) { - SafeStrCat(digest_string, SPRINTF(_T("%02x"), digest[i]), digest_len); - } - - ASSERT_STREQ(digest_string, correct_digest); -} - -TEST(Md5Test, MD5) { - CheckMD5("", _T("d41d8cd98f00b204e9800998ecf8427e")); - CheckMD5("a", _T("0cc175b9c0f1b6a831c399e269772661")); - CheckMD5("abc", _T("900150983cd24fb0d6963f7d28e17f72")); - CheckMD5("message digest", _T("f96b697d7cb7938d525a2f31aaf161d0")); - CheckMD5("abcdefghijklmnopqrstuvwxyz", _T("c3fcd3d76192e4007dfb496cca67e13b")); - CheckMD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", _T("d174ab98d277d9f5a5611c2c9f419d9f")); - CheckMD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890", _T("57edf4a22be3c955ac49da2e2107b67a")); -} - -} // namespace omaha - diff --git a/omaha/base/object_factory.h b/omaha/base/object_factory.h index b74b21c..82f917a 100644 --- a/omaha/base/object_factory.h +++ b/omaha/base/object_factory.h @@ -58,7 +58,7 @@ class Factory { typedef std::map Map; Map id_to_creators_; - DISALLOW_EVIL_CONSTRUCTORS(Factory); + DISALLOW_COPY_AND_ASSIGN(Factory); }; } // namespace omaha diff --git a/omaha/base/path.cc b/omaha/base/path.cc index 7110868..5d14caf 100644 --- a/omaha/base/path.cc +++ b/omaha/base/path.cc @@ -86,141 +86,13 @@ HRESULT FindFilesEx(const CString& dir, } // namespace detail. -// Get the starting path from the command string -CString GetStartingPathFromString(const CString& s) { - CString path; - CString str(s); - TrimCString(str); - - int len = str.GetLength(); - if (len > 0) { - if (str[0] == _T('"')) { - // For something like: "c:\Program Files\...\" ... - int idx = String_FindChar(str.GetString() + 1, _T('"')); - if (idx != -1) - path.SetString(str.GetString() + 1, idx); - } else { - // For something like: c:\PRGRA~1\... ... - int idx = String_FindChar(str, _T(' ')); - path.SetString(str, idx == -1 ? len : idx); - } - } - - return path; -} - -// Get the trailing path from the command string -CString GetTrailingPathFromString(const CString& s) { - CString path; - CString str(s); - TrimCString(str); - - int len = str.GetLength(); - if (len > 0) { - if (str[len - 1] == _T('"')) { - // For something like: regsvr32 /u /s "c:\Program Files\..." - str.Truncate(len - 1); - int idx = String_ReverseFindChar(str, _T('"')); - if (idx != -1) - path.SetString(str.GetString() + idx + 1, len - idx - 1); - } else { - // For something like: regsvr32 /u /s c:\PRGRA~1\... - int idx = String_ReverseFindChar(str, _T(' ')); - if (idx != -1) - path.SetString(str.GetString() + idx + 1, len - idx - 1); - } - } - - return path; -} - -// Get the file from the command string -HRESULT GetFileFromCommandString(const TCHAR* s, CString* file) { - ASSERT1(file); - - if (!s || !*s) { - return E_INVALIDARG; - } - - CString str(s); - TrimCString(str); - - // Handle the string starting with quotation mark - // For example: "C:\Program Files\WinZip\WINZIP32.EXE" /uninstall - if (str[0] == _T('"')) { - int idx_quote = str.Find(_T('"'), 1); - if (idx_quote != -1) { - file->SetString(str.GetString() + 1, idx_quote - 1); - return S_OK; - } else { - return E_FAIL; - } - } - - // Handle the string starting with "regsvr32" - // For example: regsvr32 /u /s "c:\program files\google\googletoolbar3.dll" - if (String_StartsWith(str, kRegSvr32Cmd1, true) || - String_StartsWith(str, kRegSvr32Cmd2, true)) { - file->SetString(GetTrailingPathFromString(str)); - return S_OK; - } - - // Handle the string starting with "rundll32" - // For example: "rundll32.exe setupapi.dll,InstallHinfSection DefaultUninstall 132 C:\WINDOWS\INF\PCHealth.inf" // NOLINT - if (String_StartsWith(str, kRunDll32Cmd1, true) || - String_StartsWith(str, kRunDll32Cmd2, true)) { - int idx_space = str.Find(_T(' ')); - ASSERT1(idx_space != -1); - int idx_comma = str.Find(_T(','), idx_space + 1); - if (idx_comma != -1) { - file->SetString(str.GetString() + idx_space + 1, - idx_comma - idx_space - 1); - TrimCString(*file); - return S_OK; - } else { - return E_FAIL; - } - } - - // Handle the string starting with "msiexec" - // For example: MsiExec.exe /I{25A13826-8E4A-4FBF-AD2B-776447FE9646} - if (String_StartsWith(str, kMsiExecCmd1, true) || - String_StartsWith(str, kMsiExecCmd2, true)) { - return E_FAIL; - } - - // Otherwise, try to find the file till reaching ".exe" - // For example: "C:\Program Files\Google\Google Desktop Search\GoogleDesktopSetup.exe -uninstall" // NOLINT - const int dot_exe_length = static_cast(_tcslen(kDotExe)); - for (int i = 0; i < str.GetLength(); ++i) { - if (String_StartsWith(str.GetString() + i, kDotExe, true)) { - file->SetString(str, i + dot_exe_length); - return S_OK; - } - } - - // As last resort, return the part from the beginning to first space found. - int idx = str.Find(_T(' ')); - if (idx == -1) { - file->SetString(str); - } else { - file->SetString(str, idx); - } - - return S_OK; -} - // Expands the string with embedded special folder variables. // TODO(omaha): This function seems to have a very specific purpose, which // is not used in our code base. Consider removing it. HRESULT ExpandStringWithSpecialFolders(CString* str) { ASSERT(str, (L"")); -#pragma warning(push) -// construction of local static object is not thread-safe -#pragma warning(disable : 4640) static std::map g_special_folders_mapping; -#pragma warning(pop) if (g_special_folders_mapping.size() == 0) { RET_IF_FAILED( @@ -236,53 +108,6 @@ HRESULT ExpandStringWithSpecialFolders(CString* str) { return S_OK; } -// Internal helper method for normalizing a path -HRESULT NormalizePathInternal(const TCHAR* path, CString* normalized_path) { - // We use '|' to separate fields - CString field; - int bar_idx = String_FindChar(path, _T('|')); - if (bar_idx == -1) - field = path; - else - field.SetString(path, bar_idx); - - if (IsRegistryPath(field)) { - CString key_name, value_name; - RET_IF_FAILED(RegSplitKeyvalueName(field, &key_name, &value_name)); - - CString reg_value; - RET_IF_FAILED(RegKey::GetValue(key_name, value_name, ®_value)); - normalized_path->Append(reg_value); - } else { - RET_IF_FAILED(ExpandStringWithSpecialFolders(&field)); - normalized_path->Append(field); - } - - if (bar_idx != -1) - return NormalizePathInternal(path + bar_idx + 1, normalized_path); - else - return S_OK; -} - -// Normalize a path -HRESULT NormalizePath(const TCHAR* path, CString* normalized_path) { - ASSERT1(normalized_path); - - normalized_path->Empty(); - - if (path) { - HRESULT hr = NormalizePathInternal(path, normalized_path); - if (FAILED(hr)) { - normalized_path->Empty(); - UTIL_LOG(LE, (_T("[NormalizePath - unable to normalize path][%s][0x%x]"), - path, hr)); - } - return hr; - } else { - return S_OK; - } -} - CString ConcatenatePath(const CString& path1, const CString& path2) { CString ret(path1); @@ -391,19 +216,6 @@ void UnenclosePath(CString* path) { } } -void RemoveMismatchedEndQuoteInDirectoryPath(CString* directory_path) { - ASSERT1(directory_path); - - if (directory_path->GetLength() <= 1) { - return; - } - - ASSERT1(directory_path->GetAt(0) != _T('"')); - if (directory_path->GetAt(directory_path->GetLength() - 1) == _T('"')) { - directory_path->Truncate(directory_path->GetLength() - 1); - } -} - HRESULT ShortPathToLongPath(const CString& short_path, CString* long_path) { ASSERT1(long_path); diff --git a/omaha/base/path.h b/omaha/base/path.h index 3a88c1c..4645454 100644 --- a/omaha/base/path.h +++ b/omaha/base/path.h @@ -23,21 +23,9 @@ namespace omaha { -// Get the starting path from the command string -CString GetStartingPathFromString(const CString& s); - -// Get the trailing path from the command string -CString GetTrailingPathFromString(const CString& s); - -// Get the file from the command string -HRESULT GetFileFromCommandString(const TCHAR* s, CString* file); - // Expands the string with embedded special folder variables HRESULT ExpandStringWithSpecialFolders(CString* str); -// Normalize a path -HRESULT NormalizePath(const TCHAR* path, CString* normalized_path); - // Concatenate two paths together CString ConcatenatePath(const CString& path1, const CString& path2); @@ -71,16 +59,6 @@ CString EnclosePathIfExe(const CString& module_path); // remove any double quotation masks from an enclosed path void UnenclosePath(CString* path); -// Removes a trailing double quote from a path. ::CommandLineToArgvW() has some -// strange treatment for quotation marks and backslashes, as detailed here: -// http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx -// -// So an argument containing a directory path with a trailing backslash: -// <> -// is incorrectly parsed with a double-quote at the end: -// <>. -void RemoveMismatchedEndQuoteInDirectoryPath(CString* directory_path); - // Converts the short path name to long name. HRESULT ShortPathToLongPath(const CString& short_path, CString* long_path); diff --git a/omaha/base/pe_utils.cc b/omaha/base/pe_utils.cc deleted file mode 100644 index ce4ca22..0000000 --- a/omaha/base/pe_utils.cc +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Utility functions related to PE files (executables) - -#include "omaha/base/pe_utils.h" - -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/scoped_any.h" - -namespace omaha { - -namespace { - -// Not really necessary as long as running on x86 architecture throughout, but -// what the hell -#if defined(BIG_ENDIAN) -uint32 GetUint32LE(void const * const p) { - uint8 const * const pu = reinterpret_cast(p); - uint32 i = pu[0] | pu[1]<<8 | pu[2]<<16 | pu[3]<<24; - return i; -} - -void PutUint32LE(uint32 i, void * const p) { - uint8 * const pu = reinterpret_cast(p); - pu[0] = i & 0xff; - pu[1] = (i >> 8) & 0xff; - pu[2] = (i >> 16) & 0xff; - pu[3] = (i >> 24) & 0xff; -} -#else // LITTLE_ENDIAN -inline uint32 GetUint32LE(void const * const p) { - uint32 const * const pu = reinterpret_cast(p); - return *pu; -} - -inline void PutUint32LE(uint32 i, void * const p) { - uint32 * const pu = reinterpret_cast(p); - *pu = i; -} -#endif - -// Magic PE constants -const uint32 kPEHeaderOffset = 60; -const uint32 kPEHeaderChecksumOffset = 88; -const uint32 kPEHeaderSizeMin = 160; -const char magic_EXE_header[] = "MZ\0\0"; -const char magic_PE_header[] = "PE\0\0"; - -} // namespace - -HRESULT SetPEChecksum(const TCHAR *filename, uint32 checksum) { - // Write the checksum field of the Windows NT-specific "optional" header. - // Use Windows API calls rather than C library calls so that it will be - // really a small routine when used in the stub executable. - - ASSERT(filename, (L"")); - - scoped_hfile file(::CreateFile(filename, - GENERIC_READ | GENERIC_WRITE, - 0, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL)); - if (!file) - return HRESULTFromLastError(); - - size_t size = ::GetFileSize(get(file), NULL); - if (size == INVALID_FILE_SIZE) - return HRESULTFromLastError(); - - scoped_file_mapping mapping(::CreateFileMapping(get(file), - NULL, - PAGE_READWRITE, - 0, - 0, - NULL)); - if (!mapping) - return HRESULTFromLastError(); - - scoped_file_view file_data(::MapViewOfFile(get(mapping), - FILE_MAP_WRITE, - 0, - 0, - size)); - if (!file_data) - return HRESULTFromLastError(); - - uint8 * image = reinterpret_cast(get(file_data)); - - return SetPEChecksumToBuffer(image, size, checksum); -} - -HRESULT GetPEChecksum(const TCHAR *filename, uint32 * checksum) { - // Read the checksum field out of the Windows NT-specific "optional" header. - // Use Windows API calls rather than C library calls so that it will be - // really a small routine when used in the stub executable. - - ASSERT(filename, (L"")); - ASSERT(checksum, (L"")); - - scoped_hfile file(::CreateFile(filename, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_READONLY, - NULL)); - if (!file) - return HRESULTFromLastError(); - - size_t size = ::GetFileSize(get(file), NULL); - if (size == INVALID_FILE_SIZE) - return HRESULTFromLastError(); - - scoped_file_mapping mapping(::CreateFileMapping(get(file), - NULL, - PAGE_READONLY, - 0, - 0, - NULL)); - if (!mapping) - return HRESULTFromLastError(); - - scoped_file_view file_data(::MapViewOfFile(get(mapping), - FILE_MAP_READ, - 0, - 0, - size)); - if (!file_data) - return HRESULTFromLastError(); - - uint8 * image = reinterpret_cast(get(file_data)); - - return GetPEChecksumFromBuffer(image, size, checksum); -} - -HRESULT SetPEChecksumToBuffer(uint8 *buffer, size_t size, uint32 checksum) { - // Sanity checks - if (size < 64) { - ASSERT(false, (L"File too short to be valid executable")); - return E_FAIL; - } - - uint32 x = GetUint32LE(magic_EXE_header); - if (::memcmp(buffer, &x, 2)) { - ASSERT(false, (L"Missing executable's magic number")); - return E_FAIL; - } - - uint32 peheader = GetUint32LE(buffer + kPEHeaderOffset); - if (size < peheader + kPEHeaderSizeMin) { - ASSERT(false, (L"Too small given PE header size")); - return E_FAIL; - } - - x = GetUint32LE(magic_PE_header); - if (::memcmp(buffer + peheader, &x, 4)) { - ASSERT(false, (L"Missing PE header magic number")); - return E_FAIL; - } - - // Finally, write the checksum - PutUint32LE(checksum, &x); - ::memcpy(buffer + peheader + kPEHeaderChecksumOffset, &x, 4); - - return S_OK; -} - -HRESULT GetPEChecksumFromBuffer(const unsigned char *buffer, - size_t size, - uint32 *checksum) { - // Sanity checks - if (size < 64) { - ASSERT(false, (L"File too short to be valid executable")); - return E_FAIL; - } - - uint32 x = GetUint32LE(magic_EXE_header); - if (::memcmp(buffer, &x, 2)) { - ASSERT(false, (L"Missing executable's magic number")); - return E_FAIL; - } - - uint32 peheader = GetUint32LE(buffer + kPEHeaderOffset); - if (size < peheader + kPEHeaderSizeMin) { - ASSERT(false, (L"Too small given PE header size")); - return E_FAIL; - } - - x = GetUint32LE(magic_PE_header); - if (::memcmp(buffer + peheader, &x, 4)) { - ASSERT(false, (L"Missing PE header magic number")); - return E_FAIL; - } - - // Finally, read the checksum - - *checksum = GetUint32LE(buffer + peheader + kPEHeaderChecksumOffset); - - return S_OK; -} - -} // namespace omaha - diff --git a/omaha/base/pe_utils.h b/omaha/base/pe_utils.h deleted file mode 100644 index cc969c6..0000000 --- a/omaha/base/pe_utils.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Utility functions related to PE files (executables) - -#ifndef OMAHA_COMMON_PE_UTILS_H_ -#define OMAHA_COMMON_PE_UTILS_H_ - -#include -#include "base/basictypes.h" - -namespace omaha { - -HRESULT SetPEChecksum(const TCHAR *filename, uint32 checksum); - -HRESULT SetPEChecksumToBuffer(unsigned char *buffer, - size_t size, uint32 checksum); - -HRESULT GetPEChecksum(const TCHAR *filename, uint32 * checksum); - -HRESULT GetPEChecksumFromBuffer(const unsigned char *buffer, - size_t size, - uint32 *checksum); - -} // namespace omaha - -#endif // OMAHA_COMMON_PE_UTILS_H_ diff --git a/omaha/base/pe_utils_unittest.cc b/omaha/base/pe_utils_unittest.cc deleted file mode 100644 index 2384e44..0000000 --- a/omaha/base/pe_utils_unittest.cc +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Unittests for pe_utils - - -#include "omaha/base/debug.h" -#include "omaha/base/file.h" -#include "omaha/base/pe_utils.h" -#include "omaha/base/utils.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -TEST(PEUtilsTest, PEUtils) { - // Get some known directories - CString windows_dir; - CString temp_dir; - DWORD dw = ::GetEnvironmentVariable(L"SystemRoot", - CStrBuf(windows_dir, MAX_PATH), MAX_PATH); - ASSERT_TRUE(dw); - dw = ::GetEnvironmentVariable(L"TEMP", CStrBuf(temp_dir, MAX_PATH), MAX_PATH); - ASSERT_TRUE(dw); - - // Get a known executable to play with - CString notepad(windows_dir + L"\\NOTEPAD.EXE"); - ASSERT_TRUE(File::Exists(notepad)); - - CString temp_exe(temp_dir + L"\\pe_utils_test.exe"); - if (File::Exists(temp_exe)) { - File::Remove(temp_exe); - } - ASSERT_FALSE(File::Exists(temp_exe)); - ASSERT_SUCCEEDED(File::Copy(notepad, temp_exe, true)); - - // Stomp on its checksum and check the result - const unsigned int kChk1 = 0xFEE1BAD; - const unsigned int kChk2 = 0x600DF00D; - - unsigned int checksum = 0; - - // Test Get/SetPEChecksum - ASSERT_SUCCEEDED(SetPEChecksum(temp_exe, kChk1)); - ASSERT_SUCCEEDED(GetPEChecksum(temp_exe, &checksum)); - ASSERT_EQ(kChk1, checksum); - - ASSERT_SUCCEEDED(SetPEChecksum(temp_exe, kChk2)); - ASSERT_SUCCEEDED(GetPEChecksum(temp_exe, &checksum)); - ASSERT_EQ(kChk2, checksum); - - // Test GetPEChecksumFromBuffer/SetPEChecksumToBuffer - std::vector buffer; - ASSERT_SUCCEEDED(ReadEntireFile(temp_exe, 0, &buffer)); - - size_t buffer_data_len = buffer.size(); - uint8 *buffer_data = reinterpret_cast(&buffer.front()); - - ASSERT_SUCCEEDED(SetPEChecksumToBuffer(buffer_data, buffer_data_len, kChk1)); - ASSERT_SUCCEEDED(GetPEChecksumFromBuffer(buffer_data, - buffer_data_len, - &checksum)); - ASSERT_EQ(kChk1, checksum); - - ASSERT_SUCCEEDED(SetPEChecksumToBuffer(buffer_data, buffer_data_len, kChk2)); - ASSERT_SUCCEEDED(GetPEChecksumFromBuffer(buffer_data, - buffer_data_len, - &checksum)); - ASSERT_EQ(kChk2, checksum); - - // Clean up - ASSERT_SUCCEEDED(File::Remove(temp_exe)); -} - -} // namespace omaha - diff --git a/omaha/base/popup_menu.cc b/omaha/base/popup_menu.cc deleted file mode 100644 index 327b32b..0000000 --- a/omaha/base/popup_menu.cc +++ /dev/null @@ -1,464 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/popup_menu.h" - -#include -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/logging.h" -#include "omaha/base/string.h" -#include "omaha/base/utils.h" - -namespace omaha { - -// Hold owner draw data -struct OwnerDrawData { - HFONT font; - CString text; - HICON icon; - - OwnerDrawData(HFONT f, const TCHAR* t, HICON i) { - font = f; - text = t; - icon = i; - } -}; - - -// Default constructor -PopupMenu::PopupMenu() - : wnd_(NULL) { - reset(menu_, ::CreatePopupMenu()); - ASSERT1(menu_); -} - -// Constructor -PopupMenu::PopupMenu(HINSTANCE inst, const TCHAR* name) - : wnd_(NULL) { - LoadFromResource(inst, name); - ASSERT1(menu_); -} - -// Destructor -PopupMenu::~PopupMenu() { -} - -// Load from resource -bool PopupMenu::LoadFromResource(HINSTANCE inst, const TCHAR* name) { - reset(menu_, GetSubMenu(reinterpret_cast(::LoadMenu(inst, name)), 0)); - return get(menu_) != NULL; -} - -// Append menu item -bool PopupMenu::AppendMenuItem(int menu_item_id, const TCHAR* text) { - return AppendMenuItem(menu_item_id, text, NULL); -} - -// Append menu item -bool PopupMenu::AppendMenuItem(int menu_item_id, - const TCHAR* text, - const MenuItemDrawStyle* style) { - int count = ::GetMenuItemCount(get(menu_)); - if (count == -1) - return false; - - return InsertMenuItem(menu_item_id, count, true, text, style); -} - -// Append separator -bool PopupMenu::AppendSeparator() { - return AppendMenuItem(-1, NULL, NULL); -} - -// Insert menu item -bool PopupMenu::InsertMenuItem(int menu_item_id, - int before_item, - bool by_pos, - const TCHAR* text) { - return InsertMenuItem(menu_item_id, before_item, by_pos, text, NULL); -} - -// Helper function that populates the MENUITEMINFO structure and sets -// accelerator keys for OWNERDRAW menu items -MENUITEMINFO PopupMenu::PrepareMenuItemInfo(int menu_item_id, const TCHAR* text, - const MenuItemDrawStyle* style) { - // Fill in the MENUITEMINFO structure - MENUITEMINFO menuitem_info; - SetZero(menuitem_info); - menuitem_info.cbSize = sizeof(MENUITEMINFO); - menuitem_info.wID = menu_item_id; - if (text == NULL) { - menuitem_info.fMask = MIIM_FTYPE | MIIM_ID; - menuitem_info.fType = MFT_SEPARATOR; - } else { - if (!style) { - menuitem_info.fMask = MIIM_STRING | MIIM_ID; - menuitem_info.fType = MFT_STRING; - menuitem_info.dwTypeData = const_cast(text); - } else { - // Handle bold font style - HFONT font = NULL; - if (style->is_bold) { - font = GetBoldFont(); - } - - // Remove '&' if it is there - CString text_str(text); - int pos = String_FindChar(text_str, _T('&')); - if (pos != -1) { - if (pos + 1 < text_str.GetLength()) { - accelerator_keys_.Add(Char_ToLower(text_str[pos + 1]), menu_item_id); - } - ReplaceCString(text_str, _T("&"), _T("")); - } - - // Set owner-draw related properties - OwnerDrawData* data = new OwnerDrawData(font, text_str, style->icon); - menuitem_info.fMask = MIIM_FTYPE | MIIM_DATA | MIIM_ID; - menuitem_info.fType = MFT_OWNERDRAW; - menuitem_info.dwItemData = reinterpret_cast(data); - } - } - - return menuitem_info; -} - -// Insert menu item -bool PopupMenu::InsertMenuItem(int menu_item_id, - int before_item, - bool by_pos, - const TCHAR* text, - const MenuItemDrawStyle* style) { - MENUITEMINFO menuitem_info = PrepareMenuItemInfo(menu_item_id, text, style); - if (!::InsertMenuItem(get(menu_), before_item, by_pos, &menuitem_info)) - return false; - - return Redraw(); -} - -// Insert separator -bool PopupMenu::InsertSeparator(int before_item, bool by_pos) { - return InsertMenuItem(-1, before_item, by_pos, NULL, NULL); -} - -// Modify a given menu item -bool PopupMenu::ModifyMenuItem(int menu_item, bool by_pos, const TCHAR* text, - const MenuItemDrawStyle* style) { - // Get OWNERDRAW data for later deletion - MENUITEMINFO menuitem_info; - SetZero(menuitem_info); - menuitem_info.cbSize = sizeof(MENUITEMINFO); - menuitem_info.fMask = MIIM_FTYPE | MIIM_DATA; - if (!::GetMenuItemInfo(get(menu_), menu_item, by_pos, &menuitem_info)) { - return false; - } - - OwnerDrawData* old_owner_data = NULL; - if ((menuitem_info.fType & MFT_OWNERDRAW) && menuitem_info.dwItemData) { - old_owner_data = - reinterpret_cast(menuitem_info.dwItemData); - } - - // Remove old accelerator mapping - int menu_item_id = by_pos ? ::GetMenuItemID(get(menu_), menu_item) : - menu_item; - int key_pos = accelerator_keys_.FindVal(menu_item_id); - if (key_pos != -1) { - accelerator_keys_.RemoveAt(key_pos); - } - - // Set new menu item info - menuitem_info = PrepareMenuItemInfo(menu_item_id, text, style); - if (!::SetMenuItemInfo(get(menu_), menu_item, by_pos, &menuitem_info)) { - return false; - } - - // Delete old owner draw data - if (old_owner_data) { - delete old_owner_data; - } - - // Redraw - return Redraw(); -} - -// Remove a menu item -bool PopupMenu::RemoveMenuItem(int menu_item, bool by_pos) { - // Get OWNERDRAW data for later deletion - MENUITEMINFO menuitem_info; - SetZero(menuitem_info); - menuitem_info.cbSize = sizeof(MENUITEMINFO); - menuitem_info.fMask = MIIM_FTYPE | MIIM_DATA; - if (!::GetMenuItemInfo(get(menu_), menu_item, by_pos, &menuitem_info)) { - return false; - } - - OwnerDrawData* old_owner_data = NULL; - if ((menuitem_info.fType & MFT_OWNERDRAW) && menuitem_info.dwItemData) { - old_owner_data = - reinterpret_cast(menuitem_info.dwItemData); - } - - // Remove the menu item - if (!::RemoveMenu(get(menu_), menu_item, by_pos ? MF_BYPOSITION : - MF_BYCOMMAND)) { - return false; - } - - // Remove old accelerator mapping - int menu_item_id = by_pos ? ::GetMenuItemID(get(menu_), menu_item) : - menu_item; - int key_pos = accelerator_keys_.FindVal(menu_item_id); - if (key_pos != -1) { - accelerator_keys_.RemoveAt(key_pos); - } - - // Delete old owner draw data - if (old_owner_data) { - delete old_owner_data; - } - - // Redraw - return Redraw(); -} - -// Enable menu item -bool PopupMenu::EnableMenuItem(int menu_item, bool by_pos, bool enabled) { - if (::EnableMenuItem(get(menu_), menu_item, - (by_pos ? MF_BYPOSITION : MF_BYCOMMAND) | - (enabled ? MF_ENABLED : MF_GRAYED)) == -1) - return false; - - return Redraw(); -} - -// Get menu state -bool PopupMenu::GetMenuState(int menu_item, bool by_pos, int* menu_state) { - int state = ::GetMenuState(get(menu_), - menu_item, by_pos ? MF_BYPOSITION : MF_BYCOMMAND); - if (menu_state) - *menu_state = state; - return state != -1; -} - -// Exists a menu item -bool PopupMenu::ExistsMenuItem(int menu_item_id) { - return GetMenuState(menu_item_id, false, NULL); -} - -// Redraw menu -bool PopupMenu::Redraw() { - if (!wnd_) - return true; - - return ::DrawMenuBar(wnd_) == TRUE; -} - -// Track menu -bool PopupMenu::Track() { - ASSERT1(wnd_); - - // If we don't set it to be foreground, it will not stop tracking even - // if we click outside of menu. - ::SetForegroundWindow(wnd_); - - POINT point = {0, 0}; - VERIFY(::GetCursorPos(&point), (_T(""))); - - uint32 kFlags = TPM_LEFTALIGN | - TPM_RETURNCMD | - TPM_NONOTIFY | - TPM_LEFTBUTTON | - TPM_VERTICAL; - int command = ::TrackPopupMenuEx(get(menu_), - kFlags, - point.x, point.y, wnd_, NULL); - - if (command != 0) - ::SendMessage(wnd_, WM_COMMAND, command, 0); - - return true; -} - -// Handle WM_MEASUREITEM message -bool PopupMenu::OnMeasureItem(MEASUREITEMSTRUCT* mi) { - ASSERT1(wnd_); - - // Get owner draw data - ASSERT1(mi->itemData); - OwnerDrawData* data = reinterpret_cast(mi->itemData); - - // Get the DC - scoped_hdc dc; - reset(dc, ::GetDC(wnd_)); - - // Select the font - HFONT old_font = reinterpret_cast(::SelectObject(get(dc), data->font)); - if (!old_font) - return false; - - // compute the size of the text - SIZE size = {0, 0}; - bool success = ::GetTextExtentPoint32(get(dc), - data->text.GetString(), - data->text.GetLength(), - &size) != 0; - if (success) { - mi->itemWidth = size.cx; - mi->itemHeight = size.cy; - } - - // deselect the title font - ::SelectObject(get(dc), old_font); - - return success; -} - -// Handle WM_MDRAWITEM message -bool PopupMenu::OnDrawItem(DRAWITEMSTRUCT* di) { - ASSERT1(di); - - // Get owner draw data - ASSERT1(di->itemData); - OwnerDrawData* data = reinterpret_cast(di->itemData); - - // Select the font - HFONT prev_font = NULL; - if (data->font) { - prev_font = reinterpret_cast(::SelectObject(di->hDC, data->font)); - if (!prev_font) { - return false; - } - } - - // Draw the text per the menuitem state - int fg_color_idx = - (di->itemState & ODS_DISABLED) ? - COLOR_GRAYTEXT : - ((di->itemState & ODS_SELECTED) ? COLOR_HIGHLIGHTTEXT : COLOR_MENUTEXT); - - int bg_color_idx = - (di->itemState & ODS_SELECTED) ? COLOR_HIGHLIGHT : COLOR_MENU; - - bool success = DrawText(data->text, di, fg_color_idx, bg_color_idx); - - // Restore the original font - if (prev_font) { - ::SelectObject(di->hDC, prev_font); - } - - // Compute the width and height - int height = di->rcItem.bottom - di->rcItem.top + 1; - int width = static_cast(::GetSystemMetrics(SM_CXMENUCHECK) * - (static_cast(height) / ::GetSystemMetrics(SM_CYMENUCHECK))); - - // Draw the icon - // TODO(omaha): Draw a grayed icon when the menuitem is disabled - if (success && data->icon) { - success = ::DrawIconEx(di->hDC, - di->rcItem.left, - di->rcItem.top, - data->icon, - width, - height, - 0, - NULL, - DI_NORMAL) != 0; - } - - return success; -} - -// Draw the text -bool PopupMenu::DrawText(const CString& text, - DRAWITEMSTRUCT* di, - int fg_color_idx, - int bg_color_idx) { - // Set the appropriate foreground and background colors - COLORREF prev_fg_color = 0, prev_bg_color = 0; - prev_fg_color = ::SetTextColor(di->hDC, ::GetSysColor(fg_color_idx)); - if (prev_fg_color == CLR_INVALID) { - return false; - } - prev_bg_color = ::SetBkColor(di->hDC, ::GetSysColor(bg_color_idx)); - if (prev_bg_color == CLR_INVALID) { - return false; - } - - // Draw the text - bool success = ::ExtTextOut( - di->hDC, - di->rcItem.left + ::GetSystemMetrics(SM_CXMENUCHECK) + 4, - di->rcItem.top, - ETO_OPAQUE, - &di->rcItem, - text.GetString(), - text.GetLength(), - NULL) == TRUE; - - // Restore the original colors - ::SetTextColor(di->hDC, prev_fg_color); - ::SetBkColor(di->hDC, prev_bg_color); - - return success; -} - -// Handle WM_MENUCHAR message -int PopupMenu::OnMenuChar(TCHAR key) { - int pos = accelerator_keys_.FindKey(Char_ToLower(key)); - if (pos != -1) - return GetMenuPosFromID(accelerator_keys_.GetValueAt(pos)); - else - return -1; -} - -HFONT PopupMenu::GetBoldFont() { - if (!bold_font_) { - NONCLIENTMETRICS ncm; - SetZero(ncm); - ncm.cbSize = sizeof(NONCLIENTMETRICS); - if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &ncm, 0)) { - ncm.lfMenuFont.lfWeight = FW_BOLD; - reset(bold_font_, ::CreateFontIndirect(&ncm.lfMenuFont)); - } else { - UTIL_LOG(LEVEL_ERROR, (_T("[PopupMenu::GetBoldFont]") - _T("[failed to get system menu font][0x%x]"), - HRESULTFromLastError())); - } - } - - ASSERT1(bold_font_); - - return get(bold_font_); -} - -// Get menu pos from ID -int PopupMenu::GetMenuPosFromID(int id) { - ASSERT1(id >= 0); - int count = ::GetMenuItemCount(get(menu_)); - if (count > 0) { - for (int pos = 0; pos < count; ++pos) { - if (::GetMenuItemID(get(menu_), pos) == static_cast(id)) { - return pos; - } - } - } - - return -1; -} - -} // namespace omaha - diff --git a/omaha/base/popup_menu.h b/omaha/base/popup_menu.h deleted file mode 100644 index 9428381..0000000 --- a/omaha/base/popup_menu.h +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_COMMON_POPUP_MENU_H_ -#define OMAHA_COMMON_POPUP_MENU_H_ - -#include "omaha/base/debug.h" -#include "omaha/base/scoped_any.h" - -namespace omaha { - -struct MenuItemDrawStyle { - bool is_bold; - HICON icon; - - MenuItemDrawStyle() : is_bold(false), icon(NULL) {} -}; - - -class PopupMenu { - public: - PopupMenu(); - PopupMenu(HINSTANCE inst, const TCHAR* name); - - ~PopupMenu(); - - // Load from resource - bool LoadFromResource(HINSTANCE inst, const TCHAR* name); - - // Append menu item - bool AppendMenuItem(int menu_item_id, const TCHAR* text); - bool AppendMenuItem(int menu_item_id, - const TCHAR* text, - const MenuItemDrawStyle* style); - - // Append separator - bool AppendSeparator(); - - // Helper function that populates the MENUITEMINFO structure and sets - // accelerator keys for OWNERDRAW menu items - MENUITEMINFO PrepareMenuItemInfo(int menu_item_id, - const TCHAR* text, - const MenuItemDrawStyle* style); - - // Insert menu item - bool InsertMenuItem(int menu_item_id, - int before_item, - bool by_pos, - const TCHAR* text); - - bool InsertMenuItem(int menu_item_id, - int before_item, - bool by_pos, - const TCHAR* text, - const MenuItemDrawStyle* style); - - // Insert separator - bool InsertSeparator(int before_item, bool by_pos); - - // Modify a given menu item - bool ModifyMenuItem(int menu_item, - bool by_pos, - const TCHAR* text, - const MenuItemDrawStyle* style); - - // Remove menu item - bool RemoveMenuItem(int menu_item, bool by_pos); - - // Enable menu item - bool EnableMenuItem(int menu_item, bool by_pos, bool enabled); - - // Get menu state - bool GetMenuState(int menu_item, bool by_pos, int* menu_state); - - // Exists a menu item - bool ExistsMenuItem(int menu_item_id); - - // Get menu pos from ID - int GetMenuPosFromID(int id); - - // Attach to the window - void AttachToWindow(HWND wnd) { - ASSERT1(wnd); - wnd_ = wnd; - } - - // Redraw menu - bool Redraw(); - - // Track menu - bool Track(); - - // Handle WM_MEASUREITEM message - bool OnMeasureItem(MEASUREITEMSTRUCT* mi); - - // Handle WM_MDRAWITEM message - bool OnDrawItem(DRAWITEMSTRUCT* di); - - // Handle WM_MENUCHAR message - int OnMenuChar(TCHAR key); - - private: - // Get bold font - HFONT GetBoldFont(); - - // Draw the text - bool DrawText(const CString& text, - DRAWITEMSTRUCT* di, - int fg_color_idx, - int bg_color_idx); - - HWND wnd_; // HWND associated with this menu - scoped_hmenu menu_; // HMENU associated with this menu - - // Bold font used in owner draw menu-item - scoped_hfont bold_font_; - - // Accelerator key used in owner draw menu-item - CSimpleMap accelerator_keys_; - - DISALLOW_EVIL_CONSTRUCTORS(PopupMenu); -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_POPUP_MENU_H_ - diff --git a/omaha/base/preprocessor_fun.h b/omaha/base/preprocessor_fun.h index c2f6c12..2bdc988 100644 --- a/omaha/base/preprocessor_fun.h +++ b/omaha/base/preprocessor_fun.h @@ -14,23 +14,8 @@ // ======================================================================== // PP_STRINGIZE - expands arguments before stringizing -// PP_STRINGIZE(PP_CAT(a,b)) => "ab" #define PP_STRINGIZE(text) PP_STRINGIZE_A((text)) #define PP_STRINGIZE_A(arg) PP_STRINGIZE_B ## (arg) #define PP_STRINGIZE_B(arg) PP_STRINGIZE_I ## arg #define PP_STRINGIZE_I(text) #text - -// T_PP_STRINGIZE - expands arguments before stringizing -// T_PP_STRINGIZE(PP_CAT(a,b)) => _T("ab") - -#define T_PP_STRINGIZE(text) T_PP_STRINGIZE_A((text)) -#define T_PP_STRINGIZE_A(arg) T_PP_STRINGIZE_B ## (arg) -#define T_PP_STRINGIZE_B(arg) T_PP_STRINGIZE_I ## arg -#define T_PP_STRINGIZE_I(text) _T(#text) - -// PP_CAT - concatenates arguments after they have been expanded -// PP_CAT(x, PP_CAT(y,z)) => xyz -#define PP_CAT(a,b) PP_CAT_I(a,b) -#define PP_CAT_I(a,b) PP_CAT_J(a##b) -#define PP_CAT_J(arg) arg diff --git a/omaha/base/proc_utils.cc b/omaha/base/proc_utils.cc index 6f82422..f9f04bd 100644 --- a/omaha/base/proc_utils.cc +++ b/omaha/base/proc_utils.cc @@ -21,7 +21,8 @@ #include "omaha/base/proc_utils.h" #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/app_util.h" #include "omaha/base/const_config.h" #include "omaha/base/const_timeouts.h" @@ -30,16 +31,16 @@ #include "omaha/base/logging.h" #include "omaha/base/process.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" #include "omaha/base/window_utils.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { ProcessTerminator::ProcessTerminator(const CString& process_name) - : recursion_level_(0), - process_name_(process_name), + : process_name_(process_name), + recursion_level_(0), flash_window_(false), session_id_(INVALID_SESSION_ID) { MakeLowerCString(process_name_); @@ -47,9 +48,9 @@ ProcessTerminator::ProcessTerminator(const CString& process_name) ProcessTerminator::ProcessTerminator(const CString& process_name, const CString& user_sid) - : recursion_level_(0), + : process_name_(process_name), + recursion_level_(0), user_sid_(user_sid), - process_name_(process_name), flash_window_(false), session_id_(INVALID_SESSION_ID) { MakeLowerCString(process_name_); @@ -58,11 +59,11 @@ ProcessTerminator::ProcessTerminator(const CString& process_name, ProcessTerminator::ProcessTerminator(const CString& process_name, const CString& user_sid, int session_id) - : recursion_level_(0), + : process_name_(process_name), + recursion_level_(0), user_sid_(user_sid), - session_id_(session_id), - process_name_(process_name), - flash_window_(false) { + flash_window_(false), + session_id_(session_id) { MakeLowerCString(process_name_); } @@ -87,7 +88,7 @@ bool ProcessTerminator::WaitForProcessInstancesToDie( UTIL_LOG(L3, (_T("[WaitForProcessInstancesToDie]"))); const size_t size = process_handles_.size(); ASSERT1(size <= MAXIMUM_WAIT_OBJECTS); - scoped_array handles(new HANDLE[size]); + std::unique_ptr handles(new HANDLE[size]); for (size_t i = 0; i < size; i++) { handles[i] = process_handles_[i]; @@ -266,7 +267,7 @@ bool ProcessTerminator::PrepareToKill(uint32 method_mask) { } // We already handled the case when we don't have enough privileges to open // the process. So if we have less handles than process ids -> some of the - // processes have died since we made a snapshot untill the time we tried to + // processes have died since we made a snapshot until the time we tried to // open handles. We need to do another snapshot and try to open handles one // more time. We need number of handles and number of ids to be equal. // We can do it with recursion. The idea is: make the next snapshot and open diff --git a/omaha/base/proc_utils.h b/omaha/base/proc_utils.h index 4cc78c6..3a584c8 100644 --- a/omaha/base/proc_utils.h +++ b/omaha/base/proc_utils.h @@ -134,7 +134,7 @@ class ProcessTerminator { int session_id_; // Disable copy constructor and assignment operator. - DISALLOW_EVIL_CONSTRUCTORS(ProcessTerminator); + DISALLOW_COPY_AND_ASSIGN(ProcessTerminator); }; // Application calling this function will be shut down diff --git a/omaha/base/process.cc b/omaha/base/process.cc index e3a723c..05a6b34 100644 --- a/omaha/base/process.cc +++ b/omaha/base/process.cc @@ -23,6 +23,8 @@ #include #include #include + +#include #include #ifndef NT_SUCCESS @@ -34,7 +36,6 @@ #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/system_info.h" @@ -51,10 +52,10 @@ const int kMaxCmdLineLengthBytes = 4096; // Constructor Process::Process(const TCHAR* name, const TCHAR* window_class_name) - : process_id_(0), - exit_code_(0), - number_of_restarts_(static_cast(-1)), + : number_of_restarts_(static_cast(-1)), name_(name), + process_id_(0), + exit_code_(0), shutdown_event_(NULL) { ASSERT1(name); command_line_ = name; @@ -63,10 +64,10 @@ Process::Process(const TCHAR* name, // Constructor Process::Process(uint32 process_id) - : process_id_(process_id), - exit_code_(0), - number_of_restarts_(static_cast(-1)), + : number_of_restarts_(static_cast(-1)), name_(itostr(static_cast(process_id))), + process_id_(process_id), + exit_code_(0), shutdown_event_(NULL) { reset(process_, ::OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, false, @@ -593,7 +594,7 @@ HRESULT Process::GetAllDescendantProcesses( ASSERT1(descendant_processes); // Take a snapshot - // Note that we do not have a seperate scoped_* type defined to wrap the + // Note that we do not have a separate scoped_* type defined to wrap the // handle returned by CreateToolhelp32Snapshot. So scoped_hfile with similar // behavior is used. scoped_hfile process_snap(::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); diff --git a/omaha/base/process.h b/omaha/base/process.h index 3a2c6e7..890ee82 100644 --- a/omaha/base/process.h +++ b/omaha/base/process.h @@ -26,7 +26,7 @@ #include #include "base/basictypes.h" #include "omaha/base/constants.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -311,7 +311,7 @@ class Process { #if !SHIPPING CString debug_info_; #endif - DISALLOW_EVIL_CONSTRUCTORS(Process); + DISALLOW_COPY_AND_ASSIGN(Process); }; } // namespace omaha diff --git a/omaha/base/process_unittest.cc b/omaha/base/process_unittest.cc index b4fe76e..fdc2b5c 100644 --- a/omaha/base/process_unittest.cc +++ b/omaha/base/process_unittest.cc @@ -59,11 +59,11 @@ TEST(ProcessTest, StartOneProcess) { // Dummy process to spin off and then find. The numeric argument will make // ping.exe run until it's killed by the ScopedProcess destructor. const TCHAR kTestExecutable[] = _T("ping.exe"); -const TCHAR kTestArguments[] = _T("-w 10000 1.1.1.1"); -const TCHAR kTestExcludeArguments[] = _T("-n 5 -w 20000 1.1.1.1"); -const TCHAR kTestExcludeString[] = _T("20000 1.1.1.1"); -const TCHAR kTestIncludeArguments[] = _T("-n 6 -w 30000 1.1.1.1"); -const TCHAR kTestIncludeString[] = _T("-w 30000 1.1.1.1"); +const TCHAR kTestArguments[] = _T("-w 10000 2.2.2.2"); +const TCHAR kTestExcludeArguments[] = _T("-n 5 -w 20000 2.2.2.2"); +const TCHAR kTestExcludeString[] = _T("20000 2.2.2.2"); +const TCHAR kTestIncludeArguments[] = _T("-n 6 -w 30000 2.2.2.2"); +const TCHAR kTestIncludeString[] = _T("-w 30000 2.2.2.2"); const int kWaitForProcessStartMs = 500; const int kMaxWaitIterations = 10; diff --git a/omaha/base/processor_type.cc b/omaha/base/processor_type.cc deleted file mode 100644 index 7517464..0000000 --- a/omaha/base/processor_type.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2006-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Processor brand detection implementation -// -#include "omaha/base/processor_type.h" -#include "omaha/base/constants.h" -#include "omaha/base/utils.h" - -namespace omaha { - -// Returns "GenuineIntel", "AuthenticAMD", etc... -CString GetProcessorType() { - // Reference for checking for chip type - // http://en.wikipedia.org/wiki/CPUID - - // There are 12 characters in the chip id (e.g. "GenuineIntel") - union { - char str[16]; - uint32 n[4]; - } regs; - SetZero(regs.str); - __asm { - xor eax, eax; // Set EAX = 0 to get CPU type - cpuid; // Now ebx, edx, ecx will contain cpu brand - mov regs.n[0], ebx; - mov regs.n[4], edx; - mov regs.n[8], ecx; - } - return CString(regs.str); -} - -// Returns true if we're running on an Intel -bool IsIntelProcessor() { - CString chip = GetProcessorType(); - return (chip == kIntelVendorId); -} - -} // namespace omaha diff --git a/omaha/base/program_instance.h b/omaha/base/program_instance.h index 06a923d..ac18c7e 100644 --- a/omaha/base/program_instance.h +++ b/omaha/base/program_instance.h @@ -35,7 +35,7 @@ namespace omaha { bool CheckSingleInstance(); CString mutex_name_; auto_mutex mutex_; - DISALLOW_EVIL_CONSTRUCTORS(ProgramInstance); + DISALLOW_COPY_AND_ASSIGN(ProgramInstance); }; } // namespace omaha diff --git a/omaha/base/queue_timer.h b/omaha/base/queue_timer.h index 10d9182..faf95a3 100644 --- a/omaha/base/queue_timer.h +++ b/omaha/base/queue_timer.h @@ -74,7 +74,7 @@ class QueueTimer { HANDLE timer_queue_; Callback callback_; - DISALLOW_EVIL_CONSTRUCTORS(QueueTimer); + DISALLOW_COPY_AND_ASSIGN(QueueTimer); }; } // namespace omaha diff --git a/omaha/base/queue_timer_unittest.cc b/omaha/base/queue_timer_unittest.cc index 696abdb..6f1cfb9 100644 --- a/omaha/base/queue_timer_unittest.cc +++ b/omaha/base/queue_timer_unittest.cc @@ -14,12 +14,14 @@ // ======================================================================== -#include -#include "base/scoped_ptr.h" #include "omaha/base/queue_timer.h" -#include "omaha/base/scoped_any.h" + +#include +#include + #include "omaha/base/timer.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -54,7 +56,7 @@ class QueueTimerTest : public testing::Test { static void TimerCallback(QueueTimer* queue_timer); HANDLE timer_queue_; - scoped_ptr queue_timer_; + std::unique_ptr queue_timer_; scoped_event ev_; volatile int cnt_; volatile int max_cnt_; diff --git a/omaha/base/reactor.cc b/omaha/base/reactor.cc index 1a02aa3..757fbea 100644 --- a/omaha/base/reactor.cc +++ b/omaha/base/reactor.cc @@ -16,8 +16,9 @@ #include "omaha/base/reactor.h" +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -70,7 +71,7 @@ HRESULT Reactor::RegisterHandle(HANDLE handle, return E_INVALIDARG; } - scoped_ptr state(new RegistrationState); + std::unique_ptr state(new RegistrationState()); state->event_handler = event_handler; state->handle = handle; state->reactor = this; @@ -153,7 +154,7 @@ HRESULT Reactor::UnregisterHandle(HANDLE handle) { // Attempts to take the ownership of the registration state for the handle. // If taking the ownership does not succeed, it means the handle has already // been unregistered. - scoped_ptr state(ReleaseHandlerState(handle)); + std::unique_ptr state(ReleaseHandlerState(handle)); if (!state.get()) { return E_UNEXPECTED; } diff --git a/omaha/base/reactor.h b/omaha/base/reactor.h index 7cad78e..86b9953 100644 --- a/omaha/base/reactor.h +++ b/omaha/base/reactor.h @@ -84,7 +84,7 @@ class Reactor { CRITICAL_SECTION cs_; std::vector handlers_; - DISALLOW_EVIL_CONSTRUCTORS(Reactor); + DISALLOW_COPY_AND_ASSIGN(Reactor); }; } // namespace omaha diff --git a/omaha/base/reactor_unittest.cc b/omaha/base/reactor_unittest.cc index f5d0456..4973dac 100644 --- a/omaha/base/reactor_unittest.cc +++ b/omaha/base/reactor_unittest.cc @@ -14,13 +14,14 @@ // ======================================================================== -#include +#include "omaha/base/reactor.h" + +#include + #include "base/rand_util.h" -#include "base/scoped_ptr.h" #include "omaha/base/event_handler.h" -#include "omaha/base/reactor.h" -#include "omaha/base/scoped_any.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -76,7 +77,7 @@ class ReactorTest scoped_handle main_thread_; LONG cnt_; - static const LONG ReactorTest::kMaxCount = 10; + static const LONG kMaxCount = 10; }; const LONG ReactorTest::kMaxCount; diff --git a/omaha/base/reg_key.cc b/omaha/base/reg_key.cc index 5560110..4a7b0c5 100644 --- a/omaha/base/reg_key.cc +++ b/omaha/base/reg_key.cc @@ -14,11 +14,11 @@ // ======================================================================== #include "omaha/base/reg_key.h" + #include #include + #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/static_assert.h" #include "omaha/base/string.h" #include "omaha/base/synchronized.h" @@ -27,25 +27,27 @@ // The bulk of Omaha is designed to run as 32-bit only. However, the crash // handler is compiled in a 64-bit form, and it needs to access the 32-bit -// registry view. For now, we use the ADDWOW64() macro to map all registry -// accesses performed through the RegKey class to the 32-bit view; if we ever -// ship a native 64-bit Omaha, we will have to start planning which registry -// views should be used at a higher levels (i.e. ConfigManager). - -#ifdef _WIN64 -#define ADDWOW64(x) ((x) | KEY_WOW64_32KEY) -#else -#define ADDWOW64(x) (x) -#endif +// registry view. KEY_WOW64_32KEY is used by default for all registry access. namespace omaha { +namespace { + +// Returns the registry access mask |sam_desired| with the WoW view override +// indicated by |wow_override|. +REGSAM ApplyWoWOverride(REGSAM sam_desired, RegKey::WoWOverride wow_override) { + return sam_desired | static_cast(wow_override); +} + +} // namespace + HRESULT RegKey::Close() { HRESULT hr = S_OK; if (h_key_ != NULL) { LONG res = RegCloseKey(h_key_); hr = HRESULT_FROM_WIN32(res); h_key_ = NULL; + wow_override_ = k32BitView; } return hr; } @@ -60,14 +62,21 @@ HRESULT RegKey::Create(HKEY hKeyParent, // lpszClass may be NULL ASSERT1(key_name); ASSERT1(hKeyParent != NULL); + ASSERT1((sam_desired & (KEY_WOW64_64KEY | KEY_WOW64_32KEY)) != + (KEY_WOW64_64KEY | KEY_WOW64_32KEY)); DWORD dw; HKEY hKey = NULL; + WoWOverride wow_override = k32BitView; + if ((sam_desired & KEY_WOW64_64KEY) != 0) + wow_override = k64BitView; + else + sam_desired |= KEY_WOW64_32KEY; LONG res = ::RegCreateKeyEx(hKeyParent, key_name, 0, lpszClass, options, - ADDWOW64(sam_desired), + sam_desired, lpSecAttr, &hKey, &dw); @@ -81,6 +90,7 @@ HRESULT RegKey::Create(HKEY hKeyParent, hr = Close(); ASSERT1(hr == S_OK); h_key_ = hKey; + wow_override_ = wow_override; } return hr; } @@ -92,16 +102,19 @@ HRESULT RegKey::Create(const TCHAR * full_key_name, LPDWORD lpdwDisposition) { // lpszClass may be NULL ASSERT1(full_key_name); + ASSERT1((sam_desired & (KEY_WOW64_64KEY | KEY_WOW64_32KEY)) != + (KEY_WOW64_64KEY | KEY_WOW64_32KEY)); CString key_name(full_key_name); - HKEY parent_key = RegKey::GetRootKeyInfo(&key_name); - if (!parent_key) { + RootKeyInfo info = GetRootKeyInfo(&key_name); + if (!info.key) { ASSERT(false, (_T("unable to get root key location %s"), full_key_name)); return HRESULT_FROM_WIN32(ERROR_KEY_NOT_FOUND); } - return Create(parent_key, key_name, lpszClass, - options, sam_desired, lpSecAttr, lpdwDisposition); + return Create(info.key, key_name, lpszClass, options, + ApplyWoWOverride(sam_desired, info.wow_override), lpSecAttr, + lpdwDisposition); } HRESULT RegKey::CreateKeys(const TCHAR* keys_to_create[], @@ -148,9 +161,16 @@ HRESULT RegKey::Open(HKEY hKeyParent, REGSAM sam_desired) { ASSERT1(key_name); ASSERT1(hKeyParent != NULL); + ASSERT1((sam_desired & (KEY_WOW64_64KEY | KEY_WOW64_32KEY)) != + (KEY_WOW64_64KEY | KEY_WOW64_32KEY)); HKEY hKey = NULL; + WoWOverride wow_override = k32BitView; + if ((sam_desired & KEY_WOW64_64KEY) != 0) + wow_override = k64BitView; + else + sam_desired |= KEY_WOW64_32KEY; LONG res = ::RegOpenKeyEx(hKeyParent, key_name, 0, - ADDWOW64(sam_desired), &hKey); + sam_desired, &hKey); HRESULT hr = HRESULT_FROM_WIN32(res); // we have to close the currently opened key @@ -160,6 +180,7 @@ HRESULT RegKey::Open(HKEY hKeyParent, hr = Close(); ASSERT1(hr == S_OK); h_key_ = hKey; + wow_override_ = wow_override; } return hr; } @@ -168,13 +189,14 @@ HRESULT RegKey::Open(const TCHAR * full_key_name, REGSAM sam_desired) { ASSERT1(full_key_name); CString key_name(full_key_name); - HKEY parent_key = RegKey::GetRootKeyInfo(&key_name); - if (!parent_key) { + RootKeyInfo info = GetRootKeyInfo(&key_name); + if (!info.key) { ASSERT(false, (_T("unable to get root key for %s"), full_key_name)); return HRESULT_FROM_WIN32(ERROR_KEY_NOT_FOUND); } - return Open(parent_key, key_name, sam_desired); + return Open(info.key, key_name, + ApplyWoWOverride(sam_desired, info.wow_override)); } // save the key and all of its subkeys and values to a file @@ -183,13 +205,14 @@ HRESULT RegKey::Save(const TCHAR* full_key_name, const TCHAR* file_name) { ASSERT1(file_name); CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); - if (!h_key) { + RootKeyInfo info = GetRootKeyInfo(&key_name); + if (!info.key) { return E_FAIL; } RegKey key; - HRESULT hr = key.Open(h_key, key_name, KEY_READ); + HRESULT hr = key.Open(info.key, key_name, + ApplyWoWOverride(KEY_READ, info.wow_override)); if (FAILED(hr)) { return hr; } @@ -207,13 +230,14 @@ HRESULT RegKey::Restore(const TCHAR* full_key_name, const TCHAR* file_name) { ASSERT1(file_name); CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); - if (!h_key) { + RootKeyInfo info = GetRootKeyInfo(&key_name); + if (!info.key) { return E_FAIL; } RegKey key; - HRESULT hr = key.Open(h_key, key_name, KEY_WRITE); + HRESULT hr = key.Open(info.key, key_name, + ApplyWoWOverride(KEY_WRITE, info.wow_override)); if (FAILED(hr)) { return hr; } @@ -231,7 +255,8 @@ bool RegKey::HasSubkey(const TCHAR * key_name) const { ASSERT1(h_key_); RegKey key; - HRESULT hr = key.Open(h_key_, key_name, KEY_READ); + HRESULT hr = key.Open(h_key_, key_name, + ApplyWoWOverride(KEY_READ, wow_override_)); key.Close(); return S_OK == hr; } @@ -243,7 +268,7 @@ HRESULT RegKey::FlushKey(const TCHAR * full_key_name) { HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + HKEY h_key = GetRootKeyInfo(&key_name).key; if (h_key != NULL) { LONG res = RegFlushKey(h_key); @@ -264,11 +289,13 @@ HRESULT RegKey::SetValueStaticHelper(const TCHAR * full_key_name, HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - hr = key.Create(h_key, key_name.GetString()); + hr = key.Create(info.key, key_name.GetString(), NULL, + REG_OPTION_NON_VOLATILE, + ApplyWoWOverride(KEY_ALL_ACCESS, info.wow_override)); if (hr == S_OK) { switch (type) { case REG_DWORD: @@ -360,11 +387,12 @@ HRESULT RegKey::GetValueStaticHelper(const TCHAR * full_key_name, HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - hr = key.Open(h_key, key_name.GetString(), KEY_READ); + hr = key.Open(info.key, key_name.GetString(), + ApplyWoWOverride(KEY_READ, info.wow_override)); if (hr == S_OK) { switch (type) { case REG_DWORD: @@ -407,7 +435,7 @@ HRESULT RegKey::GetValueStaticHelper(const TCHAR * full_key_name, break; case REG_BINARY: hr = key.GetValue(value_name, - reinterpret_cast(value), + reinterpret_cast(value), byte_count); if (SUCCEEDED(hr)) { UTIL_LOG(L6, (_T("[Read binary value: %s:%s, len = %d]"), @@ -438,7 +466,7 @@ HRESULT RegKey::GetValueStaticHelper(const TCHAR * full_key_name, // value_name may be NULL. HRESULT RegKey::GetValueHelper(const TCHAR * value_name, DWORD * type, - byte * * value, + byte** value, size_t * byte_count) const { ASSERT1(byte_count); ASSERT1(value); @@ -529,6 +557,16 @@ HRESULT RegKey::GetValue(const TCHAR * value_name, DWORD64 * value) const { // String Get // value_name may be NULL. +HRESULT RegKey::GetValue(const TCHAR * value_name, + std::unique_ptr* value_ptr) const { + ASSERT1(value_name); + ASSERT1(value_ptr); + TCHAR* value; + HRESULT hr = GetValue(value_name, &value); + value_ptr->reset(value); + return hr; +} + HRESULT RegKey::GetValue(const TCHAR * value_name, TCHAR * * value) const { ASSERT1(value); ASSERT1(h_key_); @@ -657,9 +695,24 @@ HRESULT RegKey::GetValue(const TCHAR * value_name, return hr; } +HRESULT RegKey::GetValue(const TCHAR * value_name, + std::unique_ptr* value, + size_t * byte_count) const { + ASSERT1(byte_count); + ASSERT1(value); + // value_name may be NULL + + DWORD type = 0; + BYTE* byte = nullptr; + HRESULT hr = GetValueHelper(value_name, &type, &byte, byte_count); + value->reset(byte); + ASSERT1((hr != S_OK) || (type == REG_MULTI_SZ) || (type == REG_BINARY)); + return hr; +} + // Binary data Get HRESULT RegKey::GetValue(const TCHAR * value_name, - byte * * value, + byte** value, size_t * byte_count) const { ASSERT1(byte_count); ASSERT1(value); @@ -673,7 +726,20 @@ HRESULT RegKey::GetValue(const TCHAR * value_name, // Raw data get HRESULT RegKey::GetValue(const TCHAR * value_name, - byte * * value, + std::unique_ptr* value_ptr, + size_t * byte_count, + DWORD *type) const { + ASSERT1(type); + ASSERT1(byte_count); + ASSERT1(value_ptr); + byte* value; + HRESULT hr = GetValue(value_name, &value, byte_count, type); + value_ptr->reset(value); + return hr; +} + +HRESULT RegKey::GetValue(const TCHAR * value_name, + byte** value, size_t * byte_count, DWORD *type) const { ASSERT1(type); @@ -785,11 +851,11 @@ HRESULT RegKey::RenameValue(const TCHAR* old_value_name, ASSERT1(new_value_name); ASSERT1(old_value_name); - scoped_ptr value; + std::unique_ptr value; size_t byte_count = 0; DWORD type = 0; - HRESULT hr = GetValue(old_value_name, address(value), &byte_count, &type); + HRESULT hr = GetValue(old_value_name, &value, &byte_count, &type); if (FAILED(hr)) { return hr; } @@ -807,21 +873,18 @@ bool RegKey::HasKey(const TCHAR * full_key_name) { return HasKeyHelper(full_key_name, KEY_READ); } -bool RegKey::HasNativeKey(const TCHAR * full_key_name) { - return HasKeyHelper(full_key_name, KEY_READ | KEY_WOW64_64KEY); -} - bool RegKey::HasKeyHelper(const TCHAR * full_key_name, DWORD sam_flags) { ASSERT1(full_key_name); ASSERT1(sam_flags & KEY_READ); // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - HRESULT hr = key.Open(h_key, key_name.GetString(), sam_flags); + HRESULT hr = key.Open(info.key, key_name.GetString(), + ApplyWoWOverride(sam_flags, info.wow_override)); key.Close(); return S_OK == hr; } @@ -841,10 +904,10 @@ HRESULT RegKey::CopyValue(const TCHAR * full_from_key_name, return hr; } - scoped_ptr val; + std::unique_ptr val; size_t byte_count = 0; DWORD type = 0; - hr = from_reg_key.GetValue(from_value_name, address(val), &byte_count, &type); + hr = from_reg_key.GetValue(from_value_name, &val, &byte_count, &type); if (FAILED(hr)) { return hr; } @@ -865,11 +928,12 @@ bool RegKey::HasValue(const TCHAR * full_key_name, const TCHAR * value_name) { bool has_value = false; // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - if (key.Open(h_key, key_name.GetString(), KEY_READ) == S_OK) { + if (key.Open(info.key, key_name.GetString(), + ApplyWoWOverride(KEY_READ, info.wow_override)) == S_OK) { has_value = key.HasValue(value_name); key.Close(); } @@ -887,10 +951,11 @@ HRESULT RegKey::GetValueType(const TCHAR* full_key_name, *value_type = REG_NONE; CString key_name(full_key_name); - HKEY root_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); RegKey key; - HRESULT hr = key.Open(root_key, key_name, KEY_READ); + HRESULT hr = key.Open(info.key, key_name, + ApplyWoWOverride(KEY_READ, info.wow_override)); if (FAILED(hr)) { return hr; } @@ -909,13 +974,14 @@ HRESULT RegKey::DeleteKey(const TCHAR* full_key_name, bool recursively) { // need to open the parent key first // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); // get the parent key CString parent_key(GetParentKeyInfo(&key_name)); RegKey key; - HRESULT hr = key.Open(h_key, parent_key); + HRESULT hr = key.Open(info.key, parent_key, + ApplyWoWOverride(KEY_ALL_ACCESS, info.wow_override)); if (hr == S_OK) { hr = recursively ? key.RecurseDeleteSubKey(key_name) : @@ -937,11 +1003,12 @@ HRESULT RegKey::DeleteValue(const TCHAR * full_key_name, HRESULT hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); // get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - hr = key.Open(h_key, key_name.GetString()); + hr = key.Open(info.key, key_name.GetString(), + ApplyWoWOverride(KEY_ALL_ACCESS, info.wow_override)); if (hr == S_OK) { hr = key.DeleteValue(value_name); key.Close(); @@ -955,7 +1022,8 @@ HRESULT RegKey::RecurseDeleteSubKey(const TCHAR * key_name) { ASSERT1(h_key_); RegKey key; - HRESULT hr = key.Open(h_key_, key_name); + HRESULT hr = key.Open(h_key_, key_name, + ApplyWoWOverride(KEY_ALL_ACCESS, wow_override_)); if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || hr == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND)) { hr = S_FALSE; @@ -992,10 +1060,12 @@ HRESULT RegKey::RecurseDeleteSubKey(const TCHAR * key_name) { return DeleteSubKey(key_name); } -HKEY RegKey::GetRootKeyInfo(CString * full_key_name) { +RegKey::RootKeyInfo RegKey::GetRootKeyInfo(CString* full_key_name) { ASSERT1(full_key_name); - HKEY h_key = NULL; + // All accesses go to the 32-bit view of the registry unless overridden. + RootKeyInfo result = {NULL, k32BitView}; + // get the root HKEY int index = String_FindChar(*(full_key_name), '\\'); CString root_key; @@ -1004,25 +1074,30 @@ HKEY RegKey::GetRootKeyInfo(CString * full_key_name) { root_key = *full_key_name; *full_key_name = _T(""); } else { - root_key= full_key_name->Left(index); + root_key = full_key_name->Left(index); *full_key_name = full_key_name->Right(full_key_name->GetLength() - index - 1); } if (!root_key.CompareNoCase(_T("HKLM")) || - !root_key.CompareNoCase(_T("HKEY_LOCAL_MACHINE"))) - h_key = HKEY_LOCAL_MACHINE; - else if (!root_key.CompareNoCase(_T("HKCU")) || - !root_key.CompareNoCase(_T("HKEY_CURRENT_USER"))) - h_key = HKEY_CURRENT_USER; - else if (!root_key.CompareNoCase(_T("HKU")) || - !root_key.CompareNoCase(_T("HKEY_USERS"))) - h_key = HKEY_USERS; - else if (!root_key.CompareNoCase(_T("HKCR")) || - !root_key.CompareNoCase(_T("HKEY_CLASSES_ROOT"))) - h_key = HKEY_CLASSES_ROOT; - - return h_key; + !root_key.CompareNoCase(_T("HKEY_LOCAL_MACHINE"))) { + result.key = HKEY_LOCAL_MACHINE; + } else if (!root_key.CompareNoCase(_T("HKCU")) || + !root_key.CompareNoCase(_T("HKEY_CURRENT_USER"))) { + result.key = HKEY_CURRENT_USER; + } else if (!root_key.CompareNoCase(_T("HKU")) || + !root_key.CompareNoCase(_T("HKEY_USERS"))) { + result.key = HKEY_USERS; + } else if (!root_key.CompareNoCase(_T("HKCR")) || + !root_key.CompareNoCase(_T("HKEY_CLASSES_ROOT"))) { + result.key = HKEY_CLASSES_ROOT; + } else if (!root_key.CompareNoCase(_T("HKLM[64]")) || + !root_key.CompareNoCase(_T("HKEY_LOCAL_MACHINE[64]"))) { + result.key = HKEY_LOCAL_MACHINE; + result.wow_override = k64BitView; + } + + return result; } @@ -1032,7 +1107,7 @@ bool RegKey::SafeKeyNameForDeletion(const wchar_t *key_name) { ASSERT1(key_name); CString key(key_name); - HKEY root_key = GetRootKeyInfo(&key); + HKEY root_key = GetRootKeyInfo(&key).key; if ( !root_key ) { key = key_name; @@ -1174,12 +1249,13 @@ bool RegKey::IsKeyEmpty(const TCHAR* full_key_name) { // Get the root HKEY CString key_name(full_key_name); - HKEY h_key = GetRootKeyInfo(&key_name); + RootKeyInfo info = GetRootKeyInfo(&key_name); // Open the key to check - if (h_key != NULL) { + if (info.key != NULL) { RegKey key; - HRESULT hr = key.Open(h_key, key_name.GetString(), KEY_READ); + HRESULT hr = key.Open(info.key, key_name.GetString(), + ApplyWoWOverride(KEY_READ, info.wow_override)); if (SUCCEEDED(hr)) { is_empty = key.GetSubkeyCount() == 0 && key.GetValueCount() == 0; key.Close(); @@ -1240,7 +1316,7 @@ HRESULT RegKeyWithChangeEvent::SetupEvent(bool watch_subtree, return HRESULT_FROM_WIN32(res); } -// Indicates if any changes (that are being monitored have occured) +// Indicates if any changes (that are being monitored have occurred) bool RegKeyWithChangeEvent::HasChangeOccurred() const { return IsHandleSignaled(get(change_event_)); } @@ -1258,7 +1334,7 @@ RegKeyWatcher::RegKeyWatcher(const TCHAR* reg_key, bool watch_subtree, HRESULT RegKeyWatcher::EnsureEventSetup() { UTIL_LOG(L3, (_T("[RegKeyWatcher::EnsureEventSetup]"))); if (!reg_key_with_change_event_.get()) { - scoped_ptr local_reg_key(new RegKeyWithChangeEvent); + std::unique_ptr local_reg_key(new RegKeyWithChangeEvent); if (!local_reg_key.get()) { ASSERT(false, (_T("unable to allocate local_reg_key"))); return E_FAIL; diff --git a/omaha/base/reg_key.h b/omaha/base/reg_key.h index 18a4a77..da63924 100644 --- a/omaha/base/reg_key.h +++ b/omaha/base/reg_key.h @@ -27,14 +27,15 @@ #define OMAHA_BASE_REG_KEY_H_ #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/static_assert.h" #include "omaha/base/store_watcher.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -44,12 +45,27 @@ namespace omaha { class RegKey { public: + // Registry access mask values for specifying the 32-bit or 64-bit view of the + // registry. + enum WoWOverride { + k32BitView = KEY_WOW64_32KEY, + k64BitView = KEY_WOW64_64KEY, + }; + + // A root key and WoW registry view extracted from a full key name; see + // GetRootKeyInfo. + struct RootKeyInfo { + HKEY key; + WoWOverride wow_override; + }; + RegKey(); virtual ~RegKey(); - // create a reg key + // create a reg key. If |sam_desired| does not specify KEY_WOW64_64KEY, + // KEY_WOW64_32KEY is used. HRESULT Create(HKEY hKeyParent, const TCHAR * key_name, - TCHAR * reg_class = REG_NONE, DWORD options = REG_OPTION_NON_VOLATILE, + TCHAR * reg_class = NULL, DWORD options = REG_OPTION_NON_VOLATILE, REGSAM sam_desired = KEY_ALL_ACCESS, LPSECURITY_ATTRIBUTES lp_sec_attr = NULL, LPDWORD lp_disposition = NULL); @@ -57,7 +73,7 @@ class RegKey { // create a reg key, given the full key name, including the HKEY root // (say for example, "HKLM\\Software") HRESULT Create(const TCHAR * full_key_name, - TCHAR * reg_class = REG_NONE, DWORD options = REG_OPTION_NON_VOLATILE, + TCHAR * reg_class = NULL, DWORD options = REG_OPTION_NON_VOLATILE, REGSAM sam_desired = KEY_ALL_ACCESS, LPSECURITY_ATTRIBUTES lp_sec_attr = NULL, LPDWORD lp_disposition = NULL); @@ -67,13 +83,13 @@ class RegKey { // (say for example, "HKLM\\Software") static HRESULT CreateKeys(const TCHAR* keys_to_create[], DWORD number_of_keys, - TCHAR* reg_class = REG_NONE, + TCHAR* reg_class = NULL, DWORD options = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lp_sec_attr = NULL); // Static method to create a single key. static HRESULT CreateKey(const TCHAR * full_key_name, - TCHAR * reg_class = REG_NONE, + TCHAR * reg_class = NULL, DWORD options = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lp_sec_attr = NULL); @@ -157,6 +173,8 @@ class RegKey { HRESULT GetValue(const TCHAR * value_name, DWORD64 * value) const; // get a string value - the caller must free the return buffer + HRESULT GetValue(const TCHAR * value_name, + std::unique_ptr* value_ptr) const; HRESULT GetValue(const TCHAR * value_name, TCHAR * * value) const; // get a CString value @@ -167,11 +185,20 @@ class RegKey { std::vector * value) const; // get binary data - the caller must free the return buffer + HRESULT GetValue(const TCHAR * value_name, + std::unique_ptr* value_ptr, + size_t * byte_count) const; + HRESULT GetValue(const TCHAR * value_name, byte * * value, size_t * byte_count) const; // get raw data, including type - the caller must free the return buffer + HRESULT GetValue(const TCHAR * value_name, + std::unique_ptr* value_ptr, + size_t * byte_count, + DWORD *type) const; + HRESULT GetValue(const TCHAR * value_name, byte * * value, size_t * byte_count, @@ -191,9 +218,6 @@ class RegKey { // Check if a key exists. static bool HasKey(const TCHAR * full_key_name); - // Check if a key exists in the native (i.e. non-redirected) registry. - static bool HasNativeKey(const TCHAR * full_key_name); - // check if the key has a specified value static bool HasValue(const TCHAR * full_key_name, const TCHAR * value_name); @@ -272,6 +296,10 @@ class RegKey { const TCHAR * value_name, TCHAR * * value); + static HRESULT GetValue(const TCHAR * full_key_name, + const TCHAR * value_name, + std::unique_ptr* value); + static HRESULT GetValue(const TCHAR * full_key_name, const TCHAR * value_name, CString * value); @@ -282,6 +310,11 @@ class RegKey { std::vector * value); // STATIC get binary data - the caller must free the return buffer + static HRESULT GetValue(const TCHAR * full_key_name, + const TCHAR * value_name, + std::unique_ptr* value_ptr, + size_t * byte_count); + static HRESULT GetValue(const TCHAR * full_key_name, const TCHAR * value_name, byte * * value, @@ -355,10 +388,11 @@ class RegKey { friend class RegKeyTestClass; // helper function to get the HKEY and the root key from a string - // representation modifies the argument in place and returns the key name - // e.g. HKLM\\Software\\Google\... returns HKLM, "Software\\Google\..." - // Necessary for the static versions that use the full name of the reg key - static HKEY GetRootKeyInfo(CString * full_key_name); + // representation modifies the argument in place and returns the root key and + // registry view; e.g., HKLM\\Software\\Google\... returns HKLM, + // "Software\\Google\..." + // Necessary for the static versions that use the full name of the reg key. + static RootKeyInfo GetRootKeyInfo(CString* full_key_name); // Returns true if this key name is 'safe' for deletion (doesn't specify // a key root) @@ -375,7 +409,6 @@ class RegKey { static bool IsKeyEmpty(const TCHAR* full_key_name); private: - // Helper function to check if a key exists, using the sam flags specified. // Note: KEY_READ must be included in sam_flags. static bool HasKeyHelper(const TCHAR * full_key_name, DWORD sam_flags); @@ -420,7 +453,9 @@ class RegKey { // the HKEY for the current key HKEY h_key_; - DISALLOW_EVIL_CONSTRUCTORS(RegKey); + WoWOverride wow_override_; + + DISALLOW_COPY_AND_ASSIGN(RegKey); }; // Provides all the functionality of RegKey plus @@ -439,7 +474,7 @@ class RegKeyWithChangeEvent : public RegKey { // for values for notify_filter. HRESULT SetupEvent(bool watch_subtree, DWORD notify_filter); - // Indicates if any changes (that are being monitored) have occured + // Indicates if any changes (that are being monitored) have occurred bool HasChangeOccurred() const; // Get the event that is signaled on registry changes. @@ -455,7 +490,7 @@ class RegKeyWithChangeEvent : public RegKey { private: scoped_handle change_event_; - DISALLOW_EVIL_CONSTRUCTORS(RegKeyWithChangeEvent); + DISALLOW_COPY_AND_ASSIGN(RegKeyWithChangeEvent); }; // Does the common things necessary for watching @@ -483,17 +518,17 @@ class RegKeyWatcher : public StoreWatcher { private: // Used to do the SetupEvent method - scoped_ptr reg_key_with_change_event_; + std::unique_ptr reg_key_with_change_event_; CString reg_key_string_; bool watch_subtree_; - bool allow_creation_; DWORD notify_filter_; - DISALLOW_EVIL_CONSTRUCTORS(RegKeyWatcher); + bool allow_creation_; + DISALLOW_COPY_AND_ASSIGN(RegKeyWatcher); }; -inline RegKey::RegKey() { h_key_ = NULL; } +inline RegKey::RegKey() : h_key_(NULL), wow_override_(k32BitView) {} inline RegKey::~RegKey() { Close(); } @@ -623,7 +658,7 @@ inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, REG_BINARY, &buffer, &byte_count); - scoped_array free_buffer(buffer); + std::unique_ptr free_buffer(buffer); if (SUCCEEDED(hr)) { if (byte_count == sizeof(*value)) { @@ -653,7 +688,7 @@ inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, REG_BINARY, &buffer, &byte_count); - scoped_array free_buffer(buffer); + std::unique_ptr free_buffer(buffer); if (SUCCEEDED(hr)) { if (byte_count == sizeof(*value)) { @@ -669,6 +704,18 @@ inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, return hr; } +inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, + const TCHAR* value_name, + std::unique_ptr* value_ptr) { + ASSERT1(full_key_name); + ASSERT1(value_ptr); + + TCHAR* value = nullptr; + HRESULT hr = GetValueStaticHelper(full_key_name, value_name, REG_SZ, &value); + value_ptr->reset(value); + return hr; +} + inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, const TCHAR* value_name, TCHAR** value) { @@ -700,6 +747,20 @@ inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, return GetValueStaticHelper(full_key_name, value_name, REG_MULTI_SZ, value); } +inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, + const TCHAR* value_name, + std::unique_ptr* value_ptr, + size_t* byte_count) { + ASSERT1(full_key_name); + ASSERT1(value_ptr); + ASSERT1(byte_count); + + byte* value = nullptr; + HRESULT hr = GetValue(full_key_name, value_name, &value, byte_count); + value_ptr->reset(value); + return hr; +} + inline HRESULT RegKey::GetValue(const TCHAR* full_key_name, const TCHAR* value_name, byte** value, diff --git a/omaha/base/reg_key_unittest.cc b/omaha/base/reg_key_unittest.cc index 28f1539..9e25964 100644 --- a/omaha/base/reg_key_unittest.cc +++ b/omaha/base/reg_key_unittest.cc @@ -14,6 +14,7 @@ // ======================================================================== #include "omaha/base/reg_key.h" + #include "omaha/base/debug.h" #include "omaha/base/utils.h" #include "omaha/base/dynamic_link_kernel32.h" @@ -109,59 +110,90 @@ TEST_F(RegKeyTestClass, Init) { TEST_F(RegKeyTestClass, Helper) { // Dud items cause NULL CString temp_key; + RegKey::RootKeyInfo info; // RegKey::GetRootKeyInfo turns a string into the HKEY and subtree value // Try out some dud values temp_key = _T(""); - ASSERT_TRUE(RegKey::GetRootKeyInfo(&temp_key) == NULL); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_TRUE(info.key == NULL); ASSERT_STREQ(temp_key, _T("")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("a"); - ASSERT_TRUE(RegKey::GetRootKeyInfo(&temp_key) == NULL); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_TRUE(info.key == NULL); ASSERT_STREQ(temp_key, _T("")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); // The basics temp_key = _T("HKLM\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_LOCAL_MACHINE); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_LOCAL_MACHINE); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKEY_LOCAL_MACHINE\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_LOCAL_MACHINE); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_LOCAL_MACHINE); + ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); + + temp_key = _T("HKLM[64]\\a"); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_LOCAL_MACHINE); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k64BitView); temp_key = _T("HKCU\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CURRENT_USER); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CURRENT_USER); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKEY_CURRENT_USER\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CURRENT_USER); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CURRENT_USER); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKU\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_USERS); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_USERS); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKEY_USERS\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_USERS); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_USERS); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKCR\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CLASSES_ROOT); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("HKEY_CLASSES_ROOT\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CLASSES_ROOT); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); // Make sure it is case insensitive temp_key = _T("hkcr\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CLASSES_ROOT); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); temp_key = _T("hkey_CLASSES_ROOT\\a"); - ASSERT_EQ(RegKey::GetRootKeyInfo(&temp_key), HKEY_CLASSES_ROOT); + info = RegKey::GetRootKeyInfo(&temp_key); + ASSERT_EQ(info.key, HKEY_CLASSES_ROOT); ASSERT_STREQ(temp_key, _T("a")); + ASSERT_EQ(info.wow_override, RegKey::k32BitView); // Test out temp_GetParentKeyInfo @@ -209,6 +241,7 @@ TEST(RegKeyTest, RegKey) { double double_val = 0; TCHAR * str_val = NULL; byte * binary_val = NULL; + std::unique_ptr binary_ptr; size_t byte_count = 0; // Just in case... @@ -375,6 +408,10 @@ TEST(RegKeyTest, RegKey) { ASSERT_EQ(0, memcmp(binary_val, kBinaryVal, sizeof(kBinaryVal)-1)); delete [] binary_val; + hr = r_key.GetValue(kValNameBinary, &binary_ptr, &byte_count); + ASSERT_SUCCEEDED(hr); + ASSERT_EQ(0, memcmp(binary_ptr.get(), kBinaryVal, sizeof(kBinaryVal)-1)); + // set it again hr = r_key.SetValue(kValNameBinary, (const byte *)kBinaryVal2, sizeof(kBinaryVal)-1); @@ -386,6 +423,10 @@ TEST(RegKeyTest, RegKey) { ASSERT_EQ(0, memcmp(binary_val, kBinaryVal2, sizeof(kBinaryVal2)-1)); delete [] binary_val; + hr = r_key.GetValue(kValNameBinary, &binary_ptr, &byte_count); + ASSERT_SUCCEEDED(hr); + ASSERT_EQ(0, memcmp(binary_ptr.get(), kBinaryVal2, sizeof(kBinaryVal2)-1)); + // delete the value hr = r_key.DeleteValue(kValNameBinary); ASSERT_SUCCEEDED(hr); @@ -644,6 +685,10 @@ TEST(RegKeyTest, RegKey) { ASSERT_EQ(0, memcmp(binary_val, kStBinaryVal, sizeof(kStBinaryVal)-1)); delete [] binary_val; + hr = RegKey::GetValue(kStRkey1, kStValNameBinary, &binary_ptr, &byte_count); + ASSERT_SUCCEEDED(hr); + ASSERT_EQ(0, memcmp(binary_ptr.get(), kStBinaryVal, sizeof(kStBinaryVal)-1)); + // delete the value hr = RegKey::DeleteValue(kStRkey1, kStValNameBinary); ASSERT_SUCCEEDED(hr); @@ -668,6 +713,11 @@ TEST(RegKeyTest, RegKey) { ASSERT_TRUE(binary_val == NULL); delete [] binary_val; + hr = RegKey::GetValue(kStRkey1, kStValNameBinary, &binary_ptr, &byte_count); + ASSERT_SUCCEEDED(hr); + ASSERT_EQ(byte_count, 0); + ASSERT_FALSE(binary_ptr); + // delete the value hr = RegKey::DeleteValue(kStRkey1, kStValNameBinary); ASSERT_SUCCEEDED(hr); @@ -691,6 +741,11 @@ TEST(RegKeyTest, RegKey) { ASSERT_TRUE(binary_val == NULL); delete [] binary_val; + hr = RegKey::GetValue(kStRkey1, kStValNameBinary, &binary_ptr, &byte_count); + ASSERT_SUCCEEDED(hr); + ASSERT_EQ(byte_count, 0); + ASSERT_TRUE(binary_ptr.get() == nullptr); + // delete the value hr = RegKey::DeleteValue(kStRkey1, kStValNameBinary); ASSERT_SUCCEEDED(hr); diff --git a/omaha/base/registry_hive.cc b/omaha/base/registry_hive.cc deleted file mode 100644 index 006d4cf..0000000 --- a/omaha/base/registry_hive.cc +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/registry_hive.h" -#include "omaha/base/accounts.h" -#include "omaha/base/reg_key.h" -#include "omaha/base/safe_format.h" -#include "omaha/base/string.h" -#include "omaha/base/system.h" -#include "omaha/base/user_info.h" -#include "omaha/base/utils.h" - -namespace omaha { - -RegistryHive::RegistryHive() - : hive_holding_key_(NULL) { -} - -RegistryHive::~RegistryHive() { - if ( !hive_name_.IsEmpty() ) { - UnloadHive(); - } -} - -// Loads hive for requested SID. SID should be in format "S-X-X....." -// name is a name under which the hive will be added to the HKEY_USERS, -// you could use persons name here. This parameter should not have '\\' -// characters! -// It is not recommended to load more than one hive at once - LoadHive, -// manipulate hive, UnloadHive, and then work on the next one. -// -// Hive could be already loaded: you logged out from other user but system -// had open key in your current user. In that case I open hive_holding_key_ to -// prevent system from unloading hive and do not load/unload hive - the system -// will do it. -HRESULT RegistryHive::LoadHive(TCHAR const * sid, TCHAR const *name) { - ASSERT1(sid); - ASSERT1(name); - ASSERT1(hive_name_.IsEmpty()); - ASSERT1(String_FindChar(name, _T('\\')) == -1); - - CString profile_key; - CString hive_path; - - // Need set SE_RESTORE_NAME/SE_BACKUP_NAME priveleges to current process - // otherwise loading of the hive will fail - RET_IF_FAILED(System::AdjustPrivilege(SE_RESTORE_NAME, true)); - RET_IF_FAILED(System::AdjustPrivilege(SE_BACKUP_NAME, true)); - - SafeCStringFormat(&profile_key, kProfileKeyFormat, sid); - - if ( FAILED(RegKey::GetValue(profile_key, kProfilePathValue, &hive_path)) ) { - return E_FAIL; - } - - - wchar_t temporary_buffer[MAX_PATH]; - DWORD ret = ExpandEnvironmentStrings(hive_path, temporary_buffer, MAX_PATH); - - if ( !ret || ret >= MAX_PATH ) { - return E_FAIL; - } - hive_path = temporary_buffer; - - hive_path.Append(_T("\\")); - hive_path.Append(kHiveName); - - hive_name_ = name; - - LONG res = RegLoadKey(HKEY_USERS, hive_name_, hive_path); - - if ( ERROR_SHARING_VIOLATION == res ) { - // It is quite possible that the hive is still held by system. - hive_name_ = sid; - - // if it is the case, this call will succeeed, and the system will not - // unload the hive while there are outstanding keys opened. - res = RegOpenKeyEx(HKEY_USERS, - hive_name_, - 0, - KEY_ALL_ACCESS, - &hive_holding_key_); - } - - return (res == ERROR_SUCCESS) ? S_OK : E_FAIL; -} - -// Loads hive for requested SID, but only if the SID is another user -// (since we don't need to do anything if the sid is ours) -HRESULT RegistryHive::LoadHive(TCHAR const * user_sid) { - ASSERT1(user_sid != NULL); - bool other_user = false; - - // Determine if the SID passed in is really another user - CString current_user_sid; - HRESULT hr = omaha::user_info::GetProcessUser(NULL, NULL, ¤t_user_sid); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("[RegistryHive::LoadHive - failed to get current user"))); - return hr; - } - - // user_sid is the current user - no need to load the hive - if (lstrcmpi(current_user_sid, user_sid) == 0) - return S_FALSE; - - // Get info on the sid we're being asked to load for - CString name; - CString domain; - SID_NAME_USE user_type; - hr = accounts::GetUserInfo(user_sid, &name, &domain, &user_type); - if ( FAILED(hr) || user_type != SidTypeUser ) { - // Either Sid no longer exists or Sid is not a user Sid - // (There is other possibility: Sid could be for roaming profile on domain - // which is currently down, but we do not support roaming profiles) - return FAILED(hr) ? hr : E_FAIL; - } - - hr = LoadHive(user_sid, name); // Use user name as a temporary key name. - if ( FAILED(hr) ) { - // Hive no longer present. - return E_FAIL; - } - - return S_OK; -} - - -// Unloads and saves loaded hive -HRESULT RegistryHive::UnloadHive() { - if (hive_name_.IsEmpty()) - return S_OK; - - LONG res; - if ( hive_holding_key_ ) { - res = RegCloseKey(hive_holding_key_); - hive_holding_key_ = NULL; - // no need to unload hive. System will do it. - } else { - res = RegUnLoadKey(HKEY_USERS, hive_name_); - } - hive_name_.Empty(); - return (res == ERROR_SUCCESS) ? S_OK : E_FAIL; -} - -// Does it recursively. The name should be relative to HKEY_CURRENT_USER. -HRESULT RegistryHive::DeleteUserKey(TCHAR const * key_name) { - ASSERT(key_name && *key_name, (L"")); - if ( !key_name || !*key_name ) { - return E_FAIL; - } - CString key(key_name); - ExpandKeyName(&key); - - if ( !RegKey::SafeKeyNameForDeletion(key) ) { - return E_FAIL; - } - - return RegKey::DeleteKey(key); -} - -void RegistryHive::ExpandKeyName(CString * str) { - ASSERT1(str); - - // If we haven't loaded another user's hive, use HKCU instead of - // HKEY_USERS - CString key_name; - if (hive_name_.IsEmpty()) { - key_name = _T("HKCU\\"); - } else { - key_name = _T("HKEY_USERS\\"); - key_name.Append(hive_name_ + _T("\\")); - } - - key_name.Append(*str); - *str = key_name; -} - -// Load a user registry -int LoadUserRegistry(const TCHAR* user_sid, - ProcessUserRegistryFunc* handler, - LONG_PTR param) { - ASSERT1(user_sid && *user_sid); - ASSERT1(handler); - - // Get current user SID - CString curr_user_sid; - HRESULT hr = omaha::user_info::GetProcessUser(NULL, NULL, &curr_user_sid); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("[LoadUserRegistry - can't get current user][0x%x]"), hr)); - return 0; - } - - // Is current user? - bool other_user = curr_user_sid.CompareNoCase(user_sid) != 0; - - // Get the hive for this user - RegistryHive user_hive; - if (other_user) { - // Get the info about this user - SID_NAME_USE user_type = SidTypeInvalid; - CString name, domain; - hr = accounts::GetUserInfo(user_sid, &name, &domain, &user_type); - if (FAILED(hr) || user_type != SidTypeUser) { - // Either SID no longer exists or SID is not a user Sid - // (There is other possibility: SID could be for roaming profile on domain - // which is currently down, but we do not support roaming profiles) - UTIL_LOG(LEVEL_WARNING, - (_T("[LoadUserRegistry - SID %s invalid or unsupported][0x%x]"), - user_sid, hr)); - return 0; - } - - // Load the hive - hr = user_hive.LoadHive(user_sid, domain + _T("_") + name); - if (FAILED(hr)) { - // Hive no longer present. - UTIL_LOG(LW, (_T("[LoadUserRegistry]") - _T("[hive not present for %s][0x%x]"), user_sid, hr)); - return 0; - } - } - - // Get the registry key path - CString user_reg_path; - user_hive.ExpandKeyName(&user_reg_path); - - // Call the handler - int res = (*handler)(user_sid, user_reg_path, param); - - // Unload the hive - if (other_user) { - hr = user_hive.UnloadHive(); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("[LoadUserRegistry]") - _T("[failed to save hive for %s][0x%x]"), user_sid, hr)); - } - } - - return res; -} - -// Enumerate all user registries -void EnumerateAllUserRegistries(ProcessUserRegistryFunc* handler, - LONG_PTR param) { - ASSERT1(handler); - - CSimpleArray sid_array; - accounts::GetAllUserSids(&sid_array); - for (int i = 0 ; i < sid_array.GetSize() ; ++i) { - if (LoadUserRegistry(sid_array[i], handler, param)) { - return; - } - } -} - -} // namespace omaha - diff --git a/omaha/base/registry_hive.h b/omaha/base/registry_hive.h deleted file mode 100644 index cf34680..0000000 --- a/omaha/base/registry_hive.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Other persons' registry hive manipulations. -// -#ifndef OMAHA_COMMON_REGISTRY_HIVE_H_ -#define OMAHA_COMMON_REGISTRY_HIVE_H_ - -#include -#include - -namespace omaha { - -#define kProfileKeyFormat \ - _T("HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%s") -#define kProfilePathValue _T("ProfileImagePath") -#define kHiveName _T("Ntuser.dat") - -// !!! Warning !!! -// You MUST unload hive, or this hive becomes unavailable until PC is restarted -// This means the person cannot login. -class RegistryHive { - public: - RegistryHive(); - ~RegistryHive(); - - // Loads hive for requested SID. SID should be in format "S-X-X....." - // name is a name under which the hive will be added to the HKEY_USERS, - // you could use persons name here. This parameter should not have '\\' - // characters! - // It is not recommended to load more than one hive at once - LoadHive, - // manipulate hive, UnloadHive, and then work on the next one. - HRESULT LoadHive(TCHAR const * sid, TCHAR const *name); - // Loads hive for requested SID, but only if the SID is another user - // (since we don't need to do anything if the sid is ours) - HRESULT LoadHive(TCHAR const * sid); - // Unloads and saves loaded hive - HRESULT UnloadHive(); - // Does it recursively. The name should be relative to HKEY_CURRENT_USER. - HRESULT DeleteUserKey(TCHAR const * key_name); - // Expands key name for hive: - // "Software\Google" => "HKEY_USERS\[hive_name_]\Software\Google" - void ExpandKeyName(CString * str); - - private: - CString hive_name_; - HKEY hive_holding_key_; -}; - -// Function pointer -// Return non-zero to abort the enumeration -typedef int ProcessUserRegistryFunc(const TCHAR* user_sid, - const TCHAR* user_reg_key, - LONG_PTR param); - -// Enumerate all user registries -void EnumerateAllUserRegistries(ProcessUserRegistryFunc* handler, - LONG_PTR param); - -} // namespace omaha - -#endif // OMAHA_COMMON_REGISTRY_HIVE_H_ diff --git a/omaha/base/registry_monitor_manager.cc b/omaha/base/registry_monitor_manager.cc index 9057fc0..7edec09 100644 --- a/omaha/base/registry_monitor_manager.cc +++ b/omaha/base/registry_monitor_manager.cc @@ -20,16 +20,19 @@ // The events are signaled when the corresponding monitored key changes. #include "omaha/base/registry_monitor_manager.h" + #include +#include #include #include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/base/thread.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -93,15 +96,15 @@ class ValueWatcher { CString GetCurrentValueString(); DWORD GetCurrentValueDword(); - CString last_known_value_string_; - DWORD last_known_value_dword_; + KeyWatcher* key_watcher_; bool value_is_valid_; RegistryChangeType change_type_; - CString value_name_; - int value_type_; - KeyWatcher* key_watcher_; RegistryValueChangeCallback callback_; void* callback_param_; + CString value_name_; + int value_type_; + DWORD last_known_value_dword_; + CString last_known_value_string_; }; @@ -153,7 +156,7 @@ class KeyWatcher { RegistryKeyChangeCallback callback_; void* callback_param_; - DISALLOW_EVIL_CONSTRUCTORS(KeyWatcher); + DISALLOW_COPY_AND_ASSIGN(KeyWatcher); }; class RegistryMonitorImpl : public Runnable { @@ -186,9 +189,9 @@ class RegistryMonitorImpl : public Runnable { std::vector watchers_; Thread thread_; - scoped_ptr start_monitoring_gate_; + std::unique_ptr start_monitoring_gate_; scoped_event stop_monitoring_; - DISALLOW_EVIL_CONSTRUCTORS(RegistryMonitorImpl); + DISALLOW_COPY_AND_ASSIGN(RegistryMonitorImpl); }; @@ -464,7 +467,7 @@ HRESULT RegistryMonitorImpl::MonitorKey(HKEY root_key, if (watchers_.size() >= MAXIMUM_WAIT_OBJECTS) { return GOOPDATE_E_TOO_MANY_WAITS; } - scoped_ptr key_watcher(new KeyWatcher(key_id)); + std::unique_ptr key_watcher(new KeyWatcher(key_id)); key_watcher->set_callback(callback, user_data); Watcher watcher(key_id, key_watcher.release()); watchers_.push_back(watcher); @@ -489,7 +492,7 @@ HRESULT RegistryMonitorImpl::MonitorValue( if (watchers_.size() >= MAXIMUM_WAIT_OBJECTS) { return GOOPDATE_E_TOO_MANY_WAITS; } - scoped_ptr key_watcher(new KeyWatcher(key_id)); + std::unique_ptr key_watcher(new KeyWatcher(key_id)); HRESULT hr = key_watcher->AddValue(value_name, value_type, callback, user_data); if (FAILED(hr)) { @@ -524,7 +527,7 @@ void RegistryMonitorImpl::Run() { const size_t kNumHandles = kNumNotificationHandles + 1; const size_t kStopMonitoringHandleIndex = kNumNotificationHandles; - scoped_array handles(new HANDLE[kNumHandles]); + std::unique_ptr handles(new HANDLE[kNumHandles]); for (size_t i = 0; i != watchers_.size(); ++i) { handles[i] = watchers_[i].second->notification_event(); VERIFY1(SUCCEEDED(watchers_[i].second->StartWatching())); diff --git a/omaha/base/registry_monitor_manager.h b/omaha/base/registry_monitor_manager.h index 6cf9952..6a6a314 100644 --- a/omaha/base/registry_monitor_manager.h +++ b/omaha/base/registry_monitor_manager.h @@ -22,8 +22,9 @@ #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" namespace omaha { @@ -81,9 +82,9 @@ class RegistryMonitor { HRESULT StartMonitoring(); private: - scoped_ptr impl_; + std::unique_ptr impl_; - DISALLOW_EVIL_CONSTRUCTORS(RegistryMonitor); + DISALLOW_COPY_AND_ASSIGN(RegistryMonitor); }; } // namespace omaha diff --git a/omaha/base/registry_monitor_manager_unittest.cc b/omaha/base/registry_monitor_manager_unittest.cc index cfa4dd4..bf556d9 100644 --- a/omaha/base/registry_monitor_manager_unittest.cc +++ b/omaha/base/registry_monitor_manager_unittest.cc @@ -16,13 +16,13 @@ #include #include #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/reactor.h" #include "omaha/base/reg_key.h" #include "omaha/base/registry_monitor_manager.h" #include "omaha/base/thread.h" #include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/base/registry_store.cc b/omaha/base/registry_store.cc deleted file mode 100644 index 8dad144..0000000 --- a/omaha/base/registry_store.cc +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/registry_store.h" -#include -#include "omaha/base/debug.h" -#include "omaha/base/reg_key.h" - -namespace omaha { - -bool RegistryStore::Open(const TCHAR* key_path) { - key_path_ = key_path; - return true; -} - -bool RegistryStore::Close() { - key_path_.Empty(); - return true; -} - -bool RegistryStore::Clear() { - if (RegKey::HasKey(key_path_)) { - return SUCCEEDED(RegKey::DeleteKey(key_path_, false)); - } else { - return true; - } -} - -bool RegistryStore::Read(const TCHAR* name, std::vector* data) const { - ASSERT1(name); - ASSERT1(data); - - byte* sdata = NULL; - size_t sdata_size = 0; - HRESULT hr = RegKey::GetValue(key_path_, name, &sdata, &sdata_size); - if (FAILED(hr) || !sdata || !sdata_size) - return false; - - data->resize(sdata_size); - memcpy(&data->front(), sdata, sdata_size); - - delete[] sdata; - - return true; -} - -bool RegistryStore::Write(const TCHAR* name, byte* data, int data_size) { - ASSERT1(name); - ASSERT1(data); - ASSERT1(data_size); - - return SUCCEEDED(RegKey::SetValue(key_path_, name, data, data_size)); -} - -bool RegistryStore::Exists(const TCHAR* name) { - ASSERT1(name); - - return RegKey::HasValue(key_path_, name); -} - -bool RegistryStore::Remove(const TCHAR* name) { - ASSERT1(name); - - return SUCCEEDED(RegKey::DeleteValue(key_path_, name)); -} - -bool RegistryStore::GetValueCount(uint32* value_count) { - ASSERT1(value_count); - - CString key_name(key_path_); - HKEY h_key = RegKey::GetRootKeyInfo(&key_name); - - RegKey reg_key; - if (FAILED(reg_key.Open(h_key, key_name.GetString(), KEY_READ))) - return false; - - *value_count = reg_key.GetValueCount(); - - reg_key.Close(); - - return true; -} - -bool RegistryStore::GetValueNameAt(int index, CString* value_name) { - ASSERT1(index >= 0); - ASSERT1(value_name); - - CString key_name(key_path_); - HKEY h_key = RegKey::GetRootKeyInfo(&key_name); - - RegKey reg_key; - if (FAILED(reg_key.Open(h_key, key_name.GetString(), KEY_READ))) - return false; - - HRESULT hr = reg_key.GetValueNameAt(index, value_name, NULL); - - reg_key.Close(); - - return SUCCEEDED(hr); -} - -} // namespace omaha - diff --git a/omaha/base/registry_store.h b/omaha/base/registry_store.h deleted file mode 100644 index d7e55cb..0000000 --- a/omaha/base/registry_store.h +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Declares class RegistryStore -/////////////////////////////////////////////////////////////////////////// - -#ifndef OMAHA_COMMON_REGISTRY_STORE_H__ -#define OMAHA_COMMON_REGISTRY_STORE_H__ - -#include -#include -#include -#include "base/basictypes.h" - -namespace omaha { - -class RegistryStore { - public: - // Constructor - RegistryStore() {} - - // Destructor - ~RegistryStore() {} - - // Open the store - bool Open(const TCHAR* key_path); - - // Close the store - bool Close(); - - // Clear the store - bool Clear(); - - // Read a value from the store - bool Read(const TCHAR* name, std::vector* data) const; - - // Write a value to the store - bool Write(const TCHAR* name, byte* data, int data_size); - - // Check to see a named value exists in the store - bool Exists(const TCHAR* name); - - // Remove a value from the store - bool Remove(const TCHAR* name); - - // Get the number of values for this key - bool GetValueCount(uint32* value_count); - - // Get the value name for the given value name index - bool GetValueNameAt(int index, CString* value_name); - - private: - CString key_path_; // Full path to the registry key -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_REGISTRY_STORE_H__ diff --git a/omaha/base/registry_store_unittest.cc b/omaha/base/registry_store_unittest.cc deleted file mode 100644 index 6d7bdb3..0000000 --- a/omaha/base/registry_store_unittest.cc +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// -// Unit test for RegistryStore. - -#include "omaha/base/registry_store.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -static const TCHAR kRSTestKey[] = - _T("HKCU\\Software\\Google\\Common_Installer__TEST_STORE"); -static const TCHAR kRSTestName[] = _T("TestValueName"); -static const byte kRSTestValue[] = {0x01, 0x02, 0x03, 0x04, 0x05}; -static const int kRSTestValueSize = arraysize(kRSTestValue); - -TEST(RegistryStoreTest, RegistryStore) { - RegistryStore registry_store; - uint32 value_count = 42; // We want to make sure it's overwritten with 0. - CString value_name; - std::vector data; - - // Set up and get in a known state. - EXPECT_TRUE(registry_store.Open(kRSTestKey)); - EXPECT_TRUE(registry_store.Clear()); - - // Add and test a single value - EXPECT_FALSE(registry_store.Exists(kRSTestName)); - EXPECT_FALSE(registry_store.Read(kRSTestName, &data)); - data.clear(); - - EXPECT_TRUE(registry_store.Write(kRSTestName, - const_cast(kRSTestValue), - kRSTestValueSize)); - - EXPECT_TRUE(registry_store.Exists(kRSTestName)); - EXPECT_TRUE(registry_store.Read(kRSTestName, &data)); - EXPECT_EQ(data.size(), kRSTestValueSize); - for (int i = 0; i < kRSTestValueSize; i++) - EXPECT_EQ(data[i], kRSTestValue[i]); - - // Remove and re-add value - EXPECT_TRUE(registry_store.Remove(kRSTestName)); - EXPECT_FALSE(registry_store.Exists(kRSTestName)); - EXPECT_TRUE(registry_store.GetValueCount(&value_count)); - EXPECT_EQ(value_count, 0); - EXPECT_TRUE(registry_store.Write(kRSTestName, - const_cast(kRSTestValue), - kRSTestValueSize)); - EXPECT_TRUE(registry_store.GetValueCount(&value_count)); - EXPECT_EQ(value_count, 1); - EXPECT_TRUE(registry_store.GetValueNameAt(0, &value_name)); - EXPECT_TRUE(value_name == kRSTestName); - - // Clean up and finish. - EXPECT_TRUE(registry_store.Clear()); - EXPECT_FALSE(registry_store.Exists(kRSTestName)); - EXPECT_FALSE(registry_store.GetValueCount(&value_count)); - EXPECT_TRUE(registry_store.Close()); -} - -} // namespace omaha diff --git a/omaha/base/run_as_invoker.rc b/omaha/base/run_as_invoker.rc index 8c37334..6f66001 100644 --- a/omaha/base/run_as_invoker.rc +++ b/omaha/base/run_as_invoker.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) diff --git a/omaha/base/scoped_any.h b/omaha/base/scoped_any.h deleted file mode 100644 index d7735f8..0000000 --- a/omaha/base/scoped_any.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// smartany library uses a poor compile time assert. It is actually generating -// runtime code to call the constructor of the assert class. Most likely to -// improve performance, the library uses a static instance of the compile time -// assert object. In theory the code is not thread-safe. In practice, since the -// compile time assert is an empty class, there should be no problems. The long -// term solution requires changing smartany to use a better compile time assert -// which is completely evaluated at compile time and it has no effects -// whatsoever at runtime. Short term, the code should include these wrappers -// to silence the compiler warning. - -#ifndef OMAHA_COMMON_SCOPED_ANY__ -#define OMAHA_COMMON_SCOPED_ANY__ - -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) -#include "omaha/third_party/smartany/scoped_any.h" -#pragma warning(pop) - -#endif // OMAHA_COMMON_SCOPED_ANY__ - diff --git a/omaha/base/scoped_impersonation.h b/omaha/base/scoped_impersonation.h index aa08849..6a78061 100644 --- a/omaha/base/scoped_impersonation.h +++ b/omaha/base/scoped_impersonation.h @@ -23,7 +23,7 @@ #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/base/scoped_impersonation_unittest.cc b/omaha/base/scoped_impersonation_unittest.cc index a476a34..4c44471 100644 --- a/omaha/base/scoped_impersonation_unittest.cc +++ b/omaha/base/scoped_impersonation_unittest.cc @@ -15,11 +15,10 @@ #include #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scoped_impersonation.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/vista_utils.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/base/scoped_ptr_address.h b/omaha/base/scoped_ptr_address.h deleted file mode 100644 index 0fa6930..0000000 --- a/omaha/base/scoped_ptr_address.h +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// Helper functions to enable a useful pattern of using scoped pointers in -// which the ownership of the memory is transferred out to an empty -// scoped_ptr or scoped_array. -// -// The usage pattern is as follows: -// void foo(Bar** b); -// -// scoped_ptr p; -// foo(address(p)); -// -// To receive the ownwership of the resource the scoped pointer must be -// empty, otherwise it will leak. -// -// As an implementation detail, the scoped pointers in "base/scoped_ptr.h" do -// not offer support for this idiom. The code below may break if the -// implementation of the scoped_ptr changes. The code works with the vast -// majority of the scoped_ptr implementations though. -// -// TODO(omaha): add unit tests. - -#ifndef OMAHA_COMMON_SCOPED_PTR_ADDRESS__ -#define OMAHA_COMMON_SCOPED_PTR_ADDRESS__ - -#include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/debug.h" - -template -inline T** address(const scoped_ptr& t) { - COMPILE_ASSERT(sizeof(T*) == sizeof(scoped_ptr), types_do_not_match); - ASSERT1(!t.get()); - return reinterpret_cast(&const_cast&>(t)); -} - -template -inline T** address(const scoped_array& t) { - COMPILE_ASSERT(sizeof(T*) == sizeof(scoped_ptr), types_do_not_match); - ASSERT1(!t.get()); - return reinterpret_cast(&const_cast&>(t)); -} - -#endif // OMAHA_COMMON_SCOPED_PTR_ADDRESS__ - diff --git a/omaha/base/scoped_ptr_cotask.h b/omaha/base/scoped_ptr_cotask.h index 2f45f99..bbf8d26 100644 --- a/omaha/base/scoped_ptr_cotask.h +++ b/omaha/base/scoped_ptr_cotask.h @@ -20,6 +20,7 @@ #define OMAHA_COMMON_SCOPED_PTR_COTASK_H__ #include +#include #include "omaha/base/debug.h" // scoped_ptr_cotask is identical to scoped_ptr, except that CoTaskMemFree is diff --git a/omaha/base/security/build.scons b/omaha/base/security/build.scons index b16a905..8eaeaeb 100644 --- a/omaha/base/security/build.scons +++ b/omaha/base/security/build.scons @@ -26,12 +26,12 @@ security_env.Append( CCFLAGS = [ '/wd4242', # conversion from 'type1' to 'type2', possible loss of data '/wd4244', # conversion from 'type1' to 'type2', possible loss of data + '/wd4245', # initializing': conversion from/to signed/unsigned mismatch ], ) security_inputs = [ 'hmac.c', - 'md5.c', 'p256.c', 'p256_ec.c', 'p256_ecdsa.c', @@ -41,7 +41,4 @@ security_inputs = [ 'util.c', ] -# Precompiled headers cannot be used with C files. -security_env.ComponentStaticLibraryMultiarch('security', - security_inputs, - use_pch_default=False) +security_env.ComponentStaticLibraryMultiarch('security', security_inputs) diff --git a/omaha/base/security/hash-internal.h b/omaha/base/security/hash-internal.h index ce6522a..501e199 100644 --- a/omaha/base/security/hash-internal.h +++ b/omaha/base/security/hash-internal.h @@ -16,8 +16,8 @@ #ifndef OMAHA_BASE_SECURITY_HASH_INTERNAL_H_ #define OMAHA_BASE_SECURITY_HASH_INTERNAL_H_ -#include #include +#include #ifdef LITE_EMULATED_64BIT_OPS #define LITE_LShiftU64(a, b) LShiftU64((a), (b)) diff --git a/omaha/base/security/hmac.c b/omaha/base/security/hmac.c index 87e0166..667076d 100644 --- a/omaha/base/security/hmac.c +++ b/omaha/base/security/hmac.c @@ -20,7 +20,6 @@ #include #include "sha.h" -#include "md5.h" #include "sha256.h" static void HMAC_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { @@ -47,11 +46,6 @@ static void HMAC_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { } } -void HMAC_MD5_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { - MD5_init(&ctx->hash); - HMAC_init(ctx, key, len); -} - void HMAC_SHA_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) { SHA_init(&ctx->hash); HMAC_init(ctx, key, len); diff --git a/omaha/base/security/hmac.h b/omaha/base/security/hmac.h index 4a66741..baf545f 100644 --- a/omaha/base/security/hmac.h +++ b/omaha/base/security/hmac.h @@ -28,7 +28,6 @@ typedef struct LITE_HMAC_CTX { uint8_t opad[64]; } LITE_HMAC_CTX; -void HMAC_MD5_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len); void HMAC_SHA_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len); void HMAC_SHA256_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len); const uint8_t* HMAC_final(LITE_HMAC_CTX* ctx); diff --git a/omaha/base/security/hmac_unittest.cc b/omaha/base/security/hmac_unittest.cc index 0a5abd5..339926a 100644 --- a/omaha/base/security/hmac_unittest.cc +++ b/omaha/base/security/hmac_unittest.cc @@ -35,88 +35,74 @@ static const struct KAT { const char* sha1; const char* sha256; } KATS[] = { - { -"x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", 16, -"Hi There", -"9294727a3638bb1c13f48ef8158bfc9d", -"b617318655057264e28bc0b6fb378c8ef146be00", -"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" - }, { -"Jefe", 4, -"what do ya want for nothing?", -"750c783e6ab0b503eaa86e310a5db738", -"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", -"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" - }, { -"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 16, -"xdddddddddddddddddddddddddddddddddddddddddddddddddd" -"dddddddddddddddddddddddddddddddddddddddddddddddddd", -"56be34521d144c88dbb8c733f0e8b3f6", -"125d7342b9ac11cd91a39af48aa17b4f63f175d3", -"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" - }, { -"x0102030405060708090a0b0c0d0e0f10111213141516171819", 25, -"xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" -"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", -"697eaf0aca3a3aea3a75164746ffaa79", -"4c9007f4026250c6bc8414f9bf50c86c2d7235da", -"82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" - }, { -"x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", 16, -"Test With Truncation", -"56461ef2342edc00f9bab995690efd4c", -"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04", -"a3b6167473100ee06e0c796c2955552bfa6f7c0a6a8aef8b93f860aab0cd20c5" - }, { -"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 80, -"Test Using Larger Than Block-Size Key - Hash Key First", -"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd", -"aa4ae5e15272d00e95705637ce8a3b55ed402112", -NULL }, { -"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaa", 8 * 16 + 3, -"Test Using Larger Than Block-Size Key - Hash Key First", -NULL, -NULL, -"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" - }, { -"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 80, -"Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data", -"6f630fad67cda0ee1fb1f562db3aa53e", -"e8e99d0f45237d786d6bbaa7965c7808bbff1a91", -NULL - } , { -"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" -"aaaaaa", 8 * 16 + 3, -"This is a test using a larger than block-size key and a larger t" -"han block-size data. The key needs to be hashed before being use" -"d by the HMAC algorithm.", -NULL, -NULL, -"9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" - }, - { 0 } -}; + {"x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", 16, "Hi There", + "9294727a3638bb1c13f48ef8158bfc9d", + "b617318655057264e28bc0b6fb378c8ef146be00", + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"}, + {"Jefe", 4, "what do ya want for nothing?", + "750c783e6ab0b503eaa86e310a5db738", + "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"}, + {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 16, + "xdddddddddddddddddddddddddddddddddddddddddddddddddd" + "dddddddddddddddddddddddddddddddddddddddddddddddddd", + "56be34521d144c88dbb8c733f0e8b3f6", + "125d7342b9ac11cd91a39af48aa17b4f63f175d3", + "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"}, + {"x0102030405060708090a0b0c0d0e0f10111213141516171819", 25, + "xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + "697eaf0aca3a3aea3a75164746ffaa79", + "4c9007f4026250c6bc8414f9bf50c86c2d7235da", + "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"}, + {"x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", 16, "Test With Truncation", + "56461ef2342edc00f9bab995690efd4c", + "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04", + "a3b6167473100ee06e0c796c2955552bfa6f7c0a6a8aef8b93f860aab0cd20c5"}, + {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + 80, "Test Using Larger Than Block-Size Key - Hash Key First", + "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd", + "aa4ae5e15272d00e95705637ce8a3b55ed402112", nullptr}, + {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa", + 8 * 16 + 3, "Test Using Larger Than Block-Size Key - Hash Key First", + nullptr, nullptr, + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"}, + {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + 80, + "Test Using Larger Than Block-Size Key and Larger Than One Block-Size " + "Data", + "6f630fad67cda0ee1fb1f562db3aa53e", + "e8e99d0f45237d786d6bbaa7965c7808bbff1a91", nullptr}, + {"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaa", + 8 * 16 + 3, + "This is a test using a larger than block-size key and a larger t" + "han block-size data. The key needs to be hashed before being use" + "d by the HMAC algorithm.", + nullptr, nullptr, + "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"}, + {nullptr}}; TEST_F(HmacTest, RFC2202andRFC4131) { // This tests against the RFC2202 & RFC4131 test vectors @@ -128,16 +114,6 @@ TEST_F(HmacTest, RFC2202andRFC4131) { string data = katp->data[0] == 'x' ? omaha::a2b_hex(katp->data + 1) : katp->data; - if (katp->md5) { - HMAC_MD5_init(&hmac, key.data(), katp->md5_keylength); - HMAC_update(&hmac, data.data(), data.size()); - - EXPECT_EQ(omaha::b2a_hex( - reinterpret_cast(HMAC_final(&hmac)), - HMAC_size(&hmac)), - katp->md5); - } - if (katp->sha1) { HMAC_SHA_init(&hmac, key.data(), key.size()); HMAC_update(&hmac, data.data(), data.size()); diff --git a/omaha/base/security/md5.c b/omaha/base/security/md5.c deleted file mode 100644 index 940fbea..0000000 --- a/omaha/base/security/md5.c +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Optimized for minimal code size. - -#include "md5.h" - -#include -#include - -#define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -static const char Kr[64] = -{ - 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, - 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, - 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, - 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 -}; - -static const uint32_t KK[64] = -{ - 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, - 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, - 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, - 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, - 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, - 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, - 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, - 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, - 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, - 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, - 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, - 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 -}; - -static void MD5_Transform(LITE_MD5_CTX* ctx) { - uint32_t W[64]; - uint32_t A, B, C, D; - uint8_t* p = ctx->buf; - int t; - - for(t = 0; t < 16; ++t) { - uint32_t tmp = *p++; - tmp |= (uint32_t)*p++ << 8u; - tmp |= (uint32_t)*p++ << 16u; - tmp |= (uint32_t)*p++ << 24u; - W[t] = tmp; - } - - A = ctx->state[0]; - B = ctx->state[1]; - C = ctx->state[2]; - D = ctx->state[3]; - - for(t = 0; t < 64; t++) { - uint32_t f, tmp; - int g; - - if (t < 16) { - f = (D^(B&(C^D))); - g = t; - } else if ( t < 32) { - f = (C^(D&(B^C))); - g = (5*t + 1) & 15; - } else if ( t < 48) { - f = (B^C^D); - g = (3*t + 5) & 15; - } else { - f = (C^(B|(~D))); - g = (7*t) & 15; - } - - tmp = D; - D = C; - C = B; - B = B + rol(Kr[t], (A+f+KK[t]+W[g])); - A = tmp; - } - - ctx->state[0] += A; - ctx->state[1] += B; - ctx->state[2] += C; - ctx->state[3] += D; -} - -static const HASH_VTAB MD5_VTAB = { - MD5_init, - MD5_update, - MD5_final, - MD5_hash, - MD5_DIGEST_SIZE -}; - -void MD5_init(LITE_MD5_CTX* ctx) { - ctx->f = &MD5_VTAB; - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xEFCDAB89; - ctx->state[2] = 0x98BADCFE; - ctx->state[3] = 0x10325476; - ctx->count = 0; -} - - -void MD5_update(LITE_MD5_CTX* ctx, const void* data, size_t len) { - unsigned int i = (unsigned int)(ctx->count & 63); - const uint8_t* p = (const uint8_t*)data; - - ctx->count += len; - - while (len--) { - ctx->buf[i++] = *p++; - if (i == 64) { - MD5_Transform(ctx); - i = 0; - } - } -} - - -const uint8_t* MD5_final(LITE_MD5_CTX* ctx) { - uint8_t* p = ctx->buf; - uint64_t cnt = LITE_LShiftU64(ctx->count, 3); - int i; - - MD5_update(ctx, (uint8_t*)"\x80", 1); - while ((ctx->count & 63) != 56) { - MD5_update(ctx, (uint8_t*)"\0", 1); - } - for (i = 0; i < 8; ++i) { - uint8_t tmp = (uint8_t) LITE_RShiftU64(cnt, i * 8); - MD5_update(ctx, &tmp, 1); - } - - for (i = 0; i < 4; i++) { - uint32_t tmp = ctx->state[i]; - *p++ = tmp; - *p++ = tmp >> 8; - *p++ = tmp >> 16; - *p++ = tmp >> 24; - } - - return ctx->buf; -} - - -/* Convenience function */ -const uint8_t* MD5_hash(const void* data, size_t len, uint8_t* digest) { - LITE_MD5_CTX ctx; - MD5_init(&ctx); - MD5_update(&ctx, data, len); - memcpy(digest, MD5_final(&ctx), MD5_DIGEST_SIZE); - return digest; -} diff --git a/omaha/base/security/md5.h b/omaha/base/security/md5.h deleted file mode 100644 index c351a27..0000000 --- a/omaha/base/security/md5.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_BASE_SECURITY_MD5_H_ -#define OMAHA_BASE_SECURITY_MD5_H_ - -#include -#include -#include "hash-internal.h" - -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -typedef HASH_CTX LITE_MD5_CTX; - -void MD5_init(LITE_MD5_CTX* ctx); -void MD5_update(LITE_MD5_CTX* ctx, const void* data, size_t len); -const uint8_t* MD5_final(LITE_MD5_CTX* ctx); - -// Convenience method. Returns digest address. -// NOTE: *digest needs to hold MD5_DIGEST_SIZE bytes. -const uint8_t* MD5_hash(const void* data, size_t len, uint8_t* digest); - -#define MD5_DIGEST_SIZE 16 - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif // OMAHA_BASE_SECURITY_MD5_H_ diff --git a/omaha/base/security/p256.c b/omaha/base/security/p256.c index 49a68a8..b1e14f4 100644 --- a/omaha/base/security/p256.c +++ b/omaha/base/security/p256.c @@ -173,7 +173,6 @@ void p256_modmul(const p256_int* MOD, memcpy(c, tmp, P256_NBYTES); } -int p256_is_odd(const p256_int* a) { return P256_DIGIT(a, 0) & 1; } int p256_is_even(const p256_int* a) { return !(P256_DIGIT(a, 0) & 1); } p256_digit p256_shl(const p256_int* a, int n, p256_int* b) { @@ -448,10 +447,10 @@ void p256_from_le_bin(const uint8_t src[P256_NBYTES], p256_int* dst) { for (i = 0; i < P256_NDIGITS; ++i) { P256_DIGIT(dst, i) = - p[0] | - (p[1] << 8) | - (p[2] << 16) | - (p[3] << 24); + (uint32_t)p[0] | + ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); p += 4; } } diff --git a/omaha/base/security/p256.h b/omaha/base/security/p256.h index bb74ff8..42e1edd 100644 --- a/omaha/base/security/p256.h +++ b/omaha/base/security/p256.h @@ -98,7 +98,6 @@ p256_digit p256_shl(const p256_int* a, int n, p256_int* b); void p256_shr(const p256_int* a, int n, p256_int* b); int p256_is_zero(const p256_int* a); -int p256_is_odd(const p256_int* a); int p256_is_even(const p256_int* a); // Returns -1, 0 or 1. diff --git a/omaha/base/security/p256_ecdsa.c b/omaha/base/security/p256_ecdsa.c index fbd51b3..ba6cc74 100644 --- a/omaha/base/security/p256_ecdsa.c +++ b/omaha/base/security/p256_ecdsa.c @@ -14,8 +14,8 @@ // ======================================================================== #include "p256_ecdsa.h" -#include "p256.h" #include "hmac.h" +#include "p256.h" #include "sha256.h" // Compute k based on given {key, message} pair, 0 < k < n. diff --git a/omaha/base/security/p256_prng.c b/omaha/base/security/p256_prng.c index 581226d..82ed438 100644 --- a/omaha/base/security/p256_prng.c +++ b/omaha/base/security/p256_prng.c @@ -15,8 +15,8 @@ #include -#include "p256_prng.h" #include "hmac.h" +#include "p256_prng.h" #include "sha256.h" static void uint64tobin(uint64_t v, uint8_t* t) { diff --git a/omaha/base/security/p256_prng.h b/omaha/base/security/p256_prng.h index 1701874..98ae5c6 100644 --- a/omaha/base/security/p256_prng.h +++ b/omaha/base/security/p256_prng.h @@ -26,8 +26,8 @@ // NOTE: leakage of initial- and subsequent (if any) seed material allows for // re-generation of the psuedo random sequence and thus derived key material. -#include #include +#include #ifdef __cplusplus extern "C" { @@ -36,8 +36,8 @@ extern "C" { #define P256_PRNG_SIZE 32 typedef struct P256_PRNG_CTX { - uint32_t Key[P256_PRNG_SIZE]; - uint32_t V[P256_PRNG_SIZE]; + uint8_t Key[P256_PRNG_SIZE]; + uint8_t V[P256_PRNG_SIZE]; uint64_t instance_count; uint64_t call_count; } P256_PRNG_CTX; diff --git a/omaha/base/security/p256_unittest.c b/omaha/base/security/p256_unittest.c index 3158ffa..f454ed3 100644 --- a/omaha/base/security/p256_unittest.c +++ b/omaha/base/security/p256_unittest.c @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include "p256.h" diff --git a/omaha/base/security/sha.c b/omaha/base/security/sha.c index 11cd3d7..3b0a795 100644 --- a/omaha/base/security/sha.c +++ b/omaha/base/security/sha.c @@ -17,8 +17,8 @@ #include "sha.h" -#include #include +#include #define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits)))) @@ -29,10 +29,10 @@ static void SHA1_Transform(SHA_CTX* ctx) { int t; for(t = 0; t < 16; ++t) { - uint32_t tmp = *p++ << 24; - tmp |= *p++ << 16; - tmp |= *p++ << 8; - tmp |= *p++; + uint32_t tmp = (uint32_t)(*p++) << 24; + tmp |= (uint32_t)(*p++) << 16; + tmp |= (uint32_t)(*p++) << 8; + tmp |= (uint32_t)(*p++); W[t] = tmp; } diff --git a/omaha/base/security/sha256.c b/omaha/base/security/sha256.c index 0414e6a..501dd9a 100644 --- a/omaha/base/security/sha256.c +++ b/omaha/base/security/sha256.c @@ -17,6 +17,7 @@ #include "sha256.h" +#include #include #define ror(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits)))) @@ -47,10 +48,10 @@ static void SHA256_Transform(LITE_SHA256_CTX* ctx) { int t; for(t = 0; t < 16; ++t) { - uint32_t tmp = *p++ << 24; - tmp |= *p++ << 16; - tmp |= *p++ << 8; - tmp |= *p++; + uint32_t tmp = (uint32_t)*p++ << 24; + tmp |= (uint32_t)*p++ << 16; + tmp |= (uint32_t)*p++ << 8; + tmp |= (uint32_t)*p++; W[t] = tmp; } diff --git a/omaha/base/security/sha256.h b/omaha/base/security/sha256.h index 8146f43..560b6e7 100644 --- a/omaha/base/security/sha256.h +++ b/omaha/base/security/sha256.h @@ -16,8 +16,8 @@ #ifndef OMAHA_BASE_SECURITY_SHA256_H_ #define OMAHA_BASE_SECURITY_SHA256_H_ -#include #include +#include #include "hash-internal.h" #ifdef __cplusplus diff --git a/omaha/base/security/sha256_unittest.cc b/omaha/base/security/sha256_unittest.cc index 1c66900..11f1807 100644 --- a/omaha/base/security/sha256_unittest.cc +++ b/omaha/base/security/sha256_unittest.cc @@ -22,7 +22,7 @@ namespace omaha { // This test data from http://en.wikipedia.org/wiki/SHA-2: struct { - char* binary; + const char* binary; byte hash[32]; } test_hash256[] = { "", diff --git a/omaha/base/security/util.c b/omaha/base/security/util.c index 7fb083c..51514a0 100644 --- a/omaha/base/security/util.c +++ b/omaha/base/security/util.c @@ -9,3 +9,19 @@ void *always_memset(void *s, int c, size_t n) { always_memset_impl((char*) s, c, n); return s; } + +int ct_memeq(const void* s1, const void* s2, uint32_t n) { + uint8_t diff = 0; + const uint8_t* ps1 = s1; + const uint8_t* ps2 = s2; + + while (n--) { + diff |= *ps1 ^ *ps2; + ps1++; + ps2++; + } + + // Counter-intuitive, but we can't just return diff because we don't want to + // leak the xor of non-equal bytes + return 0 != diff; +} diff --git a/omaha/base/security/util.h b/omaha/base/security/util.h index 32edcaf..05f8bc7 100644 --- a/omaha/base/security/util.h +++ b/omaha/base/security/util.h @@ -2,9 +2,22 @@ #define SECURITY_UTIL_LITE_UTIL_H_ #include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus /* An implementation of memset that ought not to be optimized away; * useful for scrubbing security sensitive buffers. */ void *always_memset(void *s, int c, size_t n); +/* Constant-time memory equality test. Returns 0 to indicate equivalence to + * behave in a memcmp()-compatible way. */ +int ct_memeq(const void* s1, const void* s2, uint32_t n); + +#ifdef __cplusplus +} +#endif // __cplusplus + #endif // SECURITY_UTIL_LITE_UTIL_H_ diff --git a/omaha/base/serializable_object.cc b/omaha/base/serializable_object.cc deleted file mode 100644 index 04ca9fa..0000000 --- a/omaha/base/serializable_object.cc +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Provides the base class framework for those objects to be serialized -// -// HACK: -// -// During the serialization/deserialization of vector members, we -// coerce the type from vector to vector since we are unable to -// get the real type vector at later time. This is feasible because -// vector in the vector library we are linking now keeps track of -// only front() and end() pointers and use them to calculate size(). -// We need to check whether this approach is still OK if we upgrade the -// standard libraries. - -#include "omaha/base/serializable_object.h" -#include -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" - -namespace omaha { - -// Serialize -bool SerializableObject::Serialize(std::vector* data) const { - ASSERT(data, (_T(""))); - - // Estimate how much memory we need - size_t size = data->size(); - for (size_t i = 0; i < members_.size(); ++i) - size += (members_[i].size > 0) ? members_[i].size : sizeof(int); - - // Reserve the estimated size fo vector memory - data->reserve(size); - - // Copy over the data - for (size_t i = 0; i < members_.size(); ++i) { - switch (members_[i].type) { - case SERIALIZABLE_VALUE_TYPE: { - size_t pos = data->size(); - data->resize(data->size() + members_[i].size); - memcpy(&(*data)[pos], members_[i].ptr, members_[i].size); - break; - } - - case SERIALIZABLE_CSTRING: { - CString* s = reinterpret_cast(members_[i].ptr); - SerializeValueList(data, - reinterpret_cast(s->GetString()), - sizeof(TCHAR), - s->GetLength()); - break; - } - - case SERIALIZABLE_NESTED_OBJECT: { - SerializableObject* nested_obj = - reinterpret_cast(members_[i].ptr); - if (!nested_obj->Serialize(data)) - return false; - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_VALUE_TYPE: { - // Hack: coerce vector to vector - std::vector* v = - reinterpret_cast*>(members_[i].ptr); - if (v->size() != 0) { - SerializeValueList(data, - &v->front(), - members_[i].size, - v->size() / members_[i].size); - } else { - SerializeValueList(data, - NULL, - members_[i].size, - v->size() / members_[i].size); - } - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_CSTRING: { - std::vector* v = - reinterpret_cast*>(members_[i].ptr); - SerializeSizeAndCount(data, 1, v->size()); - if (!v->empty()) { - for (std::vector::const_iterator it = v->begin(); - it != v->end(); - ++it) { - SerializeValueList(data, - reinterpret_cast(it->GetString()), - sizeof(TCHAR), - it->GetLength()); - } - } - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_NESTED_OBJECT: { - if (!SerializeVectorNestedObject(data, members_[i].ptr)) - return false; - break; - } - - default: - ASSERT(false, (_T(""))); - return false; - } - } - - return true; -} - -// Serialize the size and count values -void SerializableObject::SerializeSizeAndCount(std::vector* data, - size_t size, - size_t count) const { - ASSERT(data, (_T(""))); - - // Get current size - const size_t pos = data->size(); - - // Adjust the size of the data buffer - data->resize(data->size() + 2 * sizeof(int)); - - // Get pointer to the position of data buffer we start to write - byte* ptr = &((*data)[pos]); - - // Push size - memcpy(ptr, &size, sizeof(int)); - ptr += sizeof(int); - - // Push count - memcpy(ptr, &count, sizeof(int)); - ptr += sizeof(int); -} - -// Serialize a list of value-typed elements -// -// Args: -// ser_data: pointer to the vector for the serialized data -// raw_data: pointer to the raw data to be serialized -// size: the size of the element in the list -// count: the number of the elements in the list -void SerializableObject::SerializeValueList(std::vector* ser_data, - const byte* raw_data, - size_t size, - size_t count) const { - ASSERT(ser_data, (_T(""))); - - // Serialize the size and count values - SerializeSizeAndCount(ser_data, size, count); - - // Push data - if (count > 0) { - // Get current size - const size_t pos = ser_data->size(); - - // Adjust the size of the data buffer - ser_data->resize(ser_data->size() + count * size); - - // Get pointer to the position of data buffer we start to write - byte* ptr = &((*ser_data)[pos]); - - // Copy data - memcpy(ptr, raw_data, count * size); - } -} - -// Deserialize -bool SerializableObject::Deserialize(byte* data, size_t size, uint32 version) { - ASSERT(data, (_T(""))); - - byte* tail = data + size; - byte** data_ptr = &data; - if (!DeserializeHelper(data_ptr, size, version)) - return false; - - if (*data_ptr != tail) { - UTIL_LOG(LE, (_T("[SerializableObject::Deserialize]") - _T("[failed to deserialize all data]"))); - return false; - } - - return true; -} - -// Deserialize helper -bool SerializableObject::DeserializeHelper(byte** data, - size_t size, - uint32 version) { - ASSERT(data, (_T(""))); - - byte* tail = *data + size; - - for (size_t i = 0; i < members_.size(); ++i) { - // Ignore those members which are persisted in newer versions - if (version != kLatestSerializableVersion && - members_[i].version > version) { - continue; - } - - switch (members_[i].type) { - case SERIALIZABLE_VALUE_TYPE: - if (*data + members_[i].size > tail) { - UTIL_LOG(L6, (_T("[SerializableObject::DeserializeHelper]") - _T("[overflow when deserializing value type]"))); - return false; - } - memcpy(members_[i].ptr, *data, members_[i].size); - *data += members_[i].size; - break; - - case SERIALIZABLE_CSTRING: { - std::vector deser_data; - if (!DeserializeValueList(&deser_data, - members_[i].size, - data, - tail - *data)) - return false; - CString* s = reinterpret_cast(members_[i].ptr); - if (deser_data.size() != 0) { - const size_t length = deser_data.size() / members_[i].size; - if (length > INT_MAX) { - return false; - } - s->SetString(reinterpret_cast(&deser_data.front()), - static_cast(length)); - } else { - s->SetString(_T("")); - } - break; - } - - case SERIALIZABLE_NESTED_OBJECT: { - SerializableObject* nested_obj = - reinterpret_cast(members_[i].ptr); - if (!nested_obj->DeserializeHelper(data, size, version)) - return false; - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_VALUE_TYPE: { - // Hack: coerce vector to vector - std::vector* v = - reinterpret_cast*>(members_[i].ptr); - if (!DeserializeValueList(v, members_[i].size, data, tail - *data)) - return false; - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_CSTRING: { - std::vector* v = - reinterpret_cast*>(members_[i].ptr); - size_t count = 0; - if (!DeserializeSizeAndCount(&count, 1, data, tail - *data)) - return false; - for (size_t j = 0; j < count; ++j) { - std::vector deser_data; - if (!DeserializeValueList(&deser_data, - members_[i].size, - data, - tail - *data)) - return false; - - CString s; - if (deser_data.size() != 0) { - const size_t length = deser_data.size() / members_[i].size; - if (length > INT_MAX) { - return false; - } - s = CString(reinterpret_cast(&deser_data.front()), - static_cast(length)); - } - v->push_back(s); - } - break; - } - - case SERIALIZABLE_VECTOR | SERIALIZABLE_NESTED_OBJECT: { - if (!DeserializeVectorNestedObject(data, - tail - *data, - members_[i].ptr, - version)) - return false; - break; - } - - default: - ASSERT(false, (_T(""))); - break; - } - } - - return true; -} - -// Serialize the size and count values -bool SerializableObject::DeserializeSizeAndCount(size_t* count, - size_t size, - byte** ser_data, - size_t ser_size) const { - ASSERT(ser_data, (_T(""))); - - byte* ser_tail = *ser_data + ser_size; - - // Check to make sure that the serialization data should at least contain - // 'size' and 'count' - if (*ser_data + 2 * sizeof(int) > ser_tail) { - UTIL_LOG(L6, (_T("[SerializableObject::DeserializeSizeAndCount]") - _T("[overflow when deserializing size and count]"))); - return false; - } - - // Get size - // If the passing size is 0, skip the size check - size_t size2 = *(reinterpret_cast(*ser_data)); - *ser_data += sizeof(int); - if (size && size != size2) - return false; - - // Get count - *count = *(reinterpret_cast(*ser_data)); - *ser_data += sizeof(int); - - return true; -} - -// Deserialize a list of value-typed elements -// -// Args: -// ser_data: pointer to the vector for the serialized data -// size: the size of the element in the list -// raw_data: pointer to the raw data to be serialized -// ser_size: size of the serization data -bool SerializableObject::DeserializeValueList(std::vector* raw_data, - size_t size, - byte** ser_data, - size_t ser_size) { - ASSERT(raw_data, (_T(""))); - - byte* ser_tail = *ser_data + ser_size; - - // Deserialize the size and count values - size_t count = 0; - bool ret = DeserializeSizeAndCount(&count, size, ser_data, ser_size); - if (!ret) - return false; - - // Check to make sure that the serialization data is in the right size - if (*ser_data + count * size > ser_tail) { - UTIL_LOG(L6, (_T("[SerializableObject::DeserializeValueList]") - _T("[overflow when deserializing value list]"))); - return false; - } - - // Get data - raw_data->resize(size * count); - if (count > 0) { - memcpy(&raw_data->front(), *ser_data, count * size); - *ser_data += count * size; - } - - return true; -} - -} // namespace omaha - diff --git a/omaha/base/serializable_object.h b/omaha/base/serializable_object.h deleted file mode 100644 index 9b7ee4b..0000000 --- a/omaha/base/serializable_object.h +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Declares class SerializableObject -// -// Provides the base class framework for those objects to be serialized -// -// Currently we support the serialization for the following member type -// -// 1) Value-type object -// 2) CString -// 3) Nested serializable object -// 4) Vector of the value-type objects -// 5) Vector of CString -// 6) Vector of serializable objects -// -// Usage: -// -// 1) Declare the object class, which you want to serialize, to be derived -// from SerializableObject -// 2) In its constructor, call AddSerializableMember(...) to add those fields -// to be included in the serialization -// 3) If you need to serialize a vector of serializable objects, -// a) The inner object class has to implement copy constructor and -// operator = -// b) The outer object class has to override SerializeVectorNestedObject() -// and DeserializeVectorNestedObject() (see sample) -// -// Versioning support: -// -// To add new fields in the new version, call -// AddSerializableMember(version, &member); -// If "version" is not given, it is 0 by default. -// -// To deserialize the data for latest version, call -// Deserialize(data, size, kLatestSerializableVersion); -// To deserialize the data for a particular version, call -// Deserialize(data, size, version); -// -// Sample: -// -// class FooObject : public SerializableObject { -// ... -// }; -// -// class BarObject : public SerializableObject { -// public: -// BarObject() { -// AddSerializableMember(&value1_); -// AddSerializableMember(&value2_); -// AddSerializableMember(&value3_); -// AddSerializableMember(&value4_); -// AddSerializableMember(&value5_); -// AddSerializableMember(&value6_); -// AddSerializableMember(1, &value7_); // New version -// } -// -// protected: -// virtual bool SerializeVectorNestedObject(std::vector* data, -// const byte* ptr) const { -// ASSERT(data, (_T(""))); -// ASSERT(ptr, (_T(""))); -// if (ptr == reinterpret_cast(&value6_)) -// return SerializeVectorNestedObjectHelper(data, &value6_); -// return false; -// } -// -// virtual bool DeserializeVectorNestedObject(byte** data, -// int size, -// byte* ptr, -// uint32 version) { -// ASSERT(data, (_T(""))); -// ASSERT(*data, (_T(""))); -// ASSERT(ptr, (_T(""))); -// if (ptr == reinterpret_cast(&value6_)) -// return DeserializeVectorNestedObjectHelper(data, -// size, -// &value6_, -// version); -// return false; -// } -// -// private: -// int value1_; -// CString value2_; -// FooObject value3_; -// std::vector value4_; -// std::vector value5_; -// std::vector value6_; -// int value7_; -// }; -// -// Binary format: -// -// 1) Value type: data -// e.g. 100 => 64 00 00 00 -// 2) CString: size count data -// e.g. "ABC" => 02 00 00 00 03 00 00 00 41 00 42 00 43 00 -// 3) Vector: size count data -// e.g. vector = {1, 2} -// => 04 00 00 00 02 00 00 00 01 00 00 00 02 00 00 00 -// -// TODO(omaha): -// 1) Define struct TypeTrait for all type-related info -// 2) Initialize TypeTrait on per-type basis instead of per-object basis - -#ifndef OMAHA_COMMON_SERIALIZABLE_OBJECT_H_ -#define OMAHA_COMMON_SERIALIZABLE_OBJECT_H_ - -#include -#include "base/basictypes.h" -#include "omaha/base/debug.h" -#include "omaha/base/type_utils.h" - -namespace omaha { - -// Constants -const uint32 kLatestSerializableVersion = 0xFFFFFFFF; - -// Serializable object -class SerializableObject { - private: - // Define SerializableMemberType, for internal use - typedef uint32 SerializableMemberType; - - #define SERIALIZABLE_VALUE_TYPE 1 - #define SERIALIZABLE_CSTRING 2 - #define SERIALIZABLE_NESTED_OBJECT 3 - #define SERIALIZABLE_VECTOR 0x8000 - - // Serializable member info - struct SerializableMemberInfo { - byte* ptr; // Pointers to the serializable member - SerializableMemberType type; // Type of the serializable member - size_t size; // Size of the serializable member - uint32 version; // Version when the member is added - - SerializableMemberInfo() - : ptr(NULL), type(SERIALIZABLE_VALUE_TYPE), size(0) {} - }; - - public: - // Constructor - SerializableObject() {} - - // Destructor - virtual ~SerializableObject() {} - - // Serialize - bool Serialize(std::vector* data) const; - - // Deserialize the data for the latest version - bool Deserialize(byte* data, size_t size) { - return Deserialize(data, size, kLatestSerializableVersion); - } - - // Deserialize the data for a particular version - bool Deserialize(byte* data, size_t size, uint32 version); - - protected: - // Clear the serializable member list - void ClearSerializableMemberList() { - members_.clear(); - } - - // Add value-typed member to the serializable member list - template - void AddSerializableMember(T* ptr) { - return AddSerializableMember(0, ptr); - } - - // Add value-typed member to the serializable member list - template - void AddSerializableMember(uint32 version, T* ptr) { - if (SUPERSUBCLASS(SerializableObject, T)) { - #pragma warning(push) - // reinterpret_cast used between related classes - #pragma warning(disable : 4946) - return AddSerializableMember(version, - reinterpret_cast(ptr), - sizeof(T)); - #pragma warning(pop) - } - SerializableMemberInfo member; - member.ptr = reinterpret_cast(ptr); - member.type = SERIALIZABLE_VALUE_TYPE; - member.size = sizeof(T); - member.version = version; - members_.push_back(member); - } - - // Add CString-typed member to the serializable member list - void AddSerializableMember(CString* ptr) { - AddSerializableMember(0, ptr); - } - - // Add CString-typed member to the serializable member list - void AddSerializableMember(uint32 version, CString* ptr) { - SerializableMemberInfo member; - member.ptr = reinterpret_cast(ptr); - member.type = SERIALIZABLE_CSTRING; - member.size = sizeof(TCHAR); - member.version = version; - members_.push_back(member); - } - - // Add nested serializable member to the serializable member list - void AddSerializableMember(SerializableObject* ptr, size_t size) { - AddSerializableMember(0, ptr, size); - } - - // Add nested serializable member to the serializable member list - void AddSerializableMember(uint32 version, - SerializableObject* ptr, - size_t size) { - SerializableMemberInfo member; - member.ptr = reinterpret_cast(ptr); - member.type = SERIALIZABLE_NESTED_OBJECT; - member.size = size; - member.version = version; - members_.push_back(member); - } - - // Add vector-typed member to the serializable member list - template - void AddSerializableMember(std::vector* ptr) { - AddSerializableMember(0, ptr); - } - - // Add vector-typed member to the serializable member list - template - void AddSerializableMember(uint32 version, std::vector* ptr) { - SerializableMemberInfo member; - member.ptr = reinterpret_cast(ptr); - member.version = version; - - if (SUPERSUBCLASS(CString, T)) { - member.type = - static_cast(SERIALIZABLE_VECTOR | - SERIALIZABLE_CSTRING); - member.size = sizeof(TCHAR); - } else if (SUPERSUBCLASS(SerializableObject, T)) { - member.type = - static_cast(SERIALIZABLE_VECTOR | - SERIALIZABLE_NESTED_OBJECT); - member.size = sizeof(T); - } else { - member.type = - static_cast(SERIALIZABLE_VECTOR | - SERIALIZABLE_VALUE_TYPE); - member.size = sizeof(T); - } - - members_.push_back(member); - } - - // If there is a vector of SerializableObject to be serialized, the derived - // class need to provide the implementation - virtual bool SerializeVectorNestedObject(std::vector*, - const byte*) const { - ASSERT(false, (_T("Provide the implementation in the derived class."))); - return false; - } - - // Helper method to serialize a vector of SerializableObject - template - bool SerializeVectorNestedObjectHelper(std::vector* data, - const std::vector* list) const { - ASSERT(data, (_T(""))); - ASSERT(list, (_T(""))); - ASSERT(SUPERSUBCLASS(SerializableObject, T), (_T(""))); - - // Size of SerializableObject is unknown - SerializeSizeAndCount(data, 0, list->size()); - for (size_t i = 0; i < list->size(); ++i) { - // To work around compiler complaint while using dynamic_cast - SerializableObject* so = - const_cast( - static_cast(&(*list)[i])); - bool res = so->Serialize(data); - if (!res) - return false; - } - return true; - } - - // If there is a vector of SerializableObject to be serialized, the derived - // class need to provide the implementation - virtual bool DeserializeVectorNestedObject(byte**, size_t, byte*, uint32) { - ASSERT(false, (_T("provide the implementation in the derived class."))); - return false; - } - - // Helper method to deserialize a vector of SerializableObject - template - bool DeserializeVectorNestedObjectHelper(byte** data, - size_t size, - std::vector* list, - uint32 version) { - ASSERT(data, (_T(""))); - ASSERT(*data, (_T(""))); - ASSERT(size, (_T(""))); - ASSERT(list, (_T(""))); - ASSERT(SUPERSUBCLASS(SerializableObject, T), (_T(""))); - - byte* tail = *data + size; - - // Size of SerializableObject is unknown - size_t count = 0; - bool res = DeserializeSizeAndCount(&count, 0, data, size); - if (!res) - return false; - - for (size_t i = 0; i < count; ++i) { - T obj; - res = obj.DeserializeHelper(data, tail - *data, version); - if (!res) - return false; - list->push_back(obj); - } - return true; - } - - private: - // Serialize the size and count values - void SerializeSizeAndCount(std::vector* data, - size_t size, - size_t count) const; - - // Serialize a list of value-typed elements - void SerializeValueList(std::vector* ser_data, - const byte* raw_data, - size_t size, - size_t count) const; - - // Deserialize helper - bool DeserializeHelper(byte** data, size_t size, uint32 version); - - // Deserialize the size and count values - bool DeserializeSizeAndCount(size_t* count, - size_t size, - byte** ser_data, - size_t ser_size) const; - - // Deserialize a list of value-typed elements - bool DeserializeValueList(std::vector* raw_data, - size_t size, - byte** ser_data, - size_t ser_size); - - // List of serializable members - std::vector members_; - - // We need to initialize TypeTrait on per-type basis instead of per-object - // basis and remove the following use of macro. - DISALLOW_EVIL_CONSTRUCTORS(SerializableObject); -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_SERIALIZABLE_OBJECT_H_ diff --git a/omaha/base/serializable_object_unittest.cc b/omaha/base/serializable_object_unittest.cc deleted file mode 100644 index 1de7017..0000000 --- a/omaha/base/serializable_object_unittest.cc +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/serializable_object.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -// Template test function to round-trip an object through its serialized form. -// Requires the object to implement SetTestValues() and VerifyTestValues(). -template -void TestSerializeRoundTrip() { - T in; - T out; - std::vector data; - - in.SetTestValues(); - in.VerifyTestValues(); // sanity check to catch broken tests - EXPECT_TRUE(in.Serialize(&data)); - EXPECT_TRUE(out.Deserialize(&data[0], data.size())); - out.VerifyTestValues(); -} - - -// Ordinary values. -class SimpleValues : public SerializableObject { - public: - SimpleValues() { - AddSerializableMember(&value1_); - AddSerializableMember(&value2_); - AddSerializableMember(&value3_); - AddSerializableMember(&value4_); - } - - virtual void SetTestValues() { - value1_ = 452; - value2_ = 'Z'; - value3_ = false; - value4_ = 9276554; - } - - virtual void VerifyTestValues() { - EXPECT_EQ(452, value1_); - EXPECT_EQ('Z', value2_); - EXPECT_EQ(false, value3_); - EXPECT_EQ(9276554, value4_); - } - - private: - int value1_; - char value2_; - bool value3_; - int value4_; -}; - -TEST(SerializableObjectTest, SimpleValues) { - TestSerializeRoundTrip(); -} - - -// Strings. -const TCHAR kString1[] = _T("an example\tvalue\n"); -const TCHAR kString2[] = _T(""); -const TCHAR kString3[] = _T("and the mome raths outgrabe"); - -class StringValues : public SerializableObject { - public: - StringValues() { - AddSerializableMember(&string1_); - AddSerializableMember(&string2_); - AddSerializableMember(&string3_); - } - - virtual void SetTestValues() { - string1_ = kString1; - string2_ = kString2; - string3_ = kString3; - } - - virtual void VerifyTestValues() { - EXPECT_STREQ(kString1, string1_); - EXPECT_STREQ(kString2, string2_); - EXPECT_STREQ(kString3, string3_); - } - - private: - CString string1_; - CString string2_; - CString string3_; -}; - -TEST(SerializableObjectTest, StringValues) { - TestSerializeRoundTrip(); -} - - -// Nested objects. -class NestedObjects : public SerializableObject { - public: - NestedObjects() { - AddSerializableMember(&simple_values_); - AddSerializableMember(&string_values_); - } - - virtual void SetTestValues() { - simple_values_.SetTestValues(); - string_values_.SetTestValues(); - } - - virtual void VerifyTestValues() { - simple_values_.VerifyTestValues(); - string_values_.VerifyTestValues(); - } - - private: - SimpleValues simple_values_; - StringValues string_values_; -}; - -TEST(SerializableObjectTest, NestedObjects) { - TestSerializeRoundTrip(); -} - - -// Vector of values. -class ValueVector : public SerializableObject { - public: - ValueVector() { - AddSerializableMember(&vector_); - AddSerializableMember(&empty_vector_); - } - - virtual void SetTestValues() { - vector_.push_back(5); - vector_.push_back(8); - vector_.push_back(13); - } - - virtual void VerifyTestValues() { - EXPECT_EQ(0, empty_vector_.size()); - EXPECT_EQ(3, vector_.size()); - EXPECT_EQ(5, vector_[0]); - EXPECT_EQ(8, vector_[1]); - EXPECT_EQ(13, vector_[2]); - } - - private: - std::vector vector_; - std::vector empty_vector_; -}; - -TEST(SerializableObjectTest, ValueVector) { - TestSerializeRoundTrip(); -} - - -// Vector of objects. -class InnerObject : public SerializableObject { - public: - InnerObject() : value_(-1) { - AddSerializableMember(&value_); - } - - explicit InnerObject(int i) : value_(i) { - AddSerializableMember(&value_); - } - - InnerObject(const InnerObject& other) { - AddSerializableMember(&value_); - value_ = other.value_; - } - - InnerObject& operator=(const InnerObject& other) { - value_ = other.value_; - return *this; - } - - int value() { - return value_; - } - - private: - int value_; -}; - -class ObjectVector : public SerializableObject { - public: - ObjectVector() { - AddSerializableMember(&vector_); - } - - virtual void SetTestValues() { - vector_.push_back(InnerObject(21)); - vector_.push_back(InnerObject(34)); - vector_.push_back(InnerObject(55)); - } - - virtual void VerifyTestValues() { - EXPECT_EQ(3, vector_.size()); - EXPECT_EQ(21, vector_[0].value()); - EXPECT_EQ(34, vector_[1].value()); - EXPECT_EQ(55, vector_[2].value()); - } - - virtual bool SerializeVectorNestedObject(std::vector* data, - const byte* ptr) const { - EXPECT_TRUE(data); - EXPECT_TRUE(ptr); - if (ptr == reinterpret_cast(&vector_)) - return SerializeVectorNestedObjectHelper(data, &vector_); - return false; - } - - virtual bool DeserializeVectorNestedObject(byte** data, - size_t size, - byte* ptr, - uint32 version) { - EXPECT_TRUE(data); - EXPECT_TRUE(ptr); - if (ptr == reinterpret_cast(&vector_)) { - return DeserializeVectorNestedObjectHelper(data, size, - &vector_, version); - } - return false; - } - - private: - std::vector vector_; -}; - -TEST(SerializableObjectTest, ObjectVector) { - TestSerializeRoundTrip(); -} - -} // namespace omaha - diff --git a/omaha/base/service_utils.h b/omaha/base/service_utils.h index 103e307..d8b036c 100644 --- a/omaha/base/service_utils.h +++ b/omaha/base/service_utils.h @@ -79,7 +79,7 @@ class ScmDatabase { static bool IsServiceMarkedDeleted(SC_HANDLE service); private: - DISALLOW_EVIL_CONSTRUCTORS(ScmDatabase); + DISALLOW_COPY_AND_ASSIGN(ScmDatabase); }; // Utility functions for the service's installation, overinstall etc. diff --git a/omaha/base/service_utils_unittest.cc b/omaha/base/service_utils_unittest.cc index 00fe871..66ccd32 100644 --- a/omaha/base/service_utils_unittest.cc +++ b/omaha/base/service_utils_unittest.cc @@ -36,8 +36,10 @@ HRESULT TestEnumCallback(void* context, const wchar_t* service_name) { TEST(ServiceUtilsTest, ScmDatabaseEnumerateServices) { found_service = false; - EXPECT_TRUE(SUCCEEDED(ScmDatabase::EnumerateServices(TestEnumCallback, - reinterpret_cast(_T("RpcSs"))))); + TCHAR service_name[] = _T("RpcSs"); + EXPECT_TRUE(SUCCEEDED( + ScmDatabase::EnumerateServices(TestEnumCallback, + reinterpret_cast(service_name)))); EXPECT_TRUE(found_service); } diff --git a/omaha/base/shared_memory_ptr.h b/omaha/base/shared_memory_ptr.h deleted file mode 100644 index d813cc6..0000000 --- a/omaha/base/shared_memory_ptr.h +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Defines template class used to share data -// between processes. -// - -#ifndef OMAHA_COMMON_SHARED_MEMORY_PTR_H__ -#define OMAHA_COMMON_SHARED_MEMORY_PTR_H__ - -#include "base/debug.h" -#include "base/singleton.h" -#include "base/system_info.h" -#include "base/vista_utils.h" - -namespace omaha { - -// SharedMemoryPtr class is designed to allow seamless data sharing process boundaries. -// All the data passed as a template parameter will be shared between processes. -// Very important to remember that for now - all shared data should be on stack. -// For example if the class A had stl vector as a member, the members of the vector -// would be allocated not from shared memory and therefore will not be shared. -// That could be solved with allocators, but for now we don't need that. -// -// Here is a typical example of usage: -// Class A { -// int i_; -// double d_; -// ....... -// ........ -// -// public: -// set_double(double d){d_=d;} -// double get_double(){return d_}; -// -// }; -// -// ... Prosess one... -// SharedMemoryPtr spA("ABC"); -// if (!spA) -// return false; -// -// spA->set_double(3.14); -// -// ... Process two ... -// -// -// SharedMemoryPtr spA1("ABC"); -// if (!spA1) -// return false; -// -// process two will see the value set by process one. -// it will be 3.14 -// double d = spA1->get_double(); -// - -// You should implement a class member of SystemSharedData if the data you want -// to share is several hundred bytes. Always try this approach first before you implement -// new class that is derived from SharedMemoryPtr. The main difference is that SharedMemoryPtr -// will allocate a least page of shared memory. If your class is just a member of SystemSharedData -// memory mapped file will be shared between members. It is just more efficient. -// Look in system_shared_data.h , shared_data_member.h, and system_shared_data_members.h -// for more details. - -// Forward declaration. -template class SharedMemoryPtr; - -// During several code reviews it has been noticed that the same error gets repeated over and over. -// People create SharedMemoryPtr. And than the access to member functions of SomeData -// is not synchronized by __mutexBlock or __mutexScope. So we need to somehow find a way to make -// automatic syncronization whenever people access shared data methods or members. -// Since by design the only way we can acess shared data is through operator -> of SharedMemoryPtr -// we need to somehow invoke synchronization at the time of access. -// We can implement this mainly because of the mechanics of operator-> dictated by C++ standard. -// When you apply operator-> to a type that's not a built-in pointer, the compiler does an interesting thing. -// After looking up and applying the user-defined operator-> to that type, it applies operator-> again to the result. -// The compiler keeps doing this recursively until it reaches a pointer to a built-in type, and only then proceeds with member access. -// It follows that a SharedMemoryPtr operator-> does not have to return a pointer. -// It can return an object that in turn implements operator->, without changing the use syntax. -// So we can implement: pre- and postfunction calls. (See Stroustrup 2000) -// If you return an object of some type X -// by value from operator->, the sequence of execution is as follows: -// 1. Constructor of type X -// 2. X::operator-> called; returns a pointer to an object of type T of SharedMemoryPtr -// 3. Member access -// 4. Destructor of X -// In a nutshell, we have a way of implementing locked function calls. - -template -class SharedDataLockingProxy { -public: - // Lock on construction. - SharedDataLockingProxy(SharedMemoryPtr * mem_ptr, T* shared_data) - : mem_ptr_(mem_ptr), shared_data_(shared_data) { - mem_ptr_->Lock(); - } - // Unlock on destruction. - ~SharedDataLockingProxy() { - mem_ptr_->Unlock(); - } - // operator - T* operator->() const { - ASSERT(shared_data_ != NULL, (L"NULL object pointer being dereferenced")); - return shared_data_; - } -private: - SharedDataLockingProxy& operator=(const SharedDataLockingProxy&); - SharedMemoryPtr* mem_ptr_; - T* shared_data_; - // To allow this implicit locking - copy constructor must be - // enabled. hence, no DISALLOW_EVIL_CONSTRUCTORS -}; - -template class SharedMemoryPtr - : public LockType { - // Handle to disk file if we're backing this shared memory by a file - HANDLE file_; - // Local handle to file mapping. - HANDLE file_mapping_; - // pointer to a view. - T* data_; - // If the first time creation can do some initialization. - bool first_instance_; -public: - // The heart of the whole idea. Points to shared memrory - // instead of the beginning of the class. - SharedDataLockingProxy operator->() { - return SharedDataLockingProxy(this, data_); - } - // To check after creation. - // For example: - // SharedMemoryPtr sm; - // if (sm) - // { do whatever you want} - // else - // {error reporting} - operator bool() const {return ((file_mapping_ != NULL) && (data_ != NULL));} - - // Initialize memory mapped file and sync mechanics. - // by calling InitializeSharedAccess - SharedMemoryPtr(const CString& name, - LPSECURITY_ATTRIBUTES sa, - LPSECURITY_ATTRIBUTES sa_mutex, - bool read_only) - : file_(INVALID_HANDLE_VALUE), - file_mapping_(NULL), - data_(NULL) { - HRESULT hr = InitializeSharedAccess(name, false, sa, sa_mutex, read_only); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("InitializeSharedAccess failed [%s][%s][0x%x]"), - name, read_only ? _T("R") : _T("RW"), hr)); - } - } - - // Use this constructor if you want to back the shared memory by a file. - // NOTE: if using a persistent shared memory, every object with this same - // name should be persistent. Otherwise, the objects marked as - // non-persistent will lead to InitializeSharedData called again if - // they are instantiated before the ones marked as persistent. - SharedMemoryPtr(bool persist, - LPSECURITY_ATTRIBUTES sa, - LPSECURITY_ATTRIBUTES sa_mutex, - bool read_only) - : file_(INVALID_HANDLE_VALUE), - file_mapping_(NULL), - data_(NULL) { - // Each shared data must implement GetFileName() to use this c-tor. The - // implementation should be: - // const CString GetFileName() const {return L"C:\\directory\file";} - // This is purposedly different from GetSharedName, so that the user is - // well aware that a file name is expected, not a mutex name. - HRESULT hr = InitializeSharedAccess(data_->GetFileName(), - persist, - sa, - sa_mutex, - read_only); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("InitializeSharedAccess failed [%s][%s][0x%x]"), - data_->GetFileName(), read_only ? _T("R") : _T("RW"), hr)); - } - } - - // Initialize memory mapped file and sync mechanics. - // by calling InitializeSharedAccess - SharedMemoryPtr() : - file_(INVALID_HANDLE_VALUE), file_mapping_(NULL), data_(NULL) { - // This should never happen but let's assert - // in case it does. - // Each shared data must implement GetSharedData() to use this c-tor. - // The implementation should be: - // const TCHAR * GetSharedName() const - // {return L"Some_unique_string_with_no_spaces";} - HRESULT hr = InitializeSharedAccess(data_->GetSharedName(), - false, - NULL, - NULL, - false); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("InitializeSharedAccess failed [%s][%s][0x%x]"), - data_->GetSharedName(), _T("RW"), hr)); - } - } - - // Clean up. - ~SharedMemoryPtr() { - Cleanup(); - } - - void Cleanup() { - __mutexScope(this); - if (data_) - UnmapViewOfFile(data_); - if (file_mapping_) - VERIFY(CloseHandle(file_mapping_), (L"")); - if (file_ != INVALID_HANDLE_VALUE) - VERIFY(CloseHandle(file_), (L"")); - } - - // Initialize memory mapped file and sync object. - bool InitializeSharedAccess(const CString& name, - bool persist, - LPSECURITY_ATTRIBUTES sa, - LPSECURITY_ATTRIBUTES sa_mutex, - bool read_only) { - return InitializeSharedAccessInternal(name, - persist, - sa, - sa_mutex, - read_only, - sizeof(T), - &T::InitializeSharedData); - } - - private: - // Initialize memory mapped file and sync object. - // - // This internal method allows template method folding by only using things - // that are consistent in all templates. Things that vary are passed in. - bool InitializeSharedAccessInternal(const CString& name, bool persist, - LPSECURITY_ATTRIBUTES sa, - LPSECURITY_ATTRIBUTES sa_mutex, - bool read_only, - size_t data_size, - void (T::*initialize_shared_data) - (const CString&)) { - // If this memory mapped object is backed by a file, then "name" is a fully - // qualified name with backslashes. Since we can't use backslashes in a - // mutex's name, let's make another name where we convert them to - // underscores. - CString mem_name(name); - if (persist) { - mem_name.Replace(_T('\\'), _T('_')); - } - - // Initialize the mutex - CString mutex_name(mem_name + _T("MUTEX")); - LPSECURITY_ATTRIBUTES mutex_attr = sa_mutex ? sa_mutex : sa; - if (!InitializeWithSecAttr(mutex_name, mutex_attr)) { - ASSERT(false, (L"Failed to initialize mutex. Err=%i", ::GetLastError())); - return false; - } - - // everything is synchronized till the end of the function or return. - __mutexScope(this); - - first_instance_ = false; - - if (persist) { - // Back this shared memory by a file - file_ = CreateFile(name, - GENERIC_READ | (read_only ? 0 : GENERIC_WRITE), - FILE_SHARE_READ | (read_only ? 0 : FILE_SHARE_WRITE), - sa, - OPEN_ALWAYS, - NULL, - NULL); - if (file_ == INVALID_HANDLE_VALUE) - return false; - - if (!read_only && GetLastError() != ERROR_ALREADY_EXISTS) - first_instance_ = true; - } else { - ASSERT(file_ == INVALID_HANDLE_VALUE, (L"")); - file_ = INVALID_HANDLE_VALUE; - } - - if (read_only) { - file_mapping_ = OpenFileMapping(FILE_MAP_READ, false, mem_name); - if (!file_mapping_) { - UTIL_LOG(LW, (L"[OpenFileMapping failed][error %i]", ::GetLastError())); - } - } else { - file_mapping_ = CreateFileMapping(file_, sa, - PAGE_READWRITE, 0, data_size, mem_name); - ASSERT(file_mapping_, (L"CreateFileMapping. Err=%i", ::GetLastError())); - } - - if (!file_mapping_) { - return false; - } else if (!read_only && - file_ == INVALID_HANDLE_VALUE && - GetLastError() != ERROR_ALREADY_EXISTS) { - first_instance_ = true; - } - - data_ = reinterpret_cast(MapViewOfFile(file_mapping_, - FILE_MAP_READ | - (read_only ? 0 : FILE_MAP_WRITE), - 0, - 0, - data_size)); - - if (!data_) { - ASSERT(false, (L"MapViewOfFile. Err=%i", ::GetLastError())); - VERIFY(CloseHandle(file_mapping_), (L"")); - file_mapping_ = NULL; - - if (file_ != INVALID_HANDLE_VALUE) { - VERIFY(CloseHandle(file_), (L"")); - file_ = INVALID_HANDLE_VALUE; - } - - return false; - } - - if (!first_instance_) { - return true; - } - - // If this is the first instance of shared object - // call initialization function. This is nice but - // at the same time we can not share built in data types. - // SharedMemoryPtr - will not compile. But this is OK - // We don't want all the overhead to just share couple of bytes. - // Signature is void InitializeSharedData() - (data_->*initialize_shared_data)(name); - - return true; - } - - DISALLOW_EVIL_CONSTRUCTORS(SharedMemoryPtr); -}; - -// Sometimes we want Singletons that are shared between processes. -// SharedMemoryPtr can do that. But if used in C-written module there will be -// a need to make SharedMemoryPtr a global object. Making a Singleton from SharedMemoryPtr -// is possible in this situation, but syntactically this is very difficult to read. -// The following template solves the problem. It hides difficult to read details inside. -// Usage is the same as SharedMemoryPtr (ONLY through -> operator). Completely thread-safe. -// Can be used in two ways: -// Class A { -// public: -// void foo(){} -// -//}; -// SharedMemorySingleton a, b; -// a->foo(); -// b->foo(); //refers to the same data in any process. -// -// or -// -// class A : public SharedMemorySingleton { -// public: -// void foo(){} -//}; -// A a, b; -// a->foo(); -// b->foo(); //refers to the same data in any process. - -template class SharedMemorySingleton { -public: - SharedDataLockingProxy operator->() { - return - Singleton >::Instance()->operator->(); - } -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_SHARED_MEMORY_PTR_H__ diff --git a/omaha/base/shell.cc b/omaha/base/shell.cc index e0e46c7..95e8600 100644 --- a/omaha/base/shell.cc +++ b/omaha/base/shell.cc @@ -28,192 +28,13 @@ #include "omaha/base/logging.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/utils.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { -// create and store a shortcut -// uses shell IShellLink and IPersistFile interfaces -HRESULT Shell::CreateLink(const TCHAR *source, - const TCHAR *destination, - const TCHAR *working_dir, - const TCHAR *arguments, - const TCHAR *description, - WORD hotkey_virtual_key_code, - WORD hotkey_modifiers, - const TCHAR *icon) { - ASSERT1(source); - ASSERT1(destination); - ASSERT1(working_dir); - ASSERT1(arguments); - ASSERT1(description); - - scoped_co_init co_init(COINIT_APARTMENTTHREADED); - HRESULT hr = co_init.hresult(); - if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) { - UTIL_LOG(LEVEL_ERROR, (_T("[Shell::CreateLink - failed to co_init]"), hr)); - return hr; - } - - UTIL_LOG(L1, (_T("[Create shell link]") - _T("[source %s dest %s dir %s arg %s desc %s hotkey %x:%x]"), - source, destination, working_dir, arguments, description, - hotkey_modifiers, hotkey_virtual_key_code)); - - // Get a pointer to the IShellLink interface - CComPtr shell_link; - - RET_IF_FAILED(shell_link.CoCreateInstance(CLSID_ShellLink)); - ASSERT(shell_link, (L"")); - - // Set the path to the shortcut target and add the description - VERIFY1(SUCCEEDED(shell_link->SetPath(source))); - VERIFY1(SUCCEEDED(shell_link->SetArguments(arguments))); - VERIFY1(SUCCEEDED(shell_link->SetDescription(description))); - VERIFY1(SUCCEEDED(shell_link->SetWorkingDirectory(working_dir))); - - // If we are given an icon, then set it - // For now, we always use the first icon if this happens to have multiple ones - if (icon) { - VERIFY1(SUCCEEDED(shell_link->SetIconLocation(icon, 0))); - } - -// C4201: nonstandard extension used : nameless struct/union -#pragma warning(disable : 4201) - union { - WORD flags; - struct { // little-endian machine: - WORD virtual_key:8; // low order byte - WORD modifiers:8; // high order byte - }; - } hot_key; -#pragma warning(default : 4201) - - hot_key.virtual_key = hotkey_virtual_key_code; - hot_key.modifiers = hotkey_modifiers; - - if (hot_key.flags) { - shell_link->SetHotkey(hot_key.flags); - } - - // Query IShellLink for the IPersistFile interface for saving the shortcut in - // persistent storage - CComQIPtr persist_file(shell_link); - if (!persist_file) - return E_FAIL; - - // Save the link by calling IPersistFile::Save - RET_IF_FAILED(persist_file->Save(destination, TRUE)); - - return S_OK; -} - -HRESULT Shell::RemoveLink(const TCHAR *link) { - ASSERT(link, (L"")); - ASSERT(*link, (L"")); - - return File::Remove(link); -} - -// Open a URL in a new browser window -HRESULT Shell::OpenLinkInNewWindow(const TCHAR* url, UseBrowser use_browser) { - ASSERT1(url); - - HRESULT hr = S_OK; - CString browser_path; - - // Try to open with default browser - if (use_browser == USE_DEFAULT_BROWSER) { - // Load full browser path from regkey - hr = GetDefaultBrowserPath(&browser_path); - - // If there is a default browser and it is not AOL, load the url in that - // browser - if (SUCCEEDED(hr) && !String_Contains(browser_path, _T("aol"))) { - if (!browser_path.IsEmpty()) { - // Have we figured out how to append the URL onto the browser path? - bool acceptable_url = false; - - if (ReplaceCString(browser_path, _T("\"%1\""), url)) { - // the "browser.exe "%1"" case - acceptable_url = true; - } else if (ReplaceCString(browser_path, _T("%1"), url)) { - // the "browser.exe %1 "case - acceptable_url = true; - } else if (ReplaceCString(browser_path, _T("-nohome"), url)) { - // the "browser.exe -nohome" case - acceptable_url = true; - } else { - // the browser.exe case. - // simply append the quoted url. - EnclosePath(&browser_path); - browser_path.AppendChar(_T(' ')); - CString quoted_url(url); - EnclosePath("ed_url); - browser_path.Append(quoted_url); - acceptable_url = true; - } - - if (acceptable_url) { - hr = System::ShellExecuteCommandLine(browser_path, NULL, NULL); - if (SUCCEEDED(hr)) { - return S_OK; - } else { - UTIL_LOG(LE, (_T("[Shell::OpenLinkInNewWindow]") - _T("[failed to start default browser to open url]") - _T("[%s][0x%x]"), url, hr)); - } - } - } - } - } - - // Try to open with IE if can't open with default browser or required - if (use_browser == USE_DEFAULT_BROWSER || - use_browser == USE_INTERNET_EXPLORER) { - hr = GetIEPath(&browser_path); - if (SUCCEEDED(hr)) { - hr = System::ShellExecuteProcess(browser_path, url, NULL, NULL); - if (SUCCEEDED(hr)) { - return S_OK; - } else { - UTIL_LOG(LE, (_T("[Shell::OpenLinkInNewWindow]") - _T("[failed to start IE to open url][%s][0x%x]"), - url, hr)); - } - } - } - - // Try to open with Firefox if can't open with default browser or required - if (use_browser == USE_DEFAULT_BROWSER || use_browser == USE_FIREFOX) { - hr = RegKey::GetValue(kRegKeyFirefox, kRegValueFirefox, &browser_path); - if (SUCCEEDED(hr) && !browser_path.IsEmpty()) { - ReplaceCString(browser_path, _T("%1"), url); - hr = System::ShellExecuteCommandLine(browser_path, NULL, NULL); - if (SUCCEEDED(hr)) { - return S_OK; - } else { - UTIL_LOG(LE, (_T("[Shell::OpenLinkInNewWindow]") - _T("[failed to start Firefox to open url][%s][0x%x]"), - url, hr)); - } - } - } - - // ShellExecute the url directly as a last resort - hr = Shell::Execute(url); - if (FAILED(hr)) { - UTIL_LOG(LE, (_T("[Shell::OpenLinkInNewWindow]") - _T("[failed to run ShellExecute to open url][%s][0x%x]"), - url, hr)); - } - - return hr; -} - HRESULT Shell::Execute(const TCHAR* file) { ASSERT1(file); @@ -351,36 +172,6 @@ HRESULT Shell::GetSpecialFolderKeywordsMapping( return S_OK; } -HRESULT Shell::DeleteDirectory(const TCHAR* dir) { - ASSERT1(dir && *dir); - - if (!SafeDirectoryNameForDeletion(dir)) { - return E_INVALIDARG; - } - - uint32 dir_len = lstrlen(dir); - if (dir_len >= MAX_PATH) { - return E_INVALIDARG; - } - - // the 'from' must be double-terminated with 0. Reserve space for one more - // zero at the end - TCHAR from[MAX_PATH + 1] = {0}; - lstrcpyn(from, dir, MAX_PATH); - from[1 + dir_len] = 0; // the second zero terminator. - - SHFILEOPSTRUCT file_op = {0}; - - file_op.hwnd = 0; - file_op.wFunc = FO_DELETE; - file_op.pFrom = from; - file_op.pTo = 0; - file_op.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; - - // ::SHFileOperation returns non-zero on errors - return ::SHFileOperation(&file_op) ? HRESULTFromLastError() : S_OK; -} - HRESULT Shell::GetApplicationExecutablePath(const CString& exe, CString* path) { ASSERT1(path); diff --git a/omaha/base/shell.h b/omaha/base/shell.h index eb5ef45..bc1d074 100644 --- a/omaha/base/shell.h +++ b/omaha/base/shell.h @@ -39,29 +39,8 @@ enum UseBrowser { class Shell { public: - - // create and store a shortcut link - // note that icon can be NULL if no icon is required - // note that we always pick the 0th icon for now, this can be changed later - // [relevant with EXE and compound icons] - static HRESULT CreateLink(const TCHAR *source, - const TCHAR *destination, - const TCHAR *working_dir, - const TCHAR *arguments, - const TCHAR *description, - WORD hotkey_virtual_key_code, - WORD hotkey_modifiers, - const TCHAR *icon); - // For information on hotkey modifiers see MSDN IShellLink::GetHotKey method. - - // Delete a shortcut link - static HRESULT RemoveLink(const TCHAR *link); - - // Open a URL in a new browser window - static HRESULT OpenLinkInNewWindow(const TCHAR* url, UseBrowser use_browser); - // Execute a file - static HRESULT Shell::Execute(const TCHAR* file); + static HRESULT Execute(const TCHAR* file); // Get the location of a special folder. The special folders are identified // by a unique integer - see the platform SDK files shfolder.h and @@ -79,9 +58,6 @@ class Shell { static HRESULT GetSpecialFolderKeywordsMapping( std::map* special_folders_map); - // Recursively delete a directory including its files. - static HRESULT DeleteDirectory(const TCHAR* dir); - // Reads the application executable path from // HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths. static HRESULT GetApplicationExecutablePath(const CString& exe, @@ -91,7 +67,7 @@ class Shell { static HRESULT BasicGetSpecialFolder(DWORD csidl, CString* folder_path); - DISALLOW_EVIL_CONSTRUCTORS(Shell); + DISALLOW_COPY_AND_ASSIGN(Shell); }; } // namespace omaha diff --git a/omaha/base/shell_unittest.cc b/omaha/base/shell_unittest.cc index 2573ce9..8a4f44c 100644 --- a/omaha/base/shell_unittest.cc +++ b/omaha/base/shell_unittest.cc @@ -28,36 +28,6 @@ namespace omaha { -TEST(ShellTest, ShellLink) { - if (IsTestRunByLocalSystem()) { - return; - } - - CString desktop; - EXPECT_SUCCEEDED(GetFolderPath(CSIDL_DESKTOP, &desktop)); - CString link(desktop + _T("\\Shell Unittest.lnk")); - Shell::RemoveLink(link); - ASSERT_FALSE(File::Exists(link)); - - CString install_dir; - ASSERT_SUCCEEDED(Shell::GetSpecialFolder(CSIDL_PROGRAM_FILES, - true, - &install_dir)); - install_dir += _T("\\Shell Unittest"); - CString exe = install_dir + _T("\\foo.bar.exe"); - ASSERT_SUCCEEDED(Shell::CreateLink(exe, - link, - install_dir, - _T(""), - _T("Google Update Unit Test"), - 'W', - HOTKEYF_ALT | HOTKEYF_CONTROL, - NULL)); - ASSERT_TRUE(File::Exists(link)); - ASSERT_SUCCEEDED(Shell::RemoveLink(link)); - ASSERT_FALSE(File::Exists(link)); -} - struct Folders { DWORD csidl; CString name; diff --git a/omaha/base/shutdown_handler.h b/omaha/base/shutdown_handler.h index fb8f661..1246144 100644 --- a/omaha/base/shutdown_handler.h +++ b/omaha/base/shutdown_handler.h @@ -18,10 +18,12 @@ #ifndef OMAHA_BASE_SHUTDOWN_HANDLER_H_ #define OMAHA_BASE_SHUTDOWN_HANDLER_H_ +#include #include + #include "base/basictypes.h" #include "omaha/base/event_handler.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -43,7 +45,7 @@ class ShutdownHandler : public EventHandler { scoped_event shutdown_event_; ShutdownCallback* shutdown_callback_; bool is_machine_; - DISALLOW_EVIL_CONSTRUCTORS(ShutdownHandler); + DISALLOW_COPY_AND_ASSIGN(ShutdownHandler); }; } // namespace omaha diff --git a/omaha/base/signatures.cc b/omaha/base/signatures.cc index a0013bb..7485f16 100644 --- a/omaha/base/signatures.cc +++ b/omaha/base/signatures.cc @@ -21,18 +21,17 @@ #include "omaha/base/signatures.h" #include #include -#include #pragma warning(disable : 4245) // C4245 : conversion from 'type1' to 'type2', signed/unsigned mismatch #include #pragma warning(default : 4245) +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/const_utils.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/security/sha256.h" #include "omaha/base/security/sha.h" #include "omaha/base/string.h" @@ -40,17 +39,16 @@ namespace omaha { -const ALG_ID kHashAlgorithm = CALG_SHA1; -const ALG_ID kHash256Algorithm = CALG_SHA_256; -const DWORD kEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING; -const DWORD kCertificateNameType = CERT_NAME_SIMPLE_DISPLAY_TYPE; -const DWORD kKeyPairType = AT_SIGNATURE; +constexpr ALG_ID kHashAlgorithm = CALG_SHA1; +constexpr DWORD kEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING; +constexpr DWORD kCertificateNameType = CERT_NAME_SIMPLE_DISPLAY_TYPE; +constexpr DWORD kKeyPairType = AT_SIGNATURE; // Maximum file size allowed for performing authentication. -const size_t kMaxFileSizeForAuthentication = 512 * 1024 * 1024; // 512MB +constexpr size_t kMaxFileSizeForAuthentication = 512 * 1024 * 1024; // 512MB // Buffer size used to read files from disk. -const size_t kFileReadBufferSize = 128 * 1024; +constexpr size_t kFileReadBufferSize = 128 * 1024; namespace CryptDetails { @@ -89,39 +87,6 @@ typedef close_fun smart_destroy_hash; typedef scoped_any scoped_crypt_hash; -// Providers implementing SHA256 can be instantiated using different names. -// On Vista and up, both the default provider and the enhanced RSA/AES -// provider support SHA256. On Windows XP, the named provider has a different -// name, therefore, the code falls back to a specific named provider in case -// of errors. -HRESULT CryptAcquireContextWithFallback(DWORD provider_type, - HCRYPTPROV* provider) { - const TCHAR* kHashCryptoProvider[] = { - NULL, // The default provider. - MS_ENH_RSA_AES_PROV, // The named provider for Vista and up. - MS_ENH_RSA_AES_PROV_XP // The named provider for XP SP3 and up. - }; - - // Try different providers until one of them succeeds. - HRESULT hr = S_OK; - CryptDetails::scoped_crypt_context scoped_csp_handle; - for (size_t i = 0; i != arraysize(kHashCryptoProvider); ++i) { - if (::CryptAcquireContext(address(scoped_csp_handle), - NULL, - kHashCryptoProvider[i], - provider_type, - CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - UTIL_LOG(L6, (_T("[CryptAcquireContext succeeded]"))); - *provider = release(scoped_csp_handle); - return S_OK; - } else { - hr = HRESULTFromLastError(); - UTIL_LOG(LE, (_T("[CryptAcquireContext failed][0x%08lX]"), hr)); - } - } - return hr; -} - class SHA256Hash : public HashInterface { public: SHA256Hash() { @@ -389,9 +354,9 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& filepaths, uint64 curr_len = 0; std::vector buf(kFileReadBufferSize); - COMPILE_ASSERT(kFileReadBufferSize <= INT_MAX, buffer_size_too_large); + static_assert(kFileReadBufferSize <= INT_MAX); - scoped_ptr hasher( + std::unique_ptr hasher( CryptDetails::CreateHasher(use_sha256_)); for (size_t i = 0; i < filepaths.size(); ++i) { @@ -471,7 +436,7 @@ HRESULT CryptoHash::ComputeOrValidate(const std::vector& buffer_in, return E_INVALIDARG; } - scoped_ptr hasher( + std::unique_ptr hasher( CryptDetails::CreateHasher(use_sha256_)); const size_t datalen = buffer_in.size(); @@ -1055,7 +1020,6 @@ HRESULT CryptoVerifySignature::Validate(const std::vector& buffer_in, L"[could not create hash], err 0x%08lx", err)); return HRESULT_FROM_WIN32(err); } - UTIL_LOG(L3, (L"CryptoVerifySignature::Validate new hash 0x%08lx", hash)); b = ::CryptHashData(get(hash), &buffer_in.front(), diff --git a/omaha/base/signatures.h b/omaha/base/signatures.h index ba11c1b..8a5b3f4 100644 --- a/omaha/base/signatures.h +++ b/omaha/base/signatures.h @@ -27,7 +27,7 @@ #include #include #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/base/signatures_unittest.cc b/omaha/base/signatures_unittest.cc index 6bcabc4..6031046 100644 --- a/omaha/base/signatures_unittest.cc +++ b/omaha/base/signatures_unittest.cc @@ -36,8 +36,8 @@ namespace omaha { namespace { struct { - char* binary; - char* base64; + const char* binary; + const char* base64; } test_data[] = { "", "", "what", "d2hhdA==", @@ -48,7 +48,7 @@ struct { // This test data from http://en.wikipedia.org/wiki/SHA-1: const struct { - char* binary; + const char* binary; byte hash[20]; } test_hash[] = { "The quick brown fox jumps over the lazy dog", @@ -61,7 +61,7 @@ const struct { // This test data from http://en.wikipedia.org/wiki/SHA-2: struct { - char* binary; + const char* binary; byte hash[32]; } test_hash256[] = { "", diff --git a/omaha/base/signaturevalidator.cc b/omaha/base/signaturevalidator.cc index 2468fa6..62e800b 100644 --- a/omaha/base/signaturevalidator.cc +++ b/omaha/base/signaturevalidator.cc @@ -347,46 +347,58 @@ bool CertInfo::ExtractPublicKeyHash(const CERT_CONTEXT* cert_context, } void CertList::FindFirstCert(const CertInfo** result_cert_info, - const CString &company_name_to_match, + const std::vector& company_name_to_match, const CString &orgn_unit_to_match, const CString &trust_authority_to_match, bool allow_test_variant, bool check_cert_is_valid_now) const { - if (!result_cert_info) + if (!result_cert_info) { return; + } + (*result_cert_info) = NULL; for (CertInfoList::const_iterator cert_iter = cert_list_.begin(); cert_iter != cert_list_.end(); ++cert_iter) { - // If any of the criteria does not match, continue on to next certificate - if (!company_name_to_match.IsEmpty()) { - const TCHAR* certificate_company_name = - (*cert_iter)->issuing_company_name_; - bool names_match = company_name_to_match == certificate_company_name; - if (!names_match && allow_test_variant) { - CString test_variant = company_name_to_match; - test_variant += _T(" (TEST)"); - names_match = test_variant == certificate_company_name; + // Find a match between the name of the certificate and one of the + // company names provided as a paramer.. + bool names_match = false; + for (size_t i = 0; i != company_name_to_match.size(); ++i) { + const TCHAR* certificate_company_name = + (*cert_iter)->issuing_company_name_; + names_match = company_name_to_match[i] == certificate_company_name; + if (!names_match && allow_test_variant) { + CString test_variant = company_name_to_match[i]; + test_variant += _T(" (TEST)"); + names_match = test_variant == certificate_company_name; + } + if (names_match) { + break; + } } - if (!names_match) + + // If any of the criteria does not match, continue on to next certificate. + if (!names_match) { continue; - } - if (!orgn_unit_to_match.IsEmpty() && - orgn_unit_to_match != (*cert_iter)->issuing_dept_name_) - continue; - if (!trust_authority_to_match.IsEmpty() && - trust_authority_to_match != (*cert_iter)->trust_authority_name_) - continue; - // All the criteria matched. But, add only if it is a valid certificate. - if (!check_cert_is_valid_now || (*cert_iter)->IsValidNow()) { - (*result_cert_info) = (*cert_iter); - return; - } + } + if (!orgn_unit_to_match.IsEmpty() && + orgn_unit_to_match != (*cert_iter)->issuing_dept_name_) { + continue; + } + if (!trust_authority_to_match.IsEmpty() && + trust_authority_to_match != (*cert_iter)->trust_authority_name_) { + continue; + } + + // All the criteria matched. But, add only if it is a valid certificate. + if (!check_cert_is_valid_now || (*cert_iter)->IsValidNow()) { + (*result_cert_info) = (*cert_iter); + return; + } } } - void ExtractAllCertificatesFromSignature(const wchar_t* signed_file, CertList* cert_list) { if ((!signed_file) || (!cert_list)) @@ -427,7 +439,7 @@ void ExtractAllCertificatesFromSignature(const wchar_t* signed_file, // TODO(omaha): implement the valid now check by adding a parameter to // VerifyAuthenticodeSignature that adds WTD_LIFETIME_SIGNING_FLAG. HRESULT VerifyCertificate(const wchar_t* signed_file, - const wchar_t* subject, + const std::vector& subject, bool allow_test_variant, bool check_cert_is_valid_now, const std::vector* expected_hashes) { diff --git a/omaha/base/signaturevalidator.h b/omaha/base/signaturevalidator.h index 61c1fb7..b850c8d 100644 --- a/omaha/base/signaturevalidator.h +++ b/omaha/base/signaturevalidator.h @@ -169,7 +169,7 @@ class CertList { // criteria. If allow_test_variant is true, the company name will also be // deemed valid if it equals company_name_to_match + " (TEST)". void FindFirstCert(const CertInfo** result_cert_info, - const CString &company_name_to_match, + const std::vector& company_name_to_match, const CString &orgn_unit_to_match, const CString &trust_authority_to_match, bool allow_test_variant, @@ -200,7 +200,7 @@ void ExtractAllCertificatesFromSignature(const wchar_t* signed_file, // The function can verify that the certificate is valid at the time of the // call. HRESULT VerifyCertificate(const wchar_t* signed_file, - const wchar_t* subject, + const std::vector& subject, bool allow_test_variant, bool check_cert_is_valid_now, const std::vector* expected_hashes); diff --git a/omaha/base/signaturevalidator_unittest.cc b/omaha/base/signaturevalidator_unittest.cc index a85bcdf..a3e363e 100644 --- a/omaha/base/signaturevalidator_unittest.cc +++ b/omaha/base/signaturevalidator_unittest.cc @@ -28,9 +28,12 @@ namespace omaha { namespace { bool VerifySigneeIsGoogle(const wchar_t* signed_file) { + std::vector subject; + subject.push_back(kSha256CertificateSubjectName); + subject.push_back(kCertificateSubjectName); return SUCCEEDED( VerifyCertificate(signed_file, - kCertificateSubjectName, + subject, true, // Allow test variant. false, // Check certificate is valid now. NULL)); @@ -38,6 +41,7 @@ bool VerifySigneeIsGoogle(const wchar_t* signed_file) { } // namespace +// Checks Omaha Thawte certificate sha1 (11/28/2016 to 11/21/2019). TEST(CertInfoTest, CertInfo) { const TCHAR kRelativePath[] = _T("unittest_support\\sha1_14F8FDD167F92402B1570B5DC495C815.sys"); @@ -64,8 +68,10 @@ TEST(CertInfoTest, CertInfo) { EXPECT_EQ(3, cert_list.size()); const CertInfo* cert_info = NULL; + std::vector subject; + subject.push_back(kCertificateSubjectName); cert_list.FindFirstCert(&cert_info, - kCertificateSubjectName, + subject, CString(), CString(), false, // Do not allow test variant. @@ -77,9 +83,10 @@ TEST(CertInfoTest, CertInfo) { EXPECT_STREQ(kCertificatePublicKeyHash, cert_info->public_key_hash_); } +// Checks Chrome certificate sha256 (11/06/2018 to 11/17/2021). TEST(CertInfoTest, CertInfo_Sha256) { const TCHAR kRelativePath[] = - _T("unittest_support\\sha2_2a9c21acaaa63a3c58a7b9322bee948d.exe"); + _T("unittest_support\\chrome_setup.exe"); CString executable_full_path(app_util::GetCurrentModuleDirectory()); ASSERT_TRUE(::PathAppend(CStrBuf(executable_full_path, MAX_PATH), @@ -89,11 +96,20 @@ TEST(CertInfoTest, CertInfo_Sha256) { CertList cert_list; ExtractAllCertificatesFromSignature(executable_full_path, &cert_list); - EXPECT_EQ(4, cert_list.size()); + // For some reason, extracting all certificates from the file only yields + // the code signing certificates but skips the time stamping certificates. + // In the case of chrome_setup.exe the following certs are picked up: + // * Dummy certificate. + // * DigiCert SHA2 Assured ID Code Signing CA + // hash 92c1588e85af2201ce7915e8538b492f605b80c6 + // * Google LLC hash cb7e84887f3c6015fe7edfb4f8f36df7dc10590e + EXPECT_EQ(3, cert_list.size()); const CertInfo* cert_info = NULL; + std::vector subject; + subject.push_back(kSha256CertificateSubjectName); cert_list.FindFirstCert(&cert_info, - kSha256CertificateSubjectName, + subject, CString(), CString(), false, // Do not allow test variant. @@ -161,6 +177,12 @@ TEST(SignatureValidatorTest, VerifySigneeIsGoogle_Sha256) { kRelativePath)); ASSERT_TRUE(File::Exists(executable_full_path)); EXPECT_TRUE(VerifySigneeIsGoogle(executable_full_path)); + + executable_full_path = app_util::GetCurrentModuleDirectory(); + ASSERT_TRUE(::PathAppend(CStrBuf(executable_full_path, MAX_PATH), + _T("unittest_support\\chrome_setup.exe"))); + ASSERT_TRUE(File::Exists(executable_full_path)); + EXPECT_TRUE(VerifySigneeIsGoogle(executable_full_path)); } TEST(SignatureValidatorTest, VerifySigneeIsGoogle_DualSigned_Sha1AndSha256) { @@ -213,12 +235,16 @@ TEST(SignatureValidatorTest, VerifyAuthenticodeSignature) { _T("GoogleUpdate_now_expired_cert.exe"), _T("GoogleUpdate_old_signature.exe"), _T("SaveArguments.exe"), + _T("chrome_setup.exe"), + _T("sha2_0c15be4a15bb0903c901b1d6c265302f.msi"), _T("SaveArguments_OmahaTestSigned.exe"), _T("Sha1_4c40dba5f988fae57a57d6457495f98b_and_sha2_2a9c21acaaa63a3c58a7b9322bee948d.exe"), // NOLINT _T("SaveArguments_unsigned_wrong_markup_value.exe"), _T("SaveArguments_wrong_cn.exe"), }; const HRESULT kExpectedResult[] = { + S_OK, + S_OK, S_OK, S_OK, S_OK, diff --git a/omaha/base/single_instance.cc b/omaha/base/single_instance.cc deleted file mode 100644 index c536baf..0000000 --- a/omaha/base/single_instance.cc +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Synchronization functions - -#include "omaha/base/single_instance.h" -#include "omaha/base/constants.h" -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/synchronized.h" -#include "omaha/base/utils.h" - -namespace omaha { - -// Check to see whether an instance is already running across all sessions. -// If not, enter single instance protection. The user must call Shutdown() -// on that SingleInstance once single instance protection is no longer needed. -bool SingleInstance::StartupSingleInstance(const TCHAR* id) { - ASSERT1(id); - - bool already_running = false, already_running_in_different_session = false; - HRESULT hr = Startup(id, - &already_running, - &already_running_in_different_session); - ASSERT(SUCCEEDED(hr), (_T(""))); - - return already_running || already_running_in_different_session; -} - -// Check to see whether an instance is already running in this session. If not, -// enter session-only single instance protection. The user must call Shutdown() -// on that SingleInstance once single instance protection is no longer needed. -bool SingleInstance::StartupSingleSessionInstance(const TCHAR* id) { - ASSERT1(id); - - bool already_running = false; - HRESULT hr = Startup(id, &already_running, NULL); - ASSERT(SUCCEEDED(hr), (_T(""))); - - return already_running; -} - -// Startup a single instance protection. The user must call Shutdown() on -// that SingleInstance once the single instance protection is no longer needed. -// -// Returns whether or not the process is already running -// already_running means "already running in same session". -// already_running_in_different_session means "already running on machine" -HRESULT SingleInstance::Startup(const TCHAR* id, - bool* already_running, - bool* already_running_in_different_session) { - ASSERT1(id); - ASSERT1(already_running); - - CString mutex_id; - - // Use two mutexes: one to check for being the only instance in this - // session, and one for being the only instance in any terminal session. - // Only create (and check) the global mutex for one-per-machine check if - // the result is asked for. - // We don't actually obtain ownership of the mutex - // For information on the "Local" and "Global" namespace prefixes, see MSDN - // article "Kernel Object Namespaces". - - // Create a user level mutex - CreateSyncId(id, SYNC_USER, &mutex_id); - RET_IF_FAILED(CreateInstanceMutex(mutex_id, - &user_mutex_handle_, - already_running)); - - // Create a global mutex - if (already_running_in_different_session) { - CreateSyncId(id, SYNC_GLOBAL, &mutex_id); - RET_IF_FAILED(CreateInstanceMutex(mutex_id, - &global_mutex_handle_, - already_running_in_different_session)); - } - - return S_OK; -} - -// Create a mutex -HRESULT SingleInstance::CreateInstanceMutex(const TCHAR* mutex_id, - HANDLE* mutex_handle, - bool* already_running) { - ASSERT1(mutex_id && *mutex_id); - ASSERT1(mutex_handle); - ASSERT1(already_running); - - *already_running = false; - - *mutex_handle = ::CreateMutex(NULL, false, mutex_id); - DWORD last_error = ::GetLastError(); - - // We check for both values because we sometimes see access - // denied. We expect this to mean that the mutex was created by a - // different set of user credentials, which shouldn't happen under - // normal circumstances in our applications, but in fact we did - // see it happen. - if (last_error == ERROR_ALREADY_EXISTS || last_error == ERROR_ACCESS_DENIED) { - *already_running = true; - return S_OK; - } - - if (*mutex_handle == NULL) { - HRESULT hr = HRESULT_FROM_WIN32(last_error); - ASSERT(false, (_T("[SingleInstance::CreateInstanceMutex]") - _T("[failed to create mutex][%s][0x%x]"), mutex_id, hr)); - return hr; - } - - return S_OK; -} - -// Shutdown a single instance protection -HRESULT SingleInstance::Shutdown() { - if (user_mutex_handle_) { - VERIFY(::CloseHandle(user_mutex_handle_), (_T(""))); - user_mutex_handle_ = NULL; - } - - if (global_mutex_handle_) { - VERIFY(::CloseHandle(global_mutex_handle_), (_T(""))); - global_mutex_handle_ = NULL; - } - - return S_OK; -} - -// Check to see whether an instance is already running -HRESULT SingleInstance::CheckAlreadyRunning( - const TCHAR* id, - bool* already_running, - bool* already_running_in_different_session) { - ASSERT1(id); - ASSERT1(already_running); - - CString mutex_id; - - // Open a user level mutex - CreateSyncId(id, SYNC_USER, &mutex_id); - RET_IF_FAILED(OpenInstanceMutex(mutex_id, already_running)); - - // Open a global mutex - if (already_running_in_different_session) { - CreateSyncId(id, SYNC_GLOBAL, &mutex_id); - RET_IF_FAILED(OpenInstanceMutex(mutex_id, - already_running_in_different_session)); - } - - return S_OK; -} - -// Open a mutex -HRESULT SingleInstance::OpenInstanceMutex(const TCHAR* mutex_id, - bool* already_running) { - ASSERT1(mutex_id && *mutex_id); - ASSERT1(already_running); - - *already_running = false; - - scoped_handle mutex_handle(::OpenMutex(NULL, false, mutex_id)); - DWORD last_error = ::GetLastError(); - - if (get(mutex_handle) || last_error == ERROR_ACCESS_DENIED) { - UTIL_LOG(L3, (_T("[SingleInstance::OpenInstanceMutex]") - _T("[already running][0x%x]"), last_error)); - *already_running = true; - return S_OK; - } - - if (last_error != ERROR_FILE_NOT_FOUND) { - HRESULT hr = HRESULT_FROM_WIN32(last_error); - ASSERT(false, (_T("[SingleInstance::OpenInstanceMutex]") - _T("[failed to open mutex][%s][0x%x]"), mutex_id, hr)); - return hr; - } - - return S_OK; -} - -} // namespace omaha - diff --git a/omaha/base/single_instance.h b/omaha/base/single_instance.h deleted file mode 100644 index af1ca07..0000000 --- a/omaha/base/single_instance.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// Single Instance of a process running (plus some synchronization functions -// that should be moved elsewhere) -// -// synchronization functions - -#ifndef OMAHA_COMMON_SINGLE_INSTANCE_H_ -#define OMAHA_COMMON_SINGLE_INSTANCE_H_ - -#include - -#include "base/basictypes.h" -#include "omaha/base/debug.h" - -namespace omaha { - -// Used to ensure only a single instance of a process per machine -// (e.g., even in terminal server sessions) -class SingleInstance { - public: - // Constructor - SingleInstance() : user_mutex_handle_(NULL), global_mutex_handle_(NULL) {} - - // Destructor - ~SingleInstance() { Shutdown(); } - - // Check to see whether an instance is already running across all sessions. - // If not, enter single instance protection. The user must call Shutdown() - // on that SingleInstance once single instance protection is no longer needed. - bool StartupSingleInstance(const TCHAR* id); - - // Check to see whether an instance is already running for this user. If not, - // enter user-only single instance protection. The user must call Shutdown() - // on that SingleInstance once single instance protection is no longer needed. - bool StartupSingleSessionInstance(const TCHAR* id); - - // Startup a single instance protection. The user must call Shutdown() on - // that SingleInstance once the single instance protection is no longer needed. - HRESULT Startup(const TCHAR* id, - bool* already_running, - bool* already_running_in_different_session); - - // Shutdown a single instance protection - HRESULT Shutdown(); - - // Check to see whether an instance is already running - static HRESULT CheckAlreadyRunning( - const TCHAR* id, - bool* already_running, - bool* already_running_in_different_session); - - private: - // Create a mutex - static HRESULT CreateInstanceMutex(const TCHAR* mutex_id, - HANDLE* mutex_handle, - bool* already_running); - - // Open a mutex - static HRESULT OpenInstanceMutex(const TCHAR* mutex_id, - bool* already_running); - - HANDLE user_mutex_handle_; - HANDLE global_mutex_handle_; - - DISALLOW_EVIL_CONSTRUCTORS(SingleInstance); -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_SINGLE_INSTANCE_H_ diff --git a/omaha/base/singleton.h b/omaha/base/singleton.h deleted file mode 100644 index fc7c043..0000000 --- a/omaha/base/singleton.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Defines two classes -// 1. class SingletonBase. -// 2. template class Singleton. -// Creation of singletons is a common -// activity. Use Singleton class to not -// repeat code every time. - -#ifndef OMAHA_COMMON_SINGLETON_H_ -#define OMAHA_COMMON_SINGLETON_H_ - -#include "omaha/base/debug.h" -#include "omaha/base/synchronized.h" - - -// Very important design pattern. -// Singleton class can be used in two ways. -// 1. Pass the class you want to make into Singleton as a -// template parameter. -// -// class SomeClass { -// protected: -// SomeClass(){} // note - it is protected -// ~SomeClass(){} // note - it is protected -// public: -// void Foo() {} -// }; -// -// Singleton s; -// s::Instance()->Foo(); -// -// OR -// 2. You class can be derived from Singleton in a following way: -// class SomeClass : public Singleton { -// protected: -// SomeClass(){} -// ~SomeClass(){} -// public: -// void Foo() {} -// }; -// -// SomeClass::Instance()->Foo(); -// -// There is no requirement on the class you want to make into -// Singleton except is has to have constructor that takes nothing. -// As long as the class has void constructor it can become a singleton. -// However if you want you class to be trully singleton you have to make -// it constructors and destructors protected. Than you can only access your -// class through the singlenot interface Instance(). -// If simple void constructor is not enough for you class, provide some kind of -// initialization function, which could be called after the instance is -// created. - -#define kSingletonMutexName kLockPrefix L"Singleton_Creation_Lock" - -#ifdef _DEBUG - #define InstanceReturnTypeDeclaration SingletonProxy - #define InstanceReturnTypeStatement SingletonProxy -#else - #define InstanceReturnTypeDeclaration T* - #define InstanceReturnTypeStatement -#endif - -template class Singleton { - // Caching pointers to Singletons is very dangerous and goes against - // Singleton philosophy. So we will return proxy from instance in Debug mode. - // In release mode we will not go this route for efficiency. - template class SingletonProxy { - T* data_; - public: - explicit SingletonProxy(T* data) : data_(data) {} - T* operator->() const { - return data_; - } - SingletonProxy& operator=(const SingletonProxy&); - }; - - public: - Singleton() {} - - // Use double-check pattern for efficiency. - // TODO(omaha): the pattern is broken on multicore. - static InstanceReturnTypeDeclaration Instance() { - if(instance_ == NULL) { - // We use GLock here since LLock will not give us synchronization and - // SimpleLock will create deadlock if one singleton is created in the - // constructor of the other singleton. - GLock creation_lock; - TCHAR mutex_name[MAX_PATH] = {0}; - wsprintf(mutex_name, L"%s%d", - kSingletonMutexName, ::GetCurrentProcessId()); - - VERIFY1(creation_lock.Initialize(mutex_name)); - __mutexScope(creation_lock); - if(instance_ == NULL) - instance_ = GetInstance(); - } - return InstanceReturnTypeStatement(instance_); - } - - private: - static T* GetInstance() { - static MyT my_t; - return &my_t; - } - - // shared between the same type T. - static T * instance_; - - // Needed to access the protected constructor - // of a client. - class MyT : public T { - }; -}; - -// This instance_ is shared between template of the same type. -template T* Singleton::instance_ = NULL; - -#endif // OMAHA_COMMON_SINGLETON_H_ diff --git a/omaha/base/smart_handle.h b/omaha/base/smart_handle.h index 154fe04..fcfdba5 100644 --- a/omaha/base/smart_handle.h +++ b/omaha/base/smart_handle.h @@ -18,8 +18,11 @@ #ifndef OMAHA_COMMON_SMART_HANDLE_H_ #define OMAHA_COMMON_SMART_HANDLE_H_ +#include #include +#include "base/basictypes.h" + namespace omaha { /** @@ -44,7 +47,7 @@ class BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(BaseHandleTraitsT); + DISALLOW_COPY_AND_ASSIGN(BaseHandleTraitsT); }; /** @@ -122,7 +125,7 @@ class HandleT { T h_; private: - DISALLOW_EVIL_CONSTRUCTORS(HandleT); + DISALLOW_COPY_AND_ASSIGN(HandleT); }; @@ -147,7 +150,7 @@ class HandleTraitsWin32Handle : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsWin32Handle); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsWin32Handle); }; /* @@ -166,7 +169,7 @@ class HandleTraitsFindHandle : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsFindHandle); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsFindHandle); }; /* @@ -180,7 +183,7 @@ class HandleTraitsHMenu : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsHMenu); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsHMenu); }; /* @@ -193,7 +196,7 @@ class HandleTraitsHCryptKey : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsHCryptKey); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsHCryptKey); }; /* @@ -206,7 +209,7 @@ class HandleTraitsHCryptHash : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsHCryptHash); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsHCryptHash); }; /* @@ -219,7 +222,7 @@ class HandleTraitsLibrary : public BaseHandleTraitsT { } private: - DISALLOW_EVIL_CONSTRUCTORS(HandleTraitsLibrary); + DISALLOW_COPY_AND_ASSIGN(HandleTraitsLibrary); }; diff --git a/omaha/base/sta.cc b/omaha/base/sta.cc deleted file mode 100644 index 502ab7d..0000000 --- a/omaha/base/sta.cc +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/base/sta.h" - -#include -#include -#include "base/scoped_ptr.h" -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" -#include "omaha/base/sta_call.h" -#include "omaha/base/utils.h" - -namespace omaha { - -namespace { - -class CallDispatcher; - -// ApartmentState maintains the state of the apartment. It keeps a reference -// to a call dispatcher. The dispatcher is basically a window object that -// handles user messages corresponding to each call. -// -// ApartmentState is a singleton. It's lifetime is controlled by the -// 'InitializeApartment' and 'UnintializeApartment'. -// -// The current implementation is limited to the main STA. Creating multiple -// apartments in a process is not possible. -// -// TODO(omaha): implement a simple reference counting of the threads to make -// sure the all the calling threads have returned when the apt is destroyed. - -class ApartmentState { - public: - ApartmentState(DWORD thread_id, CallDispatcher* call_disp) - : thread_id_(thread_id), call_dispatcher_(call_disp) {} - - ~ApartmentState() { - ASSERT1(ref_cnt_ == 0); - } - - // Initialize the state of the singleton. - static HRESULT Initialize(DWORD reserved); - - // Uninitialize the state of the singleton. - static HRESULT Uninitialize(); - - // Accessors. - static ApartmentState* apartment_state() { - return apartment_state_; - } - - CallDispatcher& call_dispatcher() const { - ASSERT(call_dispatcher_.get(), - (_T("'InitializeApartment' has not been called."))); - return *call_dispatcher_; - } - - DWORD thread_id() const { - ASSERT(thread_id_, - (_T("'InitializeApartment' has not been called."))); - return thread_id_; - } - - private: - static int ref_cnt_; // the reference count of init/uninit. - - const DWORD thread_id_; // thread that called the InitializeApartment - scoped_ptr call_dispatcher_; - - static ApartmentState* apartment_state_; // the instance of the state - DISALLOW_EVIL_CONSTRUCTORS(ApartmentState); -}; - - -// CallDispatcher uses functors to cross call from the caller's thread to -// this apartment thread (main thread). -class CallDispatcher - : public CWindowImpl > { - public: - explicit CallDispatcher(DWORD options); - ~CallDispatcher(); - - // Two-phase initialization - HRESULT Init(); - - // The initiator of the cross call. - HRESULT DoCrossApartmentCall(BaseFunctor* caller, void* presult); - - private: - static const UINT WM_METHOD_CALL = WM_USER + 0x100; - static const UINT WM_METHOD_CALL_COMPLETE = WM_USER + 0x101; - - BEGIN_MSG_MAP(CallDispatcher) - MESSAGE_HANDLER(WM_METHOD_CALL, OnMethodCall) - END_MSG_MAP() - - private: - LRESULT OnMethodCall(UINT uMsg, WPARAM wParam, - LPARAM lParam, BOOL& bHandled); - - DWORD options_; - - // Currently only one option is supported for testing purposes. - // It testing mode, this option disables the cross-call mechanism and - // directly calls the functor in the same thread as the invoker. - static const DWORD kTestingMode = DWORD(-1); -}; - -// initialize the static data memebers -ApartmentState* ApartmentState::apartment_state_ = 0; -int ApartmentState::ref_cnt_ = 0; - -HRESULT ApartmentState::Initialize(DWORD reserved) { - CORE_LOG(L3, (_T("[ApartmentState::Initialize]"))); - ASSERT(ref_cnt_ >= 0, (_T("Apartment Reference Counting"))); - if (ref_cnt_ < 0) return E_UNEXPECTED; - - DWORD thread_id = ::GetCurrentThreadId(); - ASSERT1(thread_id); - - if (ref_cnt_ > 0) { - ASSERT(apartment_state(), (_T("Apartment State is 0."))); - bool same_thread = thread_id == apartment_state()->thread_id(); - // if initialized multiple times verify the thread identity just in case - ASSERT(same_thread, (_T("Wrong Thread."))); - if (!same_thread) return E_UNEXPECTED; - ++ref_cnt_; - return S_OK; - } - - ASSERT1(ref_cnt_ == 0); - - // do the initialization of the apartment - scoped_ptr call_disp(new CallDispatcher(reserved)); - RET_IF_FAILED(call_disp->Init()); - scoped_ptr ap_state( - new ApartmentState(thread_id, call_disp.get())); - - call_disp.release(); - ApartmentState::apartment_state_ = ap_state.release(); - - ++ref_cnt_; - return S_OK; -} - -HRESULT ApartmentState::Uninitialize() { - ASSERT(ref_cnt_ > 0, (_T("Apartment Reference Counting"))); - if (ref_cnt_ <= 0) return E_UNEXPECTED; - - DWORD thread_id = ::GetCurrentThreadId(); - ASSERT1(thread_id); - - ASSERT(apartment_state(), (_T("Apartment State is 0."))); - bool same_thread = thread_id == apartment_state()->thread_id(); - // verify the thread identity just in case - ASSERT(same_thread, (_T("Wrong Thread."))); - if (!same_thread) return E_UNEXPECTED; - - if (--ref_cnt_ == 0) { - delete ApartmentState::apartment_state(); - ApartmentState::apartment_state_ = 0; - } - - return S_OK; -} - -CallDispatcher::CallDispatcher(DWORD options) : options_(options) { - // TODO(omaha): Log -} - -CallDispatcher::~CallDispatcher() { - // TODO(omaha): Log - if (m_hWnd) { - DestroyWindow(); - } -} - -HRESULT CallDispatcher::Init() { - // Create a message-only window for the dispatcher. It is not visible, - // has no z-order, cannot be enumerated, and does not receive broadcast - // messages. The window simply dispatches messages. - const TCHAR kWndName[] = _T("{FFE21900-612E-44a9-8424-3FC71B382E61}"); - HWND hwnd = Create(HWND_MESSAGE, NULL, kWndName); - return hwnd ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); -} - -// -LRESULT CallDispatcher::OnMethodCall(UINT, WPARAM wParam, - LPARAM result, BOOL&) { - CORE_LOG(L6, (_T("[CallDispatcher::OnMethodCall]"))); - - ASSERT1(wParam); - BaseFunctor& call = *reinterpret_cast(wParam); - - // presult is non-zero if the method or function has a return type. - // presult is zero for void methods and functions. - - void* presult = reinterpret_cast(result); - - ASSERT( - ApartmentState::apartment_state()->thread_id() == ::GetCurrentThreadId(), - (_T("Wrong Thread"))); - - // the function object virtual call; - call(presult); - - bool is_async = call.is_async(); - // For async calls, do not post a message, because the caller will not be - // waiting for the call to complete. - if (!is_async && - !::PostThreadMessage(call.thread_id(), WM_METHOD_CALL_COMPLETE, 0, 0)) { - DWORD error = ::GetLastError(); - CORE_LOG(LEVEL_ERROR, - (_T("[CallDispatcher::OnMethodCall - PostThreadMessage][%d]"), error)); - ASSERT(false, (_T("Failed to PostThreadMessage."))); - - // TODO(omaha): raise here. - } - - // DO NOT ACCESS THE CALL OBJECT FROM DOWN ON. IN THE CASE OF A SYNCHRONOUS - // CALL THE CALL OBJECT MAY HAVE ALREADY DESTROYED. - - if (is_async) { - // Auto cleanup of the call object in the case of a async call. - delete &call; - } - - CORE_LOG(L6, (_T("CallDispatcher::OnMethodCall returns."))); - return true; -} - -// -HRESULT CallDispatcher::DoCrossApartmentCall(BaseFunctor* call, - void* presult) { - CORE_LOG(L6, (_T("[CallDispatcher::DoCrossApartmentCall]"))); - - ASSERT(IsWindow(), (_T("The dispatcher must have a window."))); - bool is_async = call->is_async(); - if (options_ == kTestingMode) { - (*call)(presult); - if (is_async) { - // We need to delete the functor as if we were the callee. - delete call; - } - return S_OK; - } - - if (!is_async) { - // Usually it is a mistake to call a synchronous method from the main STA - // to the main STA. - - DWORD thread_id = ApartmentState::apartment_state()->thread_id(); - ASSERT(thread_id != ::GetCurrentThreadId(), (_T("Wrong Thread"))); - - ASSERT(GetWindowThreadID() != ::GetCurrentThreadId(), - (_T("DoCrossApartmentCall calling its own thread."))); - } - - if (!PostMessage(WM_METHOD_CALL, - reinterpret_cast(call), - reinterpret_cast(presult))) { - DWORD err = ::GetLastError(); - CORE_LOG(LEVEL_ERROR, - (_T("[CallDispatcher::DoCrossApartmentCall - PostMessage][%d]"), err)); - ASSERT(false, (_T("Failed to PostMessage."))); - - return HRESULT_FROM_WIN32(err); - } - - // Once the call has been made, do not access the state of the functor as - // the other end might have already executed the call and delete the functor. - // This is true for asyncronous calls but it would not hurt for synchronous - // calls as well. - call = NULL; - - if (is_async) { - // Do not wait for the call to complete. The call will complete at - // some time in the future and the call object is going to be cleaned up. - return S_OK; - } - - // Pump all messages, waiting for WM_METHOD_CALL_COMPLETE or WM_QUIT. - MSG msg; - SetZero(msg); - int ret = 0; - while ((ret = ::GetMessage(&msg, 0, 0, 0)) != 0) { - if (ret == -1) { - DWORD error = ::GetLastError(); - CORE_LOG(LEVEL_ERROR, - (_T("[CallDispatcher::DoCrossApartmentCall - GetMessage][%d]"), - error)); - // TODO(omaha): raise here. - } - - if (msg.message == WM_METHOD_CALL_COMPLETE) { - break; - } - - ::DispatchMessage(&msg); - } - - // Repost the WM_QUIT message to properly exit all message loops. - if (msg.message == WM_QUIT) { - ASSERT1(ret == 0); - ::PostQuitMessage(static_cast(msg.wParam)); - } - - CORE_LOG(L6, (_T("CallDispatcher::DoCrossApartmentCall returns"))); - return S_OK; -} - -} // namespace - -void BaseFunctor::DoInvoke(void* presult) { - ASSERT(ApartmentState::apartment_state(), - (_T("Did you forgot to call 'InitializeApartment'?"))); - - CallDispatcher& call_dispatcher = - ApartmentState::apartment_state()->call_dispatcher(); - - HRESULT hr = call_dispatcher.DoCrossApartmentCall(this, presult); - - if (FAILED(hr)) { - ASSERT(false, (_T("Failed to call across apartments."))); - // TODO(omaha): log, report, raise. - } -} - -HRESULT InitializeApartment(DWORD reserved) { - return ApartmentState::Initialize(reserved); -} - -HRESULT UninitializeApartment() { - return ApartmentState::Uninitialize(); -} - -} // namespace omaha - diff --git a/omaha/base/sta.h b/omaha/base/sta.h deleted file mode 100644 index 073f17c..0000000 --- a/omaha/base/sta.h +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// STA initializes a custom non-COM Single Threaded Apartment to facilitate -// calling of functions and object methods in the thread of the STA. This is -// useful when creating a simple threading model based on a main thread and -// several worker threads, especially for client components that have a UI or -// use the COM STA models. -// -// The current implementation only supports initializing the main STA, which is -// the STA created by the main thread of the process. This is usually the UI -// thread. Having multiple STA in a process is not possible yet. -// -// This custom STA does not interfere with the COM STAs. -// -// In order for the STA to work properly, the STA thread must keep processing -// messages and not block, just like in the COM STA case. - -#ifndef OMAHA_COMMON_STA_H__ -#define OMAHA_COMMON_STA_H__ - -#include -#include "omaha/base/debug.h" -#include "omaha/base/scoped_any.h" - -namespace omaha { - -// Initializes the STA apartment. The 'reserved' parameter must be 0. -// InitializeApartment and UninitializeApartment are reference-counted. -HRESULT InitializeApartment(DWORD reserved); - -// Uninitializes the STA apartment. -HRESULT UninitializeApartment(); - -// A scoped_sta smart pointer is provided to manage the calls to -// InitializeApartment and UninitializeApartment. -inline HRESULT smart_sta_init_helper(DWORD reserved) { - return InitializeApartment(reserved); -} - -inline void smart_uninit_helper(HRESULT result) { - if (result == S_OK) { - VERIFY1(SUCCEEDED(UninitializeApartment())); - } -} - -typedef close_fun close_sta; - -typedef value_const sta_not_init; - -typedef scoped_any scoped_sta_close; - -struct scoped_sta { - explicit scoped_sta(DWORD reserved) - : result_(smart_sta_init_helper(reserved)) {} - - HRESULT result() const { return get(result_); } - - private: - const scoped_sta_close result_; -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_STA_H__ - diff --git a/omaha/base/sta_call.h b/omaha/base/sta_call.h deleted file mode 100644 index 4727fa9..0000000 --- a/omaha/base/sta_call.h +++ /dev/null @@ -1,1117 +0,0 @@ -// Copyright 2003-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// sta_call.h generics for cross apartment calling. -// -// The code is using compile-time and run-time polymorphism to create -// type-safe call wrappers that can be used to cross call from a -// worker thread to an STA thread. The current implementation only -// supports calling the main STA. -// -// Functions as well as object methods can be called. -// -// Examples: -// class X { -// public: -// int Add(int i, int j) { return i + j; } -// }; -// -// -// namespace { -// int Add(long i, long j) { return i + j; } -// } -// -// X x; -// int sum = CallMethod(&x, X::Add, 10, 20); -// int j = CallFunction(Add, -10, 10); -// -// The central piece of machinery is a hierarchy of functors. A functor is -// instantiated by a function template (CallFunction or CallMethod) and its -// 'Invoke' method gets called. -// Calling 'Invoke' will send the functor using 'SendMessage' -// to a window. The window message handler picks up the functor and -// calls the functor virtual operator(). -// This virtual call is what actually calls the specified function or the -// method, the only difference being that the call is now made in a thread -// different than the thread that called 'Invoke'. There is a partial -// specialization of the templates for void, so that void type is supported -// as a return type. -// -// -// !!! Limitations !!! -// -// There are a few important design and implementation limitations. They are -// mostly related to template parameters ambiguities (T or T&) especially -// for overloaded names or const types. The limitations are significant although -// the code is useful enough as it is in most of the cases. -// However, when using the code it is frustrating to discover that it does not -// compile for obvious and useful cases, a constant reminder that a better -// solution is to be seeked. -// -// -// The implementation does not support calling all 'stdcall' calling convention. -// -// The design does not support calling functions or methods that use pass by -// reference arguments: f(std::string&) . -// -// The design does not support well calling functions or methods that take -// pointer to const types parameters : f(const std::string*) . -// -// The implementation does not support calling methods of const objects. -// -// To reduce the number of templates that get instantiated, the types of the -// arguments of the call must match exactly the types of parameters of the -// function or method . In some cases static_casts mey be required -// at the point of the call. Example: CallMethod(f, static_cast(10)); - -#ifndef OMAHA_COMMON_STA_CALL_H__ -#define OMAHA_COMMON_STA_CALL_H__ - -#include "base/scoped_ptr.h" -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" - -namespace omaha { - -// C4347: 'function template' is called instead of 'function' -#pragma warning(disable : 4347) - -// The Base Functor is the base of the functor hierarchy. -class BaseFunctor { - public: - explicit BaseFunctor(bool is_async) : - thread_id_(::GetCurrentThreadId()), - is_async_(is_async) { - CORE_LOG(L6, (_T("[BaseFunctor::BaseFunctor]"))); - } - - // Functors are polymorphic objects. - virtual ~BaseFunctor() { - CORE_LOG(L6, (_T("[BaseFunctor::~BaseFunctor]"))); - } - - // Abstract virtual function call operator. This is always called - // in the callee thread by the dispatcher of the apartment. - virtual void operator()(void* presult) = 0; - - // The thread id of the calling thread. - DWORD thread_id() const { return thread_id_; } - - bool is_async() const { return is_async_; } - - protected: - - // Invoke is called by each of the derived functors. This is how - // the cross thread invocation is made and the result of the invocation - // is retrieved. Invoke is always called in the caller thread. - template - R Invoke() { - R r = R(); // ensure r is initialized even for primitive types. - if (!is_async_) { - DoInvoke(&r); - } else { - // We handle the async calls as if the call returns void. - DoInvoke(0); - } - return r; - } - - // non-template method to be called by the derived functors - // specialized for void. - void Invoke() { - // When the argument of the invocation is 0, we are not - // interested in the result. - DoInvoke(0); - } - - private: - void DoInvoke(void* presult); // Does the actual invocation. - DWORD thread_id_; // The thread id of the calling thread. - bool is_async_; // True for async calls. - - DISALLOW_EVIL_CONSTRUCTORS(BaseFunctor); -}; - -// -// 0-ary method functor. -// -template -class MethodFunctor0 : public BaseFunctor { - public: - MethodFunctor0(bool is_async, T* pt, R (T::*pm)()) : - BaseFunctor(is_async), pobj_(pt), pm_(pm) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(); - } else { - (pobj_->*pm_)(); - } - } - - R Invoke() { - // Don't forget to call the base implementation. - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(); -}; - -// -// 0-ary partial specialization for void return types. -// -template -class MethodFunctor0 : public BaseFunctor { - public: - MethodFunctor0(bool is_async, T* pt, void (T::*pm)()) : - BaseFunctor(is_async), pobj_(pt), pm_(pm) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - // the actual call. There is no return value when the return type is void. - (pobj_->*pm_)(); - } - - // Bring in the name from the Base - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(); -}; - -// -// 0-ary functor and specialization for void. -// -template -class Functor0 : public BaseFunctor { - public: - Functor0(bool is_async, R (*pf)()) : - BaseFunctor(is_async), pf_(pf) {} - - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = (*pf_)(); - } else { - (*pf_)(); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(); -}; - -template <> -class Functor0 : public BaseFunctor { - public: - Functor0(bool is_async, void (*pf)()) : - BaseFunctor(is_async), pf_(pf) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(); -}; - - -// -// 1-ary -// -template -class MethodFunctor1 : public BaseFunctor { - public: - MethodFunctor1(bool is_async, T* pt, R (T::*pm)(P), P p) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p_(p) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(p_); - } else { - (pobj_->*pm_)(p_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(P); - P p_; -}; - -template -class MethodFunctor1 : public BaseFunctor { - public: - MethodFunctor1(bool is_async, T* pt, void (T::*pm)(P), P p) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p_(p) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (pobj_->*pm_)(p_); - } - - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(P); - P p_; -}; - -template -class Functor1 : public BaseFunctor { - public: - Functor1(bool is_async, R (*pf)(P1), P1 p1) : - BaseFunctor(is_async), pf_(pf), p1_(p1) {} - - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = (*pf_)(p1_); - } else { - (*pf_)(p1_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(P1); - P1 p1_; -}; - -template -class Functor1 : public BaseFunctor { - public: - Functor1(bool is_async, void (*pf)(P1), P1 p1) : - BaseFunctor(is_async), pf_(pf), p1_(p1) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(p1_); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(P1); - P1 p1_; -}; - - -// -// 2-ary -// -template -class MethodFunctor2 : public BaseFunctor { - public: - MethodFunctor2(bool is_async, T* pt, R (T::*pm)(P1, P2), P1 p1, P2 p2) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p1_(p1), p2_(p2) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(p1_, p2_); - } else { - (pobj_->*pm_)(p1_, p2_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(P1, P2); - P1 p1_; - P2 p2_; -}; - -template -class MethodFunctor2 : public BaseFunctor { - public: - MethodFunctor2(bool is_async, T* pt, void (T::*pm)(P1, P2), P1 p1, P2 p2) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p1_(p1), p2_(p2) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (pobj_->*pm_)(p1_, p2_); - } - - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(P1, P2); - P1 p1_; - P2 p2_; -}; - -template -class Functor2 : public BaseFunctor { - public: - Functor2(bool is_async, R (*pf)(P1, P2), P1 p1, P2 p2) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2) {} - - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = pf_(p1_, p2_); - } else { - pf_(p1_, p2_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(P1, P2); - P1 p1_; - P2 p2_; -}; - -template -class Functor2 : public BaseFunctor { - public: - Functor2(bool is_async, void (*pf)(P1, P2), P1 p1, P2 p2) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(p1_, p2_); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(P1, P2); - P1 p1_; - P2 p2_; -}; - -// -// 3-ary -// -template -class MethodFunctor3 : public BaseFunctor { - public: - MethodFunctor3(bool is_async, - T* pt, - R (T::*pm)(P1, P2, P3), - P1 p1, - P2 p2, - P3 p3) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p1_(p1), p2_(p2), p3_(p3) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(p1_, p2_, p3_); - } else { - (pobj_->*pm_)(p1_, p2_, p3_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(P1, P2, P3); - P1 p1_; - P2 p2_; - P3 p3_; -}; - -template -class MethodFunctor3 : public BaseFunctor { - public: - MethodFunctor3(bool is_async, - T* pt, - void (T::*pm)(P1, P2, P3), - P1 p1, - P2 p2, - P3 p3) : - BaseFunctor(is_async), pobj_(pt), pm_(pm), p1_(p1), p2_(p2), p3_(p3) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (pobj_->*pm_)(p1_, p2_, p3_); - } - - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(P1, P2, P3); - P1 p1_; - P2 p2_; - P3 p3_; -}; - - -template -class Functor3 : public BaseFunctor { - public: - Functor3(bool is_async, R (*pf)(P1, P2, P3), P1 p1, P2 p2, P3 p3) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2), p3_(p3) {} - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = (*pf_)(p1_, p2_, p3_); - } else { - (*pf_)(p1_, p2_, p3_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(P1, P2, P3); - P1 p1_; - P2 p2_; - P3 p3_; -}; - -template -class Functor3 : public BaseFunctor { - public: - Functor3(bool is_async, void (*pf)(P1, P2, P3), P1 p1, P2 p2, P3 p3) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2), p3_(p3) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(p1_, p2_, p3_); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(P1, P2, P3); - P1 p1_; - P2 p2_; - P3 p3_; -}; - -// -// 4-ary -// -template -class MethodFunctor4 : public BaseFunctor { - public: - MethodFunctor4(bool is_async, - T* pt, - R (T::*pm)(P1, P2, P3, P4), - P1 p1, - P2 p2, - P3 p3, - P4 p4) : - BaseFunctor(is_async), - pobj_(pt), - pm_(pm), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(p1_, p2_, p3_, p4_); - } else { - (pobj_->*pm_)(p1_, p2_, p3_, p4_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(P1, P2, P3, P4); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; -}; - -template -class MethodFunctor4 : public BaseFunctor { - public: - MethodFunctor4(bool is_async, - T* pt, - void (T::*pm)(P1, P2, P3, P4), - P1 p1, - P2 p2, - P3 p3, - P4 p4) : - BaseFunctor(is_async), - pobj_(pt), - pm_(pm), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (pobj_->*pm_)(p1_, p2_, p3_, p4_); - } - - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(P1, P2, P3, P4); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; -}; - - -template -class Functor4 : public BaseFunctor { - public: - Functor4(bool is_async, R (*pf)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2), p3_(p3), p4_(p4) {} - - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = (*pf_)(p1_, p2_, p3_, p4_); - } else { - (*pf_)(p1_, p2_, p3_, p4_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(P1, P2, P3, P4); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; -}; - -template -class Functor4 : public BaseFunctor { - public: - Functor4(bool is_async, - void (*pf)(P1, P2, P3, P4), - P1 p1, - P2 p2, - P3 p3, - P4 p4) : - BaseFunctor(is_async), pf_(pf), p1_(p1), p2_(p2), p3_(p3), p4_(p4) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(p1_, p2_, p3_, p4_); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(P1, P2, P3, P4); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; -}; - -// -// 5-ary -// -template -class MethodFunctor5 : public BaseFunctor { - public: - MethodFunctor5(bool is_async, - T* pt, - R (T::*pm)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) : - BaseFunctor(is_async), - pobj_(pt), - pm_(pm), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4), - p5_(p5) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - if (presult) { - *static_cast(presult) = (pobj_->*pm_)(p1_, p2_, p3_, p4_, p5_); - } else { - (pobj_->*pm_)(p1_, p2_, p3_, p4_, p5_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - T* pobj_; - R (T::*pm_)(P1, P2, P3, P4, P5); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; - P5 p5_; -}; - -template -class MethodFunctor5 : public BaseFunctor { - public: - MethodFunctor5(bool is_async, - T* pt, - void (T::*pm)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) : - BaseFunctor(is_async), - pobj_(pt), - pm_(pm), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4), - p5_(p5) {} - - virtual void operator()(void* presult) { - ASSERT(pobj_, (_T("Null object."))); - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (pobj_->*pm_)(p1_, p2_, p3_, p4_, p5_); - } - - using BaseFunctor::Invoke; - - private: - T* pobj_; - void (T::*pm_)(P1, P2, P3, P4, P5); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; - P5 p5_; -}; - -template -class Functor5 : public BaseFunctor { - public: - Functor5(bool is_async, - R (*pf)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) : - BaseFunctor(is_async), - pf_(pf), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4), - p5_(p5) {} - virtual void operator()(void* presult) { - if (presult) { - *static_cast(presult) = (*pf_)(p1_, p2_, p3_, p4_, p5_); - } else { - (*pf_)(p1_, p2_, p3_, p4_, p5_); - } - } - - R Invoke() { - return BaseFunctor::Invoke(); - } - - private: - R (*pf_)(P1, P2, P3, P4, P5); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; - P5 p5_; -}; - -template -class Functor5 : public BaseFunctor { - public: - Functor5(bool is_async, - void (*pf)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) : - BaseFunctor(is_async), - pf_(pf), - p1_(p1), - p2_(p2), - p3_(p3), - p4_(p4), - p5_(p5) {} - - virtual void operator()(void* presult) { - ASSERT1(!presult); - presult; // unreferenced formal parameter - - (*pf_)(p1_, p2_, p3_, p4_, p5_); - } - - using BaseFunctor::Invoke; - - private: - void (*pf_)(P1, P2, P3, P4, P5); - P1 p1_; - P2 p2_; - P3 p3_; - P4 p4_; - P5 p5_; -}; - - -// This is what the clients of the STA code instantiate and call. -// -// Synchronous Callers. -// -template -R CallMethod(T* object, R (T::*pm)()) { - return MethodFunctor0(false, object, pm).Invoke(); -} - -template -R CallFunction(R (*pf)()) { - return Functor0(false, pf).Invoke(); -} - -template -R CallMethod(T* object, R (T::*pm)(P), P p) { - return MethodFunctor1(false, object, pm, p).Invoke(); -} - -template -R CallFunction(R (*pf)(P), P p) { - return Functor1(false, pf, p).Invoke(); -} - -template -R CallMethod(T* object, R (T::*pm)(P1, P2), P1 p1, P2 p2) { - return MethodFunctor2(false, object, pm, p1, p2).Invoke(); -} - -template -R CallFunction(R (*pf)(P1, P2), P1 p1, P2 p2) { - return Functor2(false, pf, p1, p2).Invoke(); -} - -template -R CallMethod(T* object, R (T::*pm)(P1, P2, P3), P1 p1, P2 p2, P3 p3) { - return MethodFunctor3(false, - object, pm, p1, p2, p3).Invoke(); -} - -template -R CallFunction(R (*pf)(P1, P2, P3), P1 p1, P2 p2, P3 p3) { - return Functor3(false, pf, p1, p2, p3).Invoke(); -} - -template -R CallMethod(T* object, - R (T::*pm)(P1, P2, P3, P4), - P1 p1, - P2 p2, - P3 p3, - P4 p4) { - return MethodFunctor4(false, - object, - pm, - p1, - p2, - p3, - p4).Invoke(); -} - -template -R CallFunction(R (*pf)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) { - return Functor4(false, pf, p1, p2, p3, p4).Invoke(); -} - -template -R CallMethod(T* object, - R (T::*pm)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) { - return MethodFunctor5(false, - object, - pm, - p1, - p2, - p3, - p4, - p5).Invoke(); -} - -template -R CallFunction(R (*pf)(P1, P2, P3, P4, P5), P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { - return Functor5(false, - pf, - p1, - p2, - p3, - p4, - p5).Invoke(); -} - -// -// Asynchronous Callers. -// -template -void CallMethodAsync(T* object, R (T::*pm)()) { - scoped_ptr > fun( - new MethodFunctor0(true, object, pm)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)()) { - scoped_ptr > fun(new Functor0(true, pf)); - fun->Invoke(); - fun.release(); -} - -template -void CallMethodAsync(T* object, R (T::*pm)(P), P p) { - scoped_ptr > fun( - new MethodFunctor1(true, object, pm, p)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)(P), P p) { - scoped_ptr > fun(new Functor1(true, pf, p)); - fun->Invoke(); - fun.release(); -} - -template -void CallMethodAsync(T* object, R (T::*pm)(P1, P2), P1 p1, P2 p2) { - scoped_ptr > fun( - new MethodFunctor2(true, object, pm, p1, p2)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)(P1, P2), P1 p1, P2 p2) { - scoped_ptr > fun( - new Functor2(true, pf, p1, p2)); - fun->Invoke(); - fun.release(); -} - -template -void CallMethodAsync(T* object, R (T::*pm)(P1, P2, P3), P1 p1, P2 p2, P3 p3) { - scoped_ptr > fun( - new MethodFunctor3(true, object, pm, p1, p2, p3)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)(P1, P2, P3), P1 p1, P2 p2, P3 p3) { - scoped_ptr > fun( - new Functor3(true, pf, p1, p2, p3)); - fun->Invoke(); - fun.release(); -} - -template -void CallMethodAsync(T* obj, - R (T::*pm)(P1, P2, P3, P4), - P1 p1, - P2 p2, - P3 p3, - P4 p4) { - scoped_ptr > fun( - new MethodFunctor4(true, obj, pm, p1, p2, p3, p4)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)(P1, P2, P3, P4), P1 p1, P2 p2, P3 p3, P4 p4) { - scoped_ptr > fun( - new Functor4(true, pf, p1, p2, p3, p4)); - fun->Invoke(); - fun.release(); -} - -template -void CallMethodAsync(T* object, - R (T::*pm)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) { - scoped_ptr > fun( - new MethodFunctor5(true, - object, - pm, - p1, - p2, - p3, - p4, - p5)); - fun->Invoke(); - fun.release(); -} - -template -void CallFunctionAsync(R (*pf)(P1, P2, P3, P4, P5), - P1 p1, - P2 p2, - P3 p3, - P4 p4, - P5 p5) { - scoped_ptr > fun( - new Functor5(true, pf, p1, p2, p3, p4, p5)); - fun->Invoke(); - fun.release(); -} - -#pragma warning(default : 4347) - -} // namespace omaha - -#endif // OMAHA_COMMON_STA_CALL_H__ - diff --git a/omaha/base/sta_unittest.cc b/omaha/base/sta_unittest.cc deleted file mode 100644 index 4042248..0000000 --- a/omaha/base/sta_unittest.cc +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - - -#include -#include "omaha/base/sta.h" -#include "omaha/base/sta_call.h" -#include "omaha/base/thread.h" -#include "omaha/base/utils.h" -#include "omaha/testing/unit_test.h" - -namespace omaha { - -namespace { - -class X { - public: - void f() {} - void f(int) {} - void f(unsigned int, X*) {} - void f(bool, char, long*) {} - - static void g() {} - static void g(int) {} - static void g(unsigned int, X*) {} - static void g(bool, char, long*) {} -}; - -class Y { - public: - HRESULT f() { return S_OK; } - HRESULT f(int) { return S_OK; } - HRESULT f(unsigned int, X*) { return S_OK; } - HRESULT f(bool, char, long*) { return S_OK; } - - static HRESULT g() { return S_OK; } - static HRESULT g(int) { return S_OK; } - static HRESULT g(unsigned int, X*) { return S_OK; } - static HRESULT g(bool, char, long*) { return S_OK; } -}; - -class Z { - public: - void f(char, signed char, unsigned char) {} - - void f(Y*) {} - // void f(const Y*) {} // not supported !!! - - void m() {} - void m() const {} -}; - -class Test { - public: - int Add(int i, int j) { return i + j; } - void Add(int i, int j, int* sum) { *sum = i + j; } -}; - -int Add(long i, long j) { return i + j; } -void Add(long i, long j, long* sum) { *sum = i + j; } - -void Print(const char*) {} -void Print1(CString*) {} - -} // namespace - -class CompileTest : public Runnable { - protected: - virtual void Run(); -}; - -void CompileTest::Run() { - X x; - Y y; - - CallFunction(X::g); - CallFunction(X::g, 10); - CallFunction(X::g, static_cast(10), &x); - CallFunction(X::g, true, 'a', static_cast(0)); - - CallFunction(Y::g); - CallFunction(Y::g, 10); - CallFunction(Y::g, static_cast(10), &x); - CallFunction(Y::g, true, 'a', static_cast(0)); - - CallMethod(&x, &X::f); - CallMethod(&x, &X::f, 10); - CallMethod(&x, &X::f, static_cast(10), &x); - CallMethod(&x, &X::f, true, 'a', static_cast(0)); - - CallMethod(&y, &Y::f); - CallMethod(&y, &Y::f, 20); - CallMethod(&y, &Y::f, static_cast(10), &x); - CallMethod(&y, &Y::f, true, 'a', static_cast(0)); - - Z z; - CallMethod(&z, - &Z::f, - 'a', - static_cast('a'), - static_cast('a')); - - - CallMethod(&z, &Z::f, &y); - - // Does not compile: template parameter 'P' is ambiguous - // const Y cy; - // CallMethod(&z, &Z::f, &cy); - - CallMethod(&z, &Z::m); - - // Does not compile: template parameter 'T' is ambiguous - // const Z cz; - // CallMethod(&cz, &Z::m); - - // Does not compile: cannot convert from 'const Z *' to 'Z *const ' - // const Z cz; - // CallMethod(&cz, &Z::m); - - CString msg(_T("test")); - CallFunction(Print, "test"); - CallFunction(Print1, &msg); -} - -class RuntimeTest : public Runnable { - protected: - virtual void Run(); -}; - -void RuntimeTest::Run() { - Test test; - { - ASSERT_EQ(CallMethod(&test, &Test::Add, 10, 20), 30); - - int sum(0); - CallMethod(&test, &Test::Add, -10, 20, &sum); - ASSERT_EQ(sum, 10); - } - - { - ASSERT_EQ(CallFunction(Add, long(10), long(20)), 30); - - long sum = 0; - CallFunction(Add, long(10), long(-20), &sum); - ASSERT_EQ(sum, -10); - } -} - - -class AsyncTest : public Runnable { - protected: - virtual void Run(); -}; - -void AsyncTest::Run() { - static X x; - static Y y; - - CallFunctionAsync(X::g); - CallFunctionAsync(X::g, 10); - CallFunctionAsync(X::g, static_cast(10), &x); - CallFunctionAsync(X::g, true, 'a', static_cast(0)); - - CallFunctionAsync(Y::g); - CallFunctionAsync(Y::g, 10); - CallFunctionAsync(Y::g, static_cast(10), &x); - CallFunctionAsync(Y::g, true, 'a', static_cast(0)); - - CallMethodAsync(&x, &X::f); - CallMethodAsync(&x, &X::f, 10); - CallMethodAsync(&x, &X::f, static_cast(10), &x); - CallMethodAsync(&x, &X::f, true, 'a', static_cast(0)); - - CallMethodAsync(&y, &Y::f); - CallMethodAsync(&y, &Y::f, 20); - CallMethodAsync(&y, &Y::f, static_cast(10), &x); - CallMethodAsync(&y, &Y::f, true, 'a', static_cast(0)); - - static Z z; - CallMethodAsync(&z, - &Z::f, - 'a', - static_cast('a'), - static_cast('a')); - - - CallMethodAsync(&z, &Z::f, &y); - - // Does not compile: template parameter 'P' is ambiguous - // const Y cy; - // CallMethod(&z, &Z::f, &cy); - - CallMethodAsync(&z, &Z::m); - - // Does not compile: template parameter 'T' is ambiguous - // const Z cz; - // CallMethod(&cz, &Z::m); - - // Does not compile: cannot convert from 'const Z *' to 'Z *const ' - // const Z cz; - // CallMethod(&cz, &Z::m); - - CString msg(_T("test")); - CallFunctionAsync(Print, "test"); - CallFunctionAsync(Print1, &msg); - - WaitWithMessageLoopTimed(1000); -} - - -TEST(STATest, CompileTest) { - ASSERT_SUCCEEDED(InitializeApartment(0)); - - Thread t; - CompileTest compile_test; - t.Start(&compile_test); - EXPECT_TRUE(WaitWithMessageLoop(t.GetThreadHandle())); - - ASSERT_SUCCEEDED(UninitializeApartment()); -} - -TEST(STATest, RuntimeTest) { - ASSERT_SUCCEEDED(InitializeApartment(0)); - - Thread t; - RuntimeTest runtime_test; - t.Start(&runtime_test); - EXPECT_TRUE(WaitWithMessageLoop(t.GetThreadHandle())); - - ASSERT_SUCCEEDED(UninitializeApartment()); -} - - -TEST(STATest, AsyncTest) { - ASSERT_SUCCEEDED(InitializeApartment(0)); - - Thread t; - AsyncTest async_test; - t.Start(&async_test); - EXPECT_TRUE(WaitWithMessageLoop(t.GetThreadHandle())); - - ASSERT_SUCCEEDED(UninitializeApartment()); -} - -TEST(STATest, ApartmentRefCounting) { - // Check the reference counting is working. - ASSERT_SUCCEEDED(InitializeApartment(0)); - ASSERT_SUCCEEDED(InitializeApartment(0)); - ASSERT_SUCCEEDED(UninitializeApartment()); - ASSERT_SUCCEEDED(UninitializeApartment()); - - // The call below will raise an assert in the the STA code. - ExpectAsserts expect_asserts; - ASSERT_EQ(E_UNEXPECTED, UninitializeApartment()); -} - -TEST(STATest, ScopedSTA) { - { - scoped_sta sta(0); - ASSERT_SUCCEEDED(sta.result()); - } - { - scoped_sta sta(0); - ASSERT_SUCCEEDED(sta.result()); - } - { - scoped_sta sta1(0); - scoped_sta sta2(0); - ASSERT_SUCCEEDED(sta1.result()); - ASSERT_SUCCEEDED(sta2.result()); - } - - ExpectAsserts expect_asserts; - ASSERT_EQ(E_UNEXPECTED, UninitializeApartment()); -} - -} // namespace omaha - diff --git a/omaha/base/store_watcher.h b/omaha/base/store_watcher.h index fb55e24..755f9bc 100644 --- a/omaha/base/store_watcher.h +++ b/omaha/base/store_watcher.h @@ -36,7 +36,7 @@ class StoreWatcher { // event using change_event(). virtual HRESULT EnsureEventSetup() = 0; - // Indicates if any changes have occured + // Indicates if any changes have occurred bool HasChangeOccurred() const { return IsHandleSignaled(change_event()); } @@ -51,7 +51,7 @@ class StoreWatcher { virtual HANDLE change_event() const = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(StoreWatcher); + DISALLOW_COPY_AND_ASSIGN(StoreWatcher); }; } // namespace omaha diff --git a/omaha/base/string.cc b/omaha/base/string.cc index eca521a..f8cd8f0 100644 --- a/omaha/base/string.cc +++ b/omaha/base/string.cc @@ -14,15 +14,17 @@ // ======================================================================== #include "omaha/base/string.h" + +#include +#include +#include #include // For INTERNET_MAX_URL_LENGTH. #include -#include #include -#include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/commontypes.h" #include "omaha/base/debug.h" -#include "omaha/base/localization.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" @@ -83,12 +85,6 @@ bool IsSpaceA(char c) { return spaces[static_cast(c)] == 1; } -int TrimCString(CString &s) { - int len = Trim(s.GetBuffer()); - s.ReleaseBufferSetLength(len); - return len; -} - void MakeLowerCString(CString & s) { int len = s.GetLength(); String_FastToLower(s.GetBuffer()); @@ -131,39 +127,6 @@ void TrimString(CString& s, const TCHAR* delimiters) { s = s.Trim(delimiters); } -// Strip the first token from the front of argument s. A token is a -// series of consecutive non-blank characters - unless the first -// character is a double-quote ("), in that case the token is the full -// quoted string -CString StripFirstQuotedToken(const CString& s) { - const int npos = -1; - - // Make a writeable copy - CString str(s); - - // Trim any surrounding blanks (and tabs, for the heck of it) - TrimString(str, L" \t"); - - // Too short to have a second token - if (str.GetLength() <= 1) - return L""; - - // What kind of token are we stripping? - if (str[0] == L'\"') { - // Remove leading quoting string - int i = str.Find(L"\"", 1); - if (i != npos) - i++; - return str.Mid(i); - } else { - // Remove leading token - int i = str.FindOneOf(L" \t"); - if (i != npos) - i++; - return str.Mid(i); - } -} - // A block of text to separate lines, and back void TextToLines(const CString& text, const TCHAR* delimiter, std::vector* lines) { ASSERT(delimiter, (L"")); @@ -213,53 +176,6 @@ void LinesToText(const std::vector& lines, const TCHAR* delimiter, CStr } } -int CleanupWhitespaceCString(CString &s) { - int len = CleanupWhitespace(s.GetBuffer()); - s.ReleaseBufferSetLength(len); - return len; -} - -int CleanupWhitespace(TCHAR *str) { - ASSERT(str, (L"")); - - TCHAR *src = str; - TCHAR *dest = str; - int num_spaces = 0; - bool at_start = true; - while (true) { - // At end of string? - TCHAR c = *src; - if (0 == c) - break; - - // Look for whitespace; copy it over if not whitespace - if (IsSpace(c)) { - ++num_spaces; - } - else { - *dest++ = c; - at_start = false; - num_spaces = 0; - } - - // Write only first consecutive space (but skip space at start) - if (1 == num_spaces && !at_start) - *dest++ = ' '; - - ++src; - } - - // Remove trailing space, if any - if (dest > str && *(dest - 1) == L' ') - --dest; - - // 0-terminate - *dest = 0; - - // TODO(portability): cast is unsafe. - return static_cast(dest - str); -} - // Take 1 single hexadecimal "digit" (as a character) and return its decimal value // Returns -1 if given invalid hex digit int HexDigitToDec(const TCHAR digit) { @@ -317,20 +233,6 @@ WCHAR *ToWide (const char *s, int len) { return w; } -const byte *BufferContains (const byte *buf, uint32 buf_len, const byte *data, uint32 data_len) { - ASSERT(data, (L"")); - ASSERT(buf, (L"")); - - for (uint32 i = 0; i < buf_len; i++) { - uint32 j = i; - uint32 k = 0; - uint32 len = 0; - while (j < buf_len && k < data_len && buf[j++] == data[k++]) { len++; } - if (len == data_len) { return buf + i; } - } - return 0; -} - // Converting the Ansi Multibyte String into unicode string. The multibyte // string is encoded using the specified codepage. // The code is pretty much like the U2W function, except the codepage can be @@ -405,7 +307,7 @@ CStringA WideToUtf8(const CString& w) { // Figure out how long the string is int req_bytes = ::WideCharToMultiByte(CP_UTF8, 0, w, -1, NULL, 0, NULL, NULL); - scoped_array utf8_buffer(new char[req_bytes]); + std::unique_ptr utf8_buffer(new char[req_bytes]); int conv_bytes = ::WideCharToMultiByte(CP_UTF8, 0, w, -1, utf8_buffer.get(), req_bytes, NULL, NULL); ASSERT1(req_bytes == conv_bytes); @@ -471,23 +373,6 @@ CString Utf8BufferToWideChar(const std::vector& buffer) { return result; } -CString AbbreviateString (const CString & title, int32 max_len) { - ASSERT (max_len, (L"")); - CString s(title); - TrimCString(s); // remove whitespace at start/end - if (s.GetLength() > max_len) { - s = s.Left (max_len - 2); - CString orig(s); - // remove partial words - while (s.GetLength() > 1 && !IsSpace(s[s.GetLength()-1])) { s = s.Left (s.GetLength() - 1); } - // but not if it would make the string very short - if (s.GetLength() < max_len / 2) { s = orig; } - s += _T(".."); - } - - return s; -} - CString GetAbsoluteUri(const CString& uri) { int i = String_FindString(uri, _T("://")); if (i==-1) return uri; @@ -553,82 +438,6 @@ CString GetUriHostNameHostOnly(const CString& uri, bool strip_leading) { return ss.Left(j); } -CString AbbreviateUri(const CString& uri, int32 max_len) { - ASSERT1(max_len); - ASSERT1(!uri.IsEmpty()); - - CString s(uri); - VERIFY1(String_FindString (s, _T("://"))); - - TrimCString(s); - // SKIP_LOC_BEGIN - RemoveFromStart (s, _T("ftp://"), false); - RemoveFromStart (s, _T("http://"), false); - RemoveFromStart (s, _T("https://"), false); - RemoveFromStart (s, _T("www."), false); - RemoveFromStart (s, _T("ftp."), false); - RemoveFromStart (s, _T("www-"), false); - RemoveFromStart (s, _T("ftp-"), false); - RemoveFromEnd (s, _T(".htm")); - RemoveFromEnd (s, _T(".html")); - RemoveFromEnd (s, _T(".asp")); - // SKIP_LOC_END - if (s.GetLength() > max_len) { - // try to keep the portion after the last / - int32 last_slash = s.ReverseFind ((TCHAR)'/'); - CString after_last_slash; - if (last_slash == -1) { after_last_slash = _T(""); } - else { after_last_slash = s.Right (uri.GetLength() - last_slash - 1); } - if (after_last_slash.GetLength() > max_len / 2) { - after_last_slash = after_last_slash.Right (max_len / 2); - } - s = s.Left (max_len - after_last_slash.GetLength() - 2); - s += ".."; - s += after_last_slash; - } - return s; -} - -// normalized version of a URI intended to map duplicates to the same string -// the normalized URI is not a valid URI -CString NormalizeUri (const CString & uri) { - CString s(uri); - TrimCString(s); - MakeLowerCString(s); - // SKIP_LOC_BEGIN - ReplaceCString (s, _T(":80"), _T("")); - - RemoveFromEnd (s, _T("/index.html")); - RemoveFromEnd (s, _T("/welcome.html")); // old netscape standard - RemoveFromEnd (s, _T("/")); - - RemoveFromStart (s, _T("ftp://"), false); - RemoveFromStart (s, _T("http://"), false); - RemoveFromStart (s, _T("https://"), false); - RemoveFromStart (s, _T("www."), false); - RemoveFromStart (s, _T("ftp."), false); - RemoveFromStart (s, _T("www-"), false); - RemoveFromStart (s, _T("ftp-"), false); - - ReplaceCString (s, _T("/./"), _T("/")); - // SKIP_LOC_END - - // TODO(omaha): - // fixup URLs like a/b/../../c - // while ($s =~ m!\/\.\.\!!) { - // $s =~ s!/[^/]*/\.\./!/!; - // } - - // TODO(omaha): - // unescape characters - // Note from RFC1630: "Sequences which start with a percent sign - // but are not followed by two hexadecimal characters are reserved - // for future extension" - // $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str; - - return s; -} - CString RemoveInternetProtocolHeader (const CString& url) { int find_colon_slash_slash = String_FindString(url, NOTRANSL(L"://")); if( find_colon_slash_slash != -1 ) { @@ -659,14 +468,6 @@ HRESULT ConvertFileUriToLocalPath(const CString& uri, CString* path_out) { return hr; } -void RemoveFromStart (CString & s, const TCHAR* remove, bool ignore_case) { - ASSERT(remove, (L"")); - - // Remove the characters if it is the prefix - if (String_StartsWith(s, remove, ignore_case)) - s.Delete(0, lstrlen(remove)); -} - bool String_EndsWith(const TCHAR *str, const TCHAR *end_str, bool ignore_case) { ASSERT(end_str, (L"")); ASSERT(str, (L"")); @@ -712,75 +513,6 @@ CString String_MakeEndWith(const TCHAR* str, const TCHAR* end_str, bool ignore_c } } -void RemoveFromEnd (CString & s, const TCHAR* remove) { - ASSERT(remove, (L"")); - - // If the suffix is shorter than the string, don't bother - int remove_len = lstrlen(remove); - if (s.GetLength() < remove_len) return; - - // If the suffix is equal - int suffix_begin = s.GetLength() - remove_len; - if (0 == lstrcmp(s.GetString() + suffix_begin, remove)) - s.Delete(suffix_begin, remove_len); -} - -CString ElideIfNeeded (const CString & input_string, int max_len, int min_len) { - ASSERT (min_len <= max_len, (L"")); - ASSERT (max_len >= TSTR_SIZE(kEllipsis)+1, (L"")); - ASSERT (min_len >= TSTR_SIZE(kEllipsis)+1, (L"")); - - CString s = input_string; - - s.TrimRight(); - if (s.GetLength() > max_len) { - int truncate_at = max_len - TSTR_SIZE(kEllipsis); - // find first space going backwards from character one after the truncation point - while (truncate_at >= min_len && !IsSpace(s.GetAt(truncate_at))) - truncate_at--; - - // skip the space(s) - while (truncate_at >= min_len && IsSpace(s.GetAt(truncate_at))) - truncate_at--; - - truncate_at++; - - if (truncate_at <= min_len || truncate_at > (max_len - static_cast(TSTR_SIZE(kEllipsis)))) { - // we weren't able to break at a word boundary, may as well use more of the string - truncate_at = max_len - TSTR_SIZE(kEllipsis); - - // skip space(s) - while (truncate_at > 0 && IsSpace(s.GetAt(truncate_at-1))) - truncate_at--; - } - - s = s.Left(truncate_at); - s += kEllipsis; - } - - UTIL_LOG(L6, (L"elide (%d %d) %s -> %s", min_len, max_len, input_string, s)); - return s; -} - -// these functions untested -// UTF8 parameter supported on XP/2000 only -HRESULT AnsiToUTF8 (char * src, int src_len, char * dest, int *dest_len) { - ASSERT (dest_len, (L"")); - ASSERT (dest, (L"")); - ASSERT (src, (L"")); - - // First use MultiByteToWideChar(CP_UTF8, ...) to convert to Unicode - // then use WideCharToMultiByte to convert from Unicode to UTF8 - WCHAR *unicode = new WCHAR [(src_len + 1) * sizeof (TCHAR)]; ASSERT (unicode, (L"")); - int chars_written = MultiByteToWideChar (CP_ACP, 0, src, src_len, unicode, src_len); - ASSERT (chars_written == src_len, (L"")); - char *unmappable = " "; - BOOL unmappable_characters = false; - *dest_len = WideCharToMultiByte (CP_UTF8, 0, unicode, chars_written, dest, *dest_len, unmappable, &unmappable_characters); - delete [] unicode; - return S_OK; -} - // Convert Wide to ANSI directly. Use only when it is all ANSI CStringA WideToAnsiDirect(const CString & in) { int in_len = in.GetLength(); @@ -796,330 +528,6 @@ CStringA WideToAnsiDirect(const CString & in) { return out; } -HRESULT UCS2ToUTF8 (LPCWSTR src, int src_len, char * dest, int *dest_len) { - ASSERT(dest_len, (L"")); - ASSERT(dest, (L"")); - - *dest_len = WideCharToMultiByte (CP_UTF8, 0, src, src_len, dest, *dest_len, NULL,NULL); - return S_OK; -} - -HRESULT UTF8ToUCS2 (const char * src, int src_len, LPWSTR dest, int *dest_len) { - ASSERT (dest_len, (L"")); - ASSERT (src, (L"")); - - *dest_len = MultiByteToWideChar (CP_UTF8, 0, src, src_len, dest, *dest_len); - ASSERT (*dest_len == src_len, (L"")); - return S_OK; -} - -HRESULT UTF8ToAnsi (char * src, int, char * dest, int *dest_len) { - ASSERT(dest_len, (L"")); - ASSERT(dest, (L"")); - ASSERT(src, (L"")); - - src; dest; dest_len; // unreferenced formal parameter - - // First use MultiByteToWideChar(CP_UTF8, ...) to convert to Unicode - // then use WideCharToMultiByte to convert from Unicode to ANSI - return E_FAIL; -} - -// clean up a string so it can be included within a JavaScript string -// mainly involves escaping characters -CString SanitizeString(const CString & in, DWORD mode) { - CString out(in); - - if (mode & kSanHtml) { - // SKIP_LOC_BEGIN - ReplaceCString(out, _T("&"), _T("&")); - ReplaceCString(out, _T("<"), _T("<")); - ReplaceCString(out, _T(">"), _T(">")); - // SKIP_LOC_END - } - - if ((mode & kSanXml) == kSanXml) { - // SKIP_LOC_BEGIN - ReplaceCString(out, _T("'"), _T("'")); - ReplaceCString(out, _T("\""), _T(""")); - // SKIP_LOC_END - } - - // Note that this SAN_JAVASCRIPT and kSanXml should not be used together. - ASSERT ((mode & (kSanJs | kSanXml)) != (kSanJs | kSanXml), (L"")); - - if ((mode & kSanJs) == kSanJs) { - // SKIP_LOC_BEGIN - ReplaceCString(out, _T("\\"), _T("\\\\")); - ReplaceCString(out, _T("\'"), _T("\\\'")); - ReplaceCString(out, _T("\""), _T("\\\"")); - ReplaceCString(out, _T("\n"), _T(" ")); - ReplaceCString(out, _T("\t"), _T(" ")); - // SKIP_LOC_END - } - - if ((mode & kSanHtmlInput) == kSanHtmlInput) { - // SKIP_LOC_BEGIN - ReplaceCString(out, _T("\""), _T(""")); - ReplaceCString(out, _T("'"), _T("'")); - // SKIP_LOC_END - } - - return out; -} - -// Bolds the periods used for abbreviation. Call this after HighlightTerms. -CString BoldAbbreviationPeriods(const CString & in) { - CString out(in); - CString abbrev; - for (int i = 0; i < kAbbreviationPeriodLength; ++i) - abbrev += _T("."); - ReplaceCString(out, abbrev, NOTRANSL(_T("")) + abbrev + NOTRANSL(_T(""))); - return out; -} - -// Unescape a escaped sequence leading by a percentage symbol '%', -// and converted the unescaped sequence (in UTF8) into unicode. -// Inputs: src is the input string. -// pos is the starting position. -// Returns: true if a EOS(null) char was encounted. -// out contains the unescaped and converted unicode string. -// consumed_length is how many bytes in the src string have been -// unescaped. -// We can avoid the expensive UTF8 conversion step if there are no higher -// ansi characters So if there aren't any, just convert it ANSI-to-WIDE -// directly, which is cheaper. -inline bool UnescapeSequence(const CString &src, int pos, - CStringW *out, int *consumed_length) { - ASSERT1(out); - ASSERT1(consumed_length); - - int length = src.GetLength(); - // (input_len - pos) / 3 is enough for un-escaping the (%xx)+ sequences. - int max_dst_length = (length - pos) / 3; - scoped_array unescaped(new char[max_dst_length]); - char *buf = unescaped.get(); - if (buf == NULL) { // no enough space ??? - *consumed_length = 0; - return false; - } - char *dst = buf; - bool is_utf8 = false; - // It is possible that there is a null character '\0' in the sequence. - // Because the CStringT does't support '\0' in it, we stop - // parsing the input string when it is encounted. - bool eos_encounted = false; - uint8 ch; - int s = pos; - while (s + 2 < length && src[s] == '%' && !eos_encounted && - ExtractChar(src, s + 1, &ch)) { - if (ch != 0) - *dst++ = ch; - else - eos_encounted = true; - if (ch >= 128) - is_utf8 = true; - s += 3; - } - - ASSERT1(dst <= buf + max_dst_length); // just to make sure - - // TODO(portability): cast is unsafe. - *consumed_length = s - pos; - if (is_utf8) - AnsiToWideString(buf, static_cast(dst - buf), CP_UTF8, out); - else - *out = AnsiToWideString(buf, static_cast(dst - buf)); - return eos_encounted; -} - -// There is an encoding called "URL-encoding". This function takes a URL-encoded string -// and converts it back to the original representation -// example: "?q=moon+doggy_%25%5E%26&" = "moon doggy_%^&" -CString Unencode(const CString &input) { - const int input_len = input.GetLength(); - const TCHAR *src = input.GetString(); - // input_len is enough for containing the unencoded string. - CString out; - TCHAR *head = out.GetBuffer(input_len); - TCHAR *dst = head; - int s = 0; - bool eos_encounted = false; - bool is_utf8 = false; - CStringW fragment; - int consumed_length = 0; - while (s < input_len && !eos_encounted) { - switch (src[s]) { - case '+' : - *dst++ = ' '; - ASSERT1(dst <= head + input_len); - ++s; - break; - case '%' : - eos_encounted = - UnescapeSequence(input, s, &fragment, &consumed_length); - if (consumed_length > 0) { - s += consumed_length; - ASSERT1(dst + fragment.GetLength() <= head + input_len); - for (int i = 0; i < fragment.GetLength(); ++i) - *dst++ = fragment[i]; - } else { - *dst++ = src[s++]; - ASSERT1(dst <= head + input_len); - } - break; - default: - *dst++ = src[s]; - ASSERT1(dst <= head + input_len); - ++s; - } - } - // TODO(portability): cast is unsafe. - int out_len = static_cast(dst - head); - out.ReleaseBuffer(out_len); - return out; -} - -CString GetTextInbetween(const CString &input, const CString &start, const CString &end) { - int start_index = String_FindString(input, start); - if (start_index == -1) - return L""; - - start_index += start.GetLength(); - int end_index = String_FindString(input, end, start_index); - if (end_index == -1) - return L""; - - return input.Mid(start_index, end_index - start_index); -} - -// Given a string, get the parameter and url-unencode it -CString GetParam(const CString & input, const CString & key) { - CString my_key(_T("?")); - my_key.Append(key); - my_key += L'='; - - return Unencode(GetTextInbetween(input, my_key, NOTRANSL(L"?"))); -} - -// Get an xml-like field from a string -CString GetField (const CString & input, const CString & field) { - CString start_field(NOTRANSL(_T("<"))); - start_field += field; - start_field += L'>'; - - int32 start = String_FindString(input, start_field); - if (start == -1) { return _T(""); } - start += 2 + lstrlen (field); - - CString end_field(NOTRANSL(_T("'; - - int32 end = String_FindString(input, end_field); - if (end == -1) { return _T(""); } - - return input.Mid (start, end - start); -} - -// ------------------------------------------------------------ -// Finds a whole word match in the query. -// If the word has non-spaces either before or after, it will not qualify as -// a match. i.e. "pie!" is not a match because of the exclamation point. -// TODO(omaha): Add parameter that will consider punctuation acceptable. -// -// Optionally will look for a colon at the end. -// If not found, return -1. -int FindWholeWordMatch (const CString &query, - const CString &word_to_match, - const bool end_with_colon, - const int index_begin) { - if (word_to_match.IsEmpty()) { - return -1; - } - - int index_word_begin = index_begin; - - // Keep going until we find a whole word match, or the string ends. - do { - index_word_begin = String_FindString (query, word_to_match, index_word_begin); - - if (-1 == index_word_begin) { - return index_word_begin; - } - - // If it's not a whole word match, keep going. - if (index_word_begin > 0 && - !IsSpaceW (query[index_word_begin - 1])) { - goto LoopEnd; - } - - if (end_with_colon) { - int index_colon = String_FindChar (query, L':', index_word_begin); - - // If there is no colon in the string, return now. - if (-1 == index_colon) { - return -1; - } - - // If there is text between the end of the word and the colon, keep going. - if (index_colon - index_word_begin != word_to_match.GetLength()) { - goto LoopEnd; - } - } else { - // If there are more chars left after this word/phrase, and - // they are not spaces, return. - if (query.GetLength() > index_word_begin + word_to_match.GetLength() && - !IsSpaceW (query.GetAt (index_word_begin + word_to_match.GetLength()))) { - goto LoopEnd; - } - } - - // It fits all the requirements, so return the index to the beginning of the word. - return index_word_begin; - -LoopEnd: - ++index_word_begin; - - } while (-1 != index_word_begin); - - return index_word_begin; -} - -// -------------------------------------------------------- -// Do whole-word replacement in "str". -void ReplaceWholeWord (const CString &string_to_replace, - const CString &replacement, - const bool trim_whitespace, - CString *str) { - ASSERT (str, (L"ReplaceWholeWord")); - - if (string_to_replace.IsEmpty() || str->IsEmpty()) { - return; - } - - int index_str = 0; - do { - index_str = FindWholeWordMatch (*str, string_to_replace, false, index_str); - - if (-1 != index_str) { - // Get the strings before and after, and trim whitespace. - CString str_before_word(str->Left (index_str)); - if (trim_whitespace) { - str_before_word.TrimRight(); - } - - CString str_after_word(str->Mid (index_str + string_to_replace.GetLength())); - if (trim_whitespace) { - str_after_word.TrimLeft(); - } - - *str = str_before_word + replacement + str_after_word; - index_str += replacement.GetLength() + 1; - } - } while (index_str != -1); -} - // -------------------------------------------------------- // Reverse (big-endian<->little-endian) the shorts that make up // Unicode characters in a byte array of Unicode chars @@ -1205,71 +613,6 @@ const WCHAR *stristrW(const WCHAR *string, const WCHAR *pattern) return NULL; } -// case sensitive Unicode strstr -// adapted from http://c.snippets.org/snip_lister.php?fname=stristr.c -const WCHAR *strstrW(const WCHAR *string, const WCHAR *pattern) -{ - ASSERT (pattern, (L"")); - ASSERT (string, (L"")); - ASSERT (string && pattern, (L"")); - const WCHAR *start; - - for (start = string; *start != 0; start++) - { - // find start of pattern in string - for ( ; ((*start!=0) && (*start != *pattern)); start++) - ; - if (0 == *start) - return NULL; - - const WCHAR *pattern_ptr = pattern; - const WCHAR *string_ptr = start; - - while (*string_ptr == *pattern_ptr) - { - string_ptr++; - pattern_ptr++; - - // if end of pattern then pattern was found - if (0 == *pattern_ptr) - return (start); - } - } - - return NULL; -} - -// ------------------------------------------------------------------------- -// Helper function -float GetLenWithWordWrap (const float len_so_far, - const float len_to_add, - const uint32 len_line) { - // lint -save -e414 Possible division by 0 - ASSERT (len_line != 0, (L"")); - - float len_total = len_so_far + len_to_add; - - // Figure out if we need to word wrap by seeing if adding the second - // string will cause us to span more lines than before. - uint32 num_lines_before = static_cast (len_so_far / len_line); - uint32 num_lines_after = static_cast (len_total / len_line); - - // If it just barely fit onto the line, do not wrap to the next line. - if (num_lines_after > 0 && (len_total / len_line - num_lines_after == 0)) { - --num_lines_after; - } - - if (num_lines_after > num_lines_before) { - // Need to word wrap. - // lint -e{790} Suspicious truncation - return num_lines_after * len_line + len_to_add; - } - else - return len_total; - - // lint -restore -} - int CalculateBase64EscapedLen(int input_len, bool do_padding) { // these formulae were copied from comments that used to go with the base64 // encoding functions @@ -1414,7 +757,7 @@ void WebSafeBase64Escape(const char *src, int szsrc, void WebSafeBase64Escape(const CStringA& src, CStringA* dest) { ASSERT(dest,(L"")); int encoded_len = CalculateBase64EscapedLen(src.GetLength()); - scoped_array buf(new char[encoded_len]); + std::unique_ptr buf(new char[encoded_len]); int len = WebSafeBase64Escape(src,src.GetLength(), buf.get(), encoded_len, false); dest->SetString(buf.get(), len); } @@ -1732,68 +1075,6 @@ int HexDigitToInt (WCHAR c) { (c - L'0')); } -// ---------------------------------------------------------------------- -// int QuotedPrintableUnescape() -// -// Check out http://www.cis.ohio-state.edu/htbin/rfc/rfc2045.html for -// more details, only briefly implemented. But from the web... -// Quoted-printable is an encoding method defined in the MIME -// standard. It is used primarily to encode 8-bit text (such as text -// that includes foreign characters) into 7-bit US ASCII, creating a -// document that is mostly readable by humans, even in its encoded -// form. All MIME compliant applications can decode quoted-printable -// text, though they may not necessarily be able to properly display the -// document as it was originally intended. As quoted-printable encoding -// is implemented most commonly, printable ASCII characters (values 33 -// through 126, excluding 61), tabs and spaces that do not appear at the -// end of lines, and end-of-line characters are not encoded. Other -// characters are represented by an equal sign (=) immediately followed -// by that character's hexadecimal value. Lines that are longer than 76 -// characters are shortened by line breaks, with the equal sign marking -// where the breaks occurred. -// -// Update: we really want QuotedPrintableUnescape to conform to rfc2047, -// which expands the q encoding. In particular, it specifices that _'s are -// to be treated as spaces. -// ---------------------------------------------------------------------- -int QuotedPrintableUnescape(const WCHAR *source, int slen, - WCHAR *dest, int len_dest) { - ASSERT(dest, (L"")); - ASSERT(source, (L"")); - - WCHAR* d = dest; - const WCHAR* p = source; - - while (*p != '\0' && p < source+slen && d < dest+len_dest) { - switch (*p) { - case '=': - if (p == source+slen-1) { - // End of line, no need to print the =.. - // TODO(portability): cast is unsafe. - return static_cast(d-dest); - } - // if its valid, convert to hex and insert - if (p < source+slen-2 && IsHexDigit(p[1]) && IsHexDigit(p[2])) { - // lint -e{734} Loss of precision - *d++ = static_cast( - HexDigitToInt(p[1]) * 16 + HexDigitToInt(p[2])); - p += 3; - } else { - p++; - } - break; - case '_': // According to rfc2047, _'s are to be treated as spaces - *d++ = ' '; p++; - break; - default: - *d++ = *p++; - break; - } - } - // TODO(portability): cast is unsafe. - return static_cast(d-dest); -} - // TODO(omaha): currently set not to use IsCharUpper because that is relatively slow // this is used in the QUIB; consider if we need to use IsCharUpper or a replacement bool String_IsUpper(TCHAR c) { @@ -2215,56 +1496,6 @@ bool String_IsIdentifierChar(const TCHAR c) { c == _T('_')); } -// Returns true if the string has letters in it. -// This is used by the keyword extractor to downweight numbers, -// IDs (sequences of numbers like social security numbers), etc. -bool String_HasAlphabetLetters (const TCHAR * str) { - ASSERT (str, (L"")); - - while (*str != '\0') { - // if (iswalpha (*str)) { - // Note that IsCharAlpha is slower but we want to avoid the CRT - if (IsCharAlpha (*str)) { - return true; - } - ++str; - } - - return false; -} - -CString String_LargeIntToApproximateString(uint64 value, bool base_ten, int* power) { - uint32 to_one_decimal; - - uint32 gig = base_ten ? 1000000000 : (1<<30); - uint32 gig_div_10 = base_ten ? 100000000 : (1<<30)/10; - uint32 meg = base_ten ? 1000000 : (1<<20); - uint32 meg_div_10 = base_ten ? 100000 : (1<<20)/10; - uint32 kilo = base_ten ? 1000 : (1<<10); - uint32 kilo_div_10 = base_ten ? 100 : (1<<10)/10; - - if (value >= gig) { - if (power) *power = 3; - to_one_decimal = static_cast(value / gig_div_10); - } else if (value >= meg) { - if (power) *power = 2; - to_one_decimal = static_cast(value / meg_div_10); - } else if (value >= kilo) { - if (power) *power = 1; - to_one_decimal = static_cast(value / kilo_div_10); - } else { - if (power) *power = 0; - return String_Int64ToString(static_cast(value), 10 /*radix*/); - } - - uint32 whole_part = to_one_decimal / 10; - - if (whole_part < 10) - return Show(0.1 * static_cast(to_one_decimal), 1); - - return String_Int64ToString(whole_part, 10 /*radix*/); -} - int String_FindString(const TCHAR *s1, const TCHAR *s2) { ASSERT(s2, (L"")); ASSERT(s1, (L"")); @@ -2319,25 +1550,6 @@ int String_FindChar(const TCHAR *str, const TCHAR c) { return -1; } -// taken from wcsrchr, modified to behave in the CString way -int String_ReverseFindChar(const TCHAR * str,TCHAR c) { - ASSERT (str, (L"")); - TCHAR *start = (TCHAR *)str; - - while (*str++) /* find end of string */ - ; - /* search towards front */ - while (--str != start && *str != (TCHAR)c) - ; - - if (*str == (TCHAR)c) { /* found ? */ - // TODO(portability): cast is unsafe. - return static_cast(str - start); - } - - return -1; -} - int String_FindChar(const TCHAR *str, const TCHAR c, int start_pos) { ASSERT (str, (L"")); int n = 0; @@ -2360,21 +1572,6 @@ bool String_Contains(const TCHAR *s1, const TCHAR *s2) { return -1 != String_FindString(s1, s2); } -void String_ReplaceChar(TCHAR *str, TCHAR old_char, TCHAR new_char) { - ASSERT (str, (L"")); - while (*str) { - if (*str == old_char) - *str = new_char; - - ++str; - } -} - -void String_ReplaceChar(CString & str, TCHAR old_char, TCHAR new_char) { - String_ReplaceChar (str.GetBuffer(), old_char, new_char); - str.ReleaseBuffer(); -} - int ReplaceCString (CString & src, const TCHAR *from, const TCHAR *to) { ASSERT(to, (L"")); ASSERT(from, (L"")); @@ -2516,40 +1713,6 @@ int ReplaceCString (CString & src, const TCHAR *from, unsigned int from_len, return matches; } -// Functions on arrays of strings - -// Returns true iff s is in the array strings (case-insensitive compare) -bool String_MemberOf(const TCHAR* const* strings, const TCHAR* s) { - ASSERT(s, (L"")); - // strings may be NULL - - const int s_length = lstrlen(s); - if (strings == NULL) - return false; - for (; *strings != NULL; strings++) { - if (0 == String_StrNCmp(*strings, s, s_length, true)) { - return true; // Found equal string - } - } - return false; -} - -// Returns index of s in the array of strings (or -1 for missing) (case-insensitive compare) -int String_IndexOf(const TCHAR* const* strings, const TCHAR* s) { - ASSERT(s, (L"")); - // strings may be NULL - - const int s_length = lstrlen(s); - if (strings == NULL) - return -1; - for (int i = 0; *strings != NULL; i++, strings++) { - if (0 == String_StrNCmp(*strings, s, s_length, true)) { - return i; // Found equal string - } - } - return -1; -} - // The internal format is a int64. time64 StringToTime(const CString & time) { return static_cast(String_StringToInt64(time)); @@ -2562,24 +1725,6 @@ CString TimeToString(const time64 & time) { return String_Int64ToString(static_cast(time), 10); } -const TCHAR *FindStringASpaceStringB (const TCHAR *s, const TCHAR *a, const TCHAR *b) { - ASSERT(s, (L"")); - ASSERT(a, (L"")); - ASSERT(b, (L"")); - - const TCHAR *search_from = s; - const TCHAR *pos; - while (*search_from && (pos = stristrW (search_from, a)) != NULL) { - const TCHAR *start = pos; - pos += lstrlen(a); - search_from = pos; - while (*pos == ' ' || *pos == '\t') pos++; - if (!String_StrNCmp (pos, b, lstrlen(b), true)) return start; - } - - return 0; -} - bool IsAlphaA (const char c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); } @@ -2588,46 +1733,6 @@ bool IsDigitA (const char c) { return (c >= '0' && c <= '9'); } -void SafeStrCat (TCHAR *dest, const TCHAR *src, int dest_buffer_len) { - _tcscat_s(dest, dest_buffer_len, src); -} - -// extracts next float in a string -// skips any non-digit characters -// return position after end of float -const TCHAR *ExtractNextDouble (const TCHAR *s, double *f) { - ASSERT (f, (L"")); - ASSERT (s, (L"")); - - CString num; - while (*s && !String_IsDigit (*s)) s++; - while (*s && (*s == '.' || String_IsDigit (*s))) { num += *s; s++; } - ASSERT (num.GetLength(), (L"")); - *f = String_StringToDouble (num); - return s; -} - -TCHAR *String_PathFindExtension(const TCHAR *path) { - ASSERT(path, (L"")); - - // Documentation says PathFindExtension string must be of max length - // MAX_PATH but a trusted tester hit the ASSERT and we don't really - // need it here, so commented out. We can't address where it is - // called because it's called from ATL code. - // ASSERT(lstrlen(path)<=MAX_PATH, (L"")); - - // point to terminating NULL - const TCHAR *ret = path + lstrlen(path); - const TCHAR *pos = ret; - - while (--pos >= path) { - if (*pos == '.') - return const_cast(pos); - } - - return const_cast(ret); -} - char String_ToLowerCharAnsi(char c) { if (c >= 'A' && c <= 'Z') return (c + ('a' - 'A')); return c; @@ -2641,50 +1746,6 @@ int String_ToLowerChar(int c) { return Char_ToLower(static_cast(c)); } - -bool String_PathRemoveFileSpec(TCHAR *path) { - ASSERT (path, (L"")); - - int len, pos; - len = pos = lstrlen (path); - - // You might think that the SHLWAPI API does not change "c:\windows" -> "c:\" - // when c:\windows is a directory, but it does. - - // If we don't want to match this weird API we can use the following to check - // for directories: - - // Check if we are already a directory. - WIN32_FILE_ATTRIBUTE_DATA attrs; - // Failure (if file does not exist) is OK. - BOOL success = GetFileAttributesEx(path, GetFileExInfoStandard, &attrs); - UTIL_LOG(L4, (_T("[String_PathRemoveFileSpec][path %s][success %d][dir %d]"), - path, - success, - attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)); - if (success && (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - // Remove trailing backslash, if any. - if (path[pos-1] == '\\') - path[pos-1] = '\0'; - return 1; - } - - // Find last backslash. - while (pos && path[pos] != '\\') pos--; - if (!pos && path[pos] != '\\') return 0; - - ASSERT (pos < len, (L"")); - - // The documentation says it removes backslash but it doesn't for c:\. - if (!pos || path[pos-1] == ':' || (pos == 1 && path[0] == '\\')) - // Keep the backslash in this case. - path[pos+1] = '\0'; - else - path[pos] = '\0'; - - return 1; -} - void String_EndWithChar(TCHAR *str, TCHAR c) { ASSERT (str, (L"")); int len = lstrlen(str); @@ -2742,19 +1803,6 @@ bool String_StringToDecimalIntChecked(const TCHAR* str, int* value) { return true; } -bool CLSIDToCString(const GUID& guid, CString* str) { - ASSERT(str, (L"")); - - LPOLESTR string_guid = NULL; - if (::StringFromCLSID(guid, &string_guid) != S_OK) { - return false; - } - *str = string_guid; - ::CoTaskMemFree(string_guid); - - return true; -} - HRESULT String_StringToBool(const TCHAR* str, bool* value) { ASSERT1(str); ASSERT1(value); @@ -2972,54 +2020,6 @@ CString BytesToHex(const std::vector& bytes) { return result; } -void JoinStrings(const std::vector& components, - const TCHAR* delim, - CString* result) { - ASSERT1(result); - result->Empty(); - - // Compute length so we can reserve memory. - size_t length = 0; - size_t delim_length = delim ? _tcslen(delim) : 0; - for (size_t i = 0; i != components.size(); ++i) { - if (i != 0) { - length += delim_length; - } - length += components[i].GetLength(); - } - - ASSERT1(length <= INT_MAX && delim_length <= INT_MAX); - if (length > INT_MAX || delim_length > INT_MAX) { - return; - } - - result->Preallocate(static_cast(length)); - - for (size_t i = 0; i != components.size(); ++i) { - if (i != 0 && delim) { - result->Append(delim, static_cast(delim_length)); - } - result->Append(components[i]); - } -} - -void JoinStringsInArray(const TCHAR* components[], - int num_components, - const TCHAR* delim, - CString* result) { - ASSERT1(result); - result->Empty(); - - for (int i = 0; i != num_components; ++i) { - if (i != 0 && delim) { - result->Append(delim); - } - if (components[i]) { - result->Append(components[i]); - } - } -} - CString FormatResourceMessage(uint32 resource_id, ...) { CString format; const bool is_loaded = !!format.LoadString(resource_id); @@ -3148,25 +2148,6 @@ static void a2b_hex_t(const char* a, T b, size_t num) { } } -string a2b_bin(const string& a, bool byte_order_msb) { - string result; - const char *data = a.c_str(); - size_t num_bytes = (a.size()+7)/8; - for (size_t byte_offset = 0; byte_offset < num_bytes; ++byte_offset) { - unsigned char c = 0; - for (size_t bit_offset = 0; bit_offset < 8; ++bit_offset) { - if (*data == '\0') - break; - if (*data++ != '0') { - size_t bits_to_shift = (byte_order_msb) ? 7-bit_offset : bit_offset; - c |= (1 << bits_to_shift); - } - } - result.append(1, c); - } - return result; -} - // This is a templated function so that T can be either a char* // or a string. This works because we use the [] operator to access // individual characters at a time. @@ -3178,17 +2159,6 @@ static void b2a_hex_t(const unsigned char* b, T a, size_t num) { } } -string b2a_bin(const string& b, bool byte_order_msb) { - string result; - for (size_t byte_offset = 0; byte_offset < b.size(); ++byte_offset) { - for (size_t bit_offset = 0; bit_offset < 8; ++bit_offset) { - size_t x = (byte_order_msb) ? 7-bit_offset : bit_offset; - result.append(1, (b[byte_offset] & (1 << x)) ? '1' : '0'); - } - } - return result; -} - void b2a_hex(const unsigned char* b, char* a, size_t num) { b2a_hex_t(b, a, num); } diff --git a/omaha/base/string.h b/omaha/base/string.h index 23caa73..ad9f1b6 100644 --- a/omaha/base/string.h +++ b/omaha/base/string.h @@ -17,7 +17,12 @@ #define OMAHA_BASE_STRING_H_ #include +#include + +#include +#include #include + #include "base/basictypes.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" @@ -27,19 +32,9 @@ namespace omaha { #define STR_SIZE(str) (arraysize(str)-1) // number of characters in char array (only for single-byte string literals!!!) #define TSTR_SIZE(tstr) (arraysize(tstr)-1) // like STR_SIZE but works on _T("string literal") ONLY!!! -#define kEllipsis L".." - // The number of replacements matches we expect, before we start allocating extra memory // to process it. This is an optimizing constant -#define kExpectedMaxReplaceMatches 100 - -// TODO(omaha): above each of these function names, we should -// define what we expect the implementation to do. that way, -// implementers will know what is desired. an example would probably -// make things easiest. -CString AbbreviateString (const CString & title, int32 max_len); -CString AbbreviateUri (const CString & uri, int32 max_len); -CString NormalizeUri (const CString & uri); +constexpr size_t kExpectedMaxReplaceMatches = 100; // removes "http://", "ftp://", "mailto:" or "file://" (note that the "file" protocol is // like: "file:///~/calendar", this method removes only the first two slashes @@ -48,77 +43,12 @@ CString RemoveInternetProtocolHeader (const CString& url); // Converts a file:// URI to a valid Windows path. HRESULT ConvertFileUriToLocalPath(const CString& uri, CString* path_out); -void RemoveFromStart (CString & s, const TCHAR* remove, bool ignore_case); -void RemoveFromEnd (CString & s, const TCHAR* remove); - -// Limit string to max length, truncating and adding ellipsis if needed -// Attempts to not leave a partial word at the end, unless min_len is reached -CString ElideIfNeeded (const CString & input_string, int max_len, int min_len); - -// The ability to clean up a string for relevant target audiences. Add flags accordingly - -// Sanitizes for insertion in an HTML document, uses the basic literals [<>&] -#define kSanHtml 0x1 - -// XML is the HTML replacements, and a few more -#define kSanXml (kSanHtml | 0x2) - -// Javascript has a seperate set of encodings [which is a superset of HTML replacements] -#define kSanJs (kSanHtml | 0x4) - -// For input fields on HTML documents -#define kSanHtmlInput 0x8 - // TODO(omaha): be consistent on use of int/uint32/int32 for lengths // The input length of the string does not include the null terminator. // Caller deletes the returned buffer. WCHAR *ToWide (const char *s, int len); -// returns pointer to data if found otherwise NULL -const byte *BufferContains (const byte *buf, uint32 buf_len, const byte *data, uint32 data_len); - -// Given a string, 'protect' the characters that are invalid for a given mode -// For instance, kSanHtml will replace < with the HTML literal equivalent -// If kSanHtml is used, and bold_periods is true, then periods used for url abbreviation are bolded. -// NOTE: If you call AbbreviateLinkForDisplay before this function, then there might be periods -// used for abbreviation. BoldAbbreviationPeriods should be called after HighlightTerms. -CString SanitizeString(const CString & in, DWORD mode); - -// Bolds the periods used for abbreviation. Call this after HighlightTerms. -CString BoldAbbreviationPeriods(const CString & in); - -// Unencode a URL encoded string -CString Unencode(const CString & input); - -CString GetTextInbetween(const CString &input, const CString &start, const CString &end); - -// Given a ? seperated string, extract a particular segment, and URL-Unencode it -CString GetParam(const CString & input, const CString & key); - -// Given an XML style string, extract the contents of a ... pair -CString GetField (const CString & input, const CString & field); - -// Finds a whole word match in the query, followed by a ":". -// If not found, return -1. -// -// Note: this is case sensitive. -int FindWholeWordMatch (const CString &query, - const CString &word_to_match, - const bool end_with_colon, - const int index_begin); - -// Do whole-word replacement in "str". -// This does not do partial matches (unlike CString::Replace), -// e.g. CString::Replace will replace "ie" within "pie" and -// this function will not. -// -// Note: this is case sensitive. -void ReplaceWholeWord (const CString &string_to_replace, - const CString &replacement, - const bool trim_whitespace, - CString *str); - // Convert Wide to ANSI directly. Use only when it is all ANSI CStringA WideToAnsiDirect(const CString & in); @@ -150,13 +80,6 @@ BOOL AnsiToWideString(const char *from, int length, UINT codepage, CString *to); // Convert char to Wchar directly CString AnsiToWideString(const char *from, int length); -// these functions untested -// they should not be used unless tested -// HRESULT AnsiToUTF8 (char * src, int src_len, char * dest, int *dest_len); -// HRESULT UTF8ToAnsi (char * src, int src_len, char * dest, int *dest_len); -// HRESULT UCS2ToUTF8 (LPCWSTR src, int src_len, char * dest, int *dest_len); -// HRESULT UTF8ToUCS2 (char * src, int src_len, LPWSTR dest, int *dest_len); - // "Absolute" is perhaps not the right term, this normalizes the Uri // given http://www.google.com changes to correct http://www.google.com/ // given http://www.google.com// changes to correct http://www.google.com/ @@ -177,24 +100,6 @@ CString GetUriHostNameHostOnly(const CString& uri, bool strip_leading_www); const char *stristr(const char *string, const char *pattern); const WCHAR *stristrW(const WCHAR *string, const WCHAR *pattern); -const WCHAR *strstrW(const WCHAR *string, const WCHAR *pattern); - -// Add len_to_add to len_so_far, assuming that if it exceeds the -// length of the line, it will word wrap onto the next line. Returns -// the total length of all the lines summed together. -float GetLenWithWordWrap (const float len_so_far, - const float len_to_add, - const uint32 len_line); - -// ---------------------------------------------------------------------- -// QuotedPrintableUnescape() -// Copies "src" to "dest", rewriting quoted printable escape sequences -// =XX to their ASCII equivalents. src is not null terminated, instead -// specify len. I recommend that slen* lines); // (LinesToText puts a delimiter at the end of the last line too) @@ -272,12 +166,6 @@ void LinesToText(const std::vector& lines, const TCHAR* delimiter, CStr // Make a CString lower case void MakeLowerCString(CString & s); -// Clean up the string: replace all whitespace with spaces, and -// replace consecutive spaces with one. -// Returns the new length of the string (not including 0-terminator) -int CleanupWhitespaceCString(CString &s); -int CleanupWhitespace(TCHAR *s); - int HexDigitToInt (WCHAR c); bool IsHexDigit (WCHAR c); @@ -329,12 +217,6 @@ CString sizet_to_str(const size_t & i); CString itostr(const int i); CString itostr(const uint32 i); -// converts a large number to an approximate value, like "1.2G" or "900M" -// base_ten = true if based on powers of 10 (like disk space) otherwise based -// on powers of two. power = 0 for *10^0, 1 for *10^3 or 2^10, 2 for *10^6 -// or 2^20, and 3 for *10^9 or 2^30, in other words: no units, K, M, or G. -CString String_LargeIntToApproximateString(uint64 value, bool base_ten, int* power); - // converts a string to an int // Does not check for overflow int32 String_StringToInt(const TCHAR * str); @@ -362,11 +244,6 @@ TCHAR String_DigitToChar(unsigned int n); // Returns true if an identifier character: letter, digit, or "_" bool String_IsIdentifierChar(const TCHAR c); -// Returns true if the string has letters in it. -// This is used by the keyword extractor to downweight numbers, -// IDs (sequences of numbers like social security numbers), etc. -bool String_HasAlphabetLetters (const TCHAR *str); - // Return the index of the first occurrence of s2 in s1, or -1 if none. int String_FindString(const TCHAR *s1, const TCHAR *s2); int String_FindString(const TCHAR *s1, const TCHAR *s2, int start_pos); @@ -376,15 +253,8 @@ int String_FindChar(const TCHAR *str, const TCHAR c); // start from index start_pos int String_FindChar(const TCHAR *str, const TCHAR c, int start_pos); -// Return the index of the first occurrence of c in string, or -1 if none. -int String_ReverseFindChar(const TCHAR * str, TCHAR c); - bool String_Contains(const TCHAR *s1, const TCHAR *s2); -// Replace old_char with new_char in str. -void String_ReplaceChar(TCHAR *str, TCHAR old_char, TCHAR new_char); -void String_ReplaceChar(CString & str, TCHAR old_char, TCHAR new_char); - // Append the given character to the string if it doesn't already end with it. // There must be room in the string to append the character if necessary. void String_EndWithChar(TCHAR *str, TCHAR c); @@ -396,7 +266,7 @@ void String_EndWithChar(TCHAR *str, TCHAR c); // do not use this function if that is a possibility // The maximum number of replacements to perform. Essentially infinite -const unsigned int kRepMax = kuint32max; +const unsigned int kRepMax = std::numeric_limits::max(); int ReplaceCString (CString & src, const TCHAR *from, unsigned int from_len, const TCHAR *to, unsigned int to_len, unsigned int max_matches); @@ -405,35 +275,13 @@ int ReplaceCString (CString & src, const TCHAR *from, unsigned int from_len, // on memory allocation error, returns the original string int ReplaceCString (CString & src, const TCHAR *from, const TCHAR *to); -// Functions on arrays of strings - -// Returns true iff s is in the array strings (case-insensitive compare) -bool String_MemberOf(const TCHAR* const* strings, const TCHAR* s); -// Returns index of s in the array of strings (or -1 for missing) (case-insensitive compare) -int String_IndexOf(const TCHAR* const* strings, const TCHAR* s); - // Serializes a time64 to a string, and then loads it out again, this string it not for human consumption time64 StringToTime(const CString & time); CString TimeToString(const time64 & time); -// looks for string A followed by any number of spaces/tabs followed by string b -// returns starting position of a if found, NULL if not -// case insensitive -const TCHAR *FindStringASpaceStringB (const TCHAR *s, const TCHAR *a, const TCHAR *b); - bool IsAlphaA (const char c); bool IsDigitA (const char c); -// TODO(omaha): deprecate since we have secure CRT now. -// dest_buffer_len includes the NULL -// always NULL terminates -// dest must be a valid string with length < dest_buffer_len -void SafeStrCat (TCHAR *dest, const TCHAR *src, int dest_buffer_len); - -const TCHAR *ExtractNextDouble (const TCHAR *s, double *f); - -TCHAR *String_PathFindExtension(const TCHAR *path); - inline TCHAR Char_ToLower(TCHAR c) { const TCHAR* result = ::CharLower(reinterpret_cast(c)); ASSERT1(HIWORD(result) == 0); @@ -446,8 +294,6 @@ int String_ToLowerChar(int c); // Replacement for the CRT tolower(c) char String_ToLowerCharAnsi(char c); -bool String_PathRemoveFileSpec(TCHAR *path); - // Escapes and unescapes strings (shlwapi-based implementation). // The indended usage for these APIs is escaping strings to make up // URLs, for example building query strings. @@ -465,9 +311,6 @@ HRESULT StringUnescape(const CString& str_in, CString* str_out); // Tests for overflow and non-int strings. bool String_StringToDecimalIntChecked(const TCHAR* str, int* value); -// Converts CLSID to a string. -bool CLSIDToCString(const GUID& guid, CString* str); - // Converts a string to a bool. HRESULT String_StringToBool(const TCHAR* str, bool* value); @@ -501,15 +344,6 @@ CString BytesToHex(const uint8* bytes, size_t num_bytes); // Converts a vector of bytes to a hex string. CString BytesToHex(const std::vector& bytes); -void JoinStrings(const std::vector& components, - const TCHAR* delim, - CString* result); - -void JoinStringsInArray(const TCHAR* components[], - int num_components, - const TCHAR* delim, - CString* result); - // Formats the specified message ID. // It is similar to CStringT::FormatMessage() but it returns an empty string // instead of throwing when the message ID cannot be loaded. @@ -538,18 +372,6 @@ void a2b_hex(const char* from, char* to, size_t num); void a2b_hex(const char* from, std::string* to, size_t num); std::string a2b_hex(const std::string& a); -// ---------------------------------------------------------------------- -// a2b_bin() -// Description: Ascii-to-Binary binary conversion. This converts -// a.size() binary characters (ascii '0' or '1') to -// ceil(a.size()/8) bytes of binary data. The first character is -// considered the most significant if byte_order_msb is set. a is -// considered to be padded with trailing 0s if its size is not a -// multiple of 8. -// Return value: ceil(a.size()/8) bytes of binary data -// ---------------------------------------------------------------------- -std::string a2b_bin(const std::string& a, bool byte_order_msb); - // ---------------------------------------------------------------------- // b2a_hex() // Description: Binary-to-Ascii hex conversion. This converts diff --git a/omaha/base/string_unittest.cc b/omaha/base/string_unittest.cc index 9c99fd2..27d7fae 100644 --- a/omaha/base/string_unittest.cc +++ b/omaha/base/string_unittest.cc @@ -16,7 +16,6 @@ #include "base/basictypes.h" #include "base/rand_util.h" #include "omaha/base/debug.h" -#include "omaha/base/localization.h" #include "omaha/base/string.h" #include "omaha/base/time.h" #include "omaha/base/timer.h" @@ -90,9 +89,9 @@ TEST(StringTest, DoubleToString) { } TEST(StringTest, StrNCpy) { - TCHAR * str1 = L"test str 1234"; - TCHAR * str2 = L"test str 12"; - TCHAR * str3 = L"Test StR 1234"; + const TCHAR * str1 = L"test str 1234"; + const TCHAR * str2 = L"test str 12"; + const TCHAR * str3 = L"Test StR 1234"; // check case sensitive ASSERT_TRUE(0 == String_StrNCmp(str1, str2, 10, false)); @@ -181,29 +180,6 @@ TEST(StringTest, EndsWith) { ASSERT_FALSE(String_EndsWith(L"The quick brown fox", L"the brown foX", true)); } -TEST(StringTest, Unencode) { - // Normal, correct usage. - // char 0x25 is '%' - ASSERT_STREQ(Unencode(L"?q=moon+doggy_%25%5E%26"), L"?q=moon doggy_%^&"); - ASSERT_STREQ(Unencode(L"%54%68%69%73+%69%73%09%61%20%74%65%73%74%0A"), - L"This is\ta test\n"); - ASSERT_STREQ(Unencode(L"This+is%09a+test%0a"), L"This is\ta test\n"); - - // NULL char. - ASSERT_STREQ(Unencode(L"Terminated%00before+this"), L"Terminated"); - ASSERT_STREQ(Unencode(L"invalid+%a%25"), L"invalid %a%"); - ASSERT_STREQ(Unencode(L"invalid+%25%41%37"), L"invalid %A7"); - ASSERT_STREQ(Unencode(L"not a symbol %RA"), L"not a symbol %RA"); - ASSERT_STREQ(Unencode(L"%ag"), L"%ag"); - ASSERT_STREQ(Unencode(L"dontdecode%dont"), L"dontdecode%dont"); - ASSERT_STREQ(Unencode(L""), L""); - ASSERT_STREQ(Unencode(L"%1"), L"%1"); - ASSERT_STREQ(Unencode(L"\x100"), L"\x100"); - ASSERT_STREQ(Unencode(L"this is%20a%20wide%20char%20\x345"), - L"this is a wide char \x345"); - ASSERT_STREQ(Unencode(L"a utf8 string %E7%BC%9c %E4%B8%8a = 2"), - L"a utf8 string \x7f1c \x4e0a = 2"); -} #if 0 static const struct { @@ -236,13 +212,6 @@ bool TestAnsiToWideString() { } #endif -TEST(StringTest, Show) { - ASSERT_STREQ(Show(0), _T("0")); - ASSERT_STREQ(Show(1), _T("1")); - ASSERT_STREQ(Show(-1), _T("-1")); -} - - // Test international strings. TEST(StringTest, International) { CString tabs_by_lang[] = { @@ -386,15 +355,6 @@ TEST(StringTest, International) { temp.ReleaseBuffer(); ASSERT_STREQ(temp, true_lower); - - // Make sure that the normal CString::Trim works the same as our fast one - CString trim_normal(tabs_by_lang[i]); - trim_normal.Trim(); - - CString trim_fast(tabs_by_lang[i]); - TrimCString(trim_fast); - - ASSERT_STREQ(trim_normal, trim_fast); } } @@ -480,142 +440,6 @@ TEST(StringTest, ReplaceCString) { } } -TEST(StringTest, GetField) { - CString s(_T("a123aa\ndd")); - - CString a(GetField (s, L"a")); - ASSERT_STREQ(a, L"a"); - - CString b(GetField (s, L"b")); - ASSERT_STREQ(b, L"123"); - - CString c(GetField (s, L"c")); - ASSERT_STREQ(c, L"aa\ndd"); -} - -TEST(StringTest, String_HasAlphabetLetters) { - ASSERT_TRUE(String_HasAlphabetLetters (L"abc")); - ASSERT_TRUE(String_HasAlphabetLetters (L"X")); - ASSERT_TRUE(String_HasAlphabetLetters (L" pie ")); - ASSERT_FALSE(String_HasAlphabetLetters (L"1")); - ASSERT_FALSE(String_HasAlphabetLetters (L"0")); - ASSERT_FALSE(String_HasAlphabetLetters (L"010")); - ASSERT_FALSE(String_HasAlphabetLetters (L"314-159")); - ASSERT_TRUE(String_HasAlphabetLetters (L"pie0")); -} - -TEST(StringTest, String_LargeIntToApproximateString) { - int power; - ASSERT_TRUE(String_LargeIntToApproximateString(10LL, true, &power) == _T("10") && power == 0); - ASSERT_TRUE(String_LargeIntToApproximateString(99LL, true, &power) == _T("99") && power == 0); - ASSERT_TRUE(String_LargeIntToApproximateString(990LL, true, &power) == _T("990") && power == 0); - ASSERT_TRUE(String_LargeIntToApproximateString(999LL, true, &power) == _T("999") && power == 0); - - ASSERT_TRUE(String_LargeIntToApproximateString(1000LL, true, &power) == _T("1.0") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(1200LL, true, &power) == _T("1.2") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(7500LL, true, &power) == _T("7.5") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(9900LL, true, &power) == _T("9.9") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(10000LL, true, &power) == _T("10") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(11000LL, true, &power) == _T("11") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(987654LL, true, &power) == _T("987") && power == 1); - - ASSERT_TRUE(String_LargeIntToApproximateString(1000000LL, true, &power) == _T("1.0") && power == 2); - ASSERT_TRUE(String_LargeIntToApproximateString(1300000LL, true, &power) == _T("1.3") && power == 2); - ASSERT_TRUE(String_LargeIntToApproximateString(987654321LL, true, &power) == _T("987") && power == 2); - - ASSERT_TRUE(String_LargeIntToApproximateString(1000000000LL, true, &power) == _T("1.0") && power == 3); - ASSERT_TRUE(String_LargeIntToApproximateString(1999999999LL, true, &power) == _T("1.9") && power == 3); - ASSERT_TRUE(String_LargeIntToApproximateString(20000000000LL, true, &power) == _T("20") && power == 3); - ASSERT_TRUE(String_LargeIntToApproximateString(1000000000000LL, true, &power) == _T("1000") && power == 3); - ASSERT_TRUE(String_LargeIntToApproximateString(12345678901234LL, true, &power) == _T("12345") && power == 3); - - ASSERT_TRUE(String_LargeIntToApproximateString(1023LL, false, &power) == _T("1023") && power == 0); - - ASSERT_TRUE(String_LargeIntToApproximateString(1024LL, false, &power) == _T("1.0") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(1134LL, false, &power) == _T("1.1") && power == 1); - ASSERT_TRUE(String_LargeIntToApproximateString(10240LL, false, &power) == _T("10") && power == 1); - - ASSERT_TRUE(String_LargeIntToApproximateString(5242880LL, false, &power) == _T("5.0") && power == 2); - - ASSERT_TRUE(String_LargeIntToApproximateString(1073741824LL, false, &power) == _T("1.0") && power == 3); - ASSERT_TRUE(String_LargeIntToApproximateString(17179869184LL, false, &power) == _T("16") && power == 3); -} - -TEST(StringTest, FindWholeWordMatch) { - // words with spaces before / after - ASSERT_EQ(0, FindWholeWordMatch (L"pi", L"pi", false, 0)); - ASSERT_EQ(1, FindWholeWordMatch (L" pi", L"pi", false, 0)); - ASSERT_EQ(1, FindWholeWordMatch (L" pi ", L"pi", false, 0)); - ASSERT_EQ(0, FindWholeWordMatch (L"pi ", L"pi", false, 0)); - - // partial matches - ASSERT_EQ(-1, FindWholeWordMatch (L"pie ", L"pi", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L" pie ", L"pi", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L"pie", L"pi", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L" pie", L"pi", false, 0)); - - // partial match with non-alphanumeric chars - ASSERT_EQ(-1, FindWholeWordMatch (L" pumpkin_pie ", L"pie", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L" pie_crust ", L"pie", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L"tartar", L"tar", false, 0)); - ASSERT_EQ(-1, FindWholeWordMatch (L"pie!", L"pie", false, 0)); -} - -TEST(StringTest, ReplaceWholeWord) { - CString str (L"pie"); - ReplaceWholeWord (L"ie", L"..", false, &str); - ASSERT_STREQ(str, L"pie"); - - ReplaceWholeWord (L"pie", L"..", false, &str); - ASSERT_STREQ(str, L".."); - - str = L"banana pie"; - ReplaceWholeWord (L"pie", L"..", false, &str); - ASSERT_STREQ(str, L"banana .."); - - str = L"banana pie"; - ReplaceWholeWord (L"banana", L"..", false, &str); - ASSERT_STREQ(str, L".. pie"); - - str = L"banana pie"; - ReplaceWholeWord (L"banana pie", L" .. ", false, &str); - ASSERT_STREQ(str, L" .. "); - - str = L"banana pie"; - ReplaceWholeWord (L"pi", L" .. ", false, &str); - ASSERT_STREQ(str, L"banana pie"); - - str = L"ishniferatsu"; - ReplaceWholeWord (L"era", L" .. ", false, &str); - ASSERT_STREQ(str, L"ishniferatsu"); - - str = L"i i i hi ii i"; - ReplaceWholeWord (L"i", L"you", false, &str); - ASSERT_STREQ(str, L"you you you hi ii you"); - - str = L"a nice cream cheese pie"; - ReplaceWholeWord (L"cream cheese", L"..", false, &str); - ASSERT_STREQ(str, L"a nice .. pie"); - - // --- - // Test replacement with whitespace trimming - - // Replace in the middle of the string. - str = L"a nice cream cheese pie"; - ReplaceWholeWord (L"cream cheese", L"..", true, &str); - ASSERT_STREQ(str, L"a nice..pie"); - - // Replace in the beginning of the string. - str = L"a nice cream cheese pie"; - ReplaceWholeWord (L"a nice", L"..", true, &str); - ASSERT_STREQ(str, L"..cream cheese pie"); - - // Replace in the end of the string. - str = L"a nice cream cheese pie"; - ReplaceWholeWord (L"pie", L"..", true, &str); - ASSERT_STREQ(str, L"a nice cream cheese.."); -} - TEST(StringTest, GetAbsoluteUri) { ASSERT_STREQ(GetAbsoluteUri(L"http://www.google.com"), L"http://www.google.com/"); @@ -627,37 +451,6 @@ TEST(StringTest, GetAbsoluteUri) { L"http://www.google.com/test"); } -void TestTrim(const TCHAR *str, const TCHAR *result) { - ASSERT_TRUE(result); - ASSERT_TRUE(str); - - size_t ptr_size = _tcslen(str) + 1; - TCHAR* ptr = new TCHAR[ptr_size]; - _tcscpy_s(ptr, ptr_size, str); - - int len = Trim(ptr); - ASSERT_STREQ(ptr, result); - ASSERT_EQ(len, lstrlen(result)); - - delete [] ptr; -} - -TEST(StringTest, Trim) { - TestTrim(L"", L""); - TestTrim(L" ", L""); - TestTrim(L"\t", L""); - TestTrim(L"\n", L""); - TestTrim(L"\n\t \t \n", L""); - TestTrim(L" joe", L"joe"); - TestTrim(L"joe ", L"joe"); - TestTrim(L" joe ", L"joe"); - TestTrim(L"joe smith ", L"joe smith"); - TestTrim(L" joe smith ", L"joe smith"); - TestTrim(L" joe smith ", L"joe smith"); - TestTrim(L" The quick brown fox,\tblah", L"The quick brown fox,\tblah"); - TestTrim(L" \tblah\n joe smith ", L"blah\n joe smith"); -} - // IsSpaceA1 is much faster without the cache clearing (which is what happends // in release mode) // IsSpaceA1 is roughly the same speed as IsSpaceA2 with cache clearing (in @@ -705,7 +498,7 @@ bool IsSpaceA3(char c) { return false; } -void TestIsSpace (char *s) { +void TestIsSpace (const char *s) { ASSERT_TRUE(s); Timer t1 (false); @@ -764,37 +557,6 @@ TEST(StringTest, IsSpace) { TestIsSpace("sdlfhdkgheorutsgj sdlj aoi oaj gldjg opre gdsfjng oate yhdnv ;zsj fpoe v;kjae hgpaieh dajlgn aegh avn WEIf h9243y 9814cu 902t7 9[-32 [O8W759 RC90817 V9pDAHc n( ny(7LKFJAOISF *&^*^%$$%#*&^(*_*)_^& 67% 796%&$*^$ 8)6 (^ 08&^ )*^ 9-7=90z& +(^ )^* %9%4386 $& (& &+ 7- &(_* "); } -void TestCleanupWhitespace(const TCHAR *str, const TCHAR *result) { - ASSERT_TRUE(result); - ASSERT_TRUE(str); - - size_t ptr_size = _tcslen(str) + 1; - TCHAR* ptr = new TCHAR[ptr_size]; - _tcscpy_s(ptr, ptr_size, str); - - int len = CleanupWhitespace(ptr); - ASSERT_STREQ(ptr, result); - ASSERT_EQ(len, lstrlen(result)); - - delete [] ptr; -} - -TEST(StringTest, CleanupWhitespace) { - TestCleanupWhitespace(L"", L""); - TestCleanupWhitespace(L"a ", L"a"); - TestCleanupWhitespace(L" a", L"a"); - TestCleanupWhitespace(L" a ", L"a"); - TestCleanupWhitespace(L"\t\n\r a ", L"a"); - TestCleanupWhitespace(L" \n a \t \r ", L"a"); - TestCleanupWhitespace(L"a b", L"a b"); - TestCleanupWhitespace(L" a \t\n\r b", L"a b"); - TestCleanupWhitespace(L" vool voop", L"vool voop"); - TestCleanupWhitespace(L"thisisaverylongstringwithsometext", - L"thisisaverylongstringwithsometext"); - TestCleanupWhitespace(L"thisisavery longstringwithsometext", - L"thisisavery longstringwithsometext"); -} - TEST(StringTest, IsDigit) { ASSERT_TRUE(String_IsDigit('0')); ASSERT_TRUE(String_IsDigit('1')); @@ -935,100 +697,6 @@ TEST(StringTest, IsHexDigit) { } } -TEST(StringTest, Remove) { - CString temp_remove; - - // Remove everything - temp_remove = _T("ftp://"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("")); - - // Remove all but 1 letter - temp_remove = _T("ftp://a"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("a")); - - // Remove the first instance - temp_remove = _T("ftp://ftp://"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("ftp://")); - - // Remove normal - temp_remove = _T("ftp://taz the tiger"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("taz the tiger")); - - // Wrong prefix - temp_remove = _T("ftp:/taz the tiger"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("ftp:/taz the tiger")); - - // Not long enough - temp_remove = _T("ftp:/"); - RemoveFromStart (temp_remove, _T("ftp://"), false); - ASSERT_STREQ(temp_remove, _T("ftp:/")); - - // Remove nothing - temp_remove = _T("ftp:/"); - RemoveFromStart (temp_remove, _T(""), false); - ASSERT_STREQ(temp_remove, _T("ftp:/")); - - // Remove 1 character - temp_remove = _T("ftp:/"); - RemoveFromStart (temp_remove, _T("f"), false); - ASSERT_STREQ(temp_remove, _T("tp:/")); - - // Wrong case - temp_remove = _T("ftp:/"); - RemoveFromStart (temp_remove, _T("F"), false); - ASSERT_STREQ(temp_remove, _T("ftp:/")); - - // Remove everything - temp_remove = _T(".edu"); - RemoveFromEnd (temp_remove, _T(".edu")); - ASSERT_STREQ(temp_remove, _T("")); - - // Remove all but 1 letter - temp_remove = _T("a.edu"); - RemoveFromEnd(temp_remove, _T(".edu")); - ASSERT_STREQ(temp_remove, _T("a")); - - // Remove the first instance - temp_remove = _T(".edu.edu"); - RemoveFromEnd(temp_remove, _T(".edu")); - ASSERT_STREQ(temp_remove, _T(".edu")); - - // Remove normal - temp_remove = _T("ftp://taz the tiger.edu"); - RemoveFromEnd(temp_remove, _T(".edu")); - ASSERT_STREQ(temp_remove, _T("ftp://taz the tiger")); - - // Wrong suffix - temp_remove = _T("ftp:/taz the tiger.edu"); - RemoveFromEnd(temp_remove, _T("/edu")); - ASSERT_STREQ(temp_remove, _T("ftp:/taz the tiger.edu")); - - // Not long enough - temp_remove = _T("edu"); - RemoveFromEnd(temp_remove, _T(".edu")); - ASSERT_STREQ(temp_remove, _T("edu")); - - // Remove nothing - temp_remove = _T(".edu"); - RemoveFromEnd(temp_remove, _T("")); - ASSERT_STREQ(temp_remove, _T(".edu")); - - // Remove 1 character - temp_remove = _T(".edu"); - RemoveFromEnd(temp_remove, _T("u")); - ASSERT_STREQ(temp_remove, _T(".ed")); - - // Wrong case - temp_remove = _T(".edu"); - RemoveFromEnd(temp_remove, _T("U")); - ASSERT_STREQ(temp_remove, _T(".edu")); -} - TEST(StringTest, WideToAnsiDirect) { CString temp_convert; ASSERT_STREQ("", WideToAnsiDirect(_T(""))); @@ -1052,117 +720,6 @@ TEST(StringTest, WideToAnsiDirect) { } } -TEST(StringTest, FindStringASpaceStringB) { - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-TYPE: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-TYPE: text/HTML", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-TYPE: text/HTML", L"content-type:", L"text/HTML")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-TYPE: text/HTML", L"content-TYPE:", L"text/HTML")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: sdfjsldkgjsdg content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: content-type: sdfjsldkgjsdg content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:content-type: sdfjsldkgjsdg content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"test/html content-type:content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:\ttext/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:\t text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"Content-Type:\t text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"aasd content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"aa content-TYPE: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"text.html content-TYPE: text/HTML", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"text/html content-TYPE: text/HTML", L"content-type:", L"text/HTML")); - ASSERT_TRUE(FindStringASpaceStringB(L"AAAA content-TYPE: text/HTML", L"content-TYPE:", L"text/HTML")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:text/html AAAAA", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/htmlaaa", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type: text/html asdsdg content-type", L"content-type:", L"text/html")); - ASSERT_TRUE(FindStringASpaceStringB(L"content-type:\ttext/htmlconttent-type:te", L"content-type:", L"text/html")); - - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: a text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: content-type: a text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: b text/html content-type: a text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type:-text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type:\ntext/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: a TEXT/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: a html/text", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"a dss content-type: a text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"text/html content-type:-text/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"text/html sdfsd fcontent-type:\ntext/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"AAAA content-type: a TEXT/html", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type: a html/text AAA", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type:", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type:content-type:", L"content-type:", L"text/html")); - ASSERT_FALSE(FindStringASpaceStringB(L"content-type:content-type: content-type:", L"content-type:", L"text/html")); -} - -TEST(StringTest, ElideIfNeeded) { - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 3, 3), L"1.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 4, 3), L"12.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 5, 3), L"123.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 6, 3), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 7, 3), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 8, 3), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 9, 3), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 10, 3), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 11, 3), L"1234 6789.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 12, 3), L"1234 6789.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 13, 3), L"1234 6789.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 14, 3), L"1234 6789 1234"); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 15, 3), L"1234 6789 1234"); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 16, 3), L"1234 6789 1234"); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 17, 3), L"1234 6789 1234"); - - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 7, 6), L"1234.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 8, 6), L"1234 6.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 9, 6), L"1234 67.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 10, 6), L"1234 678.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 11, 6), L"1234 6789.."); - ASSERT_STREQ(ElideIfNeeded(L"1234 6789 1234", 12, 6), L"1234 6789.."); -} - -TEST(StringTest, SafeStrCat) { - const int kDestLen = 7; - TCHAR dest[kDestLen]; - lstrcpyn(dest, L"short", kDestLen); - ASSERT_LT(lstrlen(dest), kDestLen); - - dest[kDestLen-1] = 'a'; - lstrcpyn(dest, L"medium123", kDestLen); - ASSERT_EQ(dest[kDestLen - 1], '\0'); - ASSERT_LT(lstrlen(dest), kDestLen); - - lstrcpyn(dest, L"longerlonger", kDestLen); - ASSERT_EQ(dest[kDestLen - 1], '\0'); - ASSERT_LT(lstrlen(dest), kDestLen); - - lstrcpyn(dest, L"12", kDestLen); - SafeStrCat(dest, L"3456", kDestLen); - ASSERT_EQ(dest[kDestLen - 1], '\0'); - ASSERT_LT(lstrlen(dest), kDestLen); -} - -void TestPathFindExtension(const TCHAR *s) { - ASSERT_STREQ(String_PathFindExtension(s), PathFindExtension(s)); -} - -TEST(StringTest, TestPathFindExtension) { - TestPathFindExtension(L"c:\\test.tmp"); - TestPathFindExtension(L"c:\\test.temp"); - TestPathFindExtension(L"c:\\t\\e\\st.temp"); - TestPathFindExtension(L"c:\\a.temp"); - TestPathFindExtension(L"\\aaa\\a.temp"); - TestPathFindExtension(L"\\a\\a.temp"); - TestPathFindExtension(L"\\a\\a.temp"); - TestPathFindExtension(L"\\a\\a.t....emp"); - TestPathFindExtension(L"\\a.a.a...a\\a.t....emp"); - TestPathFindExtension(L"\\a\\a\\bbbb\\ddddddddddddddd.temp"); - TestPathFindExtension(L"\\a\\a\\bbbb\\ddddddddddddddd.te___124567mp"); - TestPathFindExtension(L"\\a\\a\\bbbb\\ddddddd.dddddddd.te___124567mp"); -} - TEST(StringTest, TextToLinesAndBack) { const TCHAR sample_input[] = L"Now is the time\r\nfor all good men\r\nto come to the aid of their country"; const TCHAR* sample_lines[] = { L"Now is the time", L"for all good men", L"to come to the aid of their country" }; @@ -1199,15 +756,6 @@ TEST(StringTest, TrimString) { ASSERT_STREQ(L"", TrimStdString(L" ")); } -TEST(StringTest, StripFirstQuotedToken) { - ASSERT_STREQ(StripFirstQuotedToken(L""), L""); - ASSERT_STREQ(StripFirstQuotedToken(L"a" ), L""); - ASSERT_STREQ(StripFirstQuotedToken(L" a b "), L"b"); - ASSERT_STREQ(StripFirstQuotedToken(L"\"abc\" def"), L" def"); - ASSERT_STREQ(StripFirstQuotedToken(L" \"abc def\" ghi "), L" ghi"); - ASSERT_STREQ(StripFirstQuotedToken(L"\"abc\" \"def\" "), L" \"def\""); -} - TEST(StringTest, EscapeUnescape) { CString original_str(_T("test <>\"#{}|\\^[]?%&/")); CString escaped_str; @@ -1375,67 +923,6 @@ TEST(StringTest, BytesToHex) { _T("0123456789abcdef")); } -TEST(StringTest, JoinStrings) { - std::vector components; - const TCHAR* delim = _T("-"); - CString result; - - JoinStrings(components, delim, &result); - EXPECT_TRUE(result.IsEmpty()); - JoinStrings(components, NULL, &result); - EXPECT_TRUE(result.IsEmpty()); - - components.push_back(CString(_T("foo"))); - JoinStrings(components, delim, &result); - EXPECT_STREQ(result, (_T("foo"))); - JoinStrings(components, NULL, &result); - EXPECT_STREQ(result, (_T("foo"))); - - components.push_back(CString(_T("bar"))); - JoinStrings(components, delim, &result); - EXPECT_STREQ(result, (_T("foo-bar"))); - JoinStrings(components, NULL, &result); - EXPECT_STREQ(result, (_T("foobar"))); - - components.push_back(CString(_T("baz"))); - JoinStrings(components, delim, &result); - EXPECT_STREQ(result, (_T("foo-bar-baz"))); - JoinStrings(components, NULL, &result); - EXPECT_STREQ(result, (_T("foobarbaz"))); - - - JoinStringsInArray(NULL, 0, delim, &result); - EXPECT_TRUE(result.IsEmpty()); - JoinStringsInArray(NULL, 0, NULL, &result); - EXPECT_TRUE(result.IsEmpty()); - - const TCHAR* array1[] = {_T("foo")}; - JoinStringsInArray(array1, arraysize(array1), delim, &result); - EXPECT_STREQ(result, (_T("foo"))); - JoinStringsInArray(array1, arraysize(array1), NULL, &result); - EXPECT_STREQ(result, (_T("foo"))); - - const TCHAR* array2[] = {_T("foo"), _T("bar")}; - JoinStringsInArray(array2, arraysize(array2), delim, &result); - EXPECT_STREQ(result, (_T("foo-bar"))); - JoinStringsInArray(array2, arraysize(array2), NULL, &result); - EXPECT_STREQ(result, (_T("foobar"))); - - const TCHAR* array3[] = {_T("foo"), _T("bar"), _T("baz")}; - JoinStringsInArray(array3, arraysize(array3), delim, &result); - EXPECT_STREQ(result, (_T("foo-bar-baz"))); - JoinStringsInArray(array3, arraysize(array3), NULL, &result); - EXPECT_STREQ(result, (_T("foobarbaz"))); - - const TCHAR* array_null_1[] = {NULL}; - JoinStringsInArray(array_null_1, arraysize(array_null_1), delim, &result); - EXPECT_STREQ(result, (_T(""))); - - const TCHAR* array_null_2[] = {NULL, NULL}; - JoinStringsInArray(array_null_2, arraysize(array_null_2), delim, &result); - EXPECT_STREQ(result, (_T("-"))); -} - TEST(StringTest, String_ToUpper) { // String_ToUpper is a wrapper over ::CharUpper. TCHAR s[] = _T("foo"); diff --git a/omaha/base/synchronized.cc b/omaha/base/synchronized.cc index ac61762..d708271 100644 --- a/omaha/base/synchronized.cc +++ b/omaha/base/synchronized.cc @@ -82,7 +82,7 @@ HANDLE CreateEventWithSyncAccess(const TCHAR* name, EnsureCreateEx(); if (create_event_ex_function) { return create_event_ex_function(event_attributes, name, - CREATE_EVENT_MANUAL_RESET, + 0x00000001, // CREATE_EVENT_MANUAL_RESET SYNCHRONIZE | EVENT_MODIFY_STATE); // for Set/Reset, etc. } @@ -258,7 +258,7 @@ bool Gate::Wait(DWORD msec) { // Returns S_OK, and sets selected_gate to zero based index of the gate that // was opened -// Returns E_FAIL if timeout occured or gate was abandoned. +// Returns E_FAIL if timeout occurred or gate was abandoned. HRESULT Gate::WaitAny(Gate const * const *gates, int num_gates, DWORD msec, diff --git a/omaha/base/synchronized.h b/omaha/base/synchronized.h index 0e40dd4..01c3eeb 100644 --- a/omaha/base/synchronized.h +++ b/omaha/base/synchronized.h @@ -53,7 +53,6 @@ struct Lockable { // during destruction. Very convinient to use // with the macros __mutexScope and __mutexBlock class AutoSync { - bool first_time_; public: explicit AutoSync(const Lockable *pLock); explicit AutoSync(const Lockable &rLock); @@ -63,7 +62,8 @@ class AutoSync { bool FirstTime(); private: const Lockable * lock_; - DISALLOW_EVIL_CONSTRUCTORS(AutoSync); + bool first_time_; + DISALLOW_COPY_AND_ASSIGN(AutoSync); }; // the usaage: @@ -127,7 +127,7 @@ class GLock : public Lockable { CString name_; #endif mutable HANDLE mutex_; - DISALLOW_EVIL_CONSTRUCTORS(GLock); + DISALLOW_COPY_AND_ASSIGN(GLock); }; // FakeGLock looks like a GLock, but none of its methods do anything. @@ -146,7 +146,7 @@ class FakeGLock : public Lockable { virtual bool Unlock() const { return true; } private: - DISALLOW_EVIL_CONSTRUCTORS(FakeGLock); + DISALLOW_COPY_AND_ASSIGN(FakeGLock); }; // LLock stands for local lock. @@ -166,7 +166,7 @@ class LLock : public Lockable { private: mutable CRITICAL_SECTION critical_section_; - DISALLOW_EVIL_CONSTRUCTORS(LLock); + DISALLOW_COPY_AND_ASSIGN(LLock); }; // A gate is a synchronization object used to either stop all @@ -195,7 +195,7 @@ class Gate { // Returns S_OK, and sets selected_gate to zero based index of the gate that // was opened. - // Returns E_FAIL if timeout occured or gate was abandoned. + // Returns E_FAIL if timeout occurred or gate was abandoned. static HRESULT WaitAny(Gate const * const *gates, int num_gates, DWORD msec, @@ -213,7 +213,7 @@ class Gate { int *selected_gate, bool wait_all); HANDLE gate_; - DISALLOW_EVIL_CONSTRUCTORS(Gate); + DISALLOW_COPY_AND_ASSIGN(Gate); }; bool WaitAllowRepaint(const Gate& gate, DWORD msec); @@ -228,7 +228,7 @@ class AutoGateKeeper { } private: Gate *gate_; - DISALLOW_EVIL_CONSTRUCTORS(AutoGateKeeper); + DISALLOW_COPY_AND_ASSIGN(AutoGateKeeper); }; // A very simple rather fast lock - if uncontested. USE ONLY AS A GLOBAL OBJECT @@ -263,7 +263,7 @@ class AutoSimpleLock { ~AutoSimpleLock() { lock_.Unlock(); } private: const SimpleLock& lock_; - DISALLOW_EVIL_CONSTRUCTORS(AutoSimpleLock); + DISALLOW_COPY_AND_ASSIGN(AutoSimpleLock); }; class AutoSimpleLockWithDelay { @@ -273,7 +273,7 @@ class AutoSimpleLockWithDelay { ~AutoSimpleLockWithDelay() { lock_.Unlock(); } private: const SimpleLockWithDelay& lock_; - DISALLOW_EVIL_CONSTRUCTORS(AutoSimpleLockWithDelay); + DISALLOW_COPY_AND_ASSIGN(AutoSimpleLockWithDelay); }; @@ -290,7 +290,7 @@ class CriticalSection { CRITICAL_SECTION critical_section_; uint32 number_entries_; - DISALLOW_EVIL_CONSTRUCTORS(CriticalSection); + DISALLOW_COPY_AND_ASSIGN(CriticalSection); }; // A class that manages a CriticalSection with its lifetime, you pass @@ -314,7 +314,7 @@ class SingleLock { private: CriticalSection * critical_section_; - DISALLOW_EVIL_CONSTRUCTORS(SingleLock); + DISALLOW_COPY_AND_ASSIGN(SingleLock); }; // Encapsulation for kernel Event. Initializes and destroys with it's lifetime @@ -331,7 +331,7 @@ class EventObj { private: HANDLE h_; - DISALLOW_EVIL_CONSTRUCTORS(EventObj); + DISALLOW_COPY_AND_ASSIGN(EventObj); }; // Is the given handle signaled? diff --git a/omaha/base/system.cc b/omaha/base/system.cc index b212992..2c03f6e 100644 --- a/omaha/base/system.cc +++ b/omaha/base/system.cc @@ -17,14 +17,13 @@ #include #include -#include +#include #include #include "omaha/base/app_util.h" #include "omaha/base/commands.h" #include "omaha/base/commontypes.h" #include "omaha/base/const_config.h" #include "omaha/base/debug.h" -#include "omaha/base/disk.h" #include "omaha/base/dynamic_link_kernel32.h" #include "omaha/base/error.h" #include "omaha/base/file.h" @@ -32,7 +31,6 @@ #include "omaha/base/path.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/system_info.h" #include "omaha/base/utils.h" @@ -40,118 +38,28 @@ namespace omaha { -// Constant -const TCHAR kNeedRebootHiddenFileSuffix[] = _T(".needreboot"); - -HRESULT System::WaitForDiskActivity(const uint32 max_delay_milliseconds, - const uint32 sleep_time_ms, - uint32 *time_waited) { - ASSERT(time_waited, (L"")); - uint32 sleep_time = sleep_time_ms; - if (sleep_time < 20) { sleep_time = 20; } - else if (sleep_time > 1000) { sleep_time = 1000; } - HRESULT r; - *time_waited = 0; - uint64 writes = 0; - uint64 new_writes = 0; - // get current counters - if (FAILED(r=GetDiskActivityCounters(NULL, &writes, NULL, NULL))) { - return r; - } - - // wait until a write - reads may be cached - while (1) { - if (FAILED(r=GetDiskActivityCounters(NULL, &new_writes, NULL, NULL))) { - return r; - } - if (new_writes > writes) { return S_OK; } - if (*time_waited > max_delay_milliseconds) { return E_FAIL; } - SleepEx(sleep_time, TRUE); - *time_waited += sleep_time; - } -} - -HRESULT System::GetDiskActivityCounters(uint64* reads, - uint64* writes, - uint64* bytes_read, - uint64* bytes_written) { - if (reads) { - *reads = 0; - } - - if (writes) { - *writes = 0; - } +namespace { - if (bytes_read) { - *bytes_read = 0; +// Disables critical error dialogs on the current thread. +// The system does not display the critical-error-handler message box. +// Instead, the system returns the error to the calling process. +class DisableThreadErrorUI { + public: + DisableThreadErrorUI() { + // Set the error mode + prev_mode_ = SetErrorMode(SEM_FAILCRITICALERRORS); } - if (bytes_written) { - *bytes_written = 0; + ~DisableThreadErrorUI() { + // Restore the error mode + SetErrorMode(prev_mode_); } - // Don't want to risk displaying UI errors here - DisableThreadErrorUI disable_error_dialog_box; - - // for all drives - for (int drive = 0; ; drive++) { - struct _DISK_PERFORMANCE perf_data; - const int max_device_len = 50; - - // check whether we can access this device - CString device_name; - SafeCStringFormat(&device_name, _T("\\\\.\\PhysicalDrive%d"), drive); - scoped_handle device(::CreateFile(device_name, 0, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, NULL)); - - if (get(device) == INVALID_HANDLE_VALUE) { - if (!drive) { - UTIL_LOG(LEVEL_ERROR, (_T("[Failed to access drive %i][0x%x]"), - drive, - HRESULTFromLastError())); - } - break; - } - - // disk performance counters must be on (diskperf -y on older machines; - // defaults to on on newer windows) - DWORD size = 0; - if (::DeviceIoControl(get(device), - IOCTL_DISK_PERFORMANCE, - NULL, - 0, - &perf_data, - sizeof(_DISK_PERFORMANCE), - &size, - NULL)) { - if (reads) { - *reads += perf_data.ReadCount; - } - - if (writes) { - *writes += perf_data.WriteCount; - } - - if (bytes_read) { - *bytes_read += perf_data.BytesRead.QuadPart; - } - - if (bytes_written) { - *bytes_written += perf_data.BytesWritten.QuadPart; - } - } else { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, - (_T("[System::GetDiskActivityCounters - failed to ") - _T("DeviceIoControl][0x%x]"), hr)); - return hr; - } - } + protected: + UINT prev_mode_; +}; - return S_OK; -} +} // namespace HRESULT System::GetDiskStatistics(const TCHAR* path, uint64 *free_bytes_current_user, @@ -237,26 +145,6 @@ HRESULT System::GetProcessMemoryStatistics(uint64 *current_working_set, return hr; } -HRESULT System::MaxPhysicalMemoryAvailable(uint64* max_bytes) { - ASSERT1(max_bytes); - - *max_bytes = 0; - - uint32 memory_load_percentage = 0; - uint64 free_physical_memory = 0; - - RET_IF_FAILED(System::GetGlobalMemoryStatistics(&memory_load_percentage, - &free_physical_memory, NULL, NULL, NULL, NULL, NULL)); - - UTIL_LOG(L4, (_T("mem load %u max physical memory available %s"), - memory_load_percentage, - String_Int64ToString(free_physical_memory, 10))); - - *max_bytes = free_physical_memory; - - return S_OK; -} - HRESULT System::GetGlobalMemoryStatistics(uint32 *memory_load_percentage, uint64 *free_physical_memory, uint64 *total_physical_memory, @@ -297,52 +185,6 @@ HRESULT System::EmptyProcessWorkingSet() { return S_OK; } -HRESULT System::SetThreadPriority(enum Priority priority) { - int pri; - - switch (priority) { - case LOW: pri = THREAD_PRIORITY_BELOW_NORMAL; break; - case HIGH: pri = THREAD_PRIORITY_HIGHEST; break; - case NORMAL: pri = THREAD_PRIORITY_NORMAL; break; - case IDLE: pri = THREAD_PRIORITY_IDLE; break; - default: return E_FAIL; - } - - if (::SetThreadPriority(GetCurrentThread(), pri)) { - return S_OK; - } else { - return E_FAIL; - } -} - -HRESULT System::SetProcessPriority(enum Priority priority) { - DWORD pri = 0; - switch (priority) { - case LOW: pri = BELOW_NORMAL_PRIORITY_CLASS; break; - case HIGH: pri = ABOVE_NORMAL_PRIORITY_CLASS; break; - case NORMAL: pri = NORMAL_PRIORITY_CLASS; break; - case IDLE: return E_INVALIDARG; - default: return E_INVALIDARG; - } - - DWORD pid = ::GetCurrentProcessId(); - - scoped_handle handle(::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid)); - if (!valid(handle)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LE, (_T("[::OpenProcess failed][%u][0x%x]"), pid, hr)); - return hr; - } - - if (!::SetPriorityClass(get(handle), pri)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LE, (_T("[::SetPriorityClass failed][%u][0x%x]"), pid, hr)); - return hr; - } - - return S_OK; -} - // Adaptor for System::StartProcessWithEnvironment(). HRESULT System::StartProcess(const TCHAR* process_name, TCHAR* command_line, @@ -487,34 +329,12 @@ HRESULT System::StartCommandLine(const TCHAR* command_line_to_execute) { return hr; } -// Adaptor for System::StartProcessAsUserWithEnvironment(). -HRESULT System::StartProcessAsUser(HANDLE user_token, - const CString& executable_path, - const CString& parameters, - LPWSTR desktop, - PROCESS_INFORMATION* pi) { - void* env_block(NULL); - if (!::CreateEnvironmentBlock(&env_block, user_token, TRUE)) { - HRESULT hr = HRESULTFromLastError(); - ASSERT(false, (_T("[::CreateEnvironmentBlock failed][0x%x]"), hr)); - return hr; - } - ON_SCOPE_EXIT(::DestroyEnvironmentBlock, env_block); - return System::StartProcessAsUserWithEnvironment( - user_token, - executable_path, - parameters, - desktop, - env_block, - pi); -} - // TODO(omaha3): Unit test this method. HRESULT System::StartProcessAsUserWithEnvironment( HANDLE user_token, const CString& executable_path, const CString& parameters, - LPWSTR desktop, + const TCHAR* desktop, LPVOID env_block, PROCESS_INFORMATION* pi) { UTIL_LOG(L3, (_T("[StartProcessAsUserWithEnvironment][%s][%s][%s]"), @@ -527,7 +347,7 @@ HRESULT System::StartProcessAsUserWithEnvironment( cmd.Append(parameters); STARTUPINFO startup_info = { sizeof(startup_info) }; - startup_info.lpDesktop = desktop; + startup_info.lpDesktop = const_cast(desktop); DWORD creation_flags(0); creation_flags |= CREATE_UNICODE_ENVIRONMENT; @@ -604,120 +424,17 @@ HRESULT System::ShellExecuteProcess(const TCHAR* file_name_to_execute, return S_OK; } -// start another process painlessly via ::ShellExecuteEx. Use this method -// instead of the StartProcessXXX methods that use ::CreateProcess where -// possible, since ::ShellExecuteEx has better behavior on Windows Vista. -HRESULT System::ShellExecuteCommandLine(const TCHAR* command_line_to_execute, - HWND hwnd, - HANDLE* process_handle) { - ASSERT1(command_line_to_execute); - - CString exe; - CString args; - - HRESULT hr = CommandParsingSimple::SplitExeAndArgs(command_line_to_execute, - &exe, - &args); - - if (SUCCEEDED(hr)) { - hr = System::ShellExecuteProcess(exe, args, hwnd, process_handle); - if (FAILED(hr)) { - UTIL_LOG(LEVEL_ERROR, (_T("[System::ShellExecuteProcess failed]") - _T("[%s][%s][0x%08x]"), exe, args, hr)); - } - } - - return hr; -} - -// returns the number of ms the system has had no user input -int System::GetUserIdleTime() { - LASTINPUTINFO last_input_info; - last_input_info.cbSize = sizeof(LASTINPUTINFO); - // get time in windows ticks since system start of last activity - BOOL b = GetLastInputInfo(&last_input_info); - if (b == TRUE) { - return (GetTickCount()-last_input_info.dwTime); // compute idle time - } - return 0; -} - -bool System::IsUserIdle() { - // Only notify when the user has been idle less than this time - static int user_idle_threshold_ms = kUserIdleThresholdMs; - - bool is_user_idle = (GetUserIdleTime() > user_idle_threshold_ms); - UTIL_LOG(L2, (_T("System::IsUserIdle() %s; user_idle_threshold_ms = %d"), - is_user_idle ? _T("TRUE") : _T("FALSE"), - user_idle_threshold_ms)); - return is_user_idle; -} - -bool System::IsUserBusy() { - // The user is busy typing or interacting with another application - // if the user is below the minimum threshold: - static int user_idle_min_threshold_ms = kUserIdleMinThresholdMs; - // The user is probably not paying attention - // if the user is above the maximum threshold: - static int user_idle_max_threshold_ms = kUserIdleMaxThresholdMs; - - int user_idle_time = GetUserIdleTime(); - bool is_user_busy = user_idle_time < user_idle_min_threshold_ms || - user_idle_time > user_idle_max_threshold_ms; - UTIL_LOG(L2, (_T("[System::IsUserBusy() %s][user_idle_time = %d]") - _T("[user_idle_min_threshold_ms = %d]") - _T("[user_idle_max_threshold_ms = %d]"), - is_user_busy? _T("TRUE") : _T("FALSE"), - user_idle_time, - user_idle_min_threshold_ms, - user_idle_max_threshold_ms)); - return is_user_busy; -} - -bool System::IsScreensaverRunning() { - // NT 4.0 and below require testing OpenDesktop("screen-saver") - // We require W2K or better so we have an easier way - DWORD result = 0; - ::SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &result, 0); - bool is_screensaver_running = (result != FALSE); - UTIL_LOG(L2, (_T("System::IsScreensaverRunning() %s"), - is_screensaver_running? _T("TRUE") : _T("FALSE"))); - return is_screensaver_running; -} - -bool System::IsWorkstationLocked() { - bool is_workstation_locked = true; - HDESK inputdesk = ::OpenInputDesktop(0, 0, GENERIC_READ); - if (NULL != inputdesk) { - TCHAR name[256]; - DWORD needed = arraysize(name); - BOOL ok = ::GetUserObjectInformation(inputdesk, - UOI_NAME, - name, - sizeof(name), - &needed); - ::CloseDesktop(inputdesk); - if (ok) { - is_workstation_locked = (0 != lstrcmpi(name, NOTRANSL(_T("default")))); - } - } - - UTIL_LOG(L2, (_T("System::IsWorkstationLocked() %s"), - is_workstation_locked? _T("TRUE") : _T("FALSE"))); - return is_workstation_locked; -} - -bool System::IsUserAway() { - return IsScreensaverRunning() || IsWorkstationLocked(); -} - uint32 System::GetProcessHandleCount() { typedef LONG (CALLBACK *Fun)(HANDLE, int32, PVOID, ULONG, PULONG); // This new version of getting the number of open handles works on win2k. - HMODULE h = GetModuleHandle(_T("ntdll.dll")); + HMODULE module = GetModuleHandle(_T("ntdll.dll")); + if (!module) { + return 0; + } Fun NtQueryInformationProcess = - reinterpret_cast(::GetProcAddress(h, "NtQueryInformationProcess")); + reinterpret_cast(::GetProcAddress(module, + "NtQueryInformationProcess")); if (!NtQueryInformationProcess) { UTIL_LOG(LEVEL_ERROR, (_T("[NtQueryInformationProcess failed][0x%x]"), @@ -731,145 +448,7 @@ uint32 System::GetProcessHandleCount() { &count, sizeof(count), NULL) >= 0, (L"")); - - return count; -} - -uint32 System::GetProcessHandleCountOld() { - typedef BOOL (CALLBACK * Fun)(HANDLE, PDWORD); - - // GetProcessHandleCount not available on win2k - HMODULE handle = GetModuleHandle(_T("kernel32")); - Fun f = reinterpret_cast(GetProcAddress(handle, - "GetProcessHandleCount")); - - if (!f) return 0; - - DWORD count = 0; - VERIFY((*f)(GetCurrentProcess(), &count), (L"")); return count; - - // DWORD GetGuiResources (HANDLE hProcess, DWORD uiFlags); - // Parameters, hProcess - // [in] Handle to the process. The handle must have the - // PROCESS_QUERY_INFORMATION access right. For more information, see Process - // Security and Access Rights. - // uiFlags - // [in] GUI object type. This parameter can be one of the following values. - // Value Meaning - // GR_GDIOBJECTS Return the count of GDI objects. - // GR_USEROBJECTS Return the count of USER objects. -} - -void System::GetGuiObjectCount(uint32 *gdi, uint32 *user) { - if (gdi) { - *gdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); - } - if (user) { - *user = GetGuiResources(GetCurrentProcess(), GR_USEROBJECTS); - } -} - -HRESULT System::GetRebootCheckDummyFileName(const TCHAR* base_file, - CString* dummy_file) { - ASSERT1(dummy_file); - - if (base_file && *base_file) { - ASSERT1(File::Exists(base_file)); - dummy_file->SetString(base_file); - } else { - *dummy_file = app_util::GetModulePath(NULL); - if (dummy_file->IsEmpty()) { - return HRESULTFromLastError(); - } - } - dummy_file->Append(_T(".needreboot")); - return S_OK; -} - -// Is the system being rebooted? -bool System::IsRebooted(const TCHAR* base_file) { - CString dummy_file; - if (SUCCEEDED(GetRebootCheckDummyFileName(base_file, &dummy_file))) { - if (File::Exists(dummy_file)) { - // If the file exists but it is not found in the - // PendingFileRenameOperations, (probably becaused that this key is messed - // up and thus the system restart fails to delete the file), re-add it - if (!File::AreMovesPendingReboot(dummy_file, true)) { - File::MoveAfterReboot(dummy_file, NULL); - } - return false; - } else { - return true; - } - } - return false; -} - -// Mark the system as reboot required -HRESULT System::MarkAsRebootRequired(const TCHAR* base_file) { - // Create a dummy file if needed - CString dummy_file; - RET_IF_FAILED(GetRebootCheckDummyFileName(base_file, &dummy_file)); - if (File::Exists(dummy_file)) { - return S_OK; - } - - File file; - RET_IF_FAILED(file.Open(dummy_file, true, false)); - RET_IF_FAILED(file.Close()); - - // Hide it - DWORD file_attr = ::GetFileAttributes(dummy_file); - if (file_attr == INVALID_FILE_ATTRIBUTES || - !::SetFileAttributes(dummy_file, file_attr | FILE_ATTRIBUTE_HIDDEN)) { - return HRESULTFromLastError(); - } - - // Mark it as being deleted after reboot - return File::MoveAfterReboot(dummy_file, NULL); -} - -// Unmark the system as reboot required -HRESULT System::UnmarkAsRebootRequired(const TCHAR* base_file) { - CString dummy_file; - RET_IF_FAILED(GetRebootCheckDummyFileName(base_file, &dummy_file)); - - return File::RemoveFromMovesPendingReboot(dummy_file, false); -} - -// Restart the computer -HRESULT System::RestartComputer() { - RET_IF_FAILED(AdjustPrivilege(SE_SHUTDOWN_NAME, true)); - - if (!::ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION | - SHTDN_REASON_MINOR_INSTALLATION | - SHTDN_REASON_FLAG_PLANNED)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, (_T("[System::RestartComputer - failed to") - _T(" ExitWindowsEx][0x%x]"), hr)); - return hr; - } - - return S_OK; -} - -// The implementation works on all Windows versions. On NT and XP the screen -// saver is actually stored in registry at -// HKEY_CURRENT_USER\Control Panel\Desktop\SCRNSAVE.EXE but the -// GetPrivateProfileString call is automatically mapped to the registry -HRESULT System::GetCurrentScreenSaver(CString* fileName) { - if (!fileName) return E_POINTER; - - DWORD nChars = ::GetPrivateProfileString(_T("boot"), - _T("SCRNSAVE.EXE"), - _T(""), - fileName->GetBuffer(MAX_PATH), - MAX_PATH, - _T("system.ini")); - fileName->ReleaseBufferSetLength(nChars); - - return S_OK; } HRESULT System::CoCreateInstanceAsAdmin(HWND hwnd, @@ -898,50 +477,6 @@ HRESULT System::CoCreateInstanceAsAdmin(HWND hwnd, return ::CoGetObject(moniker_name, &bo, riid, ppv); } -HRESULT System::IsPrivilegeEnabled(const TCHAR* privilege, bool* present) { - ASSERT1(privilege); - ASSERT1(present); - - *present = false; - - scoped_handle token; - if (!::OpenProcessToken(::GetCurrentProcess(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, - address(token))) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, (_T("[System::IsPrivilegeEnabled - failed to ") - _T("OpenProcessToken][0x%x]"), hr)); - return hr; - } - - LUID luid = {0}; - if (!::LookupPrivilegeValue(NULL, privilege, &luid)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, (_T("[System::IsPrivilegeEnabled - failed to") - _T("LookupPrivilegeValue][0x%x]"), hr)); - return hr; - } - - PRIVILEGE_SET required_privilege = {0}; - required_privilege.PrivilegeCount = 1; - required_privilege.Control = PRIVILEGE_SET_ALL_NECESSARY; - required_privilege.Privilege[0].Luid = luid; - - BOOL result = FALSE; - if (!::PrivilegeCheck(get(token), &required_privilege, &result)) { - HRESULT hr = HRESULTFromLastError(); - UTIL_LOG(LEVEL_ERROR, (_T("[System::IsPrivilegeEnabled - failed to") - _T("PrivilegeCheck][0x%x]"), hr)); - return hr; - } - - if (required_privilege.Privilege[0].Attributes & - SE_PRIVILEGE_USED_FOR_ACCESS) { - *present = true; - } - - return S_OK; -} // Attempts to adjust current process privileges. // Only process running with administrator privileges will succeed. @@ -1111,46 +646,6 @@ bool System::IsSessionActive(DWORD session_id) { return false; } -// Is the current process running under WinSta0 -bool System::IsCurrentProcessInteractive() { - // Use a non-scoped handle, since a handle retrieved via - // ::GetProcessWindowStation() should not be closed. - HWINSTA handle_window_station(::GetProcessWindowStation()); - DWORD len = 0; - CString str_window_station; - - if (!handle_window_station || handle_window_station == INVALID_HANDLE_VALUE) { - UTIL_LOG(LEVEL_ERROR, - (_T("[System::IsCurrentProcessInteractive - ") - _T("::GetProcessWindowStation() failed (%d)]"), - ::GetLastError())); - return false; - } - - if (!::GetUserObjectInformation(handle_window_station, - UOI_NAME, - CStrBuf(str_window_station, MAX_PATH), - MAX_PATH, - &len)) { - UTIL_LOG(LEVEL_ERROR, - (_T("[System::IsCurrentProcessInteractive - ") - _T("::GetUserObjectInfoformation(hWinSta) failed (%d)]"), - ::GetLastError())); - return false; - } - - UTIL_LOG(L6, (_T("[System::IsCurrentProcessInteractive]") - _T("[WindowStation name][%s]"), - str_window_station)); - return (str_window_station == _T("WinSta0")); -} - -// is the current process running under WinSta0 for the currently active session -bool System::IsCurrentProcessActiveAndInteractive() { - return IsSessionActive(GetCurrentSessionId()) && - IsCurrentProcessInteractive(); -} - bool System::IsRunningOnBatteries() { SYSTEM_POWER_STATUS system_power_status = {0}; if (::GetSystemPowerStatus(&system_power_status)) { diff --git a/omaha/base/system.h b/omaha/base/system.h index eaea34a..23838e9 100644 --- a/omaha/base/system.h +++ b/omaha/base/system.h @@ -42,19 +42,6 @@ const DWORD kInvalidSessionId = 0xFFFFFFFF; class System { public: - // disk activity. - - // waits up to specified time for disk activity to occur; sleeps in - // increments of sleep_time. - static HRESULT WaitForDiskActivity(uint32 max_delay_milliseconds, - uint32 sleep_time_ms, - uint32 *time_waited); - // disk activity counters; may require admin on some machines? should return - // E_FAIL if so. - static HRESULT GetDiskActivityCounters(uint64 *reads, - uint64 *writes, - uint64 *bytes_read, - uint64 *bytes_written); // disk statistics. @@ -66,17 +53,6 @@ class System { uint64 *total_bytes_current_user, uint64 *free_bytes_all_users); - enum Priority { - LOW, - HIGH, - NORMAL, - IDLE - }; - - // functions to alter process/thread priority. - static HRESULT SetThreadPriority(enum Priority priority); - static HRESULT SetProcessPriority(enum Priority priority); - // The three functions below start background processes via ::CreateProcess. // Use the ShellExecuteProcessXXX functions when starting foreground // processes. @@ -108,14 +84,6 @@ class System { BOOL inherit_handles, PROCESS_INFORMATION* pi); - // Start the process with the provided token, in the specified desktop of - // the token's session. The caller needs to be SYSTEM. - static HRESULT StartProcessAsUser(HANDLE user_token, - const CString& executable_path, - const CString& parameters, - LPWSTR desktop, - PROCESS_INFORMATION* pi); - // This function is similar with the function above, and it allows an // optional environment block to be passed as an argument. // When provided, the environment block should match the user which @@ -126,7 +94,7 @@ class System { HANDLE user_token, const CString& executable_path, const CString& parameters, - LPWSTR desktop, + const TCHAR* desktop, LPVOID env_block, PROCESS_INFORMATION* pi); @@ -138,18 +106,8 @@ class System { HWND hwnd, HANDLE* process_handle); - // start another process painlessly via ::ShellExecuteEx. Use this method - // instead of the StartProcessXXX methods that use ::CreateProcess where - // possible, since ::ShellExecuteEx has better behavior on Vista. - static HRESULT ShellExecuteCommandLine(const TCHAR* command_line_to_execute, - HWND hwnd, - HANDLE* process_handle); - // memory statistics. - // max amount of memory that can be allocated without paging. - static HRESULT MaxPhysicalMemoryAvailable(uint64 *max_bytes); - // global memory stats static HRESULT GetGlobalMemoryStatistics( uint32 *memory_load_percentage, @@ -178,37 +136,9 @@ class System { // when a component is about to go idle for "awhile". static HRESULT EmptyProcessWorkingSet(); - // returns the number of ms the system has had no user input. - static int GetUserIdleTime(); - // from ntddk.h, used as a parameter to get the process handle count. static const int kProcessHandleCount = 20; static uint32 GetProcessHandleCount(); - static uint32 GetProcessHandleCountOld(); - - static void GetGuiObjectCount(uint32 *gdi, uint32 *user); - - static bool IsUserIdle(); - static bool IsUserBusy(); - static bool IsScreensaverRunning(); - static bool IsWorkstationLocked(); - static bool IsUserAway(); - - // Is the system requiring reboot. - static bool IsRebooted(const TCHAR* base_file); - - // Mark the system as reboot required. - static HRESULT MarkAsRebootRequired(const TCHAR* base_file); - - // Unmark the system as reboot required. - static HRESULT UnmarkAsRebootRequired(const TCHAR* base_file); - - // Restart the computer. - static HRESULT RestartComputer(); - - // Get the full path name of the screen saver program currently selected. - // If no screen saver is selected then "fileName" is empty. - static HRESULT GetCurrentScreenSaver(CString* fileName); // Create an instance of a COM Local Server class using either plain vanilla // CoCreateInstance, or using the Elevation moniker if Vista or later and @@ -222,9 +152,6 @@ class System { // Only process running with administrator privileges will succeed. static HRESULT AdjustPrivilege(const TCHAR* privilege, bool enable); - // Checks if the given privilege is enabled for the current process. - static HRESULT IsPrivilegeEnabled(const TCHAR* privilege, bool* present); - // Dynamically links and calls ::WTSGetActiveConsoleSessionId(). Returns // kInvalidSessionId if it cannot find the export in kernel32.dll. static DWORD WTSGetActiveConsoleSessionId(); @@ -239,13 +166,6 @@ class System { // Is there a user logged on and active in the specified session? static bool IsSessionActive(DWORD session_id); - // Is the current process running under WinSta0. - static bool IsCurrentProcessInteractive(); - - // is the current process running under WinSta0 for the currently active - // session. - static bool IsCurrentProcessActiveAndInteractive(); - // Returns true if a system battery is detected and the AC line // status is 'offline', otherwise it returns false. static bool IsRunningOnBatteries(); @@ -255,9 +175,7 @@ class System { static HRESULT CreateChildOutputPipe(HANDLE* read, HANDLE* write); private: - static HRESULT GetRebootCheckDummyFileName(const TCHAR* base_file, - CString* dummy_file); - DISALLOW_EVIL_CONSTRUCTORS(System); + DISALLOW_COPY_AND_ASSIGN(System); }; } // namespace omaha diff --git a/omaha/base/system_info.h b/omaha/base/system_info.h index 4cb07ba..4805528 100644 --- a/omaha/base/system_info.h +++ b/omaha/base/system_info.h @@ -23,6 +23,7 @@ #include #include #include +#include namespace omaha { @@ -32,7 +33,7 @@ class SystemInfo { // Find out if the OS is at least Windows 2000 // Service pack 4. If OS version is less than that // will return false, all other cases true. - static bool SystemInfo::OSWin2KSP4OrLater() { + static bool OSWin2KSP4OrLater() { return ::IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN2K), LOBYTE(_WIN32_WINNT_WIN2K), 4); diff --git a/omaha/base/system_unittest.cc b/omaha/base/system_unittest.cc index 4eae206..9af5035 100644 --- a/omaha/base/system_unittest.cc +++ b/omaha/base/system_unittest.cc @@ -20,14 +20,39 @@ // added #include "omaha/base/system.h" + +#include + #include "omaha/testing/unit_test.h" namespace omaha { -TEST(SystemTest, System) { - uint32 time_waited = 0; - ASSERT_SUCCEEDED(System::WaitForDiskActivity(10000, 25, &time_waited)); +namespace { + +uint32 GetProcessHandleCountOld() { + // GetProcessHandleCount not available on win2k + HMODULE module = ::GetModuleHandle(_T("kernel32")); + if (!module) { + return 0; + } + + decltype(&::GetProcessHandleCount) get_proccess_handle_count = nullptr; + get_proccess_handle_count = + reinterpret_cast( + GetProcAddress(module, "GetProcessHandleCount")); + if (!get_proccess_handle_count) { + return 0; + } + + DWORD count = 0; + VERIFY(get_proccess_handle_count(GetCurrentProcess(), &count), (L"")); + return count; +} + +} // namespace + +TEST(SystemTest, System) { uint64 free_bytes_current_user = 0; uint64 total_bytes_current_user = 0; uint64 free_bytes_all_users = 0; @@ -36,8 +61,7 @@ TEST(SystemTest, System) { &total_bytes_current_user, &free_bytes_all_users)); - ASSERT_EQ(System::GetProcessHandleCount(), - System::GetProcessHandleCountOld()); + ASSERT_EQ(System::GetProcessHandleCount(), GetProcessHandleCountOld()); } // Assume the workstations and PULSE are not running on batteries. The test diff --git a/omaha/base/thread.cc b/omaha/base/thread.cc index fd2aab2..8ac3839 100644 --- a/omaha/base/thread.cc +++ b/omaha/base/thread.cc @@ -25,7 +25,7 @@ namespace omaha { // while even after the thread is dead. It can appear as a handle leak in the // unit test but in fact it is not. -Thread::Thread() : thread_id_(0), thread_(NULL) { +Thread::Thread() : runner_(NULL), thread_id_(0), thread_(NULL) { } Thread::~Thread() { @@ -124,36 +124,6 @@ bool Thread::Running() const { return WAIT_TIMEOUT == WaitForSingleObject(thread_, 0); } -// Executes an APC request. -void __stdcall Thread::APCProc(ULONG_PTR param) { - ApcInfo* pInfo = reinterpret_cast(param); - if (pInfo) { - if (pInfo->receiver_) { - pInfo->receiver_->OnApc(pInfo->param_); - } - // Deallocates what was allocated in QueueApc. - delete pInfo; - } -} - -// ApcReceiver wants to execute its OnApc function in the -// context of this thread. -bool Thread::QueueApc(ApcReceiver* receiver, ULONG_PTR param) { - ASSERT1(receiver); - if (!Running()) { - // No reason to queue anything to not running thread. - return true; - } - - // This allocation will be freed in Thread::APCProc - ApcInfo* pInfo = new ApcInfo(); - pInfo->receiver_ = receiver; - pInfo->param_ = param; - return 0 != QueueUserAPC(&Thread::APCProc, - thread_, - reinterpret_cast(pInfo)); -} - bool Thread::PostMessage(UINT msg, WPARAM wparam, LPARAM lparam) { return TRUE == PostThreadMessage(thread_id_, msg, wparam, lparam); } diff --git a/omaha/base/thread.h b/omaha/base/thread.h index 8a1ee17..b2544f0 100644 --- a/omaha/base/thread.h +++ b/omaha/base/thread.h @@ -40,7 +40,7 @@ class Runnable { virtual ~Runnable() {} virtual void Run() = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(Runnable); + DISALLOW_COPY_AND_ASSIGN(Runnable); }; // Any class devived from this one will be able to call @@ -54,7 +54,7 @@ class ApcReceiver { virtual ~ApcReceiver() {} virtual void OnApc(ULONG_PTR param) = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(ApcReceiver); + DISALLOW_COPY_AND_ASSIGN(ApcReceiver); }; // This class encapsulates win32 thread management functions. @@ -77,26 +77,17 @@ class Thread { // Waits until thread exits. bool WaitTillExit(DWORD msec) const; - // Queues an APC to the ApcReceiver. - bool QueueApc(ApcReceiver* receiver, ULONG_PTR param); - // Posts message to a thread. bool PostMessage(UINT msg, WPARAM wparam, LPARAM lparam); private: static DWORD __stdcall Prepare(void* thisPointer); // Thread proc. - static void __stdcall APCProc(ULONG_PTR dwParam); Runnable* runner_; // Interface to work with. - HANDLE thread_; DWORD thread_id_; + HANDLE thread_; Gate start_gate_; // Synchronizes the thread start. - struct ApcInfo { - ApcReceiver* receiver_; - ULONG_PTR param_; - }; - - DISALLOW_EVIL_CONSTRUCTORS(Thread); + DISALLOW_COPY_AND_ASSIGN(Thread); }; } // namespace omaha diff --git a/omaha/base/thread_pool.cc b/omaha/base/thread_pool.cc index daf5721..0956e2a 100644 --- a/omaha/base/thread_pool.cc +++ b/omaha/base/thread_pool.cc @@ -15,7 +15,8 @@ #include "omaha/base/thread_pool.h" -#include "base/scoped_ptr.h" +#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -46,7 +47,7 @@ class Context { UserWorkItem* work_item_; const DWORD coinit_flags_; - DISALLOW_EVIL_CONSTRUCTORS(Context); + DISALLOW_COPY_AND_ASSIGN(Context); }; } // namespace @@ -117,7 +118,7 @@ HRESULT ThreadPool::QueueUserWorkItem(UserWorkItem* work_item, UTIL_LOG(L4, (_T("[ThreadPool::QueueUserWorkItem]"))); ASSERT1(work_item); - scoped_ptr context(new Context(this, work_item, coinit_flags)); + auto context = std::make_unique(this, work_item, coinit_flags); work_item->set_shutdown_event(get(shutdown_event_)); ::InterlockedIncrement(&work_item_count_); if (!::QueueUserWorkItem(&ThreadPool::ThreadProc, context.get(), flags)) { diff --git a/omaha/base/thread_pool.h b/omaha/base/thread_pool.h index 7849211..72ca797 100644 --- a/omaha/base/thread_pool.h +++ b/omaha/base/thread_pool.h @@ -17,8 +17,10 @@ #define OMAHA_BASE_THREAD_POOL_H_ #include +#include + #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -43,7 +45,7 @@ class UserWorkItem { // and shutdown correctly. This event is set when the thread pool is closing. // Do not close this event as is owned by the thread pool. HANDLE shutdown_event_; - DISALLOW_EVIL_CONSTRUCTORS(UserWorkItem); + DISALLOW_COPY_AND_ASSIGN(UserWorkItem); }; class ThreadPool { @@ -81,7 +83,7 @@ class ThreadPool { // the thread pool is shutting down. The shutdown delay resolution is ~10ms. int shutdown_delay_; - DISALLOW_EVIL_CONSTRUCTORS(ThreadPool); + DISALLOW_COPY_AND_ASSIGN(ThreadPool); }; } // namespace omaha diff --git a/omaha/base/thread_pool_callback.h b/omaha/base/thread_pool_callback.h index 52eac45..4657f9a 100644 --- a/omaha/base/thread_pool_callback.h +++ b/omaha/base/thread_pool_callback.h @@ -28,7 +28,7 @@ class ThreadPoolCallBack0 : public UserWorkItem { explicit ThreadPoolCallBack0(T* obj, void (T::*fun)()) : obj_(obj), fun_(fun) {} private: - virtual void DoProcess() { + void DoProcess() override { (obj_->*fun_)(); } T* obj_; @@ -43,7 +43,7 @@ class ThreadPoolCallBack1 : public UserWorkItem { explicit ThreadPoolCallBack1(T* obj, void (T::*fun)(P1), P1 p1) : obj_(obj), fun_(fun), p1_(p1) {} private: - virtual void DoProcess() { + void DoProcess() override { (obj_->*fun_)(p1_); } T* obj_; @@ -59,7 +59,7 @@ class StaticThreadPoolCallBack1 : public UserWorkItem { explicit StaticThreadPoolCallBack1(void (*fun)(P1), P1 p1) : fun_(fun), p1_(p1) {} private: - virtual void DoProcess() { + void DoProcess() override { (*fun_)(p1_); } @@ -75,7 +75,7 @@ class ThreadPoolCallBack2 : public UserWorkItem { explicit ThreadPoolCallBack2(T* obj, void (T::*fun)(P1, P2), P1 p1, P2 p2) : obj_(obj), fun_(fun), p1_(p1), p2_(p2) {} private: - virtual void DoProcess() { + void DoProcess() override { (obj_->*fun_)(p1_, p2_); } T* obj_; diff --git a/omaha/base/thread_pool_unittest.cc b/omaha/base/thread_pool_unittest.cc index 1c3a655..9d84aca 100644 --- a/omaha/base/thread_pool_unittest.cc +++ b/omaha/base/thread_pool_unittest.cc @@ -13,9 +13,11 @@ // limitations under the License. // ======================================================================== -#include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/thread_pool.h" + +#include + +#include "base/basictypes.h" #include "omaha/base/timer.h" #include "omaha/testing/unit_test.h" @@ -33,7 +35,7 @@ class MyJob1 : public UserWorkItem { private: virtual void DoProcess() { ::InterlockedExchangeAdd(&g_completed_count, 1); } - DISALLOW_EVIL_CONSTRUCTORS(MyJob1); + DISALLOW_COPY_AND_ASSIGN(MyJob1); }; // Increments the global count by 2. @@ -44,7 +46,7 @@ class MyJob2 : public UserWorkItem { private: virtual void DoProcess() { ::InterlockedExchangeAdd(&g_completed_count, 2); } - DISALLOW_EVIL_CONSTRUCTORS(MyJob2); + DISALLOW_COPY_AND_ASSIGN(MyJob2); }; // Increments the global count by 3. @@ -55,7 +57,7 @@ class MyJob3 : public UserWorkItem { private: virtual void DoProcess() { ::InterlockedExchangeAdd(&g_completed_count, 3); } - DISALLOW_EVIL_CONSTRUCTORS(MyJob3); + DISALLOW_COPY_AND_ASSIGN(MyJob3); }; // ThreadPool COM initialization test class. The class tests that the thread @@ -85,7 +87,7 @@ class UserWorkItemCoInitTest : public UserWorkItem { }; HRESULT QueueMyJob1(ThreadPool* thread_pool) { - scoped_ptr job(new MyJob1); + std::unique_ptr job(new MyJob1); HRESULT hr = thread_pool->QueueUserWorkItem(job.get(), COINIT_MULTITHREADED, WT_EXECUTEDEFAULT); @@ -97,7 +99,7 @@ HRESULT QueueMyJob1(ThreadPool* thread_pool) { } HRESULT QueueMyJob2(ThreadPool* thread_pool) { - scoped_ptr job(new MyJob2); + std::unique_ptr job(new MyJob2); HRESULT hr = thread_pool->QueueUserWorkItem(job.get(), COINIT_MULTITHREADED, WT_EXECUTEDEFAULT); @@ -109,7 +111,7 @@ HRESULT QueueMyJob2(ThreadPool* thread_pool) { } HRESULT QueueMyJob3(ThreadPool* thread_pool) { - scoped_ptr job(new MyJob3); + std::unique_ptr job(new MyJob3); HRESULT hr = thread_pool->QueueUserWorkItem(job.get(), COINIT_MULTITHREADED, WT_EXECUTEDEFAULT); @@ -124,7 +126,7 @@ HRESULT QueueUserWorkItemCoInitTest(ThreadPool* thread_pool, DWORD coinit_flags_workitem, HRESULT coinit_expected_hresult, DWORD coinit_flags_threadpool) { - scoped_ptr job( + std::unique_ptr job( new UserWorkItemCoInitTest(coinit_flags_workitem, coinit_expected_hresult)); EXPECT_HRESULT_SUCCEEDED( diff --git a/omaha/base/time.cc b/omaha/base/time.cc index ca836ef..7c4c0e8 100644 --- a/omaha/base/time.cc +++ b/omaha/base/time.cc @@ -136,34 +136,6 @@ CString ConvertTimeToGMTString(const FILETIME *ft) { return s; } -time64 ConvertTime16ToTime64(uint16 time16) { - return time16 * kTimeGranularity + kStart100NsTime; -} - -uint16 ConvertTime64ToTime16(time64 time) { - ASSERT1(time >= kStart100NsTime); - - time64 t64 = (time - kStart100NsTime) / kTimeGranularity; - ASSERT1(t64 <= kTime16Max); - - return static_cast(t64); -} - -time64 TimeTToTime64(const time_t& old_value) { - FILETIME file_time; - TimeTToFileTime(old_value, &file_time); - return FileTimeToTime64(file_time); -} - -#ifdef _DEBUG -void ComputeStartTime() { - SYSTEMTIME start_system_time = kStartSystemTime; - time64 start_100ns_time = SystemTimeToTime64(&start_system_time); - UTIL_LOG(L1, (_T("posting list starting time = %s\n"), - String_Int64ToString(start_100ns_time, 10))); -} -#endif - // Time management // Allow the unittest to override. diff --git a/omaha/base/time.h b/omaha/base/time.h index 7a1d47f..3cd86fe 100644 --- a/omaha/base/time.h +++ b/omaha/base/time.h @@ -48,12 +48,6 @@ namespace omaha { typedef uint16 time16; typedef uint64 time64; -time64 ConvertTime16ToTime64(uint16 time16); -uint16 ConvertTime64ToTime16(time64 time); - -#ifdef _DEBUG -void ComputeStartTime(); -#endif // Returns the current system time as a 64-bit value representing the // number of 100-nanosecond intervals since January 1, 1601 (UTC). @@ -71,7 +65,6 @@ time64 SystemTimeToTime64(const SYSTEMTIME *sys_time); int32 SystemTimeToInt32(const SYSTEMTIME *sys_time); int32 Time64ToInt32(const time64 & time); time64 Int32ToTime64(const int32 & time); -time64 TimeTToTime64(const time_t& old_value); // Returns the system time in GMT SYSTEMTIME Time64ToSystemTime(const time64 & time); diff --git a/omaha/base/time_unittest.cc b/omaha/base/time_unittest.cc index 9135640..4ca73c1 100644 --- a/omaha/base/time_unittest.cc +++ b/omaha/base/time_unittest.cc @@ -15,8 +15,9 @@ // // Time unittest +#include +#include #include - #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" @@ -183,7 +184,7 @@ TEST(TimeTest, FileTimeToInt64) { { FILETIME file_time = {ULONG_MAX, LONG_MAX}; - EXPECT_EQ(kint64max, FileTimeToInt64(file_time)); + EXPECT_EQ(std::numeric_limits::max(), FileTimeToInt64(file_time)); } { diff --git a/omaha/base/timer.h b/omaha/base/timer.h index 15839e4..24fabfe 100644 --- a/omaha/base/timer.h +++ b/omaha/base/timer.h @@ -46,13 +46,12 @@ class LowResTimer { bool IsRunning() const { return running_; } private: - bool running_; - uint32 start_; - uint32 elapsed_; uint32 iterations_; + uint32 elapsed_; + uint32 start_; - DISALLOW_EVIL_CONSTRUCTORS(LowResTimer); + DISALLOW_COPY_AND_ASSIGN(LowResTimer); }; inline double LowResTimer::GetSeconds() const { @@ -108,15 +107,15 @@ class Timer { #endif private: - bool running_; + uint32 iterations_; + time64 elapsed_; time64 start_; time64 split_; - time64 elapsed_; - uint32 iterations_; + static time64 count_freq_; - DISALLOW_EVIL_CONSTRUCTORS(Timer); + DISALLOW_COPY_AND_ASSIGN(Timer); }; // lint -e{31} Redefinition of symbol @@ -143,42 +142,6 @@ inline time64 Timer::Get100Nanoseconds() const { return (time64) GetNanoseconds() / 100; } -// Helper class which starts the timer in its constructor and stops it -// in its destructor. This prevents accidentally leaving the timer running -// if a function has an early exit. -// -// Usage: -// -// class A { -// Timer timer_; -// -// void foo(){ -// TimerScope (timer_); -// ...... -// } // end foo -// -// Everything is timed till the end of the function or when it returns -// from any place. - -class TimerScope { - public: - explicit TimerScope(Timer *timer) : timer_(timer) { - if (timer_) { - timer_->Start(); - } - } - - ~TimerScope() { - if (timer_ && timer_->IsRunning()) { - timer_->Stop(); - } - } - - private: - Timer *timer_; - DISALLOW_EVIL_CONSTRUCTORS(TimerScope); -}; - } // namespace omaha #endif // OMAHA_BASE_TIMER_H_ diff --git a/omaha/base/type_utils.h b/omaha/base/type_utils.h deleted file mode 100644 index edbd286..0000000 --- a/omaha/base/type_utils.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_COMMON_TYPE_UTILS_H_ -#define OMAHA_COMMON_TYPE_UTILS_H_ - -namespace omaha { - -// -// Detecting convertibility and inheritence at compile time -// (Extracted from: Modern C++ Design) -// - -// Evaluates true if U inherites from T publically, or if T and U are same type -#define SUPERSUBCLASS(T, U) \ - (ConversionUtil::exists && \ - !ConversionUtil::same_type) - -// Evaluates true only if U inherites from T publically -#define SUPERSUBCLASS_STRICT(T, U) \ - (SUPERSUBCLASS(T, U) && \ - !ConversionUtil::same_type) - -// Perform type test -template -class ConversionUtil { - private: - typedef char Small; - class Big { - char dummy[2]; - }; - static Small Test(U); - static Big Test(...); - static T MakeT(); - - public: - // Tell whether there is ConversionUtil from T to U - enum { exists = sizeof(Test(MakeT())) == sizeof(Small) }; - - // Tells whether there are ConversionUtils between T and U in both directions - enum { exists_2way = exists && ConversionUtil::exists }; - - // Tells whether there are same type - enum { same_type = false }; -}; - -// Perform same type test through partial template specialization -template -class ConversionUtil { - public: - enum { exists = 1, exists_2way = 1, same_type = 1 }; -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_TYPE_UTILS_H_ diff --git a/omaha/base/user_info.cc b/omaha/base/user_info.cc index c526bc1..c34f87e 100644 --- a/omaha/base/user_info.cc +++ b/omaha/base/user_info.cc @@ -22,12 +22,12 @@ #include #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/utils.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/base/user_info_unittest.cc b/omaha/base/user_info_unittest.cc index 0217717..5452f78 100644 --- a/omaha/base/user_info_unittest.cc +++ b/omaha/base/user_info_unittest.cc @@ -14,10 +14,10 @@ // ======================================================================== #include "omaha/base/constants.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scoped_impersonation.h" #include "omaha/base/user_info.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" // We can't make any assumption about the context the unit test runs, however // we expect the calls to succeed. diff --git a/omaha/base/user_rights.cc b/omaha/base/user_rights.cc index 4526e92..372c580 100644 --- a/omaha/base/user_rights.cc +++ b/omaha/base/user_rights.cc @@ -16,39 +16,23 @@ #include "omaha/base/user_rights.h" #include #include -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/system_info.h" #include "omaha/base/vistautil.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { -bool UserRights::TokenIsAdmin(HANDLE token) { - return BelongsToGroup(token, DOMAIN_ALIAS_RID_ADMINS); -} - -bool UserRights::UserIsAdmin() { - return BelongsToGroup(NULL, DOMAIN_ALIAS_RID_ADMINS); -} +namespace { -bool UserRights::UserIsUser() { - return BelongsToGroup(NULL, DOMAIN_ALIAS_RID_USERS); -} - -bool UserRights::UserIsPowerUser() { - return BelongsToGroup(NULL, DOMAIN_ALIAS_RID_POWER_USERS); -} - -bool UserRights::UserIsGuest() { - return BelongsToGroup(NULL, DOMAIN_ALIAS_RID_GUESTS); -} - -bool UserRights::BelongsToGroup(HANDLE token, int group_id) { +// Returns true if the owner of the current process is the primary logon token +// for the current interactive session: console, terminal services, or fast +// user switching. +static bool BelongsToGroup(HANDLE token, int group_id) { SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY; PSID group = NULL; @@ -72,28 +56,10 @@ bool UserRights::BelongsToGroup(HANDLE token, int group_id) { return !!check; } -bool UserRights::UserIsRestricted() { - scoped_handle token; - if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, address(token))) { - UTIL_LOG(LE, (_T("[UserRights::UserIsRestricted - OpenProcessToken failed]") - _T("[0x%08x]"), HRESULTFromLastError())); - return true; - } +} // namespace - return !!::IsTokenRestricted(get(token)); -} - -bool UserRights::UserIsLowOrUntrustedIntegrity() { - if (SystemInfo::IsRunningOnVistaOrLater()) { - MANDATORY_LEVEL integrity_level = MandatoryLevelUntrusted; - if (FAILED(vista_util::GetProcessIntegrityLevel(0, &integrity_level)) || - integrity_level == MandatoryLevelUntrusted || - integrity_level == MandatoryLevelLow) { - return true; - } - } - - return false; +bool UserRights::TokenIsAdmin(HANDLE token) { + return BelongsToGroup(token, DOMAIN_ALIAS_RID_ADMINS); } HRESULT UserRights::UserIsLoggedOnInteractively(bool* is_logged_on) { diff --git a/omaha/base/user_rights.h b/omaha/base/user_rights.h index 01aefd6..5f2a18c 100644 --- a/omaha/base/user_rights.h +++ b/omaha/base/user_rights.h @@ -31,25 +31,6 @@ class UserRights { // Returns true if token is a member of the local Administrators group. static bool TokenIsAdmin(HANDLE token); - // Returns true if the user belongs to the local Administrators group. - static bool UserIsAdmin(); - - // Returns true if the user belongs to the Users group. - static bool UserIsUser(); - - // Returns true if the user belongs to the Power User group. - static bool UserIsPowerUser(); - - // Returns true if the user is a Guest. - static bool UserIsGuest(); - - // Returns true if the owner of the current process has a restricted token. - static bool UserIsRestricted(); - - // Returns true if the owner of the current process runs under low or - // untrusted integrity on Vista. - static bool UserIsLowOrUntrustedIntegrity(); - // Returns true if the owner of the current process has an interactive // session: console, terminal services, or fast user switching. static HRESULT UserIsLoggedOnInteractively(bool* is_logged_on); @@ -62,11 +43,6 @@ class UserRights { static bool VerifyCallerIsSystem(); - // Returns true if the owner of the current process is the primary logon token - // for the current interactive session: console, terminal services, or fast - // user switching. - static bool BelongsToGroup(HANDLE token, int group_id); - private: DISALLOW_IMPLICIT_CONSTRUCTORS(UserRights); }; diff --git a/omaha/base/utils.cc b/omaha/base/utils.cc index 48a0409..322d586 100644 --- a/omaha/base/utils.cc +++ b/omaha/base/utils.cc @@ -14,6 +14,7 @@ // ======================================================================== #include "omaha/base/utils.h" + #include #include #include @@ -22,25 +23,21 @@ #include #include #include +#include +#include #include #include -#include "base/basictypes.h" -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" #include "omaha/base/const_addresses.h" #include "omaha/base/const_config.h" #include "omaha/base/const_timeouts.h" #include "omaha/base/const_object_names.h" -#include "omaha/base/debug.h" -#include "omaha/base/error.h" #include "omaha/base/file.h" -#include "omaha/base/logging.h" #include "omaha/base/process.h" -#include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" #include "omaha/base/shell.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/system_info.h" @@ -136,7 +133,7 @@ ULONGLONG VersionFromString(const CString& s) { quad[i] = static_cast(quad_value); - if (kuint16max < quad[i]) { + if (std::numeric_limits::max() < quad[i]) { return 0; } } @@ -1038,13 +1035,13 @@ class BasicMessageHandlerInternal : public BasicMessageHandler, BasicMessageHandler::Process(msg); } private: - DISALLOW_EVIL_CONSTRUCTORS(BasicMessageHandlerInternal); + DISALLOW_COPY_AND_ASSIGN(BasicMessageHandlerInternal); }; bool WaitWithMessageLoopAny(const std::vector& handles, uint32* pos) { BasicMessageHandlerInternal msg_handler; - ASSERT1(handles.size() <= kuint32max); + ASSERT1(handles.size() <= std::numeric_limits::max()); return WaitWithMessageLoopAnyInternal(&handles.front(), static_cast(handles.size()), pos, @@ -1110,7 +1107,7 @@ void MessageLoopWithWait::set_message_handler( HRESULT MessageLoopWithWait::Process() { while (true) { ASSERT1(callback_handles_.size() == callbacks_.size()); - ASSERT1(callback_handles_.size() <= kuint32max); + ASSERT1(callback_handles_.size() <= std::numeric_limits::max()); // The implementation allows for an empty array of handles. Taking the // address of elements in an empty container is not allowed so we must @@ -1152,7 +1149,7 @@ void MessageLoopWithWait::Process(MSG* msg, const HANDLE** handles, // Set the handles and count again because they may have changed // while processing the message. - ASSERT1(callback_handles_.size() <= kuint32max); + ASSERT1(callback_handles_.size() <= std::numeric_limits::max()); *handles = callback_handles_.empty() ? NULL : &callback_handles_.front(); *cnt = static_cast(callback_handles_.size()); @@ -1392,7 +1389,7 @@ HRESULT WriteEntireFile(const TCHAR * filepath, const std::vector& buffer_in) { ASSERT1(filepath); - if (buffer_in.size() > kuint32max) { + if (buffer_in.size() > std::numeric_limits::max()) { return E_INVALIDARG; } @@ -1432,84 +1429,6 @@ HRESULT WriteEntireFile(const TCHAR * filepath, return S_OK; } -// Conversions between a byte stream and a std::string -HRESULT BufferToString(const std::vector& buffer_in, CStringA* str_out) { - ASSERT1(str_out); - - if (buffer_in.size() > INT_MAX) { - return E_INVALIDARG; - } - - str_out->Append(reinterpret_cast(&buffer_in.front()), - static_cast(buffer_in.size())); - return S_OK; -} - -HRESULT StringToBuffer(const CStringA& str_in, std::vector* buffer_out) { - ASSERT1(buffer_out); - buffer_out->assign(str_in.GetString(), - str_in.GetString() + str_in.GetLength()); - return S_OK; -} - -HRESULT BufferToString(const std::vector& buffer_in, CString* str_out) { - ASSERT1(str_out); - - const size_t len2 = buffer_in.size(); - ASSERT1(len2 % 2 == 0); - const size_t len = len2 / 2; - - if (len > INT_MAX) { - return E_INVALIDARG; - } - - str_out->Append(reinterpret_cast(&buffer_in.front()), - static_cast(len)); - - return S_OK; -} - -HRESULT StringToBuffer(const CString& str_in, std::vector* buffer_out) { - ASSERT1(buffer_out); - - size_t len = str_in.GetLength(); - size_t len2 = len * 2; - - buffer_out->resize(len2); - ::memcpy(&buffer_out->front(), str_in.GetString(), len2); - - return S_OK; -} - -HRESULT RegSplitKeyvalueName(const CString& keyvalue_name, - CString* key_name, - CString* value_name) { - ASSERT1(key_name); - ASSERT1(value_name); - - const TCHAR kDefault[] = _T("\\(default)"); - - if (String_EndsWith(keyvalue_name, _T("\\"), false)) { - key_name->SetString(keyvalue_name, keyvalue_name.GetLength() - 1); - value_name->Empty(); - } else if (String_EndsWith(keyvalue_name, kDefault, true)) { - key_name->SetString(keyvalue_name, - keyvalue_name.GetLength() - TSTR_SIZE(kDefault)); - value_name->Empty(); - } else { - int last_slash = String_ReverseFindChar(keyvalue_name, _T('\\')); - if (last_slash == -1) { - // No slash found - bizzare and wrong - return E_FAIL; - } - key_name->SetString(keyvalue_name, last_slash); - value_name->SetString(keyvalue_name.GetString() + last_slash + 1, - keyvalue_name.GetLength() - last_slash - 1); - } - - return S_OK; -} - HRESULT ExpandEnvLikeStrings(const TCHAR* src, const std::map& keywords, CString* dest) { @@ -1913,33 +1832,6 @@ bool IsClickOnceDisabled() { return policy == URLPOLICY_DISALLOW; } -// This function only uses kernel32, and it is safe to call from DllMain. -HRESULT PinModuleIntoProcess(const CString& module_name) { - ASSERT1(!module_name.IsEmpty()); - static HMODULE module_handle = NULL; - typedef BOOL (WINAPI *Fun)(DWORD flags, - LPCWSTR module_name, - HMODULE* module_handle); - - HINSTANCE kernel_instance = ::GetModuleHandle(_T("kernel32.dll")); - ASSERT1(kernel_instance); - Fun pfn = NULL; - if (GPA(kernel_instance, "GetModuleHandleExW", &pfn)) { - if ((*pfn)(GET_MODULE_HANDLE_EX_FLAG_PIN, module_name, &module_handle)) { - return S_OK; - } - ASSERT(false, (_T("GetModuleHandleExW() failed: %d"), ::GetLastError())); - } - - module_handle = ::LoadLibrary(module_name); - ASSERT(NULL != module_handle, (_T("LoadLibrary fail: %d"), ::GetLastError())); - if (NULL == module_handle) { - return HRESULTFromLastError(); - } - - return S_OK; -} - bool ShellExecuteExEnsureParent(LPSHELLEXECUTEINFO shell_exec_info) { UTIL_LOG(L3, (_T("[ShellExecuteExEnsureParent]"))); diff --git a/omaha/base/utils.h b/omaha/base/utils.h index d6d0256..2296009 100644 --- a/omaha/base/utils.h +++ b/omaha/base/utils.h @@ -32,11 +32,12 @@ #include "base/basictypes.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" +#include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/static_assert.h" #include "omaha/base/user_info.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -164,7 +165,8 @@ bool GPA(HMODULE module, const char* function_name, T* function_pointer) { *function_pointer = reinterpret_cast(::GetProcAddress(module, function_name)); if (NULL == *function_pointer) { - UTIL_LOG(LW, (_T("[GetProcAddress failed %s]"), CA2T(function_name))); + UTIL_LOG(LW, (_T("[GetProcAddress failed %s]"), + static_cast(CA2T(function_name)))); } return NULL != *function_pointer; } @@ -195,14 +197,6 @@ GPA_WRAP(RasApi32.dll, DWORD, ERROR_MOD_NOT_FOUND); -GPA_WRAP(kernel32.dll, - AttachConsole, - (DWORD process_id), - (process_id), - WINAPI, - BOOL, - 0); - // Private Object Namespaces for Vista and above. More information here: // http://msdn2.microsoft.com/en-us/library/ms684295(VS.85).aspx GPA_WRAP(kernel32.dll, @@ -234,10 +228,16 @@ GPA_WRAP(kernel32.dll, HANDLE, NULL); -bool IsPrivateNamespaceAvailable(); - +// SHGetKnownFolderPath is only available in Vista and above. +GPA_WRAP(shell32.dll, + SHGetKnownFolderPath, + (REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR* path), + (rfid, flags, token, path), + WINAPI, + HRESULT, + HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND)); -HRESULT PinModuleIntoProcess(const CString& module_name); +bool IsPrivateNamespaceAvailable(); // Creates a directory with default security. // S_OK: Created directory @@ -554,7 +554,7 @@ class BasicMessageHandler : public MessageHandlerInterface { BasicMessageHandler() {} virtual void Process(MSG* msg); private: - DISALLOW_EVIL_CONSTRUCTORS(BasicMessageHandler); + DISALLOW_COPY_AND_ASSIGN(BasicMessageHandler); }; // An internal detail (used to handle messages @@ -641,7 +641,7 @@ class MessageLoopWithWait : public MessageLoopInterface, // What to call when a handle is signaled. std::vector callbacks_; - DISALLOW_EVIL_CONSTRUCTORS(MessageLoopWithWait); + DISALLOW_COPY_AND_ASSIGN(MessageLoopWithWait); }; // This function calls ::SetDefaultDllDirectories to retrict DLL loads to either @@ -708,18 +708,6 @@ HRESULT ReadEntireFileShareMode(const TCHAR* filepath, HRESULT WriteEntireFile(const TCHAR * filepath, const std::vector& buffer_in); -// Conversions between a byte stream and a std::string -HRESULT BufferToString(const std::vector& buffer_in, CStringA* str_out); -HRESULT BufferToString(const std::vector& buffer_in, CString* str_out); -HRESULT StringToBuffer(const CStringA& str_in, std::vector* buffer_out); -HRESULT StringToBuffer(const CString& str_in, std::vector* buffer_out); - -// Splits a "full regkey name" into a key name part and a value name part. -// Handles "(default)" as a value name. Treats a trailing "/" as "(default)". -HRESULT RegSplitKeyvalueName(const CString& keyvalue_name, - CString* key_name, - CString* value_name); - // Expands string with embedded special variables which are enclosed // in '%' pair. For example, "%PROGRAMFILES%\Google" expands to // "C:\Program Files\Google". @@ -788,7 +776,7 @@ class CallInterceptor { private: R* interceptor_; - DISALLOW_EVIL_CONSTRUCTORS(CallInterceptor); + DISALLOW_COPY_AND_ASSIGN(CallInterceptor); }; // Gets a handle of the current process. The handle is a real handle diff --git a/omaha/base/utils_unittest.cc b/omaha/base/utils_unittest.cc index 42cffe3..00d0e32 100644 --- a/omaha/base/utils_unittest.cc +++ b/omaha/base/utils_unittest.cc @@ -18,22 +18,23 @@ #include #include #include +#include "base/rand_util.h" #include "omaha/base/app_util.h" #include "omaha/base/atl_regexp.h" #include "omaha/base/constants.h" #include "omaha/base/dynamic_link_kernel32.h" #include "omaha/base/file.h" #include "omaha/base/path.h" -#include "base/rand_util.h" +#include "omaha/base/reg_key.h" #include "omaha/base/shell.h" #include "omaha/base/string.h" #include "omaha/base/time.h" #include "omaha/base/user_info.h" #include "omaha/base/utils.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/system_info.h" #include "omaha/base/vistautil.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -152,27 +153,6 @@ TEST(UtilsTest, ReadEntireFile) { // TEST(UtilsTest, WriteEntireFile) { // } -TEST(UtilsTest, RegSplitKeyvalueName) { - CString key_name, value_name; - ASSERT_SUCCEEDED(RegSplitKeyvalueName(CString(L"HKLM\\Foo\\"), - &key_name, - &value_name)); - ASSERT_STREQ(key_name, L"HKLM\\Foo"); - ASSERT_TRUE(value_name.IsEmpty()); - - ASSERT_SUCCEEDED(RegSplitKeyvalueName(CString(L"HKLM\\Foo\\(default)"), - &key_name, - &value_name)); - ASSERT_STREQ(key_name, L"HKLM\\Foo"); - ASSERT_TRUE(value_name.IsEmpty()); - - ASSERT_SUCCEEDED(RegSplitKeyvalueName(CString(L"HKLM\\Foo\\Bar"), - &key_name, - &value_name)); - ASSERT_STREQ(key_name, L"HKLM\\Foo"); - ASSERT_STREQ(value_name, L"Bar"); -} - TEST(UtilsTest, ExpandEnvLikeStrings) { std::map mapping; ASSERT_SUCCEEDED(Shell::GetSpecialFolderKeywordsMapping(&mapping)); @@ -376,7 +356,7 @@ class Counter { static int instance_count() { return instance_count_; } private: static int instance_count_; - DISALLOW_EVIL_CONSTRUCTORS(Counter); + DISALLOW_COPY_AND_ASSIGN(Counter); }; int Counter::instance_count_ = 0; @@ -452,31 +432,6 @@ TEST(UtilsTest, InvalidPath) { EXPECT_TRUE(exe_path.IsEmpty()); } -TEST(UtilsTest, PinModuleIntoProcess) { - const TCHAR module_name[] = _T("icmp.dll"); - const void* kNullModule = NULL; - - // The module should not be loaded at this time. - EXPECT_EQ(kNullModule, ::GetModuleHandle(module_name)); - - // Loads and unloads the module. - { - scoped_library module(::LoadLibrary(module_name)); - EXPECT_TRUE(module); - EXPECT_NE(kNullModule, ::GetModuleHandle(module_name)); - } - EXPECT_EQ(kNullModule, ::GetModuleHandle(module_name)); - - // Loads, pins, and unloads the module. - { - scoped_library module(::LoadLibrary(module_name)); - EXPECT_TRUE(module); - EXPECT_NE(kNullModule, ::GetModuleHandle(module_name)); - PinModuleIntoProcess(module_name); - } - EXPECT_NE(kNullModule, ::GetModuleHandle(module_name)); -} - // Assumes Windows is installed on the C: drive. TEST(UtilsTest, GetEnvironmentVariableAsString) { EXPECT_STREQ(_T("C:"), GetEnvironmentVariableAsString(_T("SystemDrive"))); @@ -630,45 +585,66 @@ TEST(UtilsTest, AddAllowedAce) { EXPECT_TRUE(AtlGetDacl(test_file_path, SE_FILE_OBJECT, &dacl)); EXPECT_EQ(original_ace_count + 2, dacl.GetAceCount()); - // TODO(omaha): An assert occurs because the ACE flags are being used on a - // file object. Add a new test to use a registry key. - ExpectAsserts expect_asserts; + EXPECT_SUCCEEDED(File::Remove(test_file_path)); +} + +TEST(UtilsTest, AddAllowedAceRegistry) { + const CString object_name = _T("CURRENT_USER\\SOFTWARE\\") GOOPDATE_MAIN_KEY + _T("AddAllowedAceRegistryTest"); + + // The registry and DACL security APIs expect different prefixes for the + // registry hives. + CString registry_key_name = object_name; + registry_key_name.Replace(_T("CURRENT_USER"), _T("HKCU")); + EXPECT_SUCCEEDED(RegKey::CreateKey(registry_key_name)); + + CDacl dacl; + EXPECT_TRUE(AtlGetDacl(object_name, SE_REGISTRY_KEY, &dacl)); + const int original_ace_count = dacl.GetAceCount(); + + // Add more access. An ACE is added. + EXPECT_SUCCEEDED(AddAllowedAce(object_name, + SE_REGISTRY_KEY, + Sids::Dialup(), + KEY_ALL_ACCESS, + 0)); + dacl.SetEmpty(); + EXPECT_TRUE(AtlGetDacl(object_name, SE_REGISTRY_KEY, &dacl)); + EXPECT_EQ(original_ace_count + 1, dacl.GetAceCount()); // Different ACE flags. An ACE is added. const BYTE kTestAce = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE; const BYTE kTestAceSubset = CONTAINER_INHERIT_ACE; - EXPECT_SUCCEEDED(AddAllowedAce(test_file_path, - SE_FILE_OBJECT, + EXPECT_SUCCEEDED(AddAllowedAce(object_name, + SE_REGISTRY_KEY, Sids::Dialup(), - FILE_ALL_ACCESS, + KEY_ALL_ACCESS, kTestAce)); dacl.SetEmpty(); - EXPECT_TRUE(AtlGetDacl(test_file_path, SE_FILE_OBJECT, &dacl)); - EXPECT_EQ(original_ace_count + 3, dacl.GetAceCount()); + EXPECT_TRUE(AtlGetDacl(object_name, SE_REGISTRY_KEY, &dacl)); + EXPECT_EQ(original_ace_count + 2, dacl.GetAceCount()); // Subset of existing ACE flags. An ACE is added because flags must be exact. - EXPECT_SUCCEEDED(AddAllowedAce(test_file_path, - SE_FILE_OBJECT, + EXPECT_SUCCEEDED(AddAllowedAce(object_name, + SE_REGISTRY_KEY, Sids::Dialup(), - FILE_ALL_ACCESS, + KEY_ALL_ACCESS, kTestAceSubset)); dacl.SetEmpty(); - EXPECT_TRUE(AtlGetDacl(test_file_path, SE_FILE_OBJECT, &dacl)); - EXPECT_EQ(original_ace_count + 4, dacl.GetAceCount()); + EXPECT_TRUE(AtlGetDacl(object_name, SE_REGISTRY_KEY, &dacl)); + EXPECT_EQ(original_ace_count + 3, dacl.GetAceCount()); // Same flags. An ACE should not be added because all values match. - // TODO(omaha): This does not work, possibly because the object is a file. - // Try the test using a registry key. - EXPECT_SUCCEEDED(AddAllowedAce(test_file_path, - SE_FILE_OBJECT, + EXPECT_SUCCEEDED(AddAllowedAce(object_name, + SE_REGISTRY_KEY, Sids::Dialup(), - FILE_ALL_ACCESS, + KEY_ALL_ACCESS, kTestAceSubset)); dacl.SetEmpty(); - EXPECT_TRUE(AtlGetDacl(test_file_path, SE_FILE_OBJECT, &dacl)); - EXPECT_EQ(original_ace_count + 5, dacl.GetAceCount()); + EXPECT_TRUE(AtlGetDacl(object_name, SE_REGISTRY_KEY, &dacl)); + EXPECT_EQ(original_ace_count + 3, dacl.GetAceCount()); - EXPECT_SUCCEEDED(File::Remove(test_file_path)); + EXPECT_SUCCEEDED(RegKey::DeleteKey(registry_key_name)); } TEST(UtilsTest, CreateForegroundParentWindowForUAC) { diff --git a/omaha/base/vista_utils.cc b/omaha/base/vista_utils.cc index e921209..e623bd3 100644 --- a/omaha/base/vista_utils.cc +++ b/omaha/base/vista_utils.cc @@ -15,8 +15,9 @@ #include "omaha/base/vista_utils.h" +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/browser_utils.h" #include "omaha/base/commontypes.h" #include "omaha/base/const_utils.h" @@ -27,7 +28,6 @@ #include "omaha/base/process.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/smart_handle.h" #include "omaha/base/synchronized.h" #include "omaha/base/system.h" @@ -35,6 +35,7 @@ #include "omaha/base/user_info.h" #include "omaha/base/user_rights.h" #include "omaha/base/utils.h" +#include "omaha/third_party/smartany/scoped_any.h" #define LOW_INTEGRITY_SID_W NOTRANSL(L"S-1-16-4096") @@ -145,7 +146,7 @@ bool IsProcessProtected() { return false; } - scoped_ptr integration_level; + std::unique_ptr integration_level; integration_level.reset(reinterpret_cast( new char[length_needed])); @@ -185,104 +186,6 @@ HRESULT RunAsCurrentUser(const CString& command_line, child_stdout, process); } -static HRESULT StartInternetExplorerAsUser(HANDLE user_token, - const CString& options) { - // Internet Explorer path - CString ie_file_path; - HRESULT result = GetIEPath(&ie_file_path); - ASSERT1(SUCCEEDED(result)); - - if (SUCCEEDED(result)) { - CString command_line(ie_file_path); - command_line += _T(' '); - command_line += options; - UTIL_LOG(L5, (_T("[StartInternetExplorerAsUser]") - _T("[Running IExplore with command line][%s]"), - command_line)); - result = RunAsUser(command_line, user_token, false, NULL, NULL); - } - return result; -} - -// -// Constants used by RestartIEUser() -// -// The IEUser executable name -const TCHAR* kIEUser = _T("IEUSER.EXE"); - -// The maximum number of simultaneous -// logged on users in FUS that we support -const int kMaximumUsers = 16; - - -// Restart IEUser processs. This is to allow for -// IEUser.exe to refresh it's ElevationPolicy cache. Due to a bug -// within IE7, IEUser.exe does not refresh it's cache unless it -// is restarted in the manner below. If the cache is not refreshed -// IEUser does not respect any new ElevationPolicies that a fresh -// setup program installs for an ActiveX control or BHO. This code -// is adapted from Toolbar. -HRESULT RestartIEUser() { - // Use the service to restart IEUser. - // This allows us to restart IEUser for: - // (a) Multiple users for the first-install case - // (we currently only restart IEUser for the current interactive user) - // (b) Even if we are started in an elevated mode - - if (!SystemInfo::IsRunningOnVistaOrLater()) { - UTIL_LOG(L5, (_T("[RestartIEUser - not running on Vista - Exiting]"))); - return S_OK; - } - - // The restart should be attempted from the system account - bool is_system_process = false; - if (FAILED(IsSystemProcess(&is_system_process)) || !is_system_process) { - ASSERT1(false); - return E_ACCESSDENIED; - } - - // Get the list of users currently running IEUser.exe processes. - scoped_handle ieuser_users[kMaximumUsers]; - int number_of_users = 0; - Process::GetUsersOfProcesses(kIEUser, kMaximumUsers, ieuser_users, - &number_of_users); - - UTIL_LOG(L5, (_T("[RestartIEUser]") - _T("[number_of_users running IEUser %d]"), number_of_users)); - - if (!number_of_users) { - UTIL_LOG(L5, (_T("[RestartIEUser][No IEUser processes running]"))); - return S_OK; - } - - // Kill current IEUser processes. - ProcessTerminator pt(kIEUser); - const int kKillWaitTimeoutMs = 5000; - bool found = false; - const int kill_method = (ProcessTerminator::KILL_METHOD_4_TERMINATE_PROCESS); - - RET_IF_FAILED(pt.KillTheProcess(kKillWaitTimeoutMs, - &found, - kill_method, - false)); - - // Restart them. - HRESULT result = S_OK; - for (int i = 0; i < number_of_users; i++) { - // To start a new ieuser.exe, simply start iexplore.exe as a normal user - // The -embedding prevents IE from opening a window - HRESULT restart_result = StartInternetExplorerAsUser(get(ieuser_users[i]), - _T("-embedding")); - if (FAILED(restart_result)) { - UTIL_LOG(LEVEL_ERROR, (_T("[StartInternetExplorerAsUser failed][0x%x]"), - restart_result)); - result = restart_result; - } - } - - return result; -} - HRESULT GetExplorerPidForCurrentUserOrSession(uint32* pid) { ASSERT1(pid); std::vector pids; @@ -298,65 +201,6 @@ HRESULT GetExplorerPidForCurrentUserOrSession(uint32* pid) { return S_OK; } -HRESULT GetExplorerTokenForLoggedInUser(HANDLE* token) { - UTIL_LOG(L3, (_T("[GetExplorerTokenForLoggedInUser]"))); - ASSERT1(token); - - // TODO(omaha): One can set the windows shell to be other than - // explorer.exe, handle this case. One way to handle this is to - // read the regkey - // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon - // The only problem with this is it can be overriden with the user reg keys. - // Need to figure out a method to do this. - // Also consider using the interactive user before picking the first explorer - // process i.e. the active user. - std::vector processes; - DWORD flags = EXCLUDE_CURRENT_PROCESS; - std::vector command_lines; - CString explorer_file_name(kExplorer); - CString user_sid; - - HRESULT hr = Process::FindProcesses(flags, - explorer_file_name, - true, - user_sid, - command_lines, - &processes); - if (FAILED(hr)) { - CORE_LOG(LEVEL_ERROR, (_T("[FindProcesses failed][0x%08x]"), hr)); - return hr; - } - - std::vector::const_iterator iter = processes.begin(); - for (; iter != processes.end(); ++iter) { - uint32 explorer_pid = *iter; - scoped_handle exp(::OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, - false, - explorer_pid)); - if (exp) { - if (::OpenProcessToken(get(exp), - TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_IMPERSONATE, - token)) { - // TODO(omaha): Consider using the GetWindowsAccountDomainSid - // method here. This method returns the domain SID associated - // with the passed in SID. This allows us to detect if the user is a - // domain user. We should prefer domain users over normal users, - // as in corporate environments, these users will be more likely to - // allow to be tunneled through a proxy. - return S_OK; - } else { - hr = HRESULTFromLastError(); - CORE_LOG(LEVEL_WARNING, (_T("[OpenProcessToken failed][0x%08x]"), hr)); - } - } else { - hr = HRESULTFromLastError(); - CORE_LOG(LEVEL_WARNING, (_T("[OpenProcess failed][0x%08x]"), hr)); - } - } - - return hr; -} - HRESULT GetPidsInSession(const TCHAR* exe_name, const TCHAR* user_sid, DWORD session_id, @@ -424,35 +268,6 @@ HRESULT GetProcessPidsForActiveUserOrSession(const TCHAR* exe_name, return S_OK; } - - -HRESULT StartProcessWithTokenOfProcess(uint32 pid, - const CString& command_line) { - UTIL_LOG(L5, (_T("[StartProcessWithTokenOfProcess]") - _T("[pid %u][command_line '%s']"), pid, command_line)); - - // Get the token from process. - scoped_handle user_token; - HRESULT hr = Process::GetImpersonationToken(pid, address(user_token)); - if (FAILED(hr)) { - CORE_LOG(LEVEL_ERROR, (_T("[GetImpersonationToken failed][0x%08x]"), hr)); - return hr; - } - - // Start process using the token. - UTIL_LOG(L5, (_T("[StartProcessWithTokenOfProcess][Running process %s]"), - command_line)); - hr = RunAsUser(command_line, get(user_token), false, NULL, NULL); - - if (FAILED(hr)) { - UTIL_LOG(LEVEL_ERROR, - (_T("[Vista::StartProcessWithTokenOfProcess - RunAsUser failed][0x%x]"), - hr)); - } - - return hr; -} - HRESULT GetLoggedOnUserToken(HANDLE* token) { ASSERT1(token); *token = NULL; diff --git a/omaha/base/vista_utils.h b/omaha/base/vista_utils.h index b068e3b..7ea8d39 100644 --- a/omaha/base/vista_utils.h +++ b/omaha/base/vista_utils.h @@ -42,15 +42,6 @@ bool IsProcessProtected(); // error value. HRESULT AllowProtectedProcessAccessToSharedObject(const TCHAR* name); -// Restarts IEUser process if we can. This is to allow for -// IEUser.exe to refresh it's ElevationPolicy cache. Due to a bug -// within IE7, IEUser.exe does not refresh it's cache unless it -// is restarted in the manner below. If the cache is not refreshed -// IEUser does not respect any new ElevationPolicies that a fresh -// setup program installs for an ActiveX control or BHO. This code -// is adapted from Toolbar. -HRESULT RestartIEUser(); - // TODO(Omaha): Move these to a different utils file, since these are not // Vista-specific. // TODO(Omaha): rename for consistency with @@ -60,9 +51,6 @@ HRESULT RestartIEUser(); // explorer.exe running in the current session. HRESULT GetExplorerPidForCurrentUserOrSession(uint32* pid); -// Returns the TOKEN of the explorer process of any user that is logged in. -HRESULT GetExplorerTokenForLoggedInUser(HANDLE* token); - // Retrieves a primary token for one of the logged on users. The logged on // user is either the current user or a user logged on in the same session as // the current user. The caller must close the token handle. @@ -88,10 +76,6 @@ HRESULT GetPidsInSession(const TCHAR* exe_name, HRESULT GetProcessPidsForActiveUserOrSession(const TCHAR* exe_name, std::vector* pids); -// Starts process with the token obtained from the specified process. -HRESULT StartProcessWithTokenOfProcess(uint32 pid, - const CString& command_line); - // Runs the command on behalf of the current user. Creates a fresh environment // block based on the user's token. If |process| and/or |child_stdout| are not // null, they will receive handles to the launched process and its output diff --git a/omaha/base/vista_utils_unittest.cc b/omaha/base/vista_utils_unittest.cc index bb7dcb6..b2956e4 100644 --- a/omaha/base/vista_utils_unittest.cc +++ b/omaha/base/vista_utils_unittest.cc @@ -16,42 +16,17 @@ #include #include "omaha/base/app_util.h" #include "omaha/base/path.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" #include "omaha/base/vista_utils.h" #include "omaha/base/vistautil.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { namespace vista { -// Exercises RunAsUser() with explorer token. For Vista, the call to -// StartProcessWithTokenOfProcess() will succeed only if the caller is SYSTEM. -TEST(VistaUtilsTest, StartProcessWithExplorerTokenTest) { - CString path = ConcatenatePath(app_util::GetSystemDir(), _T("cmd.exe")); - EnclosePath(&path); - path += _T(" /c exit 702"); - uint32 pid(0); - EXPECT_SUCCEEDED(GetExplorerPidForCurrentUserOrSession(&pid)); - - HRESULT hr = StartProcessWithTokenOfProcess(pid, path); - if (!vista_util::IsVistaOrLater()) { - EXPECT_SUCCEEDED(hr); - return; - } - - bool is_system = false; - EXPECT_SUCCEEDED(IsSystemProcess(&is_system)); - if (is_system) { - EXPECT_SUCCEEDED(hr); - return; - } - - EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_PRIVILEGE_NOT_HELD), hr); -} - // Exercises RunAsUser() with current user token. TEST(VistaUtilsTest, RunAsCurrentUserTest) { CString cmd_path = ConcatenatePath(app_util::GetSystemDir(), _T("cmd.exe")); diff --git a/omaha/base/vistautil.cc b/omaha/base/vistautil.cc index 4b0b4b4..13a539d 100644 --- a/omaha/base/vistautil.cc +++ b/omaha/base/vistautil.cc @@ -14,12 +14,14 @@ // ======================================================================== #include "omaha/base/vistautil.h" + #include #include #include #include #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -34,10 +36,22 @@ namespace omaha { namespace vista_util { +namespace { + +struct free_deleter{ + template + void operator()(T *p) const { + std::free(const_cast*>(p)); + } +}; + +template +using scoped_ptr_malloc = std::unique_ptr; +static_assert(sizeof(char *)==sizeof(scoped_ptr_malloc),""); + static SID_IDENTIFIER_AUTHORITY mandatory_label_auth = SECURITY_MANDATORY_LABEL_AUTHORITY; - static HRESULT GetSidIntegrityLevel(PSID sid, MANDATORY_LEVEL* level) { if (!IsValidSid(sid)) return E_FAIL; @@ -50,11 +64,11 @@ static HRESULT GetSidIntegrityLevel(PSID sid, MANDATORY_LEVEL* level) { sizeof(SID_IDENTIFIER_AUTHORITY))) return E_FAIL; - PUCHAR count = GetSidSubAuthorityCount(sid); + PUCHAR count = ::GetSidSubAuthorityCount(sid); if (!count || *count != 1) return E_FAIL; - DWORD* rid = GetSidSubAuthority(sid, 0); + DWORD* rid = ::GetSidSubAuthority(sid, 0); if (!rid) return E_FAIL; @@ -65,43 +79,47 @@ static HRESULT GetSidIntegrityLevel(PSID sid, MANDATORY_LEVEL* level) { return S_OK; } -// Will return S_FALSE and MandatoryLevelMedium if the acl is NULL -static HRESULT GetAclIntegrityLevel(PACL acl, MANDATORY_LEVEL* level, - bool* and_children) { - *level = MandatoryLevelMedium; - if (and_children) - *and_children = false; - if (!acl) { - // This is the default label value if the acl was empty - return S_FALSE; - } - - SYSTEM_MANDATORY_LABEL_ACE* mandatory_label_ace; - if (!GetAce(acl, 0, reinterpret_cast(&mandatory_label_ace))) - return S_FALSE; - - if (mandatory_label_ace->Header.AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) - return S_FALSE; +// Determine the mandatory level of a process +// processID, the process to query, or (0) to use the current process +// On Vista, level should alwys be filled in with either +// MandatoryLevelLow (IE) +// MandatoryLevelMedium(user), or +// MandatoryLevelHigh( Elevated Admin) +// On error, level remains unchanged +HRESULT GetProcessIntegrityLevel(DWORD process_id, MANDATORY_LEVEL* level) { + if (!IsVistaOrLater()) + return E_NOTIMPL; - if (!(mandatory_label_ace->Mask & SYSTEM_MANDATORY_LABEL_NO_WRITE_UP)) { - // I have found that if this flag is not set, a low integrity label doesn't - // prevent writes from being virtualized. MS provides zero documentation. - // I just did an MSDN search, a Google search, and a search of the Beta - // Vista SDKs, and no docs. TODO(omaha): Check docs again periodically. - // For now, act as if no label was set, and default to medium. - return S_FALSE; - } + if (process_id == 0) + process_id = ::GetCurrentProcessId(); - if (and_children) { - *and_children = ((mandatory_label_ace->Header.AceFlags & - (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE)) - == (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE)); + HRESULT result = E_FAIL; + HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id); + if (process != NULL) { + HANDLE current_token; + if (OpenProcessToken(process, + TOKEN_QUERY | TOKEN_QUERY_SOURCE, + ¤t_token)) { + DWORD label_size = 0; + TOKEN_MANDATORY_LABEL* label; + GetTokenInformation(current_token, TokenIntegrityLevel, + NULL, 0, &label_size); + if (label_size && (label = reinterpret_cast + (LocalAlloc(LPTR, label_size))) != NULL) { + if (GetTokenInformation(current_token, TokenIntegrityLevel, + label, label_size, &label_size)) { + result = GetSidIntegrityLevel(label->Label.Sid, level); + } + LocalFree(label); + } + CloseHandle(current_token); + } + CloseHandle(process); } - - return GetSidIntegrityLevel(reinterpret_cast(&mandatory_label_ace-> - SidStart), level); + return result; } +} // namespace // If successful, the caller needs to free the ACL using free(). // On failure, returns NULL. @@ -144,37 +162,6 @@ static ACL* CreateMandatoryLabelAcl(MANDATORY_LEVEL level, bool and_children) { return acl.release(); } - -TCHAR* AllocFullRegPath(HKEY root, const TCHAR* subkey) { - if (!subkey) - return NULL; - - const TCHAR* root_string; - - if (root == HKEY_CURRENT_USER) - root_string = _T("CURRENT_USER\\"); - else if (root == HKEY_LOCAL_MACHINE) - root_string = _T("MACHINE\\"); - else if (root == HKEY_CLASSES_ROOT) - root_string = _T("CLASSES_ROOT\\"); - else if (root == HKEY_USERS) - root_string = _T("USERS\\"); - else - return NULL; - - size_t root_size = _tcslen(root_string); - size_t size = root_size + _tcslen(subkey) + 1; - TCHAR* result = reinterpret_cast(LocalAlloc(LPTR, - size * sizeof(TCHAR))); - if (!result) - return NULL; - - memcpy(result, root_string, size * sizeof(TCHAR)); - memcpy(result + root_size, subkey, (1 + size - root_size) * sizeof(TCHAR)); - return result; -} - - bool IsUserNonElevatedAdmin() { // If pre-Vista return false; if (!IsVistaOrLater()) { @@ -285,7 +272,7 @@ HRESULT IsUACOn(bool* is_uac_on) { } MANDATORY_LEVEL integrity_level = MandatoryLevelUntrusted; - hr = vista_util::GetProcessIntegrityLevel(pid, &integrity_level); + hr = GetProcessIntegrityLevel(pid, &integrity_level); ASSERT(SUCCEEDED(hr), (_T("[%#x]"), hr)); if (FAILED(hr)) { return hr; @@ -366,188 +353,6 @@ HRESULT RunElevated(const TCHAR* file_path, return S_OK; } - -HRESULT GetProcessIntegrityLevel(DWORD process_id, MANDATORY_LEVEL* level) { - if (!IsVistaOrLater()) - return E_NOTIMPL; - - if (process_id == 0) - process_id = ::GetCurrentProcessId(); - - HRESULT result = E_FAIL; - HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id); - if (process != NULL) { - HANDLE current_token; - if (OpenProcessToken(process, - TOKEN_QUERY | TOKEN_QUERY_SOURCE, - ¤t_token)) { - DWORD label_size = 0; - TOKEN_MANDATORY_LABEL* label; - GetTokenInformation(current_token, TokenIntegrityLevel, - NULL, 0, &label_size); - if (label_size && (label = reinterpret_cast - (LocalAlloc(LPTR, label_size))) != NULL) { - if (GetTokenInformation(current_token, TokenIntegrityLevel, - label, label_size, &label_size)) { - result = GetSidIntegrityLevel(label->Label.Sid, level); - } - LocalFree(label); - } - CloseHandle(current_token); - } - CloseHandle(process); - } - return result; -} - - -HRESULT GetFileOrFolderIntegrityLevel(const TCHAR* file, - MANDATORY_LEVEL* level, bool* and_children) { - if (!IsVistaOrLater()) - return E_NOTIMPL; - - PSECURITY_DESCRIPTOR descriptor; - PACL acl = NULL; - - DWORD result = GetNamedSecurityInfo(const_cast(file), SE_FILE_OBJECT, - LABEL_SECURITY_INFORMATION, NULL, NULL, NULL, &acl, &descriptor); - if (result != ERROR_SUCCESS) - return HRESULT_FROM_WIN32(result); - - HRESULT hr = GetAclIntegrityLevel(acl, level, and_children); - LocalFree(descriptor); - return hr; -} - - -HRESULT SetFileOrFolderIntegrityLevel(const TCHAR* file, - MANDATORY_LEVEL level, bool and_children) { - if (!IsVistaOrLater()) - return E_NOTIMPL; - - scoped_ptr_malloc acl(CreateMandatoryLabelAcl(level, and_children)); - if (!acl.get()) { - return HRESULTFromLastError(); - } - - DWORD result = SetNamedSecurityInfo(const_cast(file), SE_FILE_OBJECT, - LABEL_SECURITY_INFORMATION, NULL, NULL, NULL, acl.get()); - return HRESULT_FROM_WIN32(result); -} - - -HRESULT GetRegKeyIntegrityLevel(HKEY root, const TCHAR* subkey, - MANDATORY_LEVEL* level, bool* and_children) { - if (!IsVistaOrLater()) - return E_NOTIMPL; - - TCHAR* reg_path = AllocFullRegPath(root, subkey); - if (!reg_path) - return E_FAIL; - - PSECURITY_DESCRIPTOR descriptor; - PACL acl = NULL; - - DWORD result = GetNamedSecurityInfo(reg_path, SE_REGISTRY_KEY, - LABEL_SECURITY_INFORMATION, NULL, NULL, NULL, &acl, &descriptor); - if (result != ERROR_SUCCESS) { - LocalFree(reg_path); - return HRESULT_FROM_WIN32(result); - } - - HRESULT hr = GetAclIntegrityLevel(acl, level, and_children); - LocalFree(descriptor); - LocalFree(reg_path); - return hr; -} - - -HRESULT SetRegKeyIntegrityLevel(HKEY root, const TCHAR* subkey, - MANDATORY_LEVEL level, bool and_children) { - if (!IsVistaOrLater()) - return E_NOTIMPL; - - TCHAR* reg_path = AllocFullRegPath(root, subkey); - if (!reg_path) - return E_FAIL; - - scoped_ptr_malloc acl(CreateMandatoryLabelAcl(level, and_children)); - if (!acl.get()) { - HRESULT hr = HRESULTFromLastError(); - LocalFree(reg_path); - return hr; - } - - DWORD result = SetNamedSecurityInfo(reg_path, SE_REGISTRY_KEY, - LABEL_SECURITY_INFORMATION, NULL, NULL, NULL, acl.get()); - LocalFree(reg_path); - return HRESULT_FROM_WIN32(result); -} - - -CSecurityDesc* BuildSecurityDescriptor(MANDATORY_LEVEL level, - ACCESS_MASK mask) { - if (!IsVistaOrLater()) { - return NULL; - } - - scoped_ptr security_descriptor(new CSecurityDesc); - HRESULT hr = vista_util::SetMandatorySacl(level, security_descriptor.get()); - if (FAILED(hr)) { - return NULL; - } - - - // Fill out the rest of the security descriptor from the process token. - CAccessToken token; - if (!token.GetProcessToken(TOKEN_QUERY)) { - return NULL; - } - - // The owner. - CSid sid_owner; - if (!token.GetOwner(&sid_owner)) { - return NULL; - } - security_descriptor->SetOwner(sid_owner); - - // The group. - CSid sid_group; - if (!token.GetPrimaryGroup(&sid_group)) { - return NULL; - } - security_descriptor->SetGroup(sid_group); - - // The discretionary access control list. - CDacl dacl; - if (!token.GetDefaultDacl(&dacl)) { - return NULL; - } - - // Add an access control entry mask for the current user. - // This is what grants this user access from lower integrity levels. - CSid sid_user; - if (!token.GetUser(&sid_user)) { - return NULL; - } - - if (!dacl.AddAllowedAce(sid_user, mask)) { - return NULL; - } - - // Lastly, save the dacl to this descriptor. - security_descriptor->SetDacl(dacl); - return security_descriptor.release(); -} - -CSecurityDesc* CreateLowIntegritySecurityDesc(ACCESS_MASK mask) { - return BuildSecurityDescriptor(MandatoryLevelLow, mask); -} - -CSecurityDesc* CreateMediumIntegritySecurityDesc(ACCESS_MASK mask) { - return BuildSecurityDescriptor(MandatoryLevelMedium, mask); -} - HRESULT SetMandatorySacl(MANDATORY_LEVEL level, CSecurityDesc* sd) { ASSERT1(sd); diff --git a/omaha/base/vistautil.h b/omaha/base/vistautil.h index 8f5d303..5cfb8a5 100644 --- a/omaha/base/vistautil.h +++ b/omaha/base/vistautil.h @@ -97,27 +97,6 @@ bool IsUserAdmin(); // Vista. In case of XP always returns false. bool IsUserNonElevatedAdmin(); -// Determine the mandatory level of a process -// processID, the process to query, or (0) to use the current process -// On Vista, level should alwys be filled in with either -// MandatoryLevelLow (IE) -// MandatoryLevelMedium(user), or -// MandatoryLevelHigh( Elevated Admin) -// On error, level remains unchanged -HRESULT GetProcessIntegrityLevel(DWORD processID, MANDATORY_LEVEL* level); - -// Elevated processes need to be careful how they launch child processes -// to avoid having them inherit too many credentials or not being able to -// elevate their own IE processes normally. Microsoft's advice from -// http://msdn.microsoft.com/library/en-us/ietechcol/dnwebgen/protectedmode.asp -// will launch a low integrity IE, but that IE cannot elevate properly since -// it was running from the wrong token. The best method I can gather is to find -// an existing process on the machine running at normal user rights, and launch -// this process impersonating that token rather than trying to adjust token -// privileges of the elevated token. TODO(omaha): Implement and test this. -HRESULT CreateProcessAsNormalUserFromElevatedAdmin(const TCHAR* commandline, - STARTUPINFO* startup_info, PROCESS_INFORMATION* process_info); - // Starts a new elevated process. file_path specifies the program to be run. // If exit_code is not null, the function waits until the spawned process has // completed. The exit code of the process is returned therein. @@ -128,37 +107,6 @@ HRESULT CreateProcessAsNormalUserFromElevatedAdmin(const TCHAR* commandline, HRESULT RunElevated(const TCHAR* file_path, const TCHAR* parameters, int show_window, DWORD* exit_code); -// If there is no specific integrity level defined, return S_FALSE (1) and set -// level to MandatoryLevelMedium (the Vista default) -HRESULT GetFileOrFolderIntegrityLevel(const TCHAR* file, - MANDATORY_LEVEL* level, bool* and_children); - -// A level of MandatoryLevelUntrusted (0) will remove the integrity level for -// this file and all children -HRESULT SetFileOrFolderIntegrityLevel(const TCHAR* file, - MANDATORY_LEVEL level, bool and_children); - -// If there is no specific integrity level defined, return S_FALSE (1) and set -// level to MandatoryLevelMedium (the Vista default) -// root must be one of the 4 pre-defined roots: HKLM, HKCU, HKCR, HCU -HRESULT GetRegKeyIntegrityLevel(HKEY root, const TCHAR* subkey, - MANDATORY_LEVEL* level, bool* and_children); - -// A level of MandatoryLevelUntrusted (0) will remove the integrity label -// root must be one of the 4 pre-defined roots: HKLM, HKCU, HKCR, HCU -HRESULT SetRegKeyIntegrityLevel(HKEY root, const TCHAR* subkey, - MANDATORY_LEVEL level, bool and_children); - -// Creates a security descriptor that can be used to make an object accessible -// from the specified integrity level. When not running on Windows Vista or -// in case of errors, the function returns NULL, which results in using -// the default security descriptor. -// The caller must take ownership of the returned security descriptor. -// Mask will be added as an allowed ACE of the DACL. -// For example, use MUTEX_ALL_ACCESS for shared mutexes. -CSecurityDesc* CreateLowIntegritySecurityDesc(ACCESS_MASK mask); -CSecurityDesc* CreateMediumIntegritySecurityDesc(ACCESS_MASK mask); - // For Vista or later, add the mandatory SACL to an existing CSecurityDesc. HRESULT SetMandatorySacl(MANDATORY_LEVEL level, CSecurityDesc* sd); diff --git a/omaha/base/wmi_query.h b/omaha/base/wmi_query.h index c631056..da927b0 100644 --- a/omaha/base/wmi_query.h +++ b/omaha/base/wmi_query.h @@ -56,7 +56,7 @@ class WmiQuery { CComPtr obj_; bool at_end_; - DISALLOW_EVIL_CONSTRUCTORS(WmiQuery); + DISALLOW_COPY_AND_ASSIGN(WmiQuery); }; } // namespace omaha diff --git a/omaha/base/wtl_atlapp_wrapper.h b/omaha/base/wtl_atlapp_wrapper.h index 17b0227..e649706 100644 --- a/omaha/base/wtl_atlapp_wrapper.h +++ b/omaha/base/wtl_atlapp_wrapper.h @@ -30,6 +30,7 @@ using std::max; // 4265: class has virtual functions, but destructor is not virtual // 4996: 'function' was declared deprecated +#include #include #pragma warning(pop) diff --git a/omaha/base/xml_utils.cc b/omaha/base/xml_utils.cc index 443d029..1dfbcaf 100644 --- a/omaha/base/xml_utils.cc +++ b/omaha/base/xml_utils.cc @@ -18,11 +18,12 @@ // Utilities for working with XML files via MSXML. #include "omaha/base/xml_utils.h" + #include #include #include #include -#include "omaha/base/debug.h" + #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/string.h" @@ -287,7 +288,7 @@ bool operator==(const XMLFQName& u, const XMLFQName& v) { return !_tcscmp(u.uri, v.uri) && !_tcscmp(u.base, v.base); } else if (!u.uri && !v.uri) { // Both uris are null -> only compare the base names. - return !_tcscmp(u.base ? u.base : __T(""), v.base ? v.base : __T("")); + return !_tcscmp(u.base ? u.base : CString(), v.base ? v.base : CString()); } else { // Either uri is null -> the names are in different namespaces. return false; diff --git a/omaha/base/xml_utils.h b/omaha/base/xml_utils.h index 5ea64d4..e11c240 100644 --- a/omaha/base/xml_utils.h +++ b/omaha/base/xml_utils.h @@ -27,6 +27,9 @@ #include #include +#include "omaha/base/debug.h" +#include "omaha/base/utils.h" + namespace omaha { // Creates a DOMDocument that disallows external definitions to be included and @@ -220,7 +223,7 @@ HRESULT ForEachNodeInList(List list, template HRESULT ForEachNodeInListObj(List list, Object* object, - HRESULT (Object::*mem_fun)(IXMLDOMNode*, Cookie), + HRESULT (Object::*fun)(IXMLDOMNode*, Cookie), Cookie cookie) { ASSERT1(list); ASSERT1(object); @@ -273,7 +276,7 @@ HRESULT ForEachChildNode(IXMLDOMNode* node, template HRESULT ForEachChildNodeObj(IXMLDOMNode* node, Object* object, - HRESULT (Object::*mem_fun)(IXMLDOMNode*, Cookie), + HRESULT (Object::*fun)(IXMLDOMNode*, Cookie), Cookie cookie) { ASSERT1(node); ASSERT1(object); @@ -282,7 +285,7 @@ HRESULT ForEachChildNodeObj(IXMLDOMNode* node, CComPtr child_list; RET_IF_FAILED(node->get_childNodes(&child_list)); ASSERT1(child_list); - RET_IF_FAILED(ForEachNodeInListObj(child_list, object, mem_fun, cookie)); + RET_IF_FAILED(ForEachNodeInListObj(child_list, object, fun, cookie)); return S_OK; } diff --git a/omaha/base/xml_utils_unittest.cc b/omaha/base/xml_utils_unittest.cc index 535ccbd..e2a1aaa 100644 --- a/omaha/base/xml_utils_unittest.cc +++ b/omaha/base/xml_utils_unittest.cc @@ -20,9 +20,9 @@ #include "omaha/base/file.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/xml_utils.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/clickonce/build.scons b/omaha/clickonce/build.scons index a779a9f..2bf7e59 100644 --- a/omaha/clickonce/build.scons +++ b/omaha/clickonce/build.scons @@ -92,6 +92,6 @@ env.Depends( ], dependency = [ '%s/%s' % (clickonce_deploy_bin_dir, clickonce_binary), - '%s/GoogleUpdateSetup.exe' % (clickonce_deploy_bin_dir), + '%s/BraveUpdateSetup.exe' % (clickonce_deploy_bin_dir), ] ) diff --git a/omaha/clickonce/clickonce_bootstrap.cs b/omaha/clickonce/clickonce_bootstrap.cs index 4d3d827..33d8167 100644 --- a/omaha/clickonce/clickonce_bootstrap.cs +++ b/omaha/clickonce/clickonce_bootstrap.cs @@ -65,7 +65,7 @@ static class ClickOnceEntry { query_string = unescape_safe_chars.ToString(); string setup_path = Path.Combine(Application.StartupPath, - "GoogleUpdateSetup.exe"); + "BraveUpdateSetup.exe"); ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = setup_path; diff --git a/omaha/client/build.scons b/omaha/client/build.scons index 9467a54..5e5576a 100644 --- a/omaha/client/build.scons +++ b/omaha/client/build.scons @@ -35,4 +35,4 @@ inputs = [ ] # Build these into a library. -local_env.ComponentStaticLibrary('client', inputs) +local_env.ComponentLibrary('client', inputs) diff --git a/omaha/client/bundle_creator.cc b/omaha/client/bundle_creator.cc index 6cef990..4b11f0b 100644 --- a/omaha/client/bundle_creator.cc +++ b/omaha/client/bundle_creator.cc @@ -75,7 +75,7 @@ HRESULT UnescapeAndStoreUntrustedData(const CString& untrusted_data_escaped, return GOOPDATE_E_INVALID_INSTALLER_DATA_IN_APPARGS; } - return app->put_untrustedData(CComBSTR(CString(&buf.front()))); + return app->put_untrustedData(CComBSTR(CString(&buf.front()).GetString())); } // display_language and install_source can be empty. @@ -517,7 +517,7 @@ HRESULT CreateForOnDemand(bool is_machine, hr = internal::SetBundleProperties( lang, - name.IsEmpty() ? _T("On Demand Bundle") : name, + name.IsEmpty() ? CString(_T("On Demand Bundle")) : name, install_source, session_id, send_pings, diff --git a/omaha/client/bundle_creator_test.cc b/omaha/client/bundle_creator_test.cc index 2637730..aa3664f 100644 --- a/omaha/client/bundle_creator_test.cc +++ b/omaha/client/bundle_creator_test.cc @@ -13,6 +13,10 @@ // limitations under the License. // ======================================================================== +#include "omaha/client/bundle_creator.h" + +#include + #include "omaha/base/app_util.h" #include "omaha/base/browser_utils.h" #include "omaha/base/omaha_version.h" @@ -21,7 +25,6 @@ #include "omaha/base/system.h" #include "omaha/base/utils.h" #include "omaha/base/vistautil.h" -#include "omaha/client/bundle_creator.h" #include "omaha/client/client_utils.h" #include "omaha/common/command_line.h" #include "omaha/common/command_line_builder.h" @@ -158,10 +161,10 @@ class BundleCreatorTest : public testing::Test { EXPECT_SUCCEEDED(RegKey::DeleteKey(clients_key_name)); } - static scoped_ptr goopdates_; + static std::unique_ptr goopdates_; }; -scoped_ptr BundleCreatorTest::goopdates_; +std::unique_ptr BundleCreatorTest::goopdates_; TEST_F(BundleCreatorTest, Create) { const CString kDisplayLanguage = _T("en"); diff --git a/omaha/client/bundle_installer.cc b/omaha/client/bundle_installer.cc index 78de088..93ca692 100644 --- a/omaha/client/bundle_installer.cc +++ b/omaha/client/bundle_installer.cc @@ -15,12 +15,11 @@ #include "omaha/client/bundle_installer.h" #include -#include "base/scoped_ptr.h" + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/client/client_utils.h" #include "omaha/client/help_url_builder.h" #include "omaha/client/resource.h" @@ -433,8 +432,8 @@ BundleInstaller::BundleInstaller(HelpUrlBuilder* help_url_builder, bool is_update_all_apps, bool is_update_check_only, bool is_browser_type_supported) - : help_url_builder_(help_url_builder), - observer_(NULL), + : observer_(NULL), + help_url_builder_(help_url_builder), parent_window_(NULL), state_(kInit), result_(E_UNEXPECTED), @@ -510,7 +509,7 @@ void BundleInstaller::SetBundleParentWindow(HWND parent_window) { HRESULT BundleInstaller::ListenToShutdownEvent(bool is_machine) { ASSERT1(!shutdown_callback_.get()); HRESULT hr = ShutdownEvents::CreateShutdownHandler( - is_machine, this, address(shutdown_callback_)); + is_machine, this, &shutdown_callback_); if (FAILED(hr)) { CORE_LOG(LE, (_T("CreateShutdownHandler failed][0x%08x]"), hr)); } diff --git a/omaha/client/bundle_installer.h b/omaha/client/bundle_installer.h index 164acf6..28d05e7 100644 --- a/omaha/client/bundle_installer.h +++ b/omaha/client/bundle_installer.h @@ -19,9 +19,10 @@ #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/safe_format.h" #include "omaha/base/wtl_atlapp_wrapper.h" #include "goopdate/omaha3_idl.h" @@ -209,7 +210,7 @@ class BundleInstaller void ReleaseAppBundle(); InstallProgressObserver* observer_; - scoped_ptr help_url_builder_; + std::unique_ptr help_url_builder_; // The bundle to be installed. CComPtr app_bundle_; @@ -221,7 +222,7 @@ class BundleInstaller CMessageLoop message_loop_; // Shutdown event listener. - scoped_ptr shutdown_callback_; + std::unique_ptr shutdown_callback_; // The apps in app_bundle_. Allows easier and quicker access to the apps than // going through app_bundle_. diff --git a/omaha/client/help_url_builder.cc b/omaha/client/help_url_builder.cc index 5b1e809..76a2b6f 100644 --- a/omaha/client/help_url_builder.cc +++ b/omaha/client/help_url_builder.cc @@ -26,46 +26,12 @@ #include "omaha/base/vistautil.h" #include "omaha/common/config_manager.h" #include "omaha/common/goopdate_utils.h" +#include "omaha/common/url_utils.h" #include "goopdate/omaha3_idl.h" #include "omaha/net/http_client.h" namespace omaha { -namespace { - -// Query element name-value pair. -typedef std::pair QueryElement; - -// Builds a query string from the provided name-value pairs. -// The string does not begin or end in a pair separator. -HRESULT BuildQueryString(const std::vector& elements, - CString* query) { - ASSERT1(query); - - query->Empty(); - - for (size_t i = 0; i < elements.size(); ++i) { - CString escaped_str; - HRESULT hr = StringEscape(elements[i].second, false, &escaped_str); - if (FAILED(hr)) { - CORE_LOG(LEVEL_WARNING, (_T("[StringEscape failed][0x%08x]"), hr)); - return hr; - } - - CString element; - element.FormatMessage(_T("%1=%2"), elements[i].first, escaped_str); - - if (0 < i) { - query->Append(_T("&")); - } - query->Append(element); - } - - return S_OK; -} - -} // namespace - HRESULT HelpUrlBuilder::BuildUrl(const std::vector& app_results, CString* help_url) const { ASSERT1(help_url); @@ -86,6 +52,8 @@ HRESULT HelpUrlBuilder::BuildUrl(const std::vector& app_results, return hr; } + *help_url = _T("https://support.brave.com/"); + return S_OK; } @@ -109,7 +77,7 @@ HRESULT HelpUrlBuilder::BuildHttpGetString( CORE_LOG(LEVEL_WARNING, (_T("[GetOSInfo failed][0x%08x]"), hr)); } const CString iid_string = - ::IsEqualGUID(GUID_NULL, iid_) ? _T("") : GuidToString(iid_); + ::IsEqualGUID(GUID_NULL, iid_) ? CString() : GuidToString(iid_); std::vector elements; elements.push_back(QueryElement(_T("hl"), language_)); diff --git a/omaha/client/install.cc b/omaha/client/install.cc index 67fff68..6f05090 100644 --- a/omaha/client/install.cc +++ b/omaha/client/install.cc @@ -26,7 +26,6 @@ #include "omaha/base/process.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" @@ -43,6 +42,7 @@ #include "omaha/common/oem_install_utils.h" #include "omaha/common/ping.h" #include "omaha/setup/setup_metrics.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/splash_screen.h" namespace omaha { diff --git a/omaha/client/install_apps.cc b/omaha/client/install_apps.cc index fe1d7e9..dc18c68 100644 --- a/omaha/client/install_apps.cc +++ b/omaha/client/install_apps.cc @@ -14,15 +14,15 @@ // ======================================================================== #include "omaha/client/install_apps.h" + #include -#include "base/scoped_ptr.h" + #include "omaha/base/const_object_names.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reactor.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/shutdown_callback.h" #include "omaha/base/shutdown_handler.h" #include "omaha/base/string.h" @@ -338,16 +338,14 @@ HRESULT CreateClientUI(bool is_machine, BrowserType browser_type, BundleInstaller* installer, IAppBundle* app_bundle, - InstallProgressObserver** observer, - OmahaWndEvents** ui_sink) { + std::unique_ptr* observer, + std::unique_ptr* ui_sink) { ASSERT1(installer); ASSERT1(observer); - ASSERT1(!*observer); ASSERT1(ui_sink); - ASSERT1(!*ui_sink); - scoped_ptr progress_wnd( - new ProgressWnd(installer->message_loop(), NULL)); + auto progress_wnd = std::make_unique(installer->message_loop(), + nullptr); ScopeGuard destroy_window_guard = MakeObjGuard(*progress_wnd, &ProgressWnd::DestroyWindow); @@ -359,16 +357,16 @@ HRESULT CreateClientUI(bool is_machine, return hr; } - scoped_ptr progress_wnd_events( - new internal::InstallAppsWndEvents(is_machine, installer, browser_type)); + auto progress_wnd_events = std::make_unique( + is_machine, installer, browser_type); progress_wnd->SetEventSink(progress_wnd_events.get()); progress_wnd->Show(); installer->SetBundleParentWindow(progress_wnd->m_hWnd); destroy_window_guard.Dismiss(); - *observer = progress_wnd.release(); - *ui_sink = progress_wnd_events.release(); + observer->reset(progress_wnd.release()); + ui_sink->reset(progress_wnd_events.release()); return S_OK; } @@ -381,16 +379,14 @@ HRESULT DoInstallApps(BundleInstaller* installer, IAppBundle* app_bundle, bool is_machine, bool is_interactive, - bool is_update_all_apps, BrowserType browser_type, bool* has_ui_been_displayed) { CORE_LOG(L2, (_T("[DoInstallApps]"))); ASSERT1(installer); ASSERT1(has_ui_been_displayed); - scoped_ptr observer; - scoped_ptr ui_sink; - bool listen_to_shutdown_event = false; + std::unique_ptr observer; + std::unique_ptr ui_sink; CComPtr app_bundle_ptr; app_bundle_ptr.Attach(app_bundle); @@ -401,8 +397,8 @@ HRESULT DoInstallApps(BundleInstaller* installer, browser_type, installer, app_bundle, - address(observer), - address(ui_sink)); + &observer, + &ui_sink); if (FAILED(hr)) { CORE_LOG(LE, (_T("CreateClientUI failed][0x%08x]"), hr)); return hr; @@ -410,13 +406,10 @@ HRESULT DoInstallApps(BundleInstaller* installer, *has_ui_been_displayed = true; } else { observer.reset(new SilentProgressObserver(installer)); - if (is_update_all_apps) { - listen_to_shutdown_event = true; - } } hr = installer->InstallBundle(is_machine, - listen_to_shutdown_event, + false, app_bundle_ptr.Detach(), observer.get()); @@ -632,7 +625,6 @@ HRESULT InstallApps(bool is_machine, app_bundle.Detach(), is_machine, is_interactive, - false, // Is not update all apps. extra_args.browser_type, has_ui_been_displayed); } @@ -680,7 +672,6 @@ HRESULT UpdateAllApps(bool is_machine, app_bundle.Detach(), is_machine, is_interactive, - true, // Is update all apps. BROWSER_UNKNOWN, has_ui_been_displayed); } diff --git a/omaha/client/install_apps_internal.h b/omaha/client/install_apps_internal.h index 5eb41d6..018b5e4 100644 --- a/omaha/client/install_apps_internal.h +++ b/omaha/client/install_apps_internal.h @@ -19,7 +19,9 @@ #include #include +#include #include + #include "omaha/base/browser_utils.h" #include "goopdate/omaha3_idl.h" #include "omaha/ui/progress_wnd.h" @@ -63,15 +65,14 @@ HRESULT CreateClientUI(bool is_machine, BrowserType browser_type, BundleInstaller* installer, AppBundle* app_bundle, - InstallProgressObserver** observer, - OmahaWndEvents** ui_sink); + std::unique_ptr* observer, + std::unique_ptr* ui_sink); // Does the work for InstallApps, allowing the COM server to be mocked. HRESULT DoInstallApps(BundleInstaller* installer, IAppBundle* app_bundle, bool is_machine, bool is_interactive, - bool is_update_all_apps, BrowserType browser_type, bool* has_ui_been_displayed); diff --git a/omaha/client/shutdown_events.cc b/omaha/client/shutdown_events.cc index aa33021..1cb26ae 100644 --- a/omaha/client/shutdown_events.cc +++ b/omaha/client/shutdown_events.cc @@ -14,8 +14,9 @@ // ======================================================================== #include "omaha/client/shutdown_events.h" + #include -#include "base/scoped_ptr.h" + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -67,19 +68,18 @@ HRESULT ShutdownEvents::Shutdown() { HRESULT ShutdownEvents::CreateShutdownHandler( bool is_machine, BundleInstaller* installer, - ShutdownCallback** shutdown_callback) { + std::unique_ptr* shutdown_callback) { ASSERT1(installer); ASSERT1(shutdown_callback); - ASSERT1(!*shutdown_callback); - scoped_ptr shutdown_events(new ShutdownEvents(installer)); + auto shutdown_events = std::make_unique(installer); HRESULT hr = shutdown_events->InitializeShutdownHandler(is_machine); if (FAILED(hr)) { CORE_LOG(LE, (_T("[InitializeShutDownHandler failed][0x%08x]"), hr)); return hr; } - *shutdown_callback = shutdown_events.release(); + shutdown_callback->reset(shutdown_events.release()); return S_OK; } diff --git a/omaha/client/shutdown_events.h b/omaha/client/shutdown_events.h index 04fef05..8d4a632 100644 --- a/omaha/client/shutdown_events.h +++ b/omaha/client/shutdown_events.h @@ -18,7 +18,8 @@ #include #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/shutdown_callback.h" #include "omaha/base/synchronized.h" @@ -36,15 +37,15 @@ class ShutdownEvents : public ShutdownCallback { HRESULT InitializeShutdownHandler(bool is_machine); HRESULT Shutdown(); static HRESULT CreateShutdownHandler(bool is_machine, - BundleInstaller* installer, - ShutdownCallback** shutdown_callback); + BundleInstaller* installer, + std::unique_ptr* shutdown_callback); private: BundleInstaller* installer_; LLock lock_; - scoped_ptr reactor_; - scoped_ptr shutdown_handler_; + std::unique_ptr reactor_; + std::unique_ptr shutdown_handler_; DISALLOW_IMPLICIT_CONSTRUCTORS(ShutdownEvents); }; diff --git a/omaha/client/ua.cc b/omaha/client/ua.cc index 28cec04..4193926 100644 --- a/omaha/client/ua.cc +++ b/omaha/client/ua.cc @@ -27,7 +27,6 @@ #include "omaha/base/logging.h" #include "omaha/base/program_instance.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/utils.h" #include "omaha/base/time.h" #include "omaha/client/install_apps.h" @@ -134,16 +133,16 @@ HRESULT RegisterMSIHelperIfNeeded(bool is_machine) { } // Ensures there is only one instance of /ua per session per Omaha instance. -bool EnsureSingleUAProcess(bool is_machine, ProgramInstance** instance) { +bool EnsureSingleUAProcess(bool is_machine, + std::unique_ptr* instance) { ASSERT1(instance); - ASSERT1(!*instance); NamedObjectAttributes single_ua_process_attr; GetNamedObjectAttributes(kUpdateAppsSingleInstance, is_machine, &single_ua_process_attr); - *instance = new ProgramInstance(single_ua_process_attr.name); - return !(*instance)->EnsureSingleInstance(); + instance->reset(new ProgramInstance(single_ua_process_attr.name)); + return !instance->get()->EnsureSingleInstance(); } bool IsUpdateAppsHourlyJitterDisabled() { @@ -247,9 +246,9 @@ HRESULT UpdateApps(bool is_machine, WriteUpdateAppsStartEvent(is_machine); - scoped_ptr single_ua_process; + std::unique_ptr single_ua_process; - if (EnsureSingleUAProcess(is_machine, address(single_ua_process))) { + if (EnsureSingleUAProcess(is_machine, &single_ua_process)) { OPT_LOG(L1, (_T("[Another worker is already running. Exiting.]"))); ++metric_client_another_update_in_progress; return GOOPDATE_E_UA_ALREADY_RUNNING; diff --git a/omaha/common/app_registry_utils.cc b/omaha/common/app_registry_utils.cc index 98f0eda..7ab22ee 100644 --- a/omaha/common/app_registry_utils.cc +++ b/omaha/common/app_registry_utils.cc @@ -14,12 +14,14 @@ // ======================================================================== #include "omaha/common/app_registry_utils.h" + +#include + #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/system_info.h" #include "omaha/base/utils.h" #include "omaha/common/config_manager.h" @@ -285,7 +287,7 @@ HRESULT SetAppBranding(const CString& client_state_key_path, const TCHAR* brand_code_to_write = brand_code.IsEmpty() ? kDefaultGoogleUpdateBrandCode : - brand_code; + brand_code.GetString(); hr = state_key.SetValue(kRegValueBrandCode, brand_code_to_write); if (FAILED(hr)) { return hr; @@ -634,12 +636,12 @@ void RemoveClientStateForApps(bool is_machine, HRESULT GetLastOSVersion(bool is_machine, OSVERSIONINFOEX* os_version_out) { ASSERT1(os_version_out); - scoped_array value; + std::unique_ptr value; size_t size = 0; HRESULT hr = RegKey::GetValue( ConfigManager::Instance()->registry_update(is_machine), kRegValueLastOSVersion, - address(value), + &value, &size); if (FAILED(hr) || !value.get()) { return value.get() ? hr : E_FAIL; diff --git a/omaha/common/brave_referral_code_utils.cc b/omaha/common/brave_referral_code_utils.cc new file mode 100644 index 0000000..7a3bbb3 --- /dev/null +++ b/omaha/common/brave_referral_code_utils.cc @@ -0,0 +1,236 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "omaha/common/brave_referral_code_utils.h" + +#include +#include + +namespace omaha { + +namespace { + +bool ParseStandardReferralCode(const TCHAR* filename, CString& referral_code) { + // Scan backwards for last dash in filename. + const TCHAR* scan = filename + lstrlen(filename) - 1; + while (scan != filename && *scan != _T('-')) + --scan; + + if (*scan++ != _T('-')) + return false; + + // Standard referral code is 6 characters. + const TCHAR* ref_code = scan; + if (lstrlen(ref_code) != 6) + return false; + + // Ensure that first half of referral code is alphabetic. + for (int i = 0; i < 3; ++i) { + if ((ref_code[i] < _T('a') || ref_code[i] > _T('z')) && + (ref_code[i] < _T('A') || ref_code[i] > _T('Z'))) + return false; + } + + // Ensure that second half of referral code is numeric. + for (int i = 3; i < 6; ++i) { + if (ref_code[i] < _T('0') || ref_code[i] > _T('9')) + return false; + } + + referral_code = ref_code; + + return true; +} + +bool ParseExtendedReferralCode(const TCHAR* filename, CString& referral_code) { + // Scan backwards for second-to-last dash in filename, since this + // type of referral code has an embedded dash. + const TCHAR* scan = filename + lstrlen(filename) - 1; + while (scan != filename && *scan != _T('-')) + --scan; + + if (*scan-- != _T('-')) + return false; + + while (scan != filename && *scan != _T('-')) + --scan; + + if (*scan++ != _T('-')) + return false; + + // Ensure that referral code is alphabetic. + const TCHAR* ref_code = scan; + int dashes = 0; + for (int i = 0; i < lstrlen(ref_code); ++i) { + if ((ref_code[i] < _T('a') || ref_code[i] > _T('z')) && + (ref_code[i] < _T('A') || ref_code[i] > _T('Z')) && + (ref_code[i] != _T('-'))) + return NULL; + if (ref_code[i] == _T('-')) + ++dashes; + } + + // Ensure that referral code contains exactly one dash. + if (dashes != 1) + return false; + + referral_code = ref_code; + return true; +} + +bool ParseReferralCode(const TCHAR* installer_filename, + CString& referral_code) { + TCHAR filename[MAX_PATH]; + lstrcpyn(filename, installer_filename, MAX_PATH); + + // Strip path from filename. + PathStripPath(filename); + + // Strip extension from filename. + PathRemoveExtension(filename); + + // Strip any de-duplicating suffix from filename, e.g. "(1)". + const TCHAR* scan = filename + lstrlen(filename) - 1; + if (*scan == _T(')')) { + --scan; + while (scan != filename && *scan >= _T('0') && *scan <= _T('9')) + --scan; + if (*scan == _T('(')) + filename[scan - filename] = '\0'; + } + + // Strip trailing spaces from filename. + scan = filename + lstrlen(filename) - 1; + while (scan != filename && *scan == _T(' ')) + --scan; + + if (scan != filename && (scan != filename + lstrlen(filename))) + filename[scan - filename + 1]; + + // First check for 6-character standard referral code XXXDDD, where + // X is an alphabetic character and D is a numeric character. If not + // found, check for an alphabetic referral code of any length in the + // form XXX-XXX. + if (!ParseStandardReferralCode(filename, referral_code) && + !ParseExtendedReferralCode(filename, referral_code)) { + return false; + } + + return true; +} + +bool IsReferralCodeWhiteListed(const CString& referral_code) { + static std::vector whitelist( + {// ISOptOut2 + CString(_T("CTD238")), CString(_T("OJV851")), CString(_T("DPM796")), + CString(_T("BNI512")), CString(_T("FEB604")), CString(_T("YDQ106")), + CString(_T("NFF966")), CString(_T("FQW627")), CString(_T("AMV588")), + CString(_T("YZR853")), CString(_T("IUX155")), CString(_T("DFQ107")), + CString(_T("ZWV410")), CString(_T("ZTT758")), CString(_T("EPH628")), + CString(_T("DKD200")), CString(_T("WIR635")), CString(_T("YHC941")), + CString(_T("OPV062")), CString(_T("MTS962")), CString(_T("PSN487")), + CString(_T("MZJ289")), CString(_T("EBC998")), CString(_T("KWZ833")), + CString(_T("YQI537")), CString(_T("BUE553")), CString(_T("UGO473")), + CString(_T("CFT923")), CString(_T("WKG906")), CString(_T("OXU789")), + CString(_T("VGT997")), CString(_T("MOU235")), CString(_T("WLJ467")), + CString(_T("YXG330")), CString(_T("RNH069")), CString(_T("LRT088")), + CString(_T("BEM856")), CString(_T("DSL157")), CString(_T("ZGL739")), + CString(_T("MZX864")), CString(_T("GTW616")), CString(_T("YBX790")), + CString(_T("LJT611")), CString(_T("FST304")), CString(_T("TVJ301")), + CString(_T("RMB962")), CString(_T("NKZ324")), + + // STTier1 + CString(_T("FBI093")), CString(_T("VNI569")), CString(_T("GMM900")), + CString(_T("NOQ491")), CString(_T("IOB292")), CString(_T("JJE625")), + CString(_T("FUX638")), CString(_T("MPO928")), CString(_T("LYD303")), + CString(_T("TJF413")), CString(_T("MQP631")), CString(_T("ILY758")), + CString(_T("VBQ225")), CString(_T("UQS362")), + + // GS + CString(_T("PJJ948")), CString(_T("UIH408")), CString(_T("KXC376")), + CString(_T("OZD582")), CString(_T("JDT909")), CString(_T("IJZ122")), + CString(_T("OIE359")), CString(_T("DLQ981")), CString(_T("WIX525")), + CString(_T("PZH825")), CString(_T("NGY511")), CString(_T("QXS120")), + CString(_T("XTA152")), CString(_T("EZM037")), + + // JAc + CString(_T("DHU083")), CString(_T("UGI415")), CString(_T("RQH046")), + CString(_T("MEB961")), + + // Additional + CString(_T("KJP000")), CString(_T("UNQ913")), CString(_T("KBJ557")), + CString(_T("BOA207")), CString(_T("BYJ598")), CString(_T("ARO656")), + CString(_T("EDE311")), CString(_T("RZD797")), CString(_T("QPE677")), + CString(_T("RPW794")), CString(_T("TBD002")), CString(_T("BTZ601")), + CString(_T("DRR783")), CString(_T("RMB905")), CString(_T("ZVI549")), + CString(_T("DZF201")), CString(_T("RHI430")), CString(_T("XOX898")), + CString(_T("WGN943")), CString(_T("OSB729")), CString(_T("JWA535")), + CString(_T("TOT965")), CString(_T("NWN118")), CString(_T("YHS197")), + CString(_T("IBU843")), CString(_T("UUD854")), CString(_T("ITO318")), + CString(_T("TQD211")), CString(_T("SFM009")), CString(_T("ERQ913")), + CString(_T("VZF120")), CString(_T("WIV076")), CString(_T("LWP706")), + CString(_T("XMW172")), CString(_T("OOX752")), CString(_T("VWK786")), + CString(_T("HQK918")), CString(_T("IXX292")), CString(_T("APG060")), + CString(_T("KSU863")), CString(_T("ANM246")), CString(_T("OVK455")), + CString(_T("TSM531")), CString(_T("ZMC689")), CString(_T("XPO114")), + CString(_T("TJK021")), CString(_T("MTB027")), CString(_T("BWC385")), + CString(_T("BSB375")), CString(_T("BXV384")), CString(_T("SLY677")), + CString(_T("OIQ043")), CString(_T("DWC715")), CString(_T("CCU246")), + CString(_T("UPQ934")), CString(_T("PRI875")), CString(_T("UQN934")), + CString(_T("ASY224")), CString(_T("NUB585")), CString(_T("OLS686")), + CString(_T("QLM391")), CString(_T("PNE044")), CString(_T("PPD370")), + CString(_T("OOJ613")), CString(_T("EZM787")), CString(_T("NRX711")), + CString(_T("APV192")), CString(_T("BHD893")), CString(_T("ERX748")), + CString(_T("CBW249")), CString(_T("HYJ986")), CString(_T("CVB741")), + CString(_T("YIZ978")), CString(_T("KYW570")), CString(_T("KVC600")), + CString(_T("GMV203")), CString(_T("DVZ178")), CString(_T("IFN767")), + CString(_T("YPH104")), CString(_T("UNK157")), CString(_T("NGU383")), + CString(_T("BXN418")), CString(_T("RBW016")), CString(_T("ZQM087")), + CString(_T("TRR894")), CString(_T("IXQ557")), CString(_T("TNW414")), + CString(_T("QAA606")), CString(_T("OCA003")), CString(_T("IOJ320")), + CString(_T("ZIQ953")), CString(_T("ZJN514")), CString(_T("XMZ986")), + CString(_T("HLK526")), CString(_T("CCQ716")), CString(_T("LIR950")), + CString(_T("JRN526")), CString(_T("TZS401")), CString(_T("DSE071")), + CString(_T("CJO449")), CString(_T("ABO677")), CString(_T("GFQ506")), + CString(_T("ZWR105")), CString(_T("VBC538")), CString(_T("IQC112")), + CString(_T("FBW502")), CString(_T("XPM257")), CString(_T("MSG315")), + CString(_T("ORX404")), CString(_T("UEO521")), CString(_T("EKB849")), + CString(_T("ERW274")), CString(_T("ZYB215")), CString(_T("OOB354")), + CString(_T("UTD029")), CString(_T("OZC828")), CString(_T("HXM441")), + CString(_T("LSS305")), CString(_T("KJD945")), CString(_T("SOB703")), + CString(_T("CCJ078")), CString(_T("QFE427")), CString(_T("CZQ141")), + CString(_T("DFG223")), CString(_T("SIV168")), CString(_T("XER314")), + CString(_T("EHH775")), CString(_T("MMT745")), CString(_T("SOB084")), + CString(_T("HFS553")), CString(_T("YZV909")), CString(_T("QJQ727")), + CString(_T("HQL833")), CString(_T("BSC752")), CString(_T("APN295")), + CString(_T("AAV730")), CString(_T("YXT225")), CString(_T("CHY006")), + CString(_T("CEL792")), CString(_T("VIW485")), CString(_T("SBW951")), + CString(_T("MJM666")), CString(_T("DPX255")), CString(_T("JQP631")), + CString(_T("NHX686")), CString(_T("YAB346")), CString(_T("RDS304")), + CString(_T("FFL997")), CString(_T("UPF883")), CString(_T("JYK534")), + CString(_T("OIL401")), CString(_T("CSY475")), CString(_T("MGD911")), + CString(_T("ESP177")), CString(_T("FEX878")), CString(_T("LDD929")), + CString(_T("XOB016"))}); + return std::any_of(whitelist.begin(), whitelist.end(), + [&referral_code](CString candidate) { + return candidate == referral_code; + }); +} + +} // namespace + +CString GetReferralCode(const CString& module_file_name) { + CString referral_code; + if (!ParseReferralCode(module_file_name, referral_code)) + return _T("none"); + + referral_code.MakeUpper(); + + if (!IsReferralCodeWhiteListed(referral_code)) + return _T("none"); + + return referral_code; +} + +} // namespace omaha diff --git a/omaha/common/brave_referral_code_utils.h b/omaha/common/brave_referral_code_utils.h new file mode 100644 index 0000000..c1af729 --- /dev/null +++ b/omaha/common/brave_referral_code_utils.h @@ -0,0 +1,16 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef OMAHA_COMMON_BRAVE_REFERRAL_CODE_UTILS_H__ +#define OMAHA_COMMON_BRAVE_REFERRAL_CODE_UTILS_H__ + +#include + +namespace omaha { + +CString GetReferralCode(const CString& module_file_name); + +} // namespace omaha + +#endif // OMAHA_COMMON_BRAVE_REFERRAL_CODE_UTILS_H__ diff --git a/omaha/common/brave_stats_updater.cc b/omaha/common/brave_stats_updater.cc new file mode 100644 index 0000000..c97fbb4 --- /dev/null +++ b/omaha/common/brave_stats_updater.cc @@ -0,0 +1,91 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "omaha/common/brave_stats_updater.h" + +#include "omaha/base/safe_format.h" +#include "omaha/base/utils.h" +#include "omaha/net/network_config.h" +#include "omaha/net/network_request.h" +#include "omaha/net/simple_request.h" + +namespace omaha { + +namespace { + +CString GetChannelName(const CString& app_guid) { + if (app_guid == _T("{AFE6A462-C574-4B8A-AF43-4CC60DF4563B}")) + return _T("release"); + else if (app_guid == _T("{103BD053-949B-43A8-9120-2E424887DE11}")) + return _T("beta"); + else if (app_guid == _T("{CB2150F2-595F-4633-891A-E39720CE0531}")) + return _T("dev"); + else if (app_guid == _T("{C6CB981E-DB30-4876-8639-109F8933582C}")) + return _T("nightly"); + else + return _T(""); +} + +CString GetBraveVersion(const CString& version) { + // Strip first segment from version number. + int pos = version.Find(_T('.')); + if (pos != -1) + return version.Right(version.GetLength() - pos - 1); + return _T("0.0.0"); +} + +} // namespace + +HRESULT BraveSendStatsPing(const CString& event, const CString& app_guid, + const CString& referral_code, + const CString& version) { + // Retrieve the update server name. + CString update_server = + omaha::GetEnvironmentVariableAsString(_T("BRAVE_UPDATE_SERVER")); + if (update_server.IsEmpty()) + update_server = _T("laptop-updates.brave.com"); + + _SYSTEM_INFO system_info = {}; + ::GetNativeSystemInfo(&system_info); + + // Ensure that channel is valid/supported. + CString channel_name = GetChannelName(app_guid); + if (channel_name.IsEmpty()) { + CORE_LOG(LE, (_T("[Channel name is empty][%s]"), app_guid)); + return E_INVALIDARG; + } + + // Build the update url. + CString url; + omaha::SafeCStringAppendFormat( + &url, + _T("https://%s/1/") + _T("installerEvent?platform=%s&version=%s&channel=%s&ref=%s&event=%s"), + update_server, + system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL + ? _T("winia32-bc") + : _T("winx64-bc"), + GetBraveVersion(version), channel_name, referral_code, event); + + omaha::NetworkConfig* network_config = NULL; + omaha::NetworkConfigManager& network_manager = + omaha::NetworkConfigManager::Instance(); + HRESULT hr = network_manager.GetUserNetworkConfig(&network_config); + if (FAILED(hr)) + return hr; + + omaha::NetworkRequest network_request(network_config->session()); + + network_request.set_num_retries(1); + network_request.AddHttpRequest(new omaha::SimpleRequest); + + std::vector response_buffer; + hr = network_request.Get(url, &response_buffer); + if (FAILED(hr)) + return hr; + + return S_OK; +} + +} // namespace omaha diff --git a/omaha/common/brave_stats_updater.h b/omaha/common/brave_stats_updater.h new file mode 100644 index 0000000..5bcae62 --- /dev/null +++ b/omaha/common/brave_stats_updater.h @@ -0,0 +1,18 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef OMAHA_COMMON_BRAVE_STATS_UPDATER_H__ +#define OMAHA_COMMON_BRAVE_STATS_UPDATER_H__ + +#include + +namespace omaha { + +HRESULT BraveSendStatsPing(const CString& event, const CString& app_guid, + const CString& referral_code, + const CString& version); + +} // namespace omaha + +#endif // OMAHA_COMMON_BRAVE_STATS_UPDATER_H__ diff --git a/omaha/common/build.scons b/omaha/common/build.scons index dfaa61e..ab31018 100644 --- a/omaha/common/build.scons +++ b/omaha/common/build.scons @@ -24,6 +24,8 @@ def BuildCommonLib(env): inputs = [ 'app_registry_utils.cc', + 'brave_referral_code_utils.cc', + 'brave_stats_updater.cc', 'command_line.cc', 'command_line_builder.cc', 'config_manager.cc', @@ -45,6 +47,7 @@ def BuildCommonLib(env): 'update3_utils.cc', 'update_request.cc', 'update_response.cc', + 'url_utils.cc', 'webplugin_utils.cc', 'web_services_client.cc', 'xml_const.cc', @@ -57,7 +60,7 @@ def BuildCommonLib(env): lib_name = 'common%s' % ('', '_64')[local_env.Bit('x64')] # Build these into a library. - local_env.ComponentStaticLibrary(lib_name, inputs) + local_env.ComponentLibrary(lib_name, inputs) BuildCommonLib(env) BuildCommonLib(env.CloneAndMake64Bit()) diff --git a/omaha/common/command_line.h b/omaha/common/command_line.h index 68ccd5f..9b66f42 100644 --- a/omaha/common/command_line.h +++ b/omaha/common/command_line.h @@ -60,7 +60,7 @@ enum CommandLineMode { COMMANDLINE_MODE_SERVICE = 3, COMMANDLINE_MODE_REGSERVER = 4, COMMANDLINE_MODE_UNREGSERVER = 5, - COMMANDLINE_MODE_NETDIAGS = 6, + // Obsolete: COMMANDLINE_MODE_NETDIAGS = 6, COMMANDLINE_MODE_CRASH = 7, COMMANDLINE_MODE_REPORTCRASH = 8, COMMANDLINE_MODE_INSTALL = 9, @@ -103,6 +103,9 @@ struct CommandLineExtraArgs { CString experiment_labels; CString referral_id; CString language; +#if defined(HAS_DEVICE_MANAGEMENT) + CString enrollment_token; +#endif BrowserType browser_type; Tristate usage_stats_enable; bool runtime_only; diff --git a/omaha/common/command_line_builder.cc b/omaha/common/command_line_builder.cc index 6e7e448..29eb403 100644 --- a/omaha/common/command_line_builder.cc +++ b/omaha/common/command_line_builder.cc @@ -165,9 +165,6 @@ CString CommandLineBuilder::GetCommandLineArgs() const { case COMMANDLINE_MODE_UNREGSERVER: cmd_line_args = GetUnregServer(); break; - case COMMANDLINE_MODE_NETDIAGS: - cmd_line_args = GetNetDiags(); - break; case COMMANDLINE_MODE_CRASH: cmd_line_args = GetCrash(); break; @@ -302,10 +299,6 @@ CString CommandLineBuilder::GetUnregServer() const { return GetSingleSwitch(kCmdUnregServer); } -CString CommandLineBuilder::GetNetDiags() const { - return GetSingleSwitch(kCmdLineNetDiags); -} - CString CommandLineBuilder::GetCrash() const { CString cmd_line = GetSingleSwitch(kCmdLineCrash); return cmd_line; diff --git a/omaha/common/command_line_builder.h b/omaha/common/command_line_builder.h index aac6d82..ca9acea 100644 --- a/omaha/common/command_line_builder.h +++ b/omaha/common/command_line_builder.h @@ -107,7 +107,6 @@ class CommandLineBuilder { CString GetServiceUnregister() const; CString GetRegServer() const; CString GetUnregServer() const; - CString GetNetDiags() const; CString GetCrash() const; CString GetReportCrash() const; CString GetInstall() const; @@ -146,7 +145,7 @@ class CommandLineBuilder { CString offline_dir_name_; CString session_id_; - DISALLOW_EVIL_CONSTRUCTORS(CommandLineBuilder); + DISALLOW_COPY_AND_ASSIGN(CommandLineBuilder); }; } // namespace omaha diff --git a/omaha/common/command_line_builder_unittest.cc b/omaha/common/command_line_builder_unittest.cc index 783f031..bb1c757 100644 --- a/omaha/common/command_line_builder_unittest.cc +++ b/omaha/common/command_line_builder_unittest.cc @@ -61,12 +61,6 @@ TEST(CommandLineBuilder, BuildUnregServer) { EXPECT_STREQ(_T("/unregserver"), cmd_line); } -TEST(CommandLineBuilder, BuildNetDiags) { - CommandLineBuilder builder(COMMANDLINE_MODE_NETDIAGS); - CString cmd_line = builder.GetCommandLineArgs(); - EXPECT_STREQ(_T("/netdiags"), cmd_line); -} - TEST(CommandLineBuilder, BuildCrashNoFilename) { CommandLineBuilder builder(COMMANDLINE_MODE_CRASH); CString cmd_line = builder.GetCommandLineArgs(); diff --git a/omaha/common/command_line_unittest.cc b/omaha/common/command_line_unittest.cc index 0da07c6..12e3213 100644 --- a/omaha/common/command_line_unittest.cc +++ b/omaha/common/command_line_unittest.cc @@ -110,6 +110,9 @@ void VerifyCommandLineExtraArgs(const CommandLineExtraArgs& expected_val, actual_val.experiment_labels); EXPECT_STREQ(expected_val.referral_id, actual_val.referral_id); EXPECT_STREQ(expected_val.language, actual_val.language); +#if defined(HAS_DEVICE_MANAGEMENT) + EXPECT_STREQ(expected_val.enrollment_token, actual_val.enrollment_token); +#endif EXPECT_EQ(expected_val.browser_type, actual_val.browser_type); EXPECT_EQ(expected_val.usage_stats_enable, actual_val.usage_stats_enable); EXPECT_EQ(expected_val.runtime_only, actual_val.runtime_only); @@ -283,7 +286,11 @@ TEST_F(CommandLineTest, ParseCommandLine_Install) { _T("\"appguid={A4F7B07B-B9BD-4a33-B136-96D2ADFB60CB}&") _T("appname=YouTubeUploader&needsadmin=False&") _T("appguid={C7A9A2F5-C4F9-42d3-8A8B-55086A205468}&") - _T("appname=TestApp&needsadmin=true&lang=en\""); + _T("appname=TestApp&needsadmin=true&lang=en") +#if defined(HAS_DEVICE_MANAGEMENT) + _T("&etoken=f6f767ba-8cfb-4d95-a26a-b3d714ddf1a2") +#endif + _T("\""); EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); expected_.mode = COMMANDLINE_MODE_INSTALL; @@ -293,7 +300,11 @@ TEST_F(CommandLineTest, ParseCommandLine_Install) { _T("appname=YouTubeUploader&needsadmin=False&") _T("appguid=") _T("{C7A9A2F5-C4F9-42d3-8A8B-55086A205468}&") - _T("appname=TestApp&needsadmin=true&lang=en"); + _T("appname=TestApp&needsadmin=true&lang=en") +#if defined(HAS_DEVICE_MANAGEMENT) + _T("&etoken=f6f767ba-8cfb-4d95-a26a-b3d714ddf1a2") +#endif + ; CommandLineAppArgs app_args; const GUID expected_guid = {0xA4F7B07B, 0xB9BD, 0x4A33, {0xB1, 0x36, 0x96, 0xD2, 0xAD, 0xFB, 0x60, 0xCB}}; @@ -311,6 +322,9 @@ TEST_F(CommandLineTest, ParseCommandLine_Install) { expected_.extra.bundle_name = _T("YouTubeUploader"); expected_.extra.language = _T("en"); +#if defined(HAS_DEVICE_MANAGEMENT) + expected_.extra.enrollment_token = _T("f6f767ba-8cfb-4d95-a26a-b3d714ddf1a2"); +#endif VerifyCommandLineArgs(expected_, args_); @@ -843,15 +857,6 @@ TEST_F(CommandLineTest, ParseCommandLine_UpdateSessionId) { VerifyCommandLineArgs(expected_, args_); } -// Parse: /netdiags -TEST_F(CommandLineTest, ParseCommandLine_NetDiags) { - const TCHAR* kCmdLine = _T("goopdate.exe /netdiags"); - EXPECT_SUCCEEDED(ParseCommandLine(kCmdLine, &args_)); - - expected_.mode = COMMANDLINE_MODE_NETDIAGS; - VerifyCommandLineArgs(expected_, args_); -} - // Parse: /regserver TEST_F(CommandLineTest, ParseCommandLine_Regserver) { const TCHAR* kCmdLine = _T("goopdate.exe /regserver"); diff --git a/omaha/common/config_manager.cc b/omaha/common/config_manager.cc index e828794..251d62d 100644 --- a/omaha/common/config_manager.cc +++ b/omaha/common/config_manager.cc @@ -208,8 +208,8 @@ bool GetUpdatesSuppressedTimes(DWORD* start_hour, return false; } - // UpdatesSuppressedDurationMin is limited to 12 hours. - if (*start_hour > 23 || *start_min > 59 || *duration_min > 12 * kMinPerHour) { + // UpdatesSuppressedDurationMin is limited to 16 hours. + if (*start_hour > 23 || *start_min > 59 || *duration_min > 16 * kMinPerHour) { OPT_LOG(L5, (_T("[GetUpdatesSuppressedTimes][Out of bounds][%x][%x][%x]"), *start_hour, *start_min, *duration_min)); return false; @@ -508,6 +508,33 @@ HRESULT ConfigManager::GetUsageStatsReportUrl(CString* url) const { return S_OK; } +#if defined(HAS_DEVICE_MANAGEMENT) + +HRESULT ConfigManager::GetDeviceManagementUrl(CString* url) const { + ASSERT1(url); + + if (SUCCEEDED(RegKey::GetValue(MACHINE_REG_UPDATE_DEV, + kRegValueNameDeviceManagementUrl, + url))) { + CORE_LOG(L5, (_T("['device management url' override %s]"), *url)); + return S_OK; + } + + *url = kUrlDeviceManagement; + return S_OK; +} + +CPath ConfigManager::GetPolicyResponsesDir() const { + CString path; + VERIFY1(SUCCEEDED(GetDir32(CSIDL_PROGRAM_FILES, + CString(OMAHA_REL_POLICY_RESPONSES_DIR), + true, + &path))); + return CPath(path); +} + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // Returns the override from the registry locations if present. Otherwise, // returns the default value. // Default value is different value for internal users to make update checks @@ -1017,6 +1044,24 @@ CString ConfigManager::GetTargetVersionPrefix(const GUID& app_guid) { return target_version_prefix; } +bool ConfigManager::IsRollbackToTargetVersionAllowed(const GUID& app_guid) { + if (!IsEnrolledToDomain()) { + OPT_LOG(L5, (_T("[IsRollbackToTargetVersionAllowed][false][%s]") + _T("[machine is not part of a domain]"), + GuidToString(app_guid))); + return false; + } + + CString app_value_name(kRegValueRollbackToTargetVersion); + app_value_name.Append(GuidToString(app_guid)); + + DWORD is_rollback_allowed = 0; + RegKey::GetValue(kRegKeyGoopdateGroupPolicy, + app_value_name, + &is_rollback_allowed); + return !!is_rollback_allowed; +} + bool ConfigManager::AreUpdatesSuppressedNow() { DWORD start_hour = 0; DWORD start_min = 0; @@ -1114,4 +1159,22 @@ CString ConfigManager::GetDownloadPreferenceGroupPolicy() const { return CString(); } +#if defined(HAS_DEVICE_MANAGEMENT) + +CString ConfigManager::GetCloudManagementEnrollmentToken() const { + CString enrollment_token; + HRESULT hr = RegKey::GetValue(kRegKeyCloudManagementGroupPolicy, + kRegValueEnrollmentToken, &enrollment_token); + return SUCCEEDED(hr) ? enrollment_token : CString(); +} + +bool ConfigManager::IsCloudManagementEnrollmentMandatory() const { + DWORD is_mandatory = 0; + HRESULT hr = RegKey::GetValue(kRegKeyCloudManagementGroupPolicy, + kRegValueEnrollmentMandatory, &is_mandatory); + return SUCCEEDED(hr) && is_mandatory != 0; +} + +#endif // defined(HAS_DEVICE_MANAGEMENT) + } // namespace omaha diff --git a/omaha/common/config_manager.h b/omaha/common/config_manager.h index 0d53746..96e45e5 100644 --- a/omaha/common/config_manager.h +++ b/omaha/common/config_manager.h @@ -24,6 +24,7 @@ #define OMAHA_COMMON_CONFIG_MANAGER_H_ #include +#include #include #include "base/basictypes.h" #include "omaha/base/constants.h" @@ -172,6 +173,15 @@ class ConfigManager { // Returns the service endpoint where the usage stats requests are sent. HRESULT GetUsageStatsReportUrl(CString* url) const; +#if defined(HAS_DEVICE_MANAGEMENT) + // Returns the Device Management API url. + HRESULT GetDeviceManagementUrl(CString* url) const; + + // Returns the directory under which the Device Management policies are + // persisted. + CPath GetPolicyResponsesDir() const; +#endif + // Returns the time interval between update checks in seconds. // 0 indicates updates are disabled. int GetLastCheckPeriodSec(bool* is_overridden) const; @@ -257,6 +267,18 @@ class ConfigManager { // an error happened. CString GetDownloadPreferenceGroupPolicy() const; +#if defined(HAS_DEVICE_MANAGEMENT) + + // Returns the value of the "CloudManagementEnrollmentToken" group policy or + // an empty string if the policy is not set or in case of error. + CString GetCloudManagementEnrollmentToken() const; + + // Returns the value of the "CloudManagementEnrollmentMandatory" group policy + // or false if the policy is not set or in case of error. + bool IsCloudManagementEnrollmentMandatory() const; + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // Returns the network configuration override as a string. static HRESULT GetNetConfig(CString* configuration_override); @@ -285,6 +307,11 @@ class ConfigManager { // * "55.24.34": update to this specific version only. static CString GetTargetVersionPrefix(const GUID& app_guid); + // Returns whether the RollbackToTargetVersion policy has been set for the + // app. If RollbackToTargetVersion is set, the TargetVersionPrefix policy + // governs the version to rollback clients with higher versions to. + static bool IsRollbackToTargetVersionAllowed(const GUID& app_guid); + // For domain-joined machines, checks the current time against the times that // updates are suppressed. Returns true if the current time falls between the // start time and the duration. @@ -306,7 +333,7 @@ class ConfigManager { bool is_running_from_official_user_dir_; bool is_running_from_official_machine_dir_; - DISALLOW_EVIL_CONSTRUCTORS(ConfigManager); + DISALLOW_COPY_AND_ASSIGN(ConfigManager); }; } // namespace omaha diff --git a/omaha/common/config_manager_unittest.cc b/omaha/common/config_manager_unittest.cc index 189576c..fdccb2a 100644 --- a/omaha/common/config_manager_unittest.cc +++ b/omaha/common/config_manager_unittest.cc @@ -70,6 +70,23 @@ HRESULT SetPolicyString(const TCHAR* policy_name, const CString& value) { return RegKey::SetValue(kPolicyKey, policy_name, value); } +#if defined(HAS_DEVICE_MANAGEMENT) + +const TCHAR* const kCloudManagementPolicyKey = + _T("HKLM\\Software\\Policies\\") SHORT_COMPANY_NAME + _T("\\CloudManagement\\"); + +HRESULT SetCloudManagementPolicy(const TCHAR* policy_name, DWORD value) { + return RegKey::SetValue(kCloudManagementPolicyKey, policy_name, value); +} + +HRESULT SetCloudManagementPolicyString(const TCHAR* policy_name, + const CString& value) { + return RegKey::SetValue(kCloudManagementPolicyKey, policy_name, value); +} + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // DeleteDirectory can fail with ERROR_PATH_NOT_FOUND if the parent directory // does not exist. Consider this a success for testing purposes. HRESULT DeleteTestDirectory(const TCHAR* dir) { @@ -2001,4 +2018,22 @@ TEST_P(ConfigManagerTest, GetDownloadPreferenceGroupPolicy) { cm_->GetDownloadPreferenceGroupPolicy()); } +#if defined(HAS_DEVICE_MANAGEMENT) + +TEST_P(ConfigManagerTest, GetCloudManagementEnrollmentToken) { + const CString token_value = _T("f6f767ba-8cfb-4d95-a26a-b3d714ddf1a2"); + EXPECT_STREQ(cm_->GetCloudManagementEnrollmentToken(), _T("")); + EXPECT_SUCCEEDED(SetCloudManagementPolicyString( + kRegValueEnrollmentToken, token_value)); + EXPECT_STREQ(cm_->GetCloudManagementEnrollmentToken(), token_value); +} + +TEST_P(ConfigManagerTest, IsCloudManagementEnrollmentMandatory) { + EXPECT_FALSE(cm_->IsCloudManagementEnrollmentMandatory()); + EXPECT_SUCCEEDED(SetCloudManagementPolicy(kRegValueEnrollmentMandatory, 1U)); + EXPECT_TRUE(cm_->IsCloudManagementEnrollmentMandatory()); +} + +#endif // defined(HAS_DEVICE_MANAGEMENT) + } // namespace omaha diff --git a/omaha/common/const_cmd_line.h b/omaha/common/const_cmd_line.h index eb1f012..4100741 100644 --- a/omaha/common/const_cmd_line.h +++ b/omaha/common/const_cmd_line.h @@ -158,9 +158,6 @@ const TCHAR* const kCmdLinePing = _T("ping"); // These are used for debug, testing, etc. // -// Run network diagnostics. -const TCHAR* const kCmdLineNetDiags = _T("netdiags"); - // The "crash" switch indicates that Omaha should crash upon startup. // This option is used to test the crash reporting system. const TCHAR* const kCmdLineCrash = _T("crash"); @@ -303,6 +300,15 @@ const TCHAR* const kExtraArgBrowserType = _T("browser"); // applications via that API after the meta-installer exits. const TCHAR* const kExtraArgRuntime = _T("runtime"); +#if defined(HAS_DEVICE_MANAGEMENT) + +// "etoken" extra argument gives Omaha an enrollment token. Omaha will use this +// for per-machine installs to register the machine with Google's device +// management server. +const TCHAR* const kExtraArgEnrollmentToken = _T("etoken"); + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // The list of arguments that are needed for a meta-installer, to // indicate which application is being installed. These are stamped // inside the meta-installer binary. diff --git a/omaha/common/const_goopdate.h b/omaha/common/const_goopdate.h index 5383b86..1e424ce 100644 --- a/omaha/common/const_goopdate.h +++ b/omaha/common/const_goopdate.h @@ -222,10 +222,10 @@ const TCHAR* const kRegValueDelayOmahaUninstall = _T("DelayUninstall"); const TCHAR* const kRegValueOmahaEulaAccepted = _T("eulaaccepted"); // TODO(omaha3): Consider renaming these if there is not a upgrade problem. // If we can't consider moving all "gupdate" values to the customization file. -const TCHAR* const kRegValueServiceName = _T("omaha_service_name"); -const TCHAR* const kRegValueMediumServiceName = _T("omaham_service_name"); -const TCHAR* const kRegValueTaskNameC = _T("omaha_task_name_c"); -const TCHAR* const kRegValueTaskNameUA = _T("omaha_task_name_ua"); +const TCHAR* const kRegValueServiceName = _T("brave_service_name"); +const TCHAR* const kRegValueMediumServiceName = _T("bravem_service_name"); +const TCHAR* const kRegValueTaskNameC = _T("brave_task_name_c"); +const TCHAR* const kRegValueTaskNameUA = _T("brave_task_name_ua"); const TCHAR* const kRegValueLastStartedAU = _T("LastStartedAU"); const TCHAR* const kRegValueLastChecked = _T("LastChecked"); const TCHAR* const kRegValueLastCoreRun = _T("LastCoreRun"); @@ -266,10 +266,37 @@ const TCHAR* const kRegValueDataLegacyUserId = _T("; legacy"); const TCHAR* const kHeaderValueNumUidRotation = _T("cnt"); const TCHAR* const kHeaderValueUidAge = _T("age"); +#if defined(HAS_DEVICE_MANAGEMENT) + +// The full path of the registry key where Omaha persists state related to +// cloud-based device management. +const TCHAR kRegKeyCompanyEnrollment[] = + MACHINE_KEY COMPANY_MAIN_KEY _T("Enrollment\\"); + +#if defined(HAS_LEGACY_DM_CLIENT) + +// The full path of the registry key where Google Chrome stored the DM token +// when it was solely responsible for registration and use. +const TCHAR kRegKeyLegacyEnrollment[] = + MACHINE_KEY_64 COMPANY_MAIN_KEY LEGACY_DM_CLIENT_APP _T("\\Enrollment\\"); + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +// The name of the registry value, within an "Enrollment" key above, holding a +// device management token. +const TCHAR kRegValueDmToken[] = _T("dmtoken"); + +// The name of the registry value, within Omaha's ClientState key, where an +// install's enrollment token is stored. +const TCHAR kRegValueCloudManagementEnrollmentToken[] = + _T("CloudManagementEnrollmentToken"); + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // TODO(omaha3): Consider moving all "gupdate" values to the customization file. // Use a non-gupdate name for the new medium service. -const TCHAR* const kServicePrefix = _T("omaha"); -const TCHAR* const kMediumServicePrefix = _T("omaham"); +const TCHAR* const kServicePrefix = _T("brave"); +const TCHAR* const kMediumServicePrefix = _T("bravem"); const TCHAR* const kScheduledTaskNameUserPrefix = APP_NAME_IDENTIFIER _T("TaskUser"); @@ -302,6 +329,11 @@ const int kDownloadEventId = 15; // Network Request events. const int kNetworkRequestEventId = 20; +// Device management events. +const int kEnrollmentFailedEventId = 30; +const int kEnrollmentRequiresNetworkEventId = 31; +const int kRefreshPoliciesFailedEventId = 32; + // Maximum value the server can respond for elapsed_seconds attribute in // element. The value is one day plus an hour ("fall back" // daylight savings). @@ -353,11 +385,6 @@ const TCHAR* const kProgIDGoogleUpdateCoreMachine = const TCHAR* const kProgIDProcessLauncher = APP_NAME_IDENTIFIER _T(".ProcessLauncher"); -const TCHAR* const kProgIDOneClickProcessLauncherUser = - _T(SHORT_COMPANY_NAME_ANSI) _T(".OneClickProcessLauncherUser"); -const TCHAR* const kProgIDOneClickProcessLauncherMachine = - _T(SHORT_COMPANY_NAME_ANSI) _T(".OneClickProcessLauncherMachine"); - const TCHAR* const kProgIDCoCreateAsync = APP_NAME_IDENTIFIER _T(".CoCreateAsync"); diff --git a/omaha/common/const_group_policy.h b/omaha/common/const_group_policy.h index bd25ec9..715c060 100644 --- a/omaha/common/const_group_policy.h +++ b/omaha/common/const_group_policy.h @@ -26,6 +26,21 @@ namespace omaha { const TCHAR* const kRegKeyGoopdateGroupPolicy = MACHINE_KEY GOOPDATE_POLICIES_RELATIVE; +// Key containing Cloud Management Group Policy settings. All policies are in +// HKLM. +const TCHAR* const kRegKeyCloudManagementGroupPolicy = + MACHINE_KEY CLOUD_MANAGEMENT_POLICIES_RELATIVE; + +#if defined(HAS_LEGACY_DM_CLIENT) + +// The location where Google Chrome looks for an enrollment token. This will be +// phased out once registration via Google Update is fully deployed and the +// admin panel is delivering .reg files using the location below. +const TCHAR* const kRegKeyLegacyGroupPolicy = + MACHINE_KEY COMPANY_POLICIES_MAIN_KEY LEGACY_DM_CLIENT_APP _T("\\"); + +#endif // defined(HAS_LEGACY_DM_CLIENT) + // Preferences Category. const TCHAR* const kRegValueAutoUpdateCheckPeriodOverrideMinutes = _T("AutoUpdateCheckPeriodMinutes"); @@ -47,6 +62,32 @@ const TCHAR* const kRegValueDownloadPreference = _T("DownloadPreference"); // Specifies that urls that can be cached by proxies are preferred. const TCHAR* const kDownloadPreferenceCacheable = _T("cacheable"); +#if defined(HAS_DEVICE_MANAGEMENT) + +// The name of the policy holding a token used to enroll in cloud-based +// device management. +const TCHAR* const kRegValueEnrollmentToken = _T("EnrollmentToken"); + +// The name of the policy indicating that enrollment in cloud-based device +// management is mandatory. +const TCHAR* const kRegValueEnrollmentMandatory = _T("EnrollmentMandatory"); + +#if defined(HAS_LEGACY_DM_CLIENT) + +// The name of the Google Chrome policy holding a token used to enroll in +// cloud-based device management. +const TCHAR* const kRegValueCloudManagementEnrollmentTokenPolicy = + _T("CloudManagementEnrollmentToken"); + +// The name of the old Google Chrome policy holding a token used to enroll in +// cloud-based device management. +const TCHAR* const kRegValueMachineLevelUserCloudPolicyEnrollmentToken = + _T("MachineLevelUserCloudPolicyEnrollmentToken"); + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // Proxy Server Category. (The registry keys used, and the values of ProxyMode, // directly mirror that of Chrome. However, we omit ProxyBypassList, as the // domains that Omaha uses are largely fixed.) @@ -67,6 +108,8 @@ const TCHAR* const kRegValueInstallAppPrefix = _T("Install"); const TCHAR* const kRegValueUpdateAppsDefault = _T("UpdateDefault"); const TCHAR* const kRegValueUpdateAppPrefix = _T("Update"); const TCHAR* const kRegValueTargetVersionPrefix = _T("TargetVersionPrefix"); +const TCHAR* const kRegValueRollbackToTargetVersion + = _T("RollbackToTargetVersion"); const int kPolicyDisabled = 0; const int kPolicyEnabled = 1; diff --git a/omaha/common/controlled_object.h b/omaha/common/controlled_object.h deleted file mode 100644 index 26431ae..0000000 --- a/omaha/common/controlled_object.h +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2005-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// This class is similar to CComContainedObject. The primary difference is with -// respect to QueryInterface, which this class handles itself, as opposed to -// CComContainedObject that delegates that to the outer unknown. - -#ifndef OMAHA_COMMON_CONTROLLED_OBJECT_H_ -#define OMAHA_COMMON_CONTROLLED_OBJECT_H_ - -#include -#include "base/scoped_ptr.h" -#include "omaha/base/debug.h" -#include "omaha/base/logging.h" -#include "omaha/base/scoped_ptr_address.h" - -namespace omaha { - -template -class ControlledObject : public CComContainedObject { - public: - typedef CComContainedObject BaseClass; - typedef ControlledObject ControlledObj; - - // The base class CComContainedObject stores pv, and delegates to this - // controlling unknown subsequent calls to the lifetime methods - // AddRef/Release. - explicit ControlledObject(void* pv) : BaseClass(pv) {} - virtual ~ControlledObject() {} - - STDMETHOD(QueryInterface)(REFIID iid, void** ppv) throw() { - return _InternalQueryInterface(iid, ppv); - } - - // TODO(omaha): ASSERT on controlling_unknown. The unit tests need to be - // fixed for this. - static HRESULT WINAPI CreateInstance(IUnknown* controlling_unknown, - ControlledObj** pp) throw() { - ASSERT1(pp); - if (!controlling_unknown) { - CORE_LOG(LW, (_T("[CreateInstance - controlling_unknown is NULL]"))); - } - - *pp = NULL; - scoped_ptr p(new ControlledObj(controlling_unknown)); - if (!p.get()) { - return E_OUTOFMEMORY; - } - - HRESULT hr = p->FinalConstruct(); - if (FAILED(hr)) { - return hr; - } - - *pp = p.release(); - return S_OK; - } - - template - HRESULT STDMETHODCALLTYPE QueryInterface(Q** pp) throw() { - return QueryInterface(__uuidof(Q), reinterpret_cast(pp)); - } -}; - -} // namespace omaha - -#endif // OMAHA_COMMON_CONTROLLED_OBJECT_H_ - diff --git a/omaha/common/crash_utils.cc b/omaha/common/crash_utils.cc index f9e8bd7..125b558 100644 --- a/omaha/common/crash_utils.cc +++ b/omaha/common/crash_utils.cc @@ -15,7 +15,6 @@ #include "omaha/common/crash_utils.h" -#include #include #include #include @@ -23,7 +22,6 @@ #include #include -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/const_object_names.h" #include "omaha/base/constants.h" @@ -34,12 +32,12 @@ #include "omaha/base/omaha_version.h" #include "omaha/base/path.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/user_info.h" #include "omaha/base/vistautil.h" #include "omaha/common/command_line_builder.h" #include "omaha/common/config_manager.h" #include "omaha/common/goopdate_utils.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/common/ipc_protocol.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" diff --git a/omaha/common/crash_utils.h b/omaha/common/crash_utils.h index 3cd03df..cf94a88 100644 --- a/omaha/common/crash_utils.h +++ b/omaha/common/crash_utils.h @@ -20,7 +20,10 @@ #ifndef OMAHA_COMMON_CRASH_UTILS_H_ #define OMAHA_COMMON_CRASH_UTILS_H_ +#include +#include #include + #include namespace google_breakpad { diff --git a/omaha/common/crash_utils_unittest.cc b/omaha/common/crash_utils_unittest.cc index d033828..fbeec5c 100644 --- a/omaha/common/crash_utils_unittest.cc +++ b/omaha/common/crash_utils_unittest.cc @@ -22,7 +22,6 @@ #include "omaha/base/const_object_names.h" #include "omaha/base/error.h" #include "omaha/base/file.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/time.h" #include "omaha/base/user_info.h" #include "omaha/base/utils.h" @@ -32,6 +31,7 @@ #include "omaha/common/event_logger.h" #include "omaha/common/goopdate_utils.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/common/ipc_protocol.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" diff --git a/omaha/common/event_logger.cc b/omaha/common/event_logger.cc index 0ab7f8b..17e7b4d 100644 --- a/omaha/common/event_logger.cc +++ b/omaha/common/event_logger.cc @@ -17,6 +17,8 @@ #include "omaha/common/event_logger.h" #include #include +#include +#include #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -30,7 +32,7 @@ namespace omaha { void LogEventHelper(WORD type, DWORD id, size_t count, const TCHAR** strings, const TCHAR* ctx) { - ASSERT1(count <= kint16max); + ASSERT1(count <= static_cast(std::numeric_limits::max())); if (!ConfigManager::Instance()->CanLogEvents(type)) { return; } @@ -130,8 +132,6 @@ HRESULT EventLogger::ReportEvent(const TCHAR* src_name, } // Opens the log on the local computer. - // The macro RegisterEventSource has been redefined to evaluate to NULL in - // precompile.h, so we need to explicitly use ::RegisterEventSourceW here. HANDLE hlog = ::RegisterEventSourceW(NULL, src_name); if (!hlog) { return HRESULTFromLastError(); diff --git a/omaha/common/event_logger.h b/omaha/common/event_logger.h index 8a2c89f..dbeefe5 100644 --- a/omaha/common/event_logger.h +++ b/omaha/common/event_logger.h @@ -142,7 +142,7 @@ class GoogleUpdateLogEvent { int id_; bool is_machine_; - DISALLOW_EVIL_CONSTRUCTORS(GoogleUpdateLogEvent); + DISALLOW_COPY_AND_ASSIGN(GoogleUpdateLogEvent); }; } // namespace omaha diff --git a/omaha/common/exception_handler.cc b/omaha/common/exception_handler.cc index f8e57ff..ad0813f 100644 --- a/omaha/common/exception_handler.cc +++ b/omaha/common/exception_handler.cc @@ -22,6 +22,7 @@ #include #include #include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/file.h" @@ -45,8 +46,8 @@ using crash_utils::CustomInfoMap; // static HRESULT OmahaExceptionHandler::Create(bool is_machine, - const CustomInfoMap& custom_info_map, - OmahaExceptionHandler** handler_out) { + const CustomInfoMap& custom_info_map, + std::unique_ptr* handler_out) { CORE_LOG(L3, (_T("[OmahaExceptionHandler::Create][%d]"), is_machine)); ASSERT1(OkayToInstall()); @@ -55,7 +56,7 @@ HRESULT OmahaExceptionHandler::Create(bool is_machine, return E_POINTER; } - scoped_ptr outp(new OmahaExceptionHandler(is_machine)); + std::unique_ptr outp(new OmahaExceptionHandler(is_machine)); HRESULT hr = outp->Initialize(custom_info_map); if (FAILED(hr)) { CORE_LOG(L3, (_T("[Initialize failed][%#08x]"), hr)); @@ -68,7 +69,7 @@ HRESULT OmahaExceptionHandler::Create(bool is_machine, return hr; } - *handler_out = outp.release(); + handler_out->reset(outp.release()); return S_OK; } diff --git a/omaha/common/exception_handler.h b/omaha/common/exception_handler.h index 58e841a..02a7868 100644 --- a/omaha/common/exception_handler.h +++ b/omaha/common/exception_handler.h @@ -21,8 +21,9 @@ #include #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/common/const_goopdate.h" #include "omaha/common/crash_utils.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" @@ -42,7 +43,7 @@ class OmahaExceptionHandler { public: static HRESULT Create(bool is_machine, const CustomInfoMap& custom_info_map, - OmahaExceptionHandler** handler_out); + std::unique_ptr* handler_out); ~OmahaExceptionHandler(); @@ -102,7 +103,7 @@ class OmahaExceptionHandler { CString version_postfix_string_; CString crash_dir_; - scoped_ptr breakpad_exception_handler_; + std::unique_ptr breakpad_exception_handler_; std::vector custom_entries_; friend class ExceptionHandlerTest; diff --git a/omaha/common/exception_handler_unittest.cc b/omaha/common/exception_handler_unittest.cc index d118c37..dec092f 100644 --- a/omaha/common/exception_handler_unittest.cc +++ b/omaha/common/exception_handler_unittest.cc @@ -13,10 +13,9 @@ // limitations under the License. // ======================================================================== -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_ptr_address.h" -#include "omaha/common/command_line.h" #include "omaha/common/exception_handler.h" + +#include "omaha/common/command_line.h" #include "omaha/testing/unit_test.h" using google_breakpad::CustomInfoEntry; @@ -41,7 +40,7 @@ class ExceptionHandlerTest : public testing::Test { return OmahaExceptionHandler::Create(is_machine, custom_info_map, - address(handler_)); + &handler_); } void UninstallHandler() { @@ -64,7 +63,7 @@ class ExceptionHandlerTest : public testing::Test { return CString(); } - scoped_ptr handler_; + std::unique_ptr handler_; }; // Installs and uninstalls the crash handler in the user case. diff --git a/omaha/common/extra_args_parser.cc b/omaha/common/extra_args_parser.cc index 5b3645e..ee03a78 100644 --- a/omaha/common/extra_args_parser.cc +++ b/omaha/common/extra_args_parser.cc @@ -271,6 +271,13 @@ HRESULT ExtraArgsParser::HandleToken(const CString& token, return E_INVALIDARG; } args->runtime_only = true; +#if defined(HAS_DEVICE_MANAGEMENT) + } else if (name.CompareNoCase(kExtraArgEnrollmentToken) == 0) { + if (value.GetLength() > kEnrollmentTokenMaxLength) { + return E_INVALIDARG; + } + args->enrollment_token = value; +#endif // The following args are per-app. } else if (name.CompareNoCase(kExtraArgAdditionalParameters) == 0) { diff --git a/omaha/common/extra_args_parser.h b/omaha/common/extra_args_parser.h index 797ce72..c5c3778 100644 --- a/omaha/common/extra_args_parser.h +++ b/omaha/common/extra_args_parser.h @@ -49,7 +49,7 @@ class ExtraArgsParser { CommandLineAppArgs cur_extra_app_args_; bool first_app_; - DISALLOW_EVIL_CONSTRUCTORS(ExtraArgsParser); + DISALLOW_COPY_AND_ASSIGN(ExtraArgsParser); }; } // namespace omaha diff --git a/omaha/common/google_signaturevalidator.cc b/omaha/common/google_signaturevalidator.cc index f10814a..bd49288 100644 --- a/omaha/common/google_signaturevalidator.cc +++ b/omaha/common/google_signaturevalidator.cc @@ -14,9 +14,12 @@ // ======================================================================== #include "omaha/common/google_signaturevalidator.h" + #include #include #include + +#include "base/basictypes.h" #include "omaha/base/const_code_signing.h" #include "omaha/base/signaturevalidator.h" @@ -34,10 +37,14 @@ HRESULT VerifyGoogleAuthenticodeSignature(const CString& filename, expected_hashes.push_back(kPublicKeyHashes[i]); } + std::vector subject; + subject.push_back(kSha256CertificateSubjectName); + subject.push_back(kCertificateSubjectName); + const bool allow_test_variant = false; const bool check_cert_is_valid_now = false; hr = VerifyCertificate(filename, - kCertificateSubjectName, + subject, allow_test_variant, check_cert_is_valid_now, expected_hashes.empty() ? NULL : &expected_hashes); diff --git a/omaha/common/google_signaturevalidator_unittest.cc b/omaha/common/google_signaturevalidator_unittest.cc index a264406..a1ce60d 100644 --- a/omaha/common/google_signaturevalidator_unittest.cc +++ b/omaha/common/google_signaturevalidator_unittest.cc @@ -22,6 +22,10 @@ namespace omaha { +// This test uses certificate serial numbers to encode the names of the test +// files used below. This is slightly confusing since the signing tools and +// build scrips use the certificate thumbprint (the sha1 hash of +// the certificate) to choose what certificate to sign with. TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { // Check current Omaha certificate. CString filename(app_util::GetCurrentModuleDirectory()); @@ -30,7 +34,14 @@ TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { EXPECT_TRUE(File::Exists(filename)); EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); - // Check current Chrome certificate. + // Check current Chrome setup file. + filename = app_util::GetCurrentModuleDirectory(); + EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), + _T("unittest_support\\chrome_setup.exe"))); + EXPECT_TRUE(File::Exists(filename)); + EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); + + // Check 2912C70C9A2B8A3EF6F6074662D68B8D Chrome certificate. filename = app_util::GetCurrentModuleDirectory(); EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), _T("unittest_support\\chrome_certificate_") @@ -53,7 +64,7 @@ TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { EXPECT_TRUE(File::Exists(filename)); EXPECT_HRESULT_FAILED(VerifyGoogleAuthenticodeSignature(filename, true)); - // Check new Omaha/Chrome certificates. + // Check Omaha/Chrome Thawte certificate sha1 (11/28/2016 to 11/21/2019). filename = app_util::GetCurrentModuleDirectory(); EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), _T("unittest_support\\sha1_") @@ -61,6 +72,7 @@ TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { EXPECT_TRUE(File::Exists(filename)); EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); + // Check Omaha/Chrome certificate sha256 (12/15/2015 to 12/16/2018). filename = app_util::GetCurrentModuleDirectory(); EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), _T("unittest_support\\sha2_") @@ -68,6 +80,8 @@ TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { EXPECT_TRUE(File::Exists(filename)); EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); + // Check Omaha/Chrome dual signed certificates sha1 and sha2 + // (11/28/2016 to 11/21/2019) and (12/15/2015 to 12/16/2018), respectively. filename = app_util::GetCurrentModuleDirectory(); EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), _T("unittest_support\\Sha1_") @@ -76,6 +90,14 @@ TEST(GoogleSignatureValidatorTest, GoogleSignatureValidator) { _T("2a9c21acaaa63a3c58a7b9322bee948d.exe"))); EXPECT_TRUE(File::Exists(filename)); EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); + + // Check Omaha/Chrome certificate sha256 (11/06/2018 to 11/17/2021). + filename = app_util::GetCurrentModuleDirectory(); + EXPECT_TRUE(::PathAppend(CStrBuf(filename, MAX_PATH), + _T("unittest_support\\sha2_") + _T("0c15be4a15bb0903c901b1d6c265302f.msi"))); + EXPECT_TRUE(File::Exists(filename)); + EXPECT_HRESULT_SUCCEEDED(VerifyGoogleAuthenticodeSignature(filename, true)); } } // namespace omaha diff --git a/omaha/common/goopdate_command_line_validator.cc b/omaha/common/goopdate_command_line_validator.cc index 80f17a6..9d92157 100644 --- a/omaha/common/goopdate_command_line_validator.cc +++ b/omaha/common/goopdate_command_line_validator.cc @@ -77,10 +77,6 @@ HRESULT GoopdateCommandLineValidator::Setup() { SafeCStringFormat(&cmd_line, _T("/%s"), kCmdUnregServer); CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnUnregServer); - // gu.exe /netdiags - SafeCStringFormat(&cmd_line, _T("/%s"), kCmdLineNetDiags); - CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnNetDiags); - // gu.exe /crash SafeCStringFormat(&cmd_line, _T("/%s"), kCmdLineCrash); CreateScenario(cmd_line, &GoopdateCommandLineValidator::OnCrash); @@ -313,11 +309,6 @@ HRESULT GoopdateCommandLineValidator::OnUnregServer() { return S_OK; } -HRESULT GoopdateCommandLineValidator::OnNetDiags() { - args_->mode = COMMANDLINE_MODE_NETDIAGS; - return S_OK; -} - HRESULT GoopdateCommandLineValidator::OnCrash() { args_->mode = COMMANDLINE_MODE_CRASH; return S_OK; diff --git a/omaha/common/goopdate_command_line_validator.h b/omaha/common/goopdate_command_line_validator.h index 0fdd5c1..4d08417 100644 --- a/omaha/common/goopdate_command_line_validator.h +++ b/omaha/common/goopdate_command_line_validator.h @@ -18,11 +18,10 @@ #include #include - #include +#include #include "base/basictypes.h" -#include "base/scoped_ptr.h" namespace omaha { @@ -58,7 +57,6 @@ class GoopdateCommandLineValidator { HRESULT OnServiceUnregister(); HRESULT OnRegServer(); HRESULT OnUnregServer(); - HRESULT OnNetDiags(); HRESULT OnCrash(); HRESULT OnComServer(); HRESULT OnComBroker(); @@ -86,10 +84,10 @@ class GoopdateCommandLineValidator { const CommandLineParser* parser_; CommandLineArgs* args_; - scoped_ptr validator_; + std::unique_ptr validator_; MapScenarioHandlers scenario_handlers_; - DISALLOW_EVIL_CONSTRUCTORS(GoopdateCommandLineValidator); + DISALLOW_COPY_AND_ASSIGN(GoopdateCommandLineValidator); }; } // namespace omaha diff --git a/omaha/common/goopdate_utils.cc b/omaha/common/goopdate_utils.cc index 533d0f1..a2f9402 100644 --- a/omaha/common/goopdate_utils.cc +++ b/omaha/common/goopdate_utils.cc @@ -14,8 +14,11 @@ // ======================================================================== #include "omaha/common/goopdate_utils.h" + #include +#include #include + #include "omaha/base/app_util.h" #include "omaha/base/const_addresses.h" #include "omaha/base/const_object_names.h" @@ -32,8 +35,6 @@ #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/scoped_impersonation.h" #include "omaha/base/service_utils.h" #include "omaha/base/signatures.h" @@ -50,6 +51,7 @@ #include "omaha/common/const_goopdate.h" #include "omaha/common/oem_install_utils.h" #include "omaha/statsreport/metrics.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "goopdate/omaha3_idl.h" namespace omaha { @@ -1378,19 +1380,6 @@ bool IsAppInstallWorkerRunning(bool is_machine) { return !processes.empty(); } -// Returns true if the version does not begin with "1.0." or "1.1.". -bool IsGoogleUpdate2OrLater(const CString& version) { - const ULONGLONG kFirstOmaha2Version = MAKEDLLVERULL(1, 2, 0, 0); - ULONGLONG version_number = VersionFromString(version); - ASSERT1(0 != version_number); - - if (kFirstOmaha2Version <= version_number) { - return true; - } - - return false; -} - HRESULT WriteInstallerDataToTempFile(const CString& installer_data, CString* installer_data_file_path) { ASSERT1(installer_data_file_path); diff --git a/omaha/common/goopdate_utils.h b/omaha/common/goopdate_utils.h index 7c20079..d138b55 100644 --- a/omaha/common/goopdate_utils.h +++ b/omaha/common/goopdate_utils.h @@ -26,7 +26,7 @@ // is especially important because of the duplicate BrowserType definition. #include "omaha/base/browser_utils.h" #include "omaha/base/synchronized.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -242,9 +242,6 @@ HRESULT WriteNameValuePairsToHandle(const HANDLE file_handle, // Returns true is any of the install workers is running. bool IsAppInstallWorkerRunning(bool is_machine); -// Returns whether the version is an "Omaha 2" version or later. -bool IsGoogleUpdate2OrLater(const CString& version); - // Converts the installer_data value to UTF8. Then writes this UTF8 data // prefixed with the UTF8 BOM of EF BB BF to a temp file. Returns the path to // temp file that was created. The returned path will be quote-enclosed by diff --git a/omaha/common/goopdate_utils_unittest.cc b/omaha/common/goopdate_utils_unittest.cc index 1d75926..d9fd063 100644 --- a/omaha/common/goopdate_utils_unittest.cc +++ b/omaha/common/goopdate_utils_unittest.cc @@ -13,6 +13,8 @@ // limitations under the License. // ======================================================================== +#include "omaha/common/goopdate_utils.h" + #include #include #include @@ -20,6 +22,7 @@ #include #include #include + #include "omaha/base/app_util.h" #include "omaha/base/atl_regexp.h" #include "omaha/base/browser_utils.h" @@ -31,8 +34,6 @@ #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/scoped_ptr_cotask.h" #include "omaha/base/signatures.h" #include "omaha/base/string.h" @@ -45,11 +46,11 @@ #include "omaha/common/config_manager.h" #include "omaha/common/const_goopdate.h" #include "omaha/common/const_group_policy.h" -#include "omaha/common/goopdate_utils.h" #include "omaha/common/oem_install_utils.h" #include "omaha/common/update3_utils.h" #include "omaha/testing/resource.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -1055,14 +1056,14 @@ void ExpectMacMatchViaWMI(const CString& mac_address) { ASSERT_SUCCEEDED(locator.CoCreateInstance(CLSID_WbemAdministrativeLocator)); CComPtr service; - ASSERT_SUCCEEDED(locator->ConnectServer(_T("root\\cimv2"), - NULL, - NULL, - NULL, - WBEM_FLAG_CONNECT_USE_MAX_WAIT, - NULL, - NULL, - &service)); + ASSERT_SUCCEEDED(locator->ConnectServer(CComBSTR(_T("root\\cimv2")), + NULL, + NULL, + NULL, + WBEM_FLAG_CONNECT_USE_MAX_WAIT, + NULL, + NULL, + &service)); ASSERT_SUCCEEDED(update3_utils::SetProxyBlanketAllowImpersonate(service)); @@ -1464,55 +1465,6 @@ TEST(GoopdateUtilsTest, ReadNameValuePairsFromFileTest_ReadManyPairs) { ValidateStringMapEquality(pairs_write, pairs_read); } -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_LegacyVersions) { - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.0.0.0"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.103.9"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.65535.65535"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_Omaha2AndLater) { - EXPECT_TRUE(IsGoogleUpdate2OrLater(_T("1.2.0.0"))); - EXPECT_TRUE(IsGoogleUpdate2OrLater(_T("1.2.0111.2222"))); - EXPECT_TRUE(IsGoogleUpdate2OrLater(_T("1.3.456.7890"))); - EXPECT_TRUE(IsGoogleUpdate2OrLater(_T("2.0.0.0"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_VersionZero) { - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("0.0.0.0"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_VersionUpperLimits) { - EXPECT_TRUE(IsGoogleUpdate2OrLater(_T("65535.65535.65535.65535"))); - - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("65536.65536.65536.65536"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.2.65536.65536"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.65536.65536"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_TooFewElements) { - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.1"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_ExtraPeriod) { - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.2.3."))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_TooManyElements) { - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.1.2.3.4"))); -} - -TEST(GoopdateUtilsTest, IsGoogleUpdate2OrLater_Char) { - ExpectAsserts expect_asserts; - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.B.3.4"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.2.3.B"))); - EXPECT_FALSE(IsGoogleUpdate2OrLater(_T("1.2.3.9B"))); -} - TEST(GoopdateUtilsTest, WriteInstallerDataToTempFile) { CStringA utf8_bom; utf8_bom.Format("%c%c%c", 0xEF, 0xBB, 0xBF); diff --git a/omaha/common/omaha_customization_unittest.cc b/omaha/common/omaha_customization_unittest.cc index a1fb728..3ab14f1 100644 --- a/omaha/common/omaha_customization_unittest.cc +++ b/omaha/common/omaha_customization_unittest.cc @@ -45,7 +45,7 @@ TEST(OmahaCustomizationTest, Constants_BuildFiles) { // haven't changed. But, unanticipated changes to most of these // would cause build breaks anyways! Consider deleting them. #ifdef GOOGLE_UPDATE_BUILD - EXPECT_STREQ("Google Inc.", FULL_COMPANY_NAME_ANSI); + EXPECT_STREQ("Google LLC", FULL_COMPANY_NAME_ANSI); EXPECT_STREQ("Google", SHORT_COMPANY_NAME_ANSI); EXPECT_STREQ("Update", PRODUCT_NAME_ANSI); @@ -78,7 +78,6 @@ TEST(OmahaCustomizationTest, Constants_BuildFiles) { // Primary omaha_version_utils values. EXPECT_STREQ(_T("npGoogleOneClick"), ONECLICK_PLUGIN_NAME); EXPECT_STREQ(_T("npGoogleUpdate"), UPDATE_PLUGIN_NAME); - EXPECT_STREQ(_T("GoopdateBho"), BHO_NAME); // Filenames from omaha_version_utils. EXPECT_STREQ( @@ -86,7 +85,6 @@ TEST(OmahaCustomizationTest, Constants_BuildFiles) { ONECLICK_PLUGIN_FILENAME); EXPECT_STREQ(_T("npGoogleUpdate") _T(UPDATE_PLUGIN_VERSION_ANSI) _T(".dll"), UPDATE_PLUGIN_FILENAME); - EXPECT_STREQ(_T("GoopdateBho.dll"), BHO_FILENAME); } TEST(OmahaCustomizationTest, Constants_Names) { @@ -97,7 +95,7 @@ TEST(OmahaCustomizationTest, Constants_Names) { // haven't changed. But, unanticipated changes to most of these // would cause build breaks anyways! Consider deleting them. #ifdef GOOGLE_UPDATE_BUILD - EXPECT_STREQ(_T("Google Inc."), kFullCompanyName); + EXPECT_STREQ(_T("Google LLC"), kFullCompanyName); EXPECT_STREQ(_T("Google"), SHORT_COMPANY_NAME); EXPECT_STREQ(_T("Google"), kShortCompanyName); EXPECT_STREQ(_T("Update"), PRODUCT_NAME); @@ -245,7 +243,7 @@ TEST(OmahaCustomizationTest, Constants_Addresses) { EXPECT_STREQ(_T("https://update.googleapis.com/service/update2"), kUrlPing); EXPECT_STREQ(_T("https://clients2.google.com/cr/report"), kUrlCrashReport); EXPECT_STREQ(_T("https://www.google.com/support/installer/?"), kUrlMoreInfo); - EXPECT_STREQ(_T("https://clients2.google.com/service/check2"), + EXPECT_STREQ(_T("https://clients2.google.com/service/check2?crx3=true"), kUrlCodeRedCheck); EXPECT_STREQ(_T("https://clients5.google.com/tbproxy/usagestats"), kUrlUsageStatsReport); diff --git a/omaha/common/ping.cc b/omaha/common/ping.cc index 1ac43d7..b1e5409 100644 --- a/omaha/common/ping.cc +++ b/omaha/common/ping.cc @@ -14,13 +14,12 @@ // ======================================================================== #include "omaha/common/ping.h" -#include "base/scoped_ptr.h" + #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scoped_impersonation.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" @@ -38,6 +37,7 @@ #include "omaha/goopdate/app_bundle.h" #include "omaha/goopdate/update_request_utils.h" #include "omaha/goopdate/update_response_utils.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -548,8 +548,8 @@ HRESULT Ping::SendString(bool is_machine, return hr; } - scoped_ptr response(xml::UpdateResponse::Create()); - hr = web_service_client.SendString(&request_string, response.get()); + std::unique_ptr response(xml::UpdateResponse::Create()); + hr = web_service_client.SendString(false, &request_string, response.get()); if (FAILED(hr)) { CORE_LOG(LE, (_T("[WebServicesClient::SendString failed][0x%08x]"), hr)); return hr; diff --git a/omaha/common/ping.h b/omaha/common/ping.h index a79b25f..ecd5f3d 100644 --- a/omaha/common/ping.h +++ b/omaha/common/ping.h @@ -34,7 +34,7 @@ // elevated /install process if elevation was successful. The pings will be // split in two different http transactions in the case setup completed // successfully but it failed to handoff. -// * if the /handoff process launched but an error occured in the handoff +// * if the /handoff process launched but an error occurred in the handoff // process itself, then the Omaha "2" ping is sent from the /install process // and the apps "2" ping is sent from the /handoff process. // The apps ping is only sent if the handoff code did not proceed far enough @@ -63,9 +63,10 @@ #include #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "gtest/gtest_prod.h" #include "omaha/common/app_registry_utils.h" #include "omaha/common/ping_event.h" @@ -144,6 +145,9 @@ class Ping { // If the caller is local system and a user is logged on, the function // impersonatates that user. // + // Pings are always sent with a background interactivity, even if they + // correspond to on-demand, foreground installs. + // // The function returns S_OK if the ping was successfully sent using either // mechanism. HRESULT Send(bool is_fire_and_forget); @@ -242,7 +246,7 @@ class Ping { std::vector apps_data_; AppData omaha_data_; - scoped_ptr ping_request_; + std::unique_ptr ping_request_; DISALLOW_COPY_AND_ASSIGN(Ping); }; diff --git a/omaha/common/ping_event.h b/omaha/common/ping_event.h index 5b91d1a..0f046fa 100644 --- a/omaha/common/ping_event.h +++ b/omaha/common/ping_event.h @@ -17,10 +17,11 @@ #define OMAHA_COMMON_PING_EVENT_H_ #include +#include #include + #include "base/basictypes.h" #include "omaha/base/debug.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { @@ -152,8 +153,8 @@ class PingEvent { DISALLOW_COPY_AND_ASSIGN(PingEvent); }; -typedef shared_ptr PingEventPtr; -typedef std::vector PingEventVector; +using PingEventPtr = std::shared_ptr; +using PingEventVector = std::vector; } // namespace omaha diff --git a/omaha/common/protocol_definition.h b/omaha/common/protocol_definition.h index 1c5b4a2..9a5689e 100644 --- a/omaha/common/protocol_definition.h +++ b/omaha/common/protocol_definition.h @@ -82,6 +82,8 @@ struct UpdateCheck { CString tt_token; + bool is_rollback_allowed; + CString target_version_prefix; }; @@ -153,7 +155,7 @@ struct App { }; struct Request { - Request() : is_machine(false), check_period_sec(-1) { + Request() : is_machine(false), check_period_sec(-1), domain_joined(false) { memset(&hw, 0, sizeof(hw)); } @@ -192,6 +194,9 @@ struct Request { // The only group policy value supported so far is "cacheable". CString dlpref; + // True if this machine is part of a managed enterprise domain. + bool domain_joined; + Hw hw; OS os; diff --git a/omaha/common/scheduled_task_utils_unittest.cc b/omaha/common/scheduled_task_utils_unittest.cc index ba63c46..c8d05eb 100644 --- a/omaha/common/scheduled_task_utils_unittest.cc +++ b/omaha/common/scheduled_task_utils_unittest.cc @@ -15,7 +15,9 @@ #include #include +#include #include + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/file.h" diff --git a/omaha/common/stats_uploader_unittest.cc b/omaha/common/stats_uploader_unittest.cc index 520ec85..a9b8059 100644 --- a/omaha/common/stats_uploader_unittest.cc +++ b/omaha/common/stats_uploader_unittest.cc @@ -15,16 +15,17 @@ // All tests are user only. -#include -#include +#include "omaha/common/stats_uploader.h" + +#include #include +#include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_ptr_address.h" -#include "omaha/common/stats_uploader.h" #include "omaha/statsreport/metrics.h" #include "omaha/testing/unit_test.h" @@ -80,11 +81,11 @@ class StatsUploaderTest : public testing::Test { HRESULT GetMetricValue(const TCHAR* value_name, bool* value) { CString key_name = key_name_ + CString(_T("Booleans")); - scoped_array buffer; + std::unique_ptr buffer; size_t byte_count(0); HRESULT hr = RegKey::GetValue(key_name, value_name, - address(buffer), + &buffer, &byte_count); if (FAILED(hr)) { return hr; diff --git a/omaha/common/update3_utils.cc b/omaha/common/update3_utils.cc index 1756715..13715d8 100644 --- a/omaha/common/update3_utils.cc +++ b/omaha/common/update3_utils.cc @@ -46,8 +46,10 @@ HRESULT CreateGoogleUpdate3LocalClass(IGoogleUpdate3** server) { ASSERT1(server); typedef CComObject Update3; - scoped_ptr update3; - HRESULT hr = Update3::CreateInstance(address(update3)); + std::unique_ptr update3; + Update3* update3_ptr = nullptr; + HRESULT hr = Update3::CreateInstance(&update3_ptr); + update3.reset(update3_ptr); if (FAILED(hr)) { CORE_LOG(LE, (_T("[Update3 creation failed][0x%x]"), hr)); return hr; diff --git a/omaha/common/update3_utils.h b/omaha/common/update3_utils.h index 9155b9b..48098e9 100644 --- a/omaha/common/update3_utils.h +++ b/omaha/common/update3_utils.h @@ -20,8 +20,10 @@ #include #include + #include "goopdate/omaha3_idl.h" #include "omaha/base/debug.h" +#include "omaha/base/logging.h" namespace omaha { diff --git a/omaha/common/update_request.cc b/omaha/common/update_request.cc index 0f3d9b1..ad5be28 100644 --- a/omaha/common/update_request.cc +++ b/omaha/common/update_request.cc @@ -18,7 +18,6 @@ #include #include "base/cpu.h" -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" #include "omaha/base/omaha_version.h" #include "omaha/base/system.h" @@ -46,7 +45,7 @@ UpdateRequest* UpdateRequest::Create(bool is_machine, const CString& request_id) { const ConfigManager* cm = ConfigManager::Instance(); - scoped_ptr update_request(new UpdateRequest); + std::unique_ptr update_request(new UpdateRequest); request::Request& request = update_request->request_; @@ -72,6 +71,8 @@ UpdateRequest* UpdateRequest::Create(bool is_machine, request.dlpref = cm->GetDownloadPreferenceGroupPolicy(); + request.domain_joined = IsEnrolledToDomain(); + // Hardware platform attributes. // // The amount of memory available to the operating system can be less than diff --git a/omaha/common/update_request_unittest.cc b/omaha/common/update_request_unittest.cc index f0fa3a4..3982e75 100644 --- a/omaha/common/update_request_unittest.cc +++ b/omaha/common/update_request_unittest.cc @@ -13,11 +13,13 @@ // limitations under the License. // ======================================================================== -#include "base/scoped_ptr.h" +#include "omaha/common/update_request.h" + +#include + #include "omaha/base/reg_key.h" #include "omaha/base/system_info.h" #include "omaha/common/const_group_policy.h" -#include "omaha/common/update_request.h" #include "omaha/testing/unit_test.h" namespace omaha { @@ -34,14 +36,14 @@ class UpdateRequestTest : public ::testing::TestWithParam { INSTANTIATE_TEST_CASE_P(IsDomain, UpdateRequestTest, ::testing::Bool()); TEST_F(UpdateRequestTest, Create_Machine) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(true, _T("unittest"), _T("unittest"), CString())); ASSERT_TRUE(update_request.get()); EXPECT_TRUE(update_request->IsEmpty()); } TEST_F(UpdateRequestTest, Create_User) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T("unittest"), _T("unittest"), CString())); ASSERT_TRUE(update_request.get()); EXPECT_TRUE(update_request->IsEmpty()); @@ -49,7 +51,7 @@ TEST_F(UpdateRequestTest, Create_User) { TEST_F(UpdateRequestTest, HardwarePlatformAttributes) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T("unittest"), _T("unittest"), CString())); ASSERT_TRUE(update_request.get()); EXPECT_TRUE(update_request->IsEmpty()); @@ -78,7 +80,7 @@ TEST_P(UpdateRequestTest, DlPref) { kRegValueIsEnrolledToDomain, IsDomain() ? 1UL : 0UL)); - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T("unittest"), _T("unittest"), CString())); EXPECT_STREQ(_T(""), update_request->request().dlpref); diff --git a/omaha/common/url_utils.cc b/omaha/common/url_utils.cc new file mode 100644 index 0000000..f535e11 --- /dev/null +++ b/omaha/common/url_utils.cc @@ -0,0 +1,47 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/common/url_utils.h" + +#include "omaha/base/debug.h" +#include "omaha/base/string.h" + +namespace omaha { + +HRESULT BuildQueryString(const std::vector& query_params, + CString* query) { + ASSERT1(query); + CString query_part; + + CString encoded_value; + for (std::vector::const_iterator scan = query_params.begin(); + scan != query_params.end(); ++scan) { + HRESULT hr = StringEscape(scan->second, false, &encoded_value); + if (FAILED(hr)) { + return hr; + } + + if (!query_part.IsEmpty()) { + query_part.AppendChar(_T('&')); + } + query_part.Append(scan->first); + query_part.AppendChar(_T('=')); + query_part.Append(encoded_value); + } + + *query = query_part; + return S_OK; +} + +} // namespace omaha diff --git a/omaha/base/processor_type.h b/omaha/common/url_utils.h similarity index 57% rename from omaha/base/processor_type.h rename to omaha/common/url_utils.h index cedf778..511cfa8 100644 --- a/omaha/base/processor_type.h +++ b/omaha/common/url_utils.h @@ -1,4 +1,4 @@ -// Copyright 2006-2009 Google Inc. +// Copyright 2019 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,19 +11,19 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// ======================================================================== -// -// Processor brand detection declarations -// -#ifndef OMAHA_COMMON_PROCESSOR_TYPE_H_ -#define OMAHA_COMMON_PROCESSOR_TYPE_H_ +#include +#include +#include namespace omaha { -bool IsIntelProcessor(); -CString GetProcessorType(); +typedef std::pair QueryElement; -} // namespace omaha +// Assembles the parameters in |query_params| into |query|, escaping the values +// as appropriate. Returns S_OK on success, or a failure HRESULT otherwise. +// |query| is not modified in case of error. +HRESULT BuildQueryString(const std::vector& query_params, + CString* query); -#endif // OMAHA_COMMON_PROCESSOR_TYPE_H_ +} // namespace omaha diff --git a/omaha/base/shared_any.h b/omaha/common/url_utils_unittest.cc similarity index 52% rename from omaha/base/shared_any.h rename to omaha/common/url_utils_unittest.cc index d12413a..a5887bc 100644 --- a/omaha/base/shared_any.h +++ b/omaha/common/url_utils_unittest.cc @@ -1,4 +1,4 @@ -// Copyright 2007-2009 Google Inc. +// Copyright 2019 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,18 +11,24 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// ======================================================================== -// See the comments in omaha/base/scoped_any.h for details. +#include "omaha/common/url_utils.h" -#ifndef OMAHA_COMMON_SHARED_ANY__ -#define OMAHA_COMMON_SHARED_ANY__ +#include +#include +#include -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) -#include "omaha/third_party/smartany/shared_any.h" -#pragma warning(pop) +#include "omaha/testing/unit_test.h" -#endif // OMAHA_COMMON_SHARED_ANY__ +namespace omaha { +TEST(BuildQueryStringTest, Do) { + std::vector params; + params.push_back(std::make_pair(_T("one"), _T("1"))); + params.push_back(std::make_pair(_T("2"), _T("two"))); + CString query; + EXPECT_HRESULT_SUCCEEDED(BuildQueryString(params, &query)); + EXPECT_STREQ(query, _T("one=1&2=two")); +} + +} // namespace omaha diff --git a/omaha/common/web_services_client.cc b/omaha/common/web_services_client.cc index f91a0a5..d833979 100644 --- a/omaha/common/web_services_client.cc +++ b/omaha/common/web_services_client.cc @@ -14,7 +14,11 @@ // ======================================================================== #include "omaha/common/web_services_client.h" + #include +#include + +#include "omaha/base/omaha_version.h" #include "omaha/base/const_addresses.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" @@ -101,7 +105,8 @@ HRESULT WebServicesClient::CreateRequest() { return S_OK; } -HRESULT WebServicesClient::Send(const xml::UpdateRequest* update_request, +HRESULT WebServicesClient::Send(bool is_foreground, + const xml::UpdateRequest* update_request, xml::UpdateResponse* update_response) { CORE_LOG(L3, (_T("[WebServicesClient::Send]"))); ASSERT1(update_request); @@ -133,21 +138,31 @@ HRESULT WebServicesClient::Send(const xml::UpdateRequest* update_request, const bool use_encryption = update_request->has_tt_token(); return SendStringWithFallback(use_encryption, + is_foreground, &request_string, update_response); } -HRESULT WebServicesClient::SendString(const CString* request_string, +HRESULT WebServicesClient::SendString(bool is_foreground, + const CString* request_string, xml::UpdateResponse* update_response) { CORE_LOG(L3, (_T("[WebServicesClient::SendString]"))); ASSERT1(request_string); ASSERT1(update_response); - return SendStringWithFallback(false, request_string, update_response); + __mutexBlock(lock_) { + update_request_headers_.clear(); + } + + return SendStringWithFallback(false, + is_foreground, + request_string, + update_response); } HRESULT WebServicesClient::SendStringWithFallback( bool use_encryption, + bool is_foreground, const CString* request_string, xml::UpdateResponse* update_response) { CORE_LOG(L3, (_T("[WebServicesClient::SendStringWithFallback]"))); @@ -155,6 +170,15 @@ HRESULT WebServicesClient::SendStringWithFallback( ASSERT1(request_string); ASSERT1(update_response); + __mutexBlock(lock_) { + update_request_headers_.push_back( + std::make_pair(kHeaderXUpdater, + CString("Omaha-") + GetVersionString())); + update_request_headers_.push_back( + std::make_pair(kHeaderXInteractive, + is_foreground ? _T("fg") : _T("bg"))); + } + const CStringA utf8_request_string(WideToUtf8(*request_string)); CORE_LOG(L3, (_T("[sending web services request as UTF-8][%S]"), utf8_request_string)); diff --git a/omaha/common/web_services_client.h b/omaha/common/web_services_client.h index eba05ca..4b8e7fa 100644 --- a/omaha/common/web_services_client.h +++ b/omaha/common/web_services_client.h @@ -18,10 +18,10 @@ #include #include +#include #include #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/net/proxy_auth.h" namespace omaha { @@ -43,10 +43,14 @@ class WebServicesClientInterface { public: virtual ~WebServicesClientInterface() {} - virtual HRESULT Send(const xml::UpdateRequest* update_request, + // |is_foreground| specifies the interactivity level of this request. + // True means that the protocol request is part of a session initiated by the + // user. + virtual HRESULT Send(bool is_foreground, + const xml::UpdateRequest* update_request, xml::UpdateResponse* update_response) = 0; - - virtual HRESULT SendString(const CString* request_buffer, + virtual HRESULT SendString(bool is_foreground, + const CString* request_buffer, xml::UpdateResponse* response_buffer) = 0; virtual void Cancel() = 0; @@ -102,10 +106,11 @@ class WebServicesClient : public WebServicesClientInterface { const HeadersVector& headers, bool use_cup); - virtual HRESULT Send(const xml::UpdateRequest* update_request, + virtual HRESULT Send(bool is_foreground, + const xml::UpdateRequest* update_request, xml::UpdateResponse* update_response); - - virtual HRESULT SendString(const CString* request_string, + virtual HRESULT SendString(bool is_foreground, + const CString* request_string, xml::UpdateResponse* update_response); virtual void Cancel(); @@ -137,6 +142,7 @@ class WebServicesClient : public WebServicesClientInterface { // Returns S_OK if the request is successfully sent, otherwise it returns the // error corresponding to the first request sent. HRESULT SendStringWithFallback(bool use_encryption, + bool is_foreground, const CString* request_string, xml::UpdateResponse* update_response); @@ -200,7 +206,7 @@ class WebServicesClient : public WebServicesClientInterface { ProxyAuthConfig proxy_auth_config_; // Each web services request must use its own network request instance. - scoped_ptr network_request_; + std::unique_ptr network_request_; friend class WebServicesClientTest; DISALLOW_COPY_AND_ASSIGN(WebServicesClient); diff --git a/omaha/common/web_services_client_unittest.cc b/omaha/common/web_services_client_unittest.cc index 8be4c63..d188b31 100644 --- a/omaha/common/web_services_client_unittest.cc +++ b/omaha/common/web_services_client_unittest.cc @@ -13,20 +13,19 @@ // limitations under the License. // ======================================================================== -#include "base/scoped_ptr.h" +#include "omaha/common/web_services_client.h" + #include "omaha/base/const_addresses.h" #include "omaha/base/omaha_version.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/vista_utils.h" #include "omaha/common/config_manager.h" #include "omaha/common/update_request.h" #include "omaha/common/update_response.h" -#include "omaha/common/web_services_client.h" #include "omaha/net/network_request.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" using ::testing::_; @@ -34,9 +33,11 @@ namespace omaha { // TODO(omaha): test the machine case. -class WebServicesClientTest : public testing::Test { +// This test is parameterized for foreground/background boolean. +class WebServicesClientTest : public testing::Test, + public ::testing::WithParamInterface { protected: - virtual void SetUp() { + void SetUp() override { EXPECT_HRESULT_SUCCEEDED( ConfigManager::Instance()->GetUpdateCheckUrl(&update_check_url_)); @@ -49,7 +50,7 @@ class WebServicesClientTest : public testing::Test { update_response_.reset(xml::UpdateResponse::Create()); } - virtual void TearDown() { + void TearDown() override { web_service_client_.reset(); } @@ -68,20 +69,24 @@ class WebServicesClientTest : public testing::Test { CString update_check_url_; - scoped_ptr web_service_client_; - scoped_ptr update_request_; - scoped_ptr update_response_; + std::unique_ptr web_service_client_; + std::unique_ptr update_request_; + std::unique_ptr update_response_; bool reg_value_enable_ecdsa_exists_; DWORD ecdsa_enabled_; }; + +INSTANTIATE_TEST_CASE_P(IsForeground, WebServicesClientTest, ::testing::Bool()); + TEST_F(WebServicesClientTest, Send) { EXPECT_HRESULT_SUCCEEDED(web_service_client_->Initialize(update_check_url_, HeadersVector(), false)); // Test sending a user update check request. - EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(update_request_.get(), + EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(false, + update_request_.get(), update_response_.get())); EXPECT_TRUE(web_service_client_->is_http_success()); @@ -103,7 +108,7 @@ TEST_F(WebServicesClientTest, Send) { EXPECT_TRUE(etag.IsEmpty()); } -TEST_F(WebServicesClientTest, SendUsingCup) { +TEST_P(WebServicesClientTest, SendUsingCup) { EXPECT_HRESULT_SUCCEEDED(web_service_client_->Initialize(update_check_url_, HeadersVector(), true)); @@ -113,7 +118,8 @@ TEST_F(WebServicesClientTest, SendUsingCup) { EXPECT_EQ(-1, web_service_client_->http_xdaynum_header_value()); // Test sending a user update check request. - EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(update_request_.get(), + EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(GetParam(), + update_request_.get(), update_response_.get())); EXPECT_TRUE(web_service_client_->is_http_success()); @@ -136,7 +142,7 @@ TEST_F(WebServicesClientTest, SendUsingCup) { kHeaderXInteractive, &interactive_header); - EXPECT_STREQ(_T("fg"), interactive_header); + EXPECT_STREQ(GetParam() ? _T("fg") : _T("bg"), interactive_header); CString app_ids_header; network_request->QueryHeadersString( @@ -212,8 +218,9 @@ TEST_F(WebServicesClientTest, SendForcingHttps) { EXPECT_FALSE(update_request_->IsEmpty()); EXPECT_TRUE(update_request_->has_tt_token()); - EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(update_request_.get(), - update_response_.get())); + EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(false, + update_request_.get(), + update_response_.get())); EXPECT_TRUE(web_service_client_->is_http_success()); NetworkRequest* network_request(network_request()); @@ -244,7 +251,8 @@ TEST_F(WebServicesClientTest, SendWithCustomHeader) { headers, true)); - EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(update_request_.get(), + EXPECT_HRESULT_SUCCEEDED(web_service_client_->Send(false, + update_request_.get(), update_response_.get())); EXPECT_TRUE(web_service_client_->is_http_success()); @@ -262,7 +270,7 @@ TEST_F(WebServicesClientTest, SendWithCustomHeader) { EXPECT_STREQ(_T("200"), request_age_header); } -TEST_F(WebServicesClientTest, SendString) { +TEST_P(WebServicesClientTest, SendString) { EXPECT_HRESULT_SUCCEEDED(web_service_client_->Initialize(update_check_url_, HeadersVector(), false)); @@ -271,10 +279,31 @@ TEST_F(WebServicesClientTest, SendString) { CString request_string = _T("") _T(""); - scoped_ptr response(xml::UpdateResponse::Create()); - EXPECT_HRESULT_SUCCEEDED(web_service_client_->SendString(&request_string, + std::unique_ptr response(xml::UpdateResponse::Create()); + EXPECT_HRESULT_SUCCEEDED(web_service_client_->SendString(GetParam(), + &request_string, response.get())); EXPECT_TRUE(web_service_client_->is_http_success()); + + NetworkRequest* network_request(network_request()); + + CString interactive_header; + network_request->QueryHeadersString( + WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_REQUEST_HEADERS, + kHeaderXInteractive, + &interactive_header); + EXPECT_STREQ(GetParam() ? _T("fg") : _T("bg"), interactive_header); + + CString updater_header; + network_request->QueryHeadersString( + WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_REQUEST_HEADERS, + kHeaderXUpdater, + &updater_header); + + CString expected_updater_header; + SafeCStringAppendFormat(&expected_updater_header, _T("Omaha-%s"), + GetVersionString()); + EXPECT_STREQ(expected_updater_header, updater_header); } TEST_F(WebServicesClientTest, SendStringWithCustomHeader) { @@ -289,8 +318,9 @@ TEST_F(WebServicesClientTest, SendStringWithCustomHeader) { CString request_string = _T("") _T(""); - scoped_ptr response(xml::UpdateResponse::Create()); - EXPECT_HRESULT_SUCCEEDED(web_service_client_->SendString(&request_string, + std::unique_ptr response(xml::UpdateResponse::Create()); + EXPECT_HRESULT_SUCCEEDED(web_service_client_->SendString(false, + &request_string, response.get())); EXPECT_TRUE(web_service_client_->is_http_success()); diff --git a/omaha/common/xml_const.cc b/omaha/common/xml_const.cc index 0cb8727..6fee885 100644 --- a/omaha/common/xml_const.cc +++ b/omaha/common/xml_const.cc @@ -78,6 +78,7 @@ const TCHAR* const kDayOfLastActivity = _T("ad"); const TCHAR* const kDayOfLastRollCall = _T("rd"); const TCHAR* const kDedup = _T("dedup"); const TCHAR* const kDlPref = _T("dlpref"); +const TCHAR* const kDomainJoined = _T("domainjoined"); const TCHAR* const kDownloaded = _T("downloaded"); const TCHAR* const kDownloader = _T("downloader"); const TCHAR* const kDownloadTime = _T("download_time_ms"); @@ -113,6 +114,7 @@ const TCHAR* const kPlatform = _T("platform"); const TCHAR* const kProtocol = _T("protocol"); const TCHAR* const kRequestId = _T("requestid"); const TCHAR* const kRequired = _T("required"); +const TCHAR* const kRollbackAllowed = _T("rollback_allowed"); const TCHAR* const kRun = _T("run"); const TCHAR* const kServicePack = _T("sp"); const TCHAR* const kSessionId = _T("sessionid"); @@ -138,8 +140,10 @@ const TCHAR* const kTimeSinceUpdateAvailable = _T("time_since_update_available_ms"); const TCHAR* const kTotal = _T("total"); const TCHAR* const kTTToken = _T("tttoken"); -const TCHAR* const kUpdateDisabled = _T("updatedisabled"); const TCHAR* const kUpdateCheckTime= _T("update_check_time_ms"); +const TCHAR* const kUpdateDisabled = _T("updatedisabled"); +const TCHAR* const kUpdater = _T("updater"); +const TCHAR* const kUpdaterVersion = _T("updaterversion"); const TCHAR* const kUrl = _T("url"); const TCHAR* const kUserId = _T("userid"); const TCHAR* const kVersion = _T("version"); @@ -171,6 +175,7 @@ const TCHAR* const kSuccessActionExitSilentlyOnLaunchCmd = _T("exitsilentlyonlaunchcmd"); const TCHAR* const kTrue = _T("true"); const TCHAR* const kUid = _T("uid"); +const TCHAR* const kUpdater = _T("Omaha"); const TCHAR* const kUntrusted = _T("untrusted"); const TCHAR* const kUpdate = _T("update"); const TCHAR* const kVersion3 = _T("3.0"); diff --git a/omaha/common/xml_const.h b/omaha/common/xml_const.h index 2c9392e..99988f0 100644 --- a/omaha/common/xml_const.h +++ b/omaha/common/xml_const.h @@ -78,6 +78,7 @@ extern const TCHAR* const kDayOfLastActivity; extern const TCHAR* const kDayOfLastRollCall; extern const TCHAR* const kDedup; extern const TCHAR* const kDlPref; +extern const TCHAR* const kDomainJoined; extern const TCHAR* const kDownloaded; extern const TCHAR* const kDownloader; extern const TCHAR* const kDownloadTime; @@ -113,6 +114,7 @@ extern const TCHAR* const kPlatform; extern const TCHAR* const kProtocol; extern const TCHAR* const kRequestId; extern const TCHAR* const kRequired; +extern const TCHAR* const kRollbackAllowed; extern const TCHAR* const kRun; extern const TCHAR* const kServicePack; extern const TCHAR* const kSessionId; @@ -137,8 +139,10 @@ extern const TCHAR* const kTimeSinceDownloadStart; extern const TCHAR* const kTimeSinceUpdateAvailable; extern const TCHAR* const kTotal; extern const TCHAR* const kTTToken; -extern const TCHAR* const kUpdateDisabled; extern const TCHAR* const kUpdateCheckTime; +extern const TCHAR* const kUpdateDisabled; +extern const TCHAR* const kUpdater; +extern const TCHAR* const kUpdaterVersion; extern const TCHAR* const kUrl; extern const TCHAR* const kUserId; extern const TCHAR* const kVersion; @@ -171,6 +175,7 @@ extern const TCHAR* const kSuccessActionExitSilentlyOnLaunchCmd; extern const TCHAR* const kTrue; extern const TCHAR* const kUid; extern const TCHAR* const kUntrusted; +extern const TCHAR* const kUpdater; extern const TCHAR* const kUpdate; extern const TCHAR* const kVersion3; diff --git a/omaha/common/xml_parser.cc b/omaha/common/xml_parser.cc index 365b06f..2579f17 100644 --- a/omaha/common/xml_parser.cc +++ b/omaha/common/xml_parser.cc @@ -14,6 +14,7 @@ // ======================================================================== #include "omaha/common/xml_parser.h" +#include #include #include #include "base/basictypes.h" @@ -908,7 +909,16 @@ HRESULT XmlParser::BuildRequestElement() { hr = AddXMLAttributeNode(element, kXmlNamespace, - xml::attribute::kVersion, + xml::attribute::kUpdater, + xml::value::kUpdater); + if (FAILED(hr)) { + return hr; + } + + + hr = AddXMLAttributeNode(element, + kXmlNamespace, + xml::attribute::kUpdaterVersion, request_->omaha_version); if (FAILED(hr)) { return hr; @@ -1016,6 +1026,14 @@ HRESULT XmlParser::BuildRequestElement() { } } + hr = AddXMLAttributeNode(element, + kXmlNamespace, + xml::attribute::kDomainJoined, + request_->domain_joined ? _T("1") : _T("0")); + if (FAILED(hr)) { + return hr; + } + hr = BuildHwElement(element); if (FAILED(hr)) { return hr; @@ -1447,6 +1465,17 @@ HRESULT XmlParser::BuildUpdateCheckElement(const request::App& app, } if (!app.update_check.target_version_prefix.IsEmpty()) { + // RollbackToTargetVersion only applies if the TargetVersionPrefix is set. + if (app.update_check.is_rollback_allowed) { + hr = AddXMLAttributeNode(element, + kXmlNamespace, + xml::attribute::kRollbackAllowed, + xml::value::kTrue); + if (FAILED(hr)) { + return hr; + } + } + hr = AddXMLAttributeNode(element, kXmlNamespace, xml::attribute::kTargetVersionPrefix, @@ -1794,9 +1823,9 @@ HRESULT XmlParser::VisitElement(IXMLDOMNode* node) { CORE_LOG(L4, (_T("[element name][%s:%s]"), node_name.uri, node_name.base)); // Ignore elements not understood. - ElementHandler* element_handler = - element_handler_factory_.CreateObject(node_name.base); - if (element_handler) { + std::unique_ptr element_handler; + element_handler.reset(element_handler_factory_.CreateObject(node_name.base)); + if (element_handler.get()) { return element_handler->Handle(node, response_); } else { CORE_LOG(LW, (_T("[VisitElement: don't know how to handle %s:%s]"), diff --git a/omaha/common/xml_parser_unittest.cc b/omaha/common/xml_parser_unittest.cc index c6e1527..0732d4a 100644 --- a/omaha/common/xml_parser_unittest.cc +++ b/omaha/common/xml_parser_unittest.cc @@ -13,13 +13,15 @@ // limitations under the License. // ======================================================================== +#include "omaha/common/xml_parser.h" + +#include #include #include "base/utils.h" -#include "base/scoped_ptr.h" + #include "omaha/base/error.h" #include "omaha/base/reg_key.h" #include "omaha/common/const_group_policy.h" -#include "omaha/common/xml_parser.h" #include "omaha/goopdate/update_response_utils.h" #include "omaha/testing/unit_test.h" @@ -60,7 +62,7 @@ class XmlParserTest : public ::testing::TestWithParam { TEST_F(XmlParserTest, GenerateRequestWithoutUserId_MachineUpdateRequest) { // The origin URL contains an invalid XML character, the double-quote. The // expectation is that this character should be escaped to """. - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(true, _T("unittest_session"), _T("unittest_install"), @@ -72,6 +74,7 @@ TEST_F(XmlParserTest, GenerateRequestWithoutUserId_MachineUpdateRequest) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8383}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 2; xml_request.hw.has_sse = true; xml_request.hw.has_sse2 = true; @@ -98,6 +101,7 @@ TEST_F(XmlParserTest, GenerateRequestWithoutUserId_MachineUpdateRequest) { app1.iid = GuidToString(GUID_NULL); // Prevents assert. app1.ap = _T("ap_with_update_check"); app1.update_check.is_valid = true; + app1.update_check.is_rollback_allowed = true; app1.update_check.target_version_prefix = "55.2"; app1.data.push_back(data1); app1.data.push_back(data2); @@ -124,7 +128,7 @@ TEST_F(XmlParserTest, GenerateRequestWithoutUserId_MachineUpdateRequest) { app2.cohort_name = _T("Name2"); xml_request.apps.push_back(app2); - CString expected_buffer = _T("some untrusted data"); // NOLINT + CString expected_buffer = _T("some untrusted data"); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, @@ -138,7 +142,7 @@ INSTANTIATE_TEST_CASE_P(IsDomain, XmlParserTest, ::testing::Bool()); TEST_F(XmlParserTest, GenerateRequestWithUserId_MachineUpdateRequest) { // The origin URL contains an invalid XML character, the double-quote. The // expectation is that this character should be escaped to """. - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(true, _T("unittest_session"), _T("unittest_install"), @@ -152,6 +156,7 @@ TEST_F(XmlParserTest, GenerateRequestWithUserId_MachineUpdateRequest) { xml_request.omaha_shell_version = _T("1.2.3.4"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8384}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 2; xml_request.hw.has_sse = true; xml_request.hw.has_sse2 = true; @@ -223,7 +228,7 @@ TEST_F(XmlParserTest, GenerateRequestWithUserId_MachineUpdateRequest) { xml_request.apps.push_back(app2); - CString expected_buffer = _T(""); // NOLINT + CString expected_buffer = _T(""); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, @@ -246,7 +251,7 @@ TEST_F(XmlParserTest, Parse) { std::vector buffer(buffer_strings[i].GetLength()); memcpy(&buffer.front(), buffer_strings[i], buffer.size()); - scoped_ptr update_response(UpdateResponse::Create()); + std::unique_ptr update_response(UpdateResponse::Create()); EXPECT_HRESULT_SUCCEEDED(XmlParser::DeserializeResponse( buffer, update_response.get())); @@ -329,7 +334,7 @@ TEST_F(XmlParserTest, Parse_InvalidDataStatusError) { std::vector buffer(buffer_string.GetLength()); memcpy(&buffer.front(), buffer_string, buffer.size()); - scoped_ptr update_response(UpdateResponse::Create()); + std::unique_ptr update_response(UpdateResponse::Create()); EXPECT_HRESULT_SUCCEEDED(XmlParser::DeserializeResponse( buffer, update_response.get())); @@ -389,7 +394,7 @@ TEST_F(XmlParserTest, Parse_InvalidDataStatusError) { } TEST_F(XmlParserTest, Serialize_WithInvalidXmlCharacters) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T("sid"), _T("is"), _T("http://foo/\""))); request::Request& xml_request = get_xml_request(update_request.get()); @@ -398,6 +403,7 @@ TEST_F(XmlParserTest, Serialize_WithInvalidXmlCharacters) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("\"malicious segement=\"&"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 2; xml_request.hw.has_sse = true; xml_request.hw.has_sse2 = true; @@ -426,7 +432,7 @@ TEST_F(XmlParserTest, Serialize_WithInvalidXmlCharacters) { app.data.push_back(data1); xml_request.apps.push_back(app); - const CString expected_buffer = _T(""); // NOLINT + const CString expected_buffer = _T(""); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, @@ -435,7 +441,7 @@ TEST_F(XmlParserTest, Serialize_WithInvalidXmlCharacters) { } TEST_F(XmlParserTest, HwAttributes) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T(""), _T("is"), _T(""))); request::Request& xml_request = get_xml_request(update_request.get()); @@ -444,6 +450,7 @@ TEST_F(XmlParserTest, HwAttributes) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 0; xml_request.hw.has_sse = false; xml_request.hw.has_sse2 = false; @@ -459,7 +466,7 @@ TEST_F(XmlParserTest, HwAttributes) { xml_request.check_period_sec = 120000; xml_request.uid.Empty(); - CString expected_buffer = _T(""); // NOLINT + CString expected_buffer = _T(""); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, &actual_buffer)); @@ -474,7 +481,7 @@ TEST_F(XmlParserTest, HwAttributes) { xml_request.hw.has_sse42 = true; xml_request.hw.has_avx = true; - expected_buffer = _T(""); // NOLINT + expected_buffer = _T(""); // NOLINT EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, &actual_buffer)); EXPECT_STREQ(expected_buffer, actual_buffer); @@ -489,7 +496,7 @@ TEST_P(XmlParserTest, DlPref) { kRegValueDownloadPreference, kDownloadPreferenceCacheable)); - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T(""), _T("is"), _T(""))); request::Request& xml_request = get_xml_request(update_request.get()); @@ -498,6 +505,7 @@ TEST_P(XmlParserTest, DlPref) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 0; xml_request.hw.has_sse = false; xml_request.hw.has_sse2 = false; @@ -513,7 +521,7 @@ TEST_P(XmlParserTest, DlPref) { xml_request.check_period_sec = 120000; xml_request.uid.Empty(); - const TCHAR* expected_request_fmt = _T(""); // NOLINT + const TCHAR* expected_request_fmt = _T(""); // NOLINT CString expected_buffer; expected_buffer.Format(expected_request_fmt, IsDomain() ? _T(" dlpref=\"cacheable\"") : _T("")); @@ -536,7 +544,7 @@ TEST_P(XmlParserTest, DlPrefUnknownPolicy) { kRegValueDownloadPreference, _T("unknown policy"))); - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T(""), _T("is"), _T(""))); request::Request& xml_request = get_xml_request(update_request.get()); @@ -545,6 +553,7 @@ TEST_P(XmlParserTest, DlPrefUnknownPolicy) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 0; xml_request.hw.has_sse = false; xml_request.hw.has_sse2 = false; @@ -560,7 +569,7 @@ TEST_P(XmlParserTest, DlPrefUnknownPolicy) { xml_request.check_period_sec = 120000; xml_request.uid.Empty(); - const CString expected_buffer = _T(""); // NOLINT + const CString expected_buffer = _T(""); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, &actual_buffer)); @@ -571,7 +580,7 @@ TEST_P(XmlParserTest, DlPrefUnknownPolicy) { } TEST_F(XmlParserTest, PingFreshness) { - scoped_ptr update_request( + std::unique_ptr update_request( UpdateRequest::Create(false, _T(""), _T("is"), _T(""))); request::Request& xml_request = get_xml_request(update_request.get()); @@ -579,6 +588,7 @@ TEST_F(XmlParserTest, PingFreshness) { xml_request.omaha_shell_version = _T("1.2.1.1"); xml_request.test_source = _T("dev"); xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.domain_joined = true; xml_request.hw.physmemory = 0; xml_request.hw.has_sse = false; xml_request.hw.has_sse2 = false; @@ -603,7 +613,7 @@ TEST_F(XmlParserTest, PingFreshness) { xml_request.apps[0].ping.ping_freshness = _T("{d0d8cb57-ca4a-4e82-8196-84f47c0ca085}"); - const CString expected_buffer = _T(""); // NOLINT + const CString expected_buffer = _T(""); // NOLINT CString actual_buffer; EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, &actual_buffer)); @@ -611,6 +621,46 @@ TEST_F(XmlParserTest, PingFreshness) { EXPECT_STREQ(expected_buffer, actual_buffer); } +TEST_P(XmlParserTest, DomainJoined) { + EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, + kRegValueIsEnrolledToDomain, + IsDomain() ? 1UL : 0UL)); + + std::unique_ptr update_request( + UpdateRequest::Create(false, _T(""), _T("is"), _T(""))); + + request::Request& xml_request = get_xml_request(update_request.get()); + + xml_request.omaha_version = _T("1.3.24.1"); + xml_request.omaha_shell_version = _T("1.2.1.1"); + xml_request.test_source = _T("dev"); + xml_request.request_id = _T("{387E2718-B39C-4458-98CC-24B5293C8385}"); + xml_request.hw.physmemory = 0; + xml_request.hw.has_sse = false; + xml_request.hw.has_sse2 = false; + xml_request.hw.has_sse3 = false; + xml_request.hw.has_ssse3 = false; + xml_request.hw.has_sse41 = false; + xml_request.hw.has_sse42 = false; + xml_request.hw.has_avx = false; + xml_request.os.platform = _T("win"); + xml_request.os.version = _T("9.0"); + xml_request.os.service_pack = _T("Service Pack 3"); + xml_request.os.arch = _T("unknown"); + xml_request.check_period_sec = 120000; + xml_request.uid.Empty(); + + const CString expected_buffer_fmt = _T(""); // NOLINT + CString expected_buffer; + expected_buffer.Format(expected_buffer_fmt, IsDomain() ? _T("1") : _T("0")); + CString actual_buffer; + EXPECT_HRESULT_SUCCEEDED(XmlParser::SerializeRequest(*update_request, + &actual_buffer)); + EXPECT_STREQ(expected_buffer, actual_buffer); + + RegKey::DeleteValue(MACHINE_REG_UPDATE_DEV, kRegValueIsEnrolledToDomain); +} + } // namespace xml } // namespace omaha diff --git a/omaha/core/build.scons b/omaha/core/build.scons index b183152..ba434bf 100644 --- a/omaha/core/build.scons +++ b/omaha/core/build.scons @@ -32,7 +32,7 @@ local_env['CPPPATH'] += [ '$OBJ_ROOT', ] -local_env.ComponentStaticLibrary('core', inputs) +local_env.ComponentLibrary('core', inputs) core_env = env.Clone() omaha_version_info = core_env['omaha_versions_info'][0] @@ -40,6 +40,9 @@ core_env['CPPPATH'] += [ '$OBJ_ROOT', ] core_env.Append( + CCFLAGS = [ + '/wd5038', + ], LIBS = [ 'advapi32.lib', 'bits.lib', @@ -76,8 +79,10 @@ core_env.Append( core_env.GetMultiarchLibName('common'), core_env.GetMultiarchLibName('core'), core_env.GetMultiarchLibName('crash_handler'), + core_env.GetMultiarchLibName('crx_file'), core_env.GetMultiarchLibName('google_update_recovery'), core_env.GetMultiarchLibName('goopdate_lib'), + core_env.GetMultiarchLibName('libprotobuf'), core_env.GetMultiarchLibName('logging'), core_env.GetMultiarchLibName('net'), core_env.GetMultiarchLibName('omaha3_idl'), @@ -97,6 +102,13 @@ core_env.Append( ], ) +if core_env.Bit('has_device_management'): + core_env.Append( + LIBS = [ + core_env.GetMultiarchLibName('dm_proto'), + ], + ) + google_core_res_target = 'resource.res' google_core_res = core_env.RES(source = 'resource.rc', target = google_core_res_target) @@ -107,11 +119,7 @@ google_core_inputs = [ google_core_res, ] -# Disable stack checks for VC80. -if core_env['msc_ver'] >= 1400: - core_env['CCFLAGS'] += ['/GS-'] - -exe_name = 'GoogleUpdateCore' +exe_name = 'BraveUpdateCore' unsigned_core = core_env.ComponentProgram( prog_name='%s_unsigned.exe' % exe_name, diff --git a/omaha/core/core.cc b/omaha/core/core.cc index fcf3afb..a7e5d64 100644 --- a/omaha/core/core.cc +++ b/omaha/core/core.cc @@ -20,12 +20,16 @@ // be running. #include "omaha/core/core.h" + #include + #include #include #include +#include #include #include + #include "omaha/base/app_util.h" #include "omaha/base/const_object_names.h" #include "omaha/base/debug.h" @@ -51,7 +55,6 @@ #include "omaha/common/scheduled_task_utils.h" #include "omaha/common/stats_uploader.h" #include "omaha/core/core_metrics.h" -#include "omaha/core/scheduler.h" #include "omaha/core/system_monitor.h" #include "omaha/goopdate/app_command.h" #include "omaha/goopdate/app_command_configuration.h" @@ -266,20 +269,20 @@ HRESULT Core::DoMain(bool is_system, bool is_crash_handler_enabled) { MSG msg = {0}; ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); - scoped_ptr reactor(new Reactor); - scoped_ptr shutdown_handler(new ShutdownHandler); + std::unique_ptr reactor(new Reactor); + std::unique_ptr shutdown_handler(new ShutdownHandler); HRESULT hr = shutdown_handler->Initialize(reactor.get(), this, is_system_); if (FAILED(hr)) { return hr; } - scoped_ptr scheduler(new Scheduler(*this)); - hr = scheduler->Initialize(); + auto scheduler = std::make_unique(); + hr = InitializeScheduler(scheduler.get()); if (FAILED(hr)) { return hr; } - scoped_ptr system_monitor(new SystemMonitor(is_system_)); + std::unique_ptr system_monitor(new SystemMonitor(is_system_)); VERIFY1(SUCCEEDED(system_monitor->Initialize(true))); system_monitor->set_observer(this); @@ -494,9 +497,9 @@ void Core::LaunchAppCommandsOnOSUpgrade() const { ++cmd_it) { const CString& command_id = *cmd_it; - scoped_ptr configuration; + std::unique_ptr configuration; hr = AppCommandConfiguration::Load(app_guid, is_system_, command_id, - address(configuration)); + &configuration); if (FAILED(hr)) { CORE_LOG(LE, (_T("[AppCommand::Load failed][%s][%d][%s][%#08x]"), app_guid, is_system_, command_id, hr)); @@ -508,7 +511,7 @@ void Core::LaunchAppCommandsOnOSUpgrade() const { // This app command is marked for automatic launch on OS upgrade. // Attempt to launch it. (We don't care about the return value of // the process, only that we successfully created it.) - scoped_ptr app_command( + std::unique_ptr app_command( configuration->Instantiate(session_id)); std::vector parameters; @@ -597,4 +600,37 @@ void Core::CollectMetrics() const { metric_core_disk_space_available = free_bytes_current_user; } +HRESULT Core::InitializeScheduler(const Scheduler* scheduler) { + ASSERT1(scheduler); + + const ConfigManager* cm = ConfigManager::Instance(); + // Start update worker + HRESULT hr = scheduler->StartWithDelay(cm->GetUpdateWorkerStartUpDelayMs(), + cm->GetAutoUpdateTimerIntervalMs(), + [this]() { StartUpdateWorker(); }); + + if (FAILED(hr)) { + OPT_LOG(LW, (L"[Failed to start update worker scheduler][0x%08x]", hr)); + return hr; + } + + // Start Code Red worker + const int cr_timer_interval = cm->GetCodeRedTimerIntervalMs(); + hr = scheduler->StartWithDebugTimer( + cr_timer_interval, [this, cr_timer_interval](HighresTimer* debug_timer) { + StartCodeRed(); + if (debug_timer) { + int actual_time_ms = static_cast(debug_timer->GetElapsedMs()); + metric_core_cr_actual_timer_interval_ms = actual_time_ms; + } + metric_core_cr_expected_timer_interval_ms = cr_timer_interval; + }); + + if (FAILED(hr)) { + OPT_LOG(LW, (L"[Failed to start code red scheduler][0x%08x]", hr)); + return hr; + } + return S_OK; +} + } // namespace omaha diff --git a/omaha/core/core.h b/omaha/core/core.h index c3deaf6..f6ce2bc 100644 --- a/omaha/core/core.h +++ b/omaha/core/core.h @@ -24,14 +24,16 @@ #include #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/shutdown_callback.h" #include "omaha/core/google_update_core.h" +#include "omaha/core/scheduler.h" #include "omaha/core/system_monitor.h" #include "omaha/goopdate/google_update3.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -114,6 +116,8 @@ class Core static bool ShouldRunCore(bool is_system); static HRESULT UpdateLastCoreRunTime(bool is_system); + HRESULT InitializeScheduler(const Scheduler* scheduler); + bool is_system_; // True if the core has to kickoff the crash handler. @@ -123,7 +127,7 @@ class Core friend class CoreUtilsTest; - DISALLOW_EVIL_CONSTRUCTORS(Core); + DISALLOW_COPY_AND_ASSIGN(Core); }; } // namespace omaha diff --git a/omaha/core/core_unittest.cc b/omaha/core/core_unittest.cc index 9804140..14e1771 100644 --- a/omaha/core/core_unittest.cc +++ b/omaha/core/core_unittest.cc @@ -19,7 +19,6 @@ #include "omaha/base/error.h" #include "omaha/base/file.h" #include "omaha/base/path.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/thread.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" @@ -33,6 +32,7 @@ #include "omaha/goopdate/app_command_test_base.h" #include "omaha/setup/setup_service.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -53,7 +53,7 @@ class CoreRunner : public Runnable { } bool is_machine_; - DISALLOW_EVIL_CONSTRUCTORS(CoreRunner); + DISALLOW_COPY_AND_ASSIGN(CoreRunner); }; } // namespace @@ -257,7 +257,7 @@ class CoreUtilsTest : public testing::Test { return SetupUpdate3Service::DeleteService(); } - scoped_ptr core_; + std::unique_ptr core_; bool is_machine_; CAtlModule* original_atl_module_; diff --git a/omaha/core/google_update_core.cc b/omaha/core/google_update_core.cc index 5925ad4..c55f34c 100644 --- a/omaha/core/google_update_core.cc +++ b/omaha/core/google_update_core.cc @@ -14,18 +14,20 @@ // ======================================================================== #include "omaha/core/google_update_core.h" + +#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/system.h" #include "omaha/base/utils.h" #include "omaha/common/config_manager.h" #include "omaha/goopdate/app_command.h" #include "omaha/goopdate/app_command_configuration.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -66,12 +68,12 @@ STDMETHODIMP GoogleUpdateCoreBase::LaunchCmdElevated(const WCHAR* app_guid, CString session_id; GetGuid(&session_id); - scoped_ptr configuration; + std::unique_ptr configuration; // true == machine level hr = AppCommandConfiguration::Load(app_guid, true, cmd_id, - address(configuration)); + &configuration); if (FAILED(hr)) { CORE_LOG(LE, (_T("[failed to load command configuration][0x%x]"), hr)); return hr; @@ -83,7 +85,8 @@ STDMETHODIMP GoogleUpdateCoreBase::LaunchCmdElevated(const WCHAR* app_guid, scoped_process command_process; scoped_process duplicate_proc_handle; - scoped_ptr app_command(configuration->Instantiate(session_id)); + std::unique_ptr app_command( + configuration->Instantiate(session_id)); hr = app_command->Execute( NULL, std::vector(), address(command_process)); diff --git a/omaha/core/google_update_core.h b/omaha/core/google_update_core.h index d05b3a4..058a3ea 100644 --- a/omaha/core/google_update_core.h +++ b/omaha/core/google_update_core.h @@ -33,10 +33,6 @@ namespace omaha { -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) - class ATL_NO_VTABLE GoogleUpdateCoreBase : public CComObjectRootEx, public IGoogleUpdateCore, @@ -62,7 +58,7 @@ class ATL_NO_VTABLE GoogleUpdateCoreBase friend class GoogleUpdateCoreTest; - DISALLOW_EVIL_CONSTRUCTORS(GoogleUpdateCoreBase); + DISALLOW_COPY_AND_ASSIGN(GoogleUpdateCoreBase); }; template @@ -93,15 +89,12 @@ class ATL_NO_VTABLE GoogleUpdateCore END_REGISTRY_MAP() private: - - DISALLOW_EVIL_CONSTRUCTORS(GoogleUpdateCore); + DISALLOW_COPY_AND_ASSIGN(GoogleUpdateCore); }; typedef GoogleUpdateCore GoogleUpdateCoreMachine; typedef GoogleUpdateCore GoogleUpdateCoreService; -#pragma warning(pop) - } // namespace omaha #endif // OMAHA_CORE_GOOGLE_UPDATE_CORE_H_ diff --git a/omaha/core/google_update_core_unittest.cc b/omaha/core/google_update_core_unittest.cc index e4c21f0..7108bd8 100644 --- a/omaha/core/google_update_core_unittest.cc +++ b/omaha/core/google_update_core_unittest.cc @@ -20,7 +20,6 @@ #include "omaha/base/omaha_version.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/base/system.h" #include "omaha/base/timer.h" @@ -32,6 +31,7 @@ #include "omaha/core/google_update_core.h" #include "omaha/setup/setup_service.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/core/resource.rc b/omaha/core/resource.rc index 08a8b09..ddfd3a2 100644 --- a/omaha/core/resource.rc +++ b/omaha/core/resource.rc @@ -13,9 +13,7 @@ // limitations under the License. // ======================================================================== -#include #include -#include #include "resource.h" LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -57,7 +55,7 @@ BEGIN // Strings that get localized must appear as literals so the tools can replace // them. For open source builds, which don't use these tools, use constants. #ifdef GOOGLE_UPDATE_BUILD - VALUE "CompanyName", "Google Inc." + VALUE "CompanyName", "Google LLC" VALUE "FileDescription", "Google Update Core" #else VALUE "CompanyName", FULL_COMPANY_NAME_ANSI @@ -65,7 +63,6 @@ BEGIN #endif VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", "Copyright 2007-2010 Google Inc." VALUE "OriginalFilename", MAIN_EXE_BASE_NAME_ANSI ".exe" #ifdef GOOGLE_UPDATE_BUILD VALUE "ProductName", "Google Update" diff --git a/omaha/core/scheduler.cc b/omaha/core/scheduler.cc index d2363e7..79b27d4 100644 --- a/omaha/core/scheduler.cc +++ b/omaha/core/scheduler.cc @@ -14,116 +14,144 @@ // ======================================================================== #include "omaha/core/scheduler.h" -#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" -#include "omaha/base/highres_timer-win32.h" #include "omaha/base/logging.h" -#include "omaha/base/queue_timer.h" -#include "omaha/common/config_manager.h" -#include "omaha/core/core.h" -#include "omaha/core/core_metrics.h" namespace omaha { -Scheduler::Scheduler(const Core& core) - : core_(core) { - CORE_LOG(L1, (_T("[Scheduler::Scheduler]"))); +Scheduler::SchedulerItem::SchedulerItem(HANDLE timer_queue, + int start_delay_ms, + int interval_ms, + bool has_debug_timer, + ScheduledWorkWithTimer work) + : start_delay_ms_(start_delay_ms), interval_ms_(interval_ms), work_(work) { + if (has_debug_timer) { + debug_timer_.reset(new HighresTimer()); + } + + if (timer_queue) { + timer_.reset( + new QueueTimer(timer_queue, &SchedulerItem::TimerCallback, this)); + VERIFY1(SUCCEEDED( + ScheduleNext(timer_.get(), debug_timer_.get(), start_delay_ms))); + } } -Scheduler::~Scheduler() { - CORE_LOG(L1, (_T("[Scheduler::~Scheduler]"))); +Scheduler::SchedulerItem::~SchedulerItem() { + // QueueTimer dtor may block for pending callbacks. + if (timer_) { + timer_.reset(); + } - if (update_timer_.get()) { - update_timer_.reset(NULL); + if (debug_timer_) { + debug_timer_.reset(); } +} - if (code_red_timer_.get()) { - code_red_timer_.reset(NULL); +// static +HRESULT Scheduler::SchedulerItem::ScheduleNext(QueueTimer* timer, + HighresTimer* debug_timer, + int start_after_ms) { + if (!timer) { + return E_FAIL; } - if (timer_queue_) { - // The destructor blocks on deleting the timer queue and it waits for - // all timer callbacks to complete. - ::DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE); + if (debug_timer) { + debug_timer->Start(); } -} -HRESULT Scheduler::Initialize() { - CORE_LOG(L1, (_T("[Scheduler::Initialize]"))); + const HRESULT hr = timer->Start(start_after_ms, 0, WT_EXECUTEONLYONCE); - timer_queue_ = ::CreateTimerQueue(); - if (!timer_queue_) { - return HRESULTFromLastError(); + if (FAILED(hr)) { + CORE_LOG(LE, (L"[can't start queue timer][0x%08x]", hr)); } - cr_debug_timer_.reset(new HighresTimer); + return hr; +} + +// static +void Scheduler::SchedulerItem::TimerCallback(QueueTimer* timer) { + ASSERT1(timer); + if (!timer) { + return; + } - update_timer_.reset(new QueueTimer(timer_queue_, - &Scheduler::TimerCallback, - this)); - code_red_timer_.reset(new QueueTimer(timer_queue_, - &Scheduler::TimerCallback, - this)); + SchedulerItem* item = reinterpret_cast(timer->ctx()); + ASSERT1(item); - ConfigManager* config_manager = ConfigManager::Instance(); - int cr_timer_interval_ms = config_manager->GetCodeRedTimerIntervalMs(); - VERIFY1(SUCCEEDED(ScheduleCodeRedTimer(cr_timer_interval_ms))); + if (!item) { + CORE_LOG(LE, (L"[Expected timer context to contain SchedulerItem]")); + return; + } - int au_timer_interval_ms = config_manager->GetUpdateWorkerStartUpDelayMs(); - VERIFY1(SUCCEEDED(ScheduleUpdateTimer(au_timer_interval_ms))); + // This may be long running, |item| may be deleted in the meantime, + // however the dtor should block on deleting the |timer| and allow + // pending callbacks to run. + if (item && item->work_) { + item->work_(item->debug_timer()); + } - return S_OK; + if (item) { + const HRESULT hr = SchedulerItem::ScheduleNext(timer, + item->debug_timer(), + item->interval_ms()); + if (FAILED(hr)) { + CORE_LOG(L1, (L"[Scheduling next timer callback failed][0x%08x]", hr)); + } + } } -void Scheduler::TimerCallback(QueueTimer* timer) { - ASSERT1(timer); - Scheduler* scheduler = static_cast(timer->ctx()); - ASSERT1(scheduler); - scheduler->HandleCallback(timer); +Scheduler::Scheduler() { + CORE_LOG(L1, (L"[Scheduler::Scheduler]")); + timer_queue_ = ::CreateTimerQueue(); + if (!timer_queue_) { + CORE_LOG(LE, (L"[Failed to create Timer Queue][%d]", ::GetLastError())); + } } -// First, do the useful work and then reschedule the timer. Otherwise, it is -// possible that timer notifications overlap, and the timer can't be further -// rescheduled: http://b/1228095 -void Scheduler::HandleCallback(QueueTimer* timer) { - ConfigManager* config_manager = ConfigManager::Instance(); - if (update_timer_.get() == timer) { - core_.StartUpdateWorker(); - int au_timer_interval_ms = config_manager->GetAutoUpdateTimerIntervalMs(); - VERIFY1(SUCCEEDED(ScheduleUpdateTimer(au_timer_interval_ms))); - } else if (code_red_timer_.get() == timer) { - core_.StartCodeRed(); - int actual_time_ms = static_cast(cr_debug_timer_->GetElapsedMs()); - metric_core_cr_actual_timer_interval_ms = actual_time_ms; - CORE_LOG(L3, (_T("[code red actual period][%d ms]"), actual_time_ms)); - int cr_timer_interval_ms = config_manager->GetCodeRedTimerIntervalMs(); - VERIFY1(SUCCEEDED(ScheduleCodeRedTimer(cr_timer_interval_ms))); - } else { - ASSERT1(false); +Scheduler::~Scheduler() { + CORE_LOG(L1, (L"[Scheduler::~Scheduler]")); + + timers_.clear(); + + if (timer_queue_) { + // The destructor blocks on deleting the timer queue and it waits for + // all timer callbacks to complete. + ::DeleteTimerQueueEx(timer_queue_, INVALID_HANDLE_VALUE); + timer_queue_ = NULL; } +} - // Since core is a long lived process, aggregate its metrics once in a while. - core_.AggregateMetrics(); +HRESULT Scheduler::StartWithDebugTimer(int interval, + ScheduledWorkWithTimer work) const { + return DoStart(interval, interval, work, true /*has_debug_timer*/); } -HRESULT Scheduler::ScheduleUpdateTimer(int interval_ms) { - HRESULT hr = update_timer_->Start(interval_ms, 0, WT_EXECUTEONLYONCE); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[can't start update queue timer][0x%08x]"), hr)); - } - return hr; +HRESULT Scheduler::StartWithDelay(int delay, + int interval, + ScheduledWork work) const { + return DoStart(delay, interval, std::bind(work)); } -HRESULT Scheduler::ScheduleCodeRedTimer(int interval_ms) { - metric_core_cr_expected_timer_interval_ms = interval_ms; - cr_debug_timer_->Start(); - HRESULT hr = code_red_timer_->Start(interval_ms, 0, WT_EXECUTEONLYONCE); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[can't start Code Red queue timer][0x%08x]"), hr)); +HRESULT Scheduler::Start(int interval, ScheduledWork work) const { + return DoStart(interval, interval, std::bind(work)); +} + +HRESULT Scheduler::DoStart(int start_delay, + int interval, + ScheduledWorkWithTimer work_fn, + bool has_debug_timer) const { + CORE_LOG(L1, (L"[Scheduler::Start]")); + + if (!timer_queue_) { + return HRESULTFromLastError(); } - return hr; + + timers_.emplace_back(timer_queue_, start_delay, interval, has_debug_timer, + work_fn); + return S_OK; } } // namespace omaha - diff --git a/omaha/core/scheduler.h b/omaha/core/scheduler.h index 88ea5c8..c97b0b2 100644 --- a/omaha/core/scheduler.h +++ b/omaha/core/scheduler.h @@ -20,44 +20,86 @@ #define OMAHA_CORE_SCHEDULER_H__ #include -#include +#include +#include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" +#include "omaha/base/highres_timer-win32.h" +#include "omaha/base/queue_timer.h" namespace omaha { -class Core; -class HighresTimer; -class QueueTimer; +using ScheduledWork = std::function; +using ScheduledWorkWithTimer = std::function; class Scheduler { public: - explicit Scheduler(const Core& core); + explicit Scheduler(); ~Scheduler(); - // Starts the scheduler. - HRESULT Initialize(); + // Starts the scheduler that executes |work| with regular |interval| (ms). + HRESULT Start(int interval, ScheduledWork work) const; + + // Starts the scheduler that executes |work| with regular |interval| (ms) + // after an initial |delay| (ms). + HRESULT StartWithDelay(int delay, int interval, ScheduledWork work) const; + + // Start the scheduler on a regular |interval| (ms). The callback is provided + // a timer which starts after the previous item finishes execution. + HRESULT StartWithDebugTimer(int interval, ScheduledWorkWithTimer work) const; private: - static void TimerCallback(QueueTimer* timer); - void HandleCallback(QueueTimer* timer); - HRESULT ScheduleUpdateTimer(int interval_ms); - HRESULT ScheduleCodeRedTimer(int interval_ms); + class SchedulerItem { + public: + SchedulerItem(HANDLE timer_queue, + int start_delay, + int interval, + bool has_debug_timer, + ScheduledWorkWithTimer work_fn); + + ~SchedulerItem(); + + HighresTimer* debug_timer() const { + return debug_timer_ ? debug_timer_.get() : nullptr; + } + + int interval_ms() const { return interval_ms_; } + + private: + int start_delay_ms_; + int interval_ms_; - const Core& core_; + std::unique_ptr timer_; + + // Measures the actual time interval between events for debugging + // purposes. The timer is started when an alarm is set and then, + // the value of the timer is read when the alarm goes off. + std::unique_ptr debug_timer_; + + ScheduledWorkWithTimer work_; + + static HRESULT ScheduleNext(QueueTimer* timer, + HighresTimer* debug_timer, + int interval_ms); + static void TimerCallback(QueueTimer* timer); + + DISALLOW_COPY_AND_ASSIGN(SchedulerItem); + }; + + HRESULT DoStart(int start_delay, + int interval, + ScheduledWorkWithTimer work, + bool has_debug_timer = false) const; + + // Timer queue handle for all QueueTimer objects. HANDLE timer_queue_; - scoped_ptr update_timer_; - scoped_ptr code_red_timer_; - // Measures the actual time interval between code red events for debugging - // purposes. The timer is started when a code red alarm is set and then, - // the value of the timer is read when the alarm goes off. - scoped_ptr cr_debug_timer_; + mutable std::list timers_; - DISALLOW_EVIL_CONSTRUCTORS(Scheduler); + DISALLOW_COPY_AND_ASSIGN(Scheduler); }; } // namespace omaha #endif // OMAHA_CORE_SCHEDULER_H__ - diff --git a/omaha/core/scheduler_unittest.cc b/omaha/core/scheduler_unittest.cc new file mode 100644 index 0000000..d947edd --- /dev/null +++ b/omaha/core/scheduler_unittest.cc @@ -0,0 +1,184 @@ +// Copyright 2019 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ======================================================================== + +#include "omaha/core/scheduler.h" + +#include + +#include "omaha/base/constants.h" +#include "omaha/base/highres_timer-win32.h" +#include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" + +namespace omaha { + +namespace { + +inline void AssertSignalledBefore(HANDLE handle, DWORD timeout_ms) { + ASSERT_EQ(WAIT_OBJECT_0, ::WaitForSingleObject(handle, timeout_ms)); +} + +inline void AssertAllSignalledBefore(std::vector& handles, + DWORD timeout_ms) { + constexpr bool kWaitAll = true; + std::vector raw_handles; + for (auto& handle : handles) { + raw_handles.emplace_back(get(handle)); + } + const DWORD res = ::WaitForMultipleObjects( + raw_handles.size(), &raw_handles[0], kWaitAll, timeout_ms); + ASSERT_EQ(WAIT_OBJECT_0, res); +} + +inline void AssertTimeoutAfter(HANDLE handle, DWORD timeout_ms) { + ASSERT_EQ(WAIT_TIMEOUT, ::WaitForSingleObject(handle, timeout_ms)); +} + +} // namespace + +class SchedulerTest : public ::testing::Test { + protected: + void SetUp() override {} + void TearDown() override {} +}; + +TEST_F(SchedulerTest, ScheduledTaskReschedules) { + int call_count = 0; + std::vector event_handles(4); + + for (auto& handle : event_handles) { + reset(handle, ::CreateEvent(NULL, true, false, NULL)); + } + + Scheduler scheduler; + // Increase call count after 200ms and every 300ms afterwards + HRESULT hr = + scheduler.StartWithDelay(200, 300, [&call_count, &event_handles]() { + if (call_count < 4) { + ::SetEvent(get(event_handles[call_count])); + } + call_count++; + }); + ASSERT_SUCCEEDED(hr); + AssertAllSignalledBefore(event_handles, 1500); + EXPECT_GE(4, call_count); +} + +TEST_F(SchedulerTest, DeleteWhenCallbackExpires) { + int call_count = 0; + std::vector callbacks(2); + for (auto& handle : callbacks) { + reset(handle, ::CreateEvent(NULL, true, false, NULL)); + } + + // Create the scheduler in a new scope + { + Scheduler scheduler; + // Timer that runs every 250 ms + HRESULT hr = scheduler.Start(250, [&call_count, &callbacks]() { + ::SetEvent(get(callbacks[call_count])); + call_count++; + }); + // Wait for one callback, then scheduler should go out of scope + AssertSignalledBefore(get(callbacks[0]), 300); + } + // Second callback should never fire + AssertTimeoutAfter(get(callbacks[1]), 1000); + EXPECT_EQ(call_count, 1); +} + +TEST_F(SchedulerTest, DeleteSoonBeforeCallbackExpires) { + int call_count = 0; + constexpr int kInterval = 500; + constexpr int kTimeout = kInterval - 10; + scoped_handle callback_fired(::CreateEvent(NULL, true, false, NULL)); + { + Scheduler scheduler; + HRESULT hr = scheduler.Start(kInterval, [&call_count, &callback_fired]() { + call_count++; + ::SetEvent(get(callback_fired)); + }); + ASSERT_SUCCEEDED(hr); + AssertTimeoutAfter(get(callback_fired), kTimeout); + } + EXPECT_EQ(call_count, 0); +} + +TEST_F(SchedulerTest, DoesntUseDebugTimer) { + int call_count = 0; + constexpr int kExpectedIntervalMs = 100; + constexpr int kTimeout = 500; + scoped_handle callback_fired(::CreateEvent(NULL, true, false, NULL)); + { + Scheduler scheduler; + HRESULT hr = + scheduler.Start(kExpectedIntervalMs, [&call_count, &callback_fired]() { + call_count++; + ::SetEvent(get(callback_fired)); + }); + ASSERT_SUCCEEDED(hr); + AssertSignalledBefore(get(callback_fired), kTimeout); + } + ASSERT_EQ(call_count, 1); +} + +TEST_F(SchedulerTest, UsesDebugTimer) { + int call_count = 0; + constexpr int kExpectedIntervalMs = 500; + scoped_handle callback_handle(::CreateEvent(NULL, true, false, NULL)); + { + Scheduler scheduler; + HRESULT hr = scheduler.StartWithDebugTimer( + kExpectedIntervalMs, [&call_count, kExpectedIntervalMs, + &callback_handle](HighresTimer* debug_timer) { + ASSERT_TRUE(debug_timer != nullptr); + EXPECT_GE(debug_timer->GetElapsedMs(), kExpectedIntervalMs); + call_count++; + ::SetEvent(get(callback_handle)); + }); + ASSERT_SUCCEEDED(hr); + AssertSignalledBefore(get(callback_handle), kExpectedIntervalMs + 100); + } + ASSERT_EQ(call_count, 1); +} + +TEST_F(SchedulerTest, LongCallbackBlocks) { + auto scheduler = std::make_unique(); + constexpr int kInterval = 50; + constexpr int kCallbackDelay = 500; + + scoped_handle callback_start(::CreateEvent(NULL, true, false, NULL)); + scoped_handle callback_end(::CreateEvent(NULL, true, false, NULL)); + + HRESULT hr = scheduler->Start( + kInterval, [kCallbackDelay, &callback_start, &callback_end]() { + ::SetEvent(get(callback_start)); + Sleep(kCallbackDelay); + ::SetEvent(get(callback_end)); + }); + ASSERT_SUCCEEDED(hr); + // Try deleting, record how much time it takes + AssertSignalledBefore(get(callback_start), 100); + HighresTimer timer; + timer.Start(); + + // Delete the scheduler, this should block until the long callback finishes + scheduler.reset(); + + AssertSignalledBefore(get(callback_end), 600); + EXPECT_GE(timer.GetElapsedMs(), kCallbackDelay); +} + +} // namespace omaha diff --git a/omaha/core/system_monitor.h b/omaha/core/system_monitor.h index 68bd16d..f7a62d5 100644 --- a/omaha/core/system_monitor.h +++ b/omaha/core/system_monitor.h @@ -20,8 +20,9 @@ #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/registry_monitor_manager.h" namespace omaha { @@ -85,11 +86,11 @@ class SystemMonitor static void RegistryKeyChangeCallback(const TCHAR* key_name, void* user_data); - scoped_ptr registry_monitor_; + std::unique_ptr registry_monitor_; bool is_machine_; SystemMonitorObserver* observer_; - DISALLOW_EVIL_CONSTRUCTORS(SystemMonitor); + DISALLOW_COPY_AND_ASSIGN(SystemMonitor); }; } // namespace omaha diff --git a/omaha/core/system_monitor_unittest.cc b/omaha/core/system_monitor_unittest.cc index 7501b27..f404f0c 100644 --- a/omaha/core/system_monitor_unittest.cc +++ b/omaha/core/system_monitor_unittest.cc @@ -13,12 +13,13 @@ // limitations under the License. // ======================================================================== +#include "omaha/core/system_monitor.h" + #include "omaha/base/constants.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/synchronized.h" #include "omaha/common/const_goopdate.h" -#include "omaha/core/system_monitor.h" #include "omaha/testing/unit_test.h" namespace omaha { @@ -57,7 +58,7 @@ class SystemMonitorTest void MonitorClientsTest(bool is_machine); bool is_machine_; - scoped_ptr gate_; + std::unique_ptr gate_; }; void SystemMonitorTest::MonitorLastCheckedTest(bool is_machine) { diff --git a/omaha/crashhandler/build.scons b/omaha/crashhandler/build.scons index ed49851..6ff22c6 100644 --- a/omaha/crashhandler/build.scons +++ b/omaha/crashhandler/build.scons @@ -63,6 +63,9 @@ def BuildCrashHandler(local_env): gch_env = local_env.Clone() omaha_version_info = gch_env['omaha_versions_info'][0] gch_env.Append( + CCFLAGS = [ + '/wd5038', + ], LIBS = [ 'advapi32.lib', 'crypt32.lib', @@ -107,18 +110,9 @@ def BuildCrashHandler(local_env): gch_res, ] - # We disable runtime stack check to avoid increasing the code size. - # There is a compiler pragma to programmatically disable the stack checks - # but for some reason it did not work. - gch_env.FilterOut(CPPFLAGS = ['/GS']) - - # Disable stack checks for VC80. Stack checks are on by default. - if gch_env['msc_ver'] >= 1400: - gch_env['CCFLAGS'] += ['/GS-'] - # Change the name of the executable based on the architecture, and # change the names of the objects to prevent collisions. - exe_name = 'GoogleCrashHandler%s' % ('', '64')[gch_env.Bit('x64')] + exe_name = 'BraveCrashHandler%s' % ('', '64')[gch_env.Bit('x64')] unsigned_crash_handler = gch_env.ComponentProgram( prog_name='%s_unsigned.exe' % exe_name, @@ -154,15 +148,6 @@ def BuildCrashAnalysisTest(local_env): td_inputs = ['crash_analyzer_debugee_test.cc'] - # We disable runtime stack check to avoid increasing the code size. - # There is a compiler pragma to programmatically disable the stack checks - # but for some reason it did not work. - td_env.FilterOut(CPPFLAGS = ['/GS']) - - # Disable stack checks for VC80. Stack checks are on by default. - if td_env['msc_ver'] >= 1400: - td_env['CCFLAGS'] += ['/GS-'] - test_debugee = td_env.ComponentProgram( prog_name='CrashHandlerTestDebugee.exe', source=td_inputs, diff --git a/omaha/crashhandler/crash_analyzer.cc b/omaha/crashhandler/crash_analyzer.cc index e4a6bb6..d0f3dea 100644 --- a/omaha/crashhandler/crash_analyzer.cc +++ b/omaha/crashhandler/crash_analyzer.cc @@ -15,11 +15,8 @@ #include "omaha/crashhandler/crash_analyzer.h" -#include -#include #include -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/utils.h" #include "omaha/crashhandler/crash_analyzer_checks.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" @@ -193,7 +190,7 @@ bool CrashAnalyzer::ReadMemorySegment(BYTE* ptr, *size = region_size; return true; } - scoped_array region_buffer(new BYTE[region_size]); + std::unique_ptr region_buffer(new BYTE[region_size]); memset(region_buffer.get(), 0, region_size); if (!::ReadProcessMemory(client_info_.process_handle(), ptr, diff --git a/omaha/crashhandler/crash_analyzer.h b/omaha/crashhandler/crash_analyzer.h index 5b06c0e..c3d613a 100644 --- a/omaha/crashhandler/crash_analyzer.h +++ b/omaha/crashhandler/crash_analyzer.h @@ -19,11 +19,11 @@ #include #include #include +#include #include #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" namespace omaha { @@ -39,7 +39,7 @@ enum CrashAnalysisResult { // The process has a suspicious number of executable memory mappings. // This is likely the result of a spray. ANALYSIS_EXCESSIVE_EXEC_MEM, - // Crash occured near an instruction sequence that modifies the stack + // Crash occurred near an instruction sequence that modifies the stack // pointer. ANALYSIS_STACK_PIVOT, // The crashing instruction sequence looks like a bad dereference of @@ -152,7 +152,7 @@ class CrashAnalyzer { bool InitializeDebuggerAndSuspendProcess(); BYTE* GetCachedSegment(BYTE* ptr) const; - scoped_ptr debug_break_event_; + std::unique_ptr debug_break_event_; DWORD pid_; size_t exec_pages_; diff --git a/omaha/crashhandler/crash_analyzer_checks.cc b/omaha/crashhandler/crash_analyzer_checks.cc index ea0ecbc..fe30b9b 100644 --- a/omaha/crashhandler/crash_analyzer_checks.cc +++ b/omaha/crashhandler/crash_analyzer_checks.cc @@ -16,12 +16,10 @@ #include "omaha/crashhandler/crash_analyzer_checks.h" #include - #include #include #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" namespace omaha { diff --git a/omaha/crashhandler/crash_dump_util.cc b/omaha/crashhandler/crash_dump_util.cc index dc058bf..0bcae77 100644 --- a/omaha/crashhandler/crash_dump_util.cc +++ b/omaha/crashhandler/crash_dump_util.cc @@ -15,6 +15,8 @@ #include "omaha/crashhandler/crash_dump_util.h" +#include + #include "omaha/base/environment_block_modifier.h" #include "omaha/base/error.h" #include "omaha/base/process.h" @@ -73,7 +75,8 @@ HRESULT GetEnvironmentVariableToBuffer(const TCHAR* name, env_value_char.GetLength(), static_cast(value_out), static_cast(value_buffer_size)); - if (result_size < 0 || value_buffer_size != result_size) { + if (result_size < 0 || + value_buffer_size != static_cast(result_size)) { CORE_LOG(LE, (_T("[Failed to decode value][%s=%s]"), name, env_value)); return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } @@ -146,14 +149,14 @@ HRESULT GetCrashInfoFromEnvironmentVariables( HANDLE* mini_dump_handle, HANDLE* full_dump_handle, HANDLE* custom_info_handle, - google_breakpad::ClientInfo** client_info_ptr) { + std::unique_ptr* client_info_ptr) { ASSERT1(notification_event); ASSERT1(mini_dump_handle); ASSERT1(full_dump_handle); ASSERT1(custom_info_handle); ASSERT1(client_info_ptr); *notification_event = NULL; - *client_info_ptr = NULL; + client_info_ptr->reset(); *mini_dump_handle = NULL; *full_dump_handle = NULL; *custom_info_handle = NULL; @@ -168,7 +171,7 @@ HRESULT GetCrashInfoFromEnvironmentVariables( *mini_dump_handle = crash_info.mini_dump_handle; *full_dump_handle = crash_info.full_dump_handle; *custom_info_handle = crash_info.custom_info_handle; - scoped_ptr client_info; + std::unique_ptr client_info; client_info.reset(new google_breakpad::ClientInfo(NULL, crash_info.crash_process_id, crash_info.dump_type, @@ -180,7 +183,7 @@ HRESULT GetCrashInfoFromEnvironmentVariables( CORE_LOG(LE, (_T("[CrashHandler][Failed to initialize ClientInfo."))); return E_FAIL; } - *client_info_ptr = client_info.release(); + client_info_ptr->reset(client_info.release()); return S_OK; } diff --git a/omaha/crashhandler/crash_dump_util.h b/omaha/crashhandler/crash_dump_util.h index e427d05..3fb38c5 100644 --- a/omaha/crashhandler/crash_dump_util.h +++ b/omaha/crashhandler/crash_dump_util.h @@ -17,6 +17,7 @@ #define OMAHA_CRASHHANDLER_CRASH_DUMP_UTIL_H_ #include +#include #include "base/basictypes.h" #include "omaha/base/string.h" @@ -51,7 +52,7 @@ HRESULT GetCrashInfoFromEnvironmentVariables( HANDLE* mini_dump_handle, HANDLE* full_dump_handle, HANDLE* custom_info_handle, - google_breakpad::ClientInfo** client_info); + std::unique_ptr* client_info); } // namespace omaha diff --git a/omaha/crashhandler/crash_dump_util_test.cc b/omaha/crashhandler/crash_dump_util_test.cc index d1538e1..5ebede9 100644 --- a/omaha/crashhandler/crash_dump_util_test.cc +++ b/omaha/crashhandler/crash_dump_util_test.cc @@ -13,17 +13,18 @@ // limitations under the License. // ======================================================================== +#include "omaha/crashhandler/crash_dump_util.h" + + #include "omaha/base/app_util.h" #include "omaha/base/environment_block_modifier.h" #include "omaha/base/process.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/utils.h" -#include "omaha/crashhandler/crash_dump_util.h" #include "omaha/crashhandler/crash_dump_util_internal.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/crashhandler/crash_handler.cc b/omaha/crashhandler/crash_handler.cc index d547d8b..70b1f29 100644 --- a/omaha/crashhandler/crash_handler.cc +++ b/omaha/crashhandler/crash_handler.cc @@ -43,8 +43,6 @@ #include "omaha/base/reactor.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/shutdown_callback.h" #include "omaha/base/shutdown_handler.h" #include "omaha/base/string.h" @@ -60,6 +58,7 @@ #include "omaha/crashhandler/crashhandler_metrics.h" #include "omaha/crashhandler/crash_dump_util.h" #include "omaha/crashhandler/crash_worker.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/common/ipc_protocol.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" #include "third_party/breakpad/src/client/windows/crash_generation/crash_generation_server.h" @@ -111,7 +110,7 @@ HRESULT CrashHandler::Main(bool is_system) { VERIFY1(SUCCEEDED( OmahaExceptionHandler::Create(is_system, custom_info_map, - address(exception_handler_)))); + &exception_handler_))); // Are we allowed to monitor crashes? if (!ConfigManager::Instance()->CanCollectStats(is_system)) { @@ -133,12 +132,12 @@ HRESULT CrashHandler::RunAsCrashHandlerWorker() { scoped_handle mini_dump_handle; scoped_handle full_dump_handle; scoped_handle custom_info_handle; - scoped_ptr client_info; + std::unique_ptr client_info; HRESULT hr = GetCrashInfoFromEnvironmentVariables(address(notification_event), address(mini_dump_handle), address(full_dump_handle), address(custom_info_handle), - address(client_info)); + &client_info); if (FAILED(hr)) { CORE_LOG(LE, (_T("[Failed to get crash info from environment.]"))); return hr; @@ -148,7 +147,7 @@ HRESULT CrashHandler::RunAsCrashHandlerWorker() { OPT_LOG(L1, (_T("[CrashHandler][Preparing dump][%d-bit][pid %d]"), EXE_ARCH, pid)); - scoped_ptr analyzer(new CrashAnalyzer(*client_info)); + std::unique_ptr analyzer(new CrashAnalyzer(*client_info)); if (!analyzer->Init()) { analyzer.release(); } @@ -408,6 +407,7 @@ void CrashHandler::BreakpadClientConnected( ASSERT1(client_info); UNREFERENCED_PARAMETER(context); + UNREFERENCED_PARAMETER(client_info); CORE_LOG(L1, (_T("[CrashHandler][Client connected][%d-bit][pid %d]"), EXE_ARCH, client_info->pid())); } @@ -497,7 +497,7 @@ void CrashHandler::BreakpadClientCrashed( } else { CString custom_info_filename; crash_utils::GetCustomInfoFilePath(dump_file_path, &custom_info_filename); - HRESULT hr = handler->StartCrashUploader(dump_file_path, + hr = handler->StartCrashUploader(dump_file_path, custom_info_filename); if (FAILED(hr)) { OPT_LOG(LE, (_T("[StartCrashUploader() failed][0x%08x]"), hr)); @@ -575,6 +575,7 @@ void CrashHandler::BreakpadClientDisconnected( ASSERT1(client_info); UNREFERENCED_PARAMETER(context); + UNREFERENCED_PARAMETER(client_info); CORE_LOG(L1, (_T("[CrashHandler][Client exited][%d-bit][%d]"), EXE_ARCH, client_info->pid())); } diff --git a/omaha/crashhandler/crash_handler.h b/omaha/crashhandler/crash_handler.h index 5f84737..90cc79d 100644 --- a/omaha/crashhandler/crash_handler.h +++ b/omaha/crashhandler/crash_handler.h @@ -24,11 +24,10 @@ #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/shutdown_callback.h" #include "omaha/base/string.h" #include "omaha/common/exception_handler.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" #include "third_party/breakpad/src/client/windows/crash_generation/crash_generation_server.h" #include "third_party/breakpad/src/client/windows/crash_generation/minidump_generator.h" @@ -128,15 +127,15 @@ class CrashHandler : public ShutdownCallback { bool is_system_; CString crash_dir_; - scoped_ptr crash_server_; + std::unique_ptr crash_server_; DWORD main_thread_id_; - scoped_ptr reactor_; - scoped_ptr shutdown_handler_; + std::unique_ptr reactor_; + std::unique_ptr shutdown_handler_; std::map saved_crashes_; - scoped_ptr exception_handler_; + std::unique_ptr exception_handler_; DISALLOW_COPY_AND_ASSIGN(CrashHandler); }; diff --git a/omaha/crashhandler/crash_worker.cc b/omaha/crashhandler/crash_worker.cc index 91b9a5f..3d61993 100644 --- a/omaha/crashhandler/crash_worker.cc +++ b/omaha/crashhandler/crash_worker.cc @@ -15,6 +15,8 @@ #include "omaha/crashhandler/crash_worker.h" +#include + #include "omaha/base/environment_block_modifier.h" #include "omaha/base/error.h" #include "omaha/base/process.h" @@ -163,6 +165,8 @@ HRESULT GenerateMinidump(bool is_system, ASSERT1(client_info.pid() != 0); ASSERT1(client_info.process_handle()); + UNREFERENCED_PARAMETER(is_system); + // We have to get the address of EXCEPTION_INFORMATION from // the client process address space. EXCEPTION_POINTERS* client_ex_info = NULL; @@ -178,7 +182,7 @@ HRESULT GenerateMinidump(bool is_system, } // Passing an empty string as the dump directory is ok here because we are // generating the dumps using previously opened handles. - scoped_ptr dump_generator( + std::unique_ptr dump_generator( new google_breakpad::MinidumpGenerator(std::wstring(), client_info.process_handle(), client_info.pid(), @@ -191,7 +195,7 @@ HRESULT GenerateMinidump(bool is_system, dump_generator->SetDumpFile(mini_dump_file_handle); dump_generator->SetFullDumpFile(full_dump_file_handle); - scoped_array user_streams( + std::unique_ptr user_streams( new MINIDUMP_USER_STREAM[kMaxUserStreams]); memset(user_streams.get(), 0, sizeof(MINIDUMP_USER_STREAM) * kMaxUserStreams); @@ -231,6 +235,7 @@ HRESULT WriteCustomMapFile(DWORD crash_id, bool* is_uploaded_deferral_requested, HANDLE custom_info_file_handle, CrashAnalysisResult analysis_result) { + UNREFERENCED_PARAMETER(crash_id); if (!client_info->PopulateCustomInfo()) { CORE_LOG(LE, (_T("[CrashHandler][PopulateCustomInfo failed]"))); return E_FAIL; diff --git a/omaha/crashhandler/resource.rc b/omaha/crashhandler/resource.rc index dde6b28..202f861 100644 --- a/omaha/crashhandler/resource.rc +++ b/omaha/crashhandler/resource.rc @@ -13,9 +13,7 @@ // limitations under the License. // ======================================================================== -#include #include -#include #include "resource.h" LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -57,7 +55,7 @@ BEGIN // Strings that get localized must appear as literals so the tools can replace // them. For open source builds, which don't use these tools, use constants. #ifdef GOOGLE_UPDATE_BUILD - VALUE "CompanyName", "Google Inc." + VALUE "CompanyName", "Google LLC" VALUE "FileDescription", "Google Crash Handler" #else VALUE "CompanyName", FULL_COMPANY_NAME_ANSI @@ -65,7 +63,6 @@ BEGIN #endif VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", "Copyright 2007-2010 Google Inc." VALUE "OriginalFilename", MAIN_EXE_BASE_NAME_ANSI ".exe" #ifdef GOOGLE_UPDATE_BUILD VALUE "ProductName", "Google Update" diff --git a/omaha/enterprise/GoogleCloudManagement.adm b/omaha/enterprise/GoogleCloudManagement.adm new file mode 100644 index 0000000..1c76c4c Binary files /dev/null and b/omaha/enterprise/GoogleCloudManagement.adm differ diff --git a/omaha/enterprise/GoogleCloudManagement.adml b/omaha/enterprise/GoogleCloudManagement.adml new file mode 100644 index 0000000..4b806cd --- /dev/null +++ b/omaha/enterprise/GoogleCloudManagement.adml @@ -0,0 +1,31 @@ + + + + + + + + At least Google Update 1.3.34.3 + Cloud Management + Cloud management enrollment mandatory + Cloud management enrollment token + Policies to control cloud management of Google applications. + If this policy is enabled, cloud management enrollment is mandatory and blocks product installation in case of failure. + +If this policy is left unset or is disabled, cloud management enrollment is optional and does not block product installation. + If this policy is set, Google Update will attempt to enroll the machine in cloud management. + +The value of this policy is an Enrollment token retrieved from the Google Admin console. + + + + + + + + + + + + + diff --git a/omaha/enterprise/GoogleCloudManagement.admx b/omaha/enterprise/GoogleCloudManagement.admx new file mode 100644 index 0000000..de038ec --- /dev/null +++ b/omaha/enterprise/GoogleCloudManagement.admx @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/omaha/enterprise/generate_group_policy_template.py b/omaha/enterprise/generate_group_policy_template.py index 825fc3b..1e38d97 100644 --- a/omaha/enterprise/generate_group_policy_template.py +++ b/omaha/enterprise/generate_group_policy_template.py @@ -20,9 +20,12 @@ To unit test this module, just run the file from the command line. """ +from __future__ import print_function + import codecs import filecmp import os +import string import sys @@ -92,7 +95,7 @@ VALUENAME UpdatesSuppressedDurationMin DEFAULT 60 MIN 1 - MAX 720 ; Maximum duration is 720 minutes = 12 hours + MAX 960 ; Maximum duration is 960 minutes = 16 hours SPIN 30 END PART END POLICY @@ -238,6 +241,16 @@ END PART END POLICY + POLICY !!Pol_RollbackToTargetVersion + #if version >= 4 + SUPPORTED !!Sup_GoogleUpdate1_3_34_3 + #endif + EXPLAIN !!Explain_RollbackToTargetVersion$AppLegalId$ + VALUENAME RollbackToTargetVersion$AppGuid$ + VALUEOFF NUMERIC 0 + VALUEON NUMERIC 1 + END POLICY + END CATEGORY ; $AppName$ """) @@ -253,7 +266,8 @@ ALLOW_INSTALLATION_POLICY = 'Allow installation' DEFAULT_ALLOW_INSTALLATION_POLICY = ALLOW_INSTALLATION_POLICY + ' default' UPDATE_POLICY = 'Update policy override' -TARGET_VERSION_POLICY = 'Target version override' +TARGET_VERSION_POLICY = 'Target version prefix override' +ROLLBACK_VERSION_POLICY = 'Rollback to Target version' DEFAULT_UPDATE_POLICY = UPDATE_POLICY + ' default' # Update policy options that are used in multiple locations. @@ -277,6 +291,7 @@ Sup_GoogleUpdate1_3_21_81=At least Google Update 1.3.21.81 Sup_GoogleUpdate1_3_26_0=At least Google Update 1.3.26.0 Sup_GoogleUpdate1_3_33_5=At least Google Update 1.3.33.5 +Sup_GoogleUpdate1_3_34_3=At least Google Update 1.3.34.3 Cat_Google=Google Cat_GoogleUpdate=Google Update @@ -295,6 +310,7 @@ Pol_DefaultUpdatePolicy=""" + DEFAULT_UPDATE_POLICY + """ Pol_UpdatePolicy=""" + UPDATE_POLICY + """ Pol_TargetVersionPrefix=""" + TARGET_VERSION_POLICY + """ +Pol_RollbackToTargetVersion=""" + ROLLBACK_VERSION_POLICY + """ Part_AutoUpdateCheckPeriod=Minutes between update checks Part_DownloadPreference=Type of download URL to request @@ -330,7 +346,7 @@ # pylint: disable-msg=C6310 # pylint: disable-msg=C6013 -# "application's" should be preceeded by a different word in different contexts. +# "application's" should be preceded by a different word in different contexts. # The word is specified by replacing the $PreApplicationWord$ token. STRINGS_UPDATE_POLICY_OPTIONS = """\ \\n\\nOptions:\\ @@ -383,23 +399,32 @@ '; Individual Applications\n' + HORIZONTAL_RULE) +DEFAULT_ROLLBACK_DISCLAIMER = """This policy is meant to serve as temporary measure when Enterprise Administrators need to downgrade for business reasons. To ensure users are protected by the latest security updates, the most recent version should be used. When versions are downgraded to older versions, there could be incompatibilities.""" + STRINGS_APP_POLICY_EXPLANATIONS_TEMPLATE = (""" ; $AppName$ Explain_Install$AppLegalId$=Specifies whether $AppName$ can be installed using Google Update/Google Installer.\\ \\n\\nIf this policy is not configured, $AppName$ can be installed as specified by \"""" + DEFAULT_ALLOW_INSTALLATION_POLICY + """\". Explain_AutoUpdate$AppLegalId$=Specifies how Google Update handles available $AppName$ updates from Google.\\ - \\n\\nIf this policy is not configured, Google Update handles available updates as specified by \"""" + DEFAULT_UPDATE_POLICY + """\". + \\n\\nIf this policy is not configured, Google Update handles available updates as specified by \"""" + DEFAULT_UPDATE_POLICY + """\".\\ +""" + +STRINGS_UPDATE_POLICY_OPTIONS.replace('$PreApplicationWord$', 'the') + '$AppUpdateExplainExtra$') + """ Explain_TargetVersionPrefix$AppLegalId$=Specifies which version $AppName$ should be updated to.\\ \\n\\nWhen this policy is enabled, the app will be updated to the version prefixed with this policy value.\\ \\n\\nSome examples:\\n\\ - 1) Not configured: app will be update to latest version available.\\n\\ - 2) Policy value is set to "55.", the app will be updated to any minor version of 55 (e.g. 55.24.34 or 55.60.2).\\n\\ - 3) Policy value is "55.2.", the app will be updated to any minor version of 55.2 (e.g. 55.2.34 or 55.2.2).\\n\\ - 4) Policy value is "55.24.34", the app will be updated to this specific version only. -""" + -STRINGS_UPDATE_POLICY_OPTIONS.replace('$PreApplicationWord$', 'the') + '$AppUpdateExplainExtra$\n') + 1) Not configured: app will be updated to the latest version available.\\n\\ + 2) Policy value is set to "55.": the app will be updated to any minor version of 55 (e.g., 55.24.34 or 55.60.2).\\n\\ + 3) Policy value is "55.2.": the app will be updated to any minor version of 55.2 (e.g., 55.2.34 or 55.2.2).\\n\\ + 4) Policy value is "55.24.34": the app will be updated to this specific version only. + +Explain_RollbackToTargetVersion$AppLegalId$=Specifies that Google Update should roll installations of $AppName$ back to the version indicated by \"""" + TARGET_VERSION_POLICY + """\".\\ + \\n\\nThis policy setting has no effect unless \"""" + TARGET_VERSION_POLICY + """\" is set.\\ + \\n\\nIf this policy is not configured or is disabled, installs that have a version higher than that specified by \"""" + TARGET_VERSION_POLICY + """\" will be left as-is.\\ + \\n\\nIf this policy is enabled, installs that have a version higher than that specified by \"""" + TARGET_VERSION_POLICY + """\" will be downgraded to the highest available version that matches the target version.\\ + \\n\\n$AppRollbackDisclaimer$ +""" # pylint: enable-msg=C6013 # pylint: enable-msg=C6310 @@ -489,12 +514,16 @@ def _WriteTemplateForApp(template, app): strings. """ - (app_name, app_guid, update_explain_extra) = app + (app_name, app_guid, update_explain_extra, rollback_disclaimer) = app + if not rollback_disclaimer: + rollback_disclaimer = DEFAULT_ROLLBACK_DISCLAIMER + rollback_disclaimer = string.replace(rollback_disclaimer, '\n', '\\n') # pylint: disable-msg=C6004 return (template.replace('$AppName$', app_name) .replace('$AppLegalId$', _CreateLegalIdentifier(app_name)) .replace('$AppGuid$', app_guid) .replace('$AppUpdateExplainExtra$', update_explain_extra) + .replace('$AppRollbackDisclaimer$', rollback_disclaimer) ) # pylint: enable-msg=C6004 @@ -555,10 +584,12 @@ def WriteGroupPolicyTemplate(target_path, apps): TEST_APPS = [ ('Google Test Foo', '{D6B08267-B440-4c85-9F79-E195E80D9937}', - ' Check http://www.google.com/test_foo/.'), + ' Check http://www.google.com/test_foo/.', + 'Disclaimer'), (u'Google User Test Foo\u00a9\u00ae\u2122', '{104844D6-7DDA-460b-89F0-FBF8AFDD0A67}', - ' Check http://www.google.com/user_test_foo/.'), + ' Check http://www.google.com/user_test_foo/.', + ''), ] TEST_GOLD_FILENAME = 'test_gold.adm' TEST_OUTPUT_FILENAME = 'test_out.adm' @@ -570,7 +601,7 @@ def WriteGroupPolicyTemplate(target_path, apps): WriteGroupPolicyTemplate(output_path, TEST_APPS) if filecmp.cmp(gold_path, output_path, shallow=False): - print 'PASS: Contents equal.' + print('PASS: Contents equal.') else: - print 'FAIL: Contents not equal.' + print('FAIL: Contents not equal.') sys.exit(-1) diff --git a/omaha/enterprise/generate_group_policy_template_admx.py b/omaha/enterprise/generate_group_policy_template_admx.py index dcd2534..4f36930 100644 --- a/omaha/enterprise/generate_group_policy_template_admx.py +++ b/omaha/enterprise/generate_group_policy_template_admx.py @@ -19,12 +19,15 @@ To unit test this module, just run the file from the command line. """ +from __future__ import print_function + import codecs import filecmp import os import re import sys + MAIN_POLICY_KEY = r'Software\Policies\Google\Update' ADMX_HEADER = '' @@ -47,6 +50,8 @@ displayName="$(string.Sup_GoogleUpdate1_3_26_0)" /> + ''' @@ -78,8 +83,7 @@ displayName="$(string.Pol_AutoUpdateCheckPeriod)" explainText="$(string.Explain_AutoUpdateCheckPeriod)" presentation="$(presentation.Pol_AutoUpdateCheckPeriod)" - key="%(RootPolicyKey)s" - valueName="AutoUpdateCheckPeriodMinutes"> + key="%(RootPolicyKey)s"> @@ -126,14 +130,14 @@ + required="true" minValue="1" maxValue="960" /> + key="%(RootPolicyKey)s"> @@ -293,6 +297,17 @@ + + + + + + ''' ADMX_FOOTER = '' @@ -371,7 +386,7 @@ def _GeneratePolicies(apps): app_policy_list = [] for app in apps: - app_name, app_guid, _ = app + app_name, app_guid, _, _ = app app_policy_list.append(ADMX_APP_POLICY_TEMPLATE % { 'AppLegalId': _CreateLegalIdentifier(app_name), 'AppGuid': app_guid, @@ -405,11 +420,19 @@ def _GeneratePolicies(apps): ''' +ADML_DEFAULT_ROLLBACK_DISCLAIMER = ( + 'This policy is meant to serve as temporary measure when Enterprise ' + 'Administrators need to downgrade for business reasons. To ensure ' + 'users are protected by the latest security updates, the most recent ' + 'version should be used. When versions are downgraded to older ' + 'versions, there could be incompatibilities.') + ADML_PREDEFINED_STRINGS_TABLE_EN = [ ('Sup_GoogleUpdate1_2_145_5', 'At least Google Update 1.2.145.5'), ('Sup_GoogleUpdate1_3_21_81', 'At least Google Update 1.3.21.81'), ('Sup_GoogleUpdate1_3_26_0', 'At least Google Update 1.3.26.0'), ('Sup_GoogleUpdate1_3_33_5', 'At least Google Update 1.3.33.5'), + ('Sup_GoogleUpdate1_3_34_3', 'At least Google Update 1.3.34.3'), ('Cat_GoogleUpdate', 'Google Update'), ('Cat_Preferences', 'Preferences'), ('Cat_ProxyServer', 'Proxy Server'), @@ -427,6 +450,7 @@ def _GeneratePolicies(apps): ('Pol_DefaultUpdatePolicy', 'Update policy override default'), ('Pol_UpdatePolicy', 'Update policy override'), ('Pol_TargetVersionPrefix', 'Target version prefix override'), + ('Pol_RollbackToTargetVersion', 'Rollback to Target version'), ('Part_AutoUpdateCheckPeriod', 'Minutes between update checks'), ('Part_UpdateCheckSuppressedStartHour', 'Hour in a day that start to suppress update check'), @@ -572,6 +596,7 @@ def _GeneratePolicies(apps): + ''' ADML_RESOURCE_TABLE_TEMPLATE = ''' @@ -612,6 +637,9 @@ def GenerateGroupPolicyTemplateAdml(apps): app_name = app[0] app_legal_id = _CreateLegalIdentifier(app_name) app_additional_help_msg = app[2] + rollback_disclaimer = app[3] + if not rollback_disclaimer: + rollback_disclaimer = ADML_DEFAULT_ROLLBACK_DISCLAIMER app_category = ('Cat_' + app_legal_id, app_name) string_definition_list.append(app_category) @@ -651,15 +679,31 @@ def GenerateGroupPolicyTemplateAdml(apps): 'Specifies which version %s should be updated to.\n\n' 'When this policy is enabled, the app will be updated to the version ' 'prefixed with this policy value.\n\nSome examples:\n' - '1) Not configured: app will be update to latest version available.\n' - '2) Policy value is set to "55.", the app will be updated to any minor ' - 'version of 55 (e.g. 55.24.34 or 55.60.2).\n' - '3) Policy value is "55.2.", the app will be updated to any minor ' - 'version of 55.2 (e.g. 55.2.34 or 55.2.2).\n' - '4) Policy value is "55.24.34", the app will be updated to this ' + '1) Not configured: app will be updated to the latest version ' + 'available.\n' + '2) Policy value is set to "55.": the app will be updated to any minor ' + 'version of 55 (e.g., 55.24.34 or 55.60.2).\n' + '3) Policy value is "55.2.": the app will be updated to any minor ' + 'version of 55.2 (e.g., 55.2.34 or 55.2.2).\n' + '4) Policy value is "55.24.34": the app will be updated to this ' 'specific version only.' % app_name) string_definition_list.append(app_target_version_prefix_explanation) + app_rollback_to_target_version_explanation = ( + 'Explain_RollbackToTargetVersion' + app_legal_id, + 'Specifies that Google Update should roll installations of %s back to ' + 'the version indicated by "Target version prefix override".\n\n' + 'This policy setting has no effect unless "Target version prefix ' + 'override" is set.\n\n' + 'If this policy is not configured or is disabled, installs that have a ' + 'version higher than that specified by "Target version prefix ' + 'override" will be left as-is.\n\n' + 'If this policy is enabled, installs that have a version higher than ' + 'that specified by "Target version prefix override" will be downgraded ' + 'to the highest available version that matches the target version.\n\n' + '%s' % (app_name, rollback_disclaimer)) + string_definition_list.append(app_rollback_to_target_version_explanation) + app_resource_strings = [] for entry in string_definition_list: app_resource_strings.append(' %s' % @@ -723,10 +767,12 @@ def WriteGroupPolicyTemplateAdml(target_path, apps): if __name__ == '__main__': TEST_APPS = [ ('Google Test Foo', '{D6B08267-B440-4c85-9F79-E195E80D9937}', - ' Check http://www.google.com/test_foo/.'), + ' Check http://www.google.com/test_foo/.', + 'Disclaimer'), (u'Google User Test Foo\u00a9\u00ae\u2122', '{104844D6-7DDA-460b-89F0-FBF8AFDD0A67}', - ' Check http://www.google.com/user_test_foo/.'), + ' Check http://www.google.com/user_test_foo/.', + ''), ] module_dir = os.path.abspath(os.path.dirname(__file__)) gold_path = os.path.join(module_dir, 'test_gold.admx') @@ -735,16 +781,16 @@ def WriteGroupPolicyTemplateAdml(target_path, apps): WriteGroupPolicyTemplateAdmx(output_path, TEST_APPS) admx_files_equal = filecmp.cmp(gold_path, output_path, shallow=False) if not admx_files_equal: - print 'FAIL: ADMX files are not equal.' + print('FAIL: ADMX files are not equal.') gold_path = os.path.join(module_dir, 'test_gold.adml') output_path = os.path.join(module_dir, 'test_out.adml') WriteGroupPolicyTemplateAdml(output_path, TEST_APPS) adml_files_equal = filecmp.cmp(gold_path, output_path, shallow=False) if not adml_files_equal: - print 'FAIL: ADML files are not equal.' + print('FAIL: ADML files are not equal.') if admx_files_equal and adml_files_equal: - print 'SUCCESS. contents are equal' + print('SUCCESS. contents are equal') else: sys.exit(-1) diff --git a/omaha/enterprise/installer/build.scons b/omaha/enterprise/installer/build.scons index e030e77..6e2f2c0 100644 --- a/omaha/enterprise/installer/build.scons +++ b/omaha/enterprise/installer/build.scons @@ -117,7 +117,7 @@ def _BuildSampleForTest(): prefix + msi_base_name + '_' + combo[0], '$MAIN_DIR/enterprise/installer', msi_custom_action_dll, - '$STAGING_DIR/%sGoogleUpdateSetup.exe' % prefix, + '$STAGING_DIR/%sBraveUpdateSetup.exe' % prefix, output_dir = '$TARGET_ROOT/Test_Installers' ) diff --git a/omaha/enterprise/installer/custom_actions/build.scons b/omaha/enterprise/installer/custom_actions/build.scons index b915ccd..85e9525 100644 --- a/omaha/enterprise/installer/custom_actions/build.scons +++ b/omaha/enterprise/installer/custom_actions/build.scons @@ -21,17 +21,14 @@ Import('env') # Build msi_custom_action.dll # def BuildShowErrorActionDll(omaha_version_info): - prefix = omaha_version_info.filename_prefix - dll_env = env.Clone( # Build a dll, not a lib. COMPONENT_STATIC = False, ) - if prefix == 'TEST_': - dll_env['OBJPREFIX'] = dll_env.subst('test/$OBJPREFIX') - elif prefix: - raise Exception('ERROR: Unrecognized prefix "%s"' % prefix) + prefix = omaha_version_info.filename_prefix + if prefix: + dll_env['OBJPREFIX'] = dll_env.subst(prefix + 'obj/$OBJPREFIX') dll_env.Append( LIBS = [ diff --git a/omaha/enterprise/installer/custom_actions/extract_tag_action.cc b/omaha/enterprise/installer/custom_actions/extract_tag_action.cc index 003acee..021ab88 100644 --- a/omaha/enterprise/installer/custom_actions/extract_tag_action.cc +++ b/omaha/enterprise/installer/custom_actions/extract_tag_action.cc @@ -75,6 +75,7 @@ extern "C" UINT __stdcall ExtractTagInfoFromInstaller(MSIHANDLE msi_handle) { { "appname", L"APPNAME", 512 }, { "brand", L"BRAND", 4 }, // A four-character brand code. { "browser", L"BROWSER", 1 }, // A single integer digit BrowserType. + { "etoken", L"ETOKEN", 1024 }, // Limit set by DMServer. { "iid", L"IID", 38 }, // 128/4 nybbles + four dashes + two braces. { "installdataindex", L"INSTALLDATAINDEX", 50 }, { "lang", L"LANG", 10 }, diff --git a/omaha/enterprise/installer/custom_actions/msi_custom_action.rc b/omaha/enterprise/installer/custom_actions/msi_custom_action.rc index 80d38ca..7d3309b 100644 --- a/omaha/enterprise/installer/custom_actions/msi_custom_action.rc +++ b/omaha/enterprise/installer/custom_actions/msi_custom_action.rc @@ -15,7 +15,7 @@ // // This file contains the unlocalized show_error_action resources. -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -49,7 +49,6 @@ BEGIN VALUE "FileDescription", OMAHA_APP_NAME_ANSI VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", OMAHA_COPYRIGHT_STRING_ENGLISH VALUE "OriginalFilename", ACTION_DLL_BASE_NAME_ANSI VALUE "ProductName", OMAHA_APP_NAME_ANSI VALUE "ProductVersion", VERSION_NUMBER_STRING diff --git a/omaha/enterprise/installer/enterprise_installer.wxs.xml b/omaha/enterprise/installer/enterprise_installer.wxs.xml index 705627f..deecce2 100644 --- a/omaha/enterprise/installer/enterprise_installer.wxs.xml +++ b/omaha/enterprise/installer/enterprise_installer.wxs.xml @@ -1,7 +1,7 @@ - - + + - - + + @@ -141,6 +141,11 @@ Value='[ProductTag]&browser=[BROWSER]' Execute='immediate' Return='check' /> + + Before='AppendEnrollmentTokenToProductTagProperty'> (((?ProductClientState=2) AND ($ProductClientState=3)) OR ((?ProductClientState=3) AND REINSTALL)) AND (BRAND <> "") + + (((?ProductClientState=2) AND ($ProductClientState=3)) OR ((?ProductClientState=3) AND REINSTALL)) AND (ETOKEN <> "") + (((?ProductClientState=2) AND ($ProductClientState=3)) OR ((?ProductClientState=3) AND REINSTALL)) AND (BROWSER <> "") diff --git a/omaha/enterprise/installer/test/test_setup.cc b/omaha/enterprise/installer/test/test_setup.cc index bc193d9..407ec6c 100644 --- a/omaha/enterprise/installer/test/test_setup.cc +++ b/omaha/enterprise/installer/test/test_setup.cc @@ -52,7 +52,7 @@ void WriteFailureValues() { } // namespace -int wmain(int argc, wchar_t* argv[]) { +int wmain(int /*argc*/, wchar_t* /*argv[]*/) { WriteFailureValues(); return 1; } diff --git a/omaha/enterprise/installer/utils.py b/omaha/enterprise/installer/utils.py index 65b0fa0..01c3b06 100644 --- a/omaha/enterprise/installer/utils.py +++ b/omaha/enterprise/installer/utils.py @@ -5,6 +5,7 @@ """ import binascii +from datetime import date import md5 @@ -125,6 +126,7 @@ def GetWixCandleFlags( msi_upgradecode_guid=None, product_installer_path=None, product_installer_data=None, + product_icon_path=None, product_installer_install_command=None, product_installer_disable_update_registration_arg=None, product_custom_params=None, @@ -137,6 +139,7 @@ def GetWixCandleFlags( '-dProductNameLegalIdentifier=' + product_name_legal_identifier, '-dProductVersion=' + msi_product_version, '-dProductOriginalVersionString=' + product_version, + '-dProductBuildYear=' + str(date.today().year), '-dProductGuid=' + product_guid, ] @@ -179,6 +182,9 @@ def GetWixCandleFlags( '==MSI-PRODUCT-ID==', msi_product_id) flags.append('-dProductInstallerData=' + product_installer_data) + if product_icon_path: + flags.append('-dProductIcon=' + product_icon_path) + if architecture: # Translate some common strings, like from platform.machine(). arch_map = { diff --git a/omaha/enterprise/test_gold.adm b/omaha/enterprise/test_gold.adm index 8cdac1f..250ac99 100644 Binary files a/omaha/enterprise/test_gold.adm and b/omaha/enterprise/test_gold.adm differ diff --git a/omaha/enterprise/test_gold.adml b/omaha/enterprise/test_gold.adml index 2daedf8..ef99061 100644 Binary files a/omaha/enterprise/test_gold.adml and b/omaha/enterprise/test_gold.adml differ diff --git a/omaha/enterprise/test_gold.admx b/omaha/enterprise/test_gold.admx index 9a20b66..0e9f6db 100644 Binary files a/omaha/enterprise/test_gold.admx and b/omaha/enterprise/test_gold.admx differ diff --git a/omaha/google_update/build.scons b/omaha/google_update/build.scons index f107137..a9331a7 100644 --- a/omaha/google_update/build.scons +++ b/omaha/google_update/build.scons @@ -39,13 +39,12 @@ omaha_version_info = exe_env['omaha_versions_info'][0] shell_languages = omaha_version_utils.GetShellLanguagesForVersion( omaha_version_info.GetVersion()) -# TODO(omaha): While there is a precompile.h, it does not actually use PCH. exe_env.Append( CCFLAGS = [ + '/wd4265', '/wd4548', '/wd4917', - '/wd4265', - '/FIgoogle_update/precompile.h', + '/wd5038', ], LIBS = [ 'delayimp.lib', @@ -73,7 +72,6 @@ exe_env.Append( ], ) - exe_res = exe_env.RES('resource.rc') exe_env.Depends(exe_res, 'GoogleUpdate.manifest') @@ -92,12 +90,12 @@ Depends(exe_env['OBJ_ROOT'] + '/google_update/generated_resources_en.res', exe_env['MAIN_DIR'] + '/VERSION') unsigned_exe_output = exe_env.ComponentProgram( - prog_name='GoogleUpdate_unsigned', + prog_name='BraveUpdate_unsigned', source=exe_inputs, ) sign_output = env.DualSignedBinary( - target='GoogleUpdate_signed.exe', + target='BraveUpdate_signed.exe', source=unsigned_exe_output, ) diff --git a/omaha/google_update/generated_resources_am.rc b/omaha/google_update/generated_resources_am.rc index 412496c..1a22814 100644 Binary files a/omaha/google_update/generated_resources_am.rc and b/omaha/google_update/generated_resources_am.rc differ diff --git a/omaha/google_update/generated_resources_ar.rc b/omaha/google_update/generated_resources_ar.rc index 6b78c4c..c12b662 100644 Binary files a/omaha/google_update/generated_resources_ar.rc and b/omaha/google_update/generated_resources_ar.rc differ diff --git a/omaha/google_update/generated_resources_bg.rc b/omaha/google_update/generated_resources_bg.rc index e4f5988..e24daec 100644 Binary files a/omaha/google_update/generated_resources_bg.rc and b/omaha/google_update/generated_resources_bg.rc differ diff --git a/omaha/google_update/generated_resources_bn.rc b/omaha/google_update/generated_resources_bn.rc index aacd0a7..754aac5 100644 Binary files a/omaha/google_update/generated_resources_bn.rc and b/omaha/google_update/generated_resources_bn.rc differ diff --git a/omaha/google_update/generated_resources_ca.rc b/omaha/google_update/generated_resources_ca.rc index b0349bc..2ca1434 100644 Binary files a/omaha/google_update/generated_resources_ca.rc and b/omaha/google_update/generated_resources_ca.rc differ diff --git a/omaha/google_update/generated_resources_cs.rc b/omaha/google_update/generated_resources_cs.rc index d3cb1b2..54f928e 100644 Binary files a/omaha/google_update/generated_resources_cs.rc and b/omaha/google_update/generated_resources_cs.rc differ diff --git a/omaha/google_update/generated_resources_da.rc b/omaha/google_update/generated_resources_da.rc index 55bbcfa..2dc33fa 100644 Binary files a/omaha/google_update/generated_resources_da.rc and b/omaha/google_update/generated_resources_da.rc differ diff --git a/omaha/google_update/generated_resources_de.rc b/omaha/google_update/generated_resources_de.rc index 2815dfb..d8a487c 100644 Binary files a/omaha/google_update/generated_resources_de.rc and b/omaha/google_update/generated_resources_de.rc differ diff --git a/omaha/google_update/generated_resources_el.rc b/omaha/google_update/generated_resources_el.rc index f6e86bf..c08834f 100644 Binary files a/omaha/google_update/generated_resources_el.rc and b/omaha/google_update/generated_resources_el.rc differ diff --git a/omaha/google_update/generated_resources_en-GB.rc b/omaha/google_update/generated_resources_en-GB.rc index 6f1f74c..9b09a71 100644 Binary files a/omaha/google_update/generated_resources_en-GB.rc and b/omaha/google_update/generated_resources_en-GB.rc differ diff --git a/omaha/google_update/generated_resources_en.rc b/omaha/google_update/generated_resources_en.rc index 0afd082..0b0487d 100644 Binary files a/omaha/google_update/generated_resources_en.rc and b/omaha/google_update/generated_resources_en.rc differ diff --git a/omaha/google_update/generated_resources_es-419.rc b/omaha/google_update/generated_resources_es-419.rc index 6198aa0..f8af287 100644 Binary files a/omaha/google_update/generated_resources_es-419.rc and b/omaha/google_update/generated_resources_es-419.rc differ diff --git a/omaha/google_update/generated_resources_es.rc b/omaha/google_update/generated_resources_es.rc index d17e4a4..a4f5979 100644 Binary files a/omaha/google_update/generated_resources_es.rc and b/omaha/google_update/generated_resources_es.rc differ diff --git a/omaha/google_update/generated_resources_et.rc b/omaha/google_update/generated_resources_et.rc index f0609f3..a2277c0 100644 Binary files a/omaha/google_update/generated_resources_et.rc and b/omaha/google_update/generated_resources_et.rc differ diff --git a/omaha/google_update/generated_resources_fa.rc b/omaha/google_update/generated_resources_fa.rc index c55304b..84d554a 100644 Binary files a/omaha/google_update/generated_resources_fa.rc and b/omaha/google_update/generated_resources_fa.rc differ diff --git a/omaha/google_update/generated_resources_fi.rc b/omaha/google_update/generated_resources_fi.rc index 430c736..0a2386b 100644 Binary files a/omaha/google_update/generated_resources_fi.rc and b/omaha/google_update/generated_resources_fi.rc differ diff --git a/omaha/google_update/generated_resources_fil.rc b/omaha/google_update/generated_resources_fil.rc index 0acfcc0..cf4e67b 100644 Binary files a/omaha/google_update/generated_resources_fil.rc and b/omaha/google_update/generated_resources_fil.rc differ diff --git a/omaha/google_update/generated_resources_fr.rc b/omaha/google_update/generated_resources_fr.rc index 4caaa81..6dabbaa 100644 Binary files a/omaha/google_update/generated_resources_fr.rc and b/omaha/google_update/generated_resources_fr.rc differ diff --git a/omaha/google_update/generated_resources_gu.rc b/omaha/google_update/generated_resources_gu.rc index d992a2d..d85a2ed 100644 Binary files a/omaha/google_update/generated_resources_gu.rc and b/omaha/google_update/generated_resources_gu.rc differ diff --git a/omaha/google_update/generated_resources_hi.rc b/omaha/google_update/generated_resources_hi.rc index 35fc8b8..7af7ecf 100644 Binary files a/omaha/google_update/generated_resources_hi.rc and b/omaha/google_update/generated_resources_hi.rc differ diff --git a/omaha/google_update/generated_resources_hr.rc b/omaha/google_update/generated_resources_hr.rc index 034b30f..71af3cf 100644 Binary files a/omaha/google_update/generated_resources_hr.rc and b/omaha/google_update/generated_resources_hr.rc differ diff --git a/omaha/google_update/generated_resources_hu.rc b/omaha/google_update/generated_resources_hu.rc index 1a0bcf1..d705a8a 100644 Binary files a/omaha/google_update/generated_resources_hu.rc and b/omaha/google_update/generated_resources_hu.rc differ diff --git a/omaha/google_update/generated_resources_id.rc b/omaha/google_update/generated_resources_id.rc index 70c62a8..9bdb79f 100644 Binary files a/omaha/google_update/generated_resources_id.rc and b/omaha/google_update/generated_resources_id.rc differ diff --git a/omaha/google_update/generated_resources_is.rc b/omaha/google_update/generated_resources_is.rc index 76a3420..6c5dde3 100644 Binary files a/omaha/google_update/generated_resources_is.rc and b/omaha/google_update/generated_resources_is.rc differ diff --git a/omaha/google_update/generated_resources_it.rc b/omaha/google_update/generated_resources_it.rc index bbf06e4..bfb5b8f 100644 Binary files a/omaha/google_update/generated_resources_it.rc and b/omaha/google_update/generated_resources_it.rc differ diff --git a/omaha/google_update/generated_resources_iw.rc b/omaha/google_update/generated_resources_iw.rc index b0da73d..a1d1afc 100644 Binary files a/omaha/google_update/generated_resources_iw.rc and b/omaha/google_update/generated_resources_iw.rc differ diff --git a/omaha/google_update/generated_resources_ja.rc b/omaha/google_update/generated_resources_ja.rc index 02c64ba..aef39a8 100644 Binary files a/omaha/google_update/generated_resources_ja.rc and b/omaha/google_update/generated_resources_ja.rc differ diff --git a/omaha/google_update/generated_resources_kn.rc b/omaha/google_update/generated_resources_kn.rc index 67de798..15af706 100644 Binary files a/omaha/google_update/generated_resources_kn.rc and b/omaha/google_update/generated_resources_kn.rc differ diff --git a/omaha/google_update/generated_resources_ko.rc b/omaha/google_update/generated_resources_ko.rc index 6269452..1d6b6fd 100644 Binary files a/omaha/google_update/generated_resources_ko.rc and b/omaha/google_update/generated_resources_ko.rc differ diff --git a/omaha/google_update/generated_resources_lt.rc b/omaha/google_update/generated_resources_lt.rc index 2612bae..b92a483 100644 Binary files a/omaha/google_update/generated_resources_lt.rc and b/omaha/google_update/generated_resources_lt.rc differ diff --git a/omaha/google_update/generated_resources_lv.rc b/omaha/google_update/generated_resources_lv.rc index 943f5ad..5a0177b 100644 Binary files a/omaha/google_update/generated_resources_lv.rc and b/omaha/google_update/generated_resources_lv.rc differ diff --git a/omaha/google_update/generated_resources_ml.rc b/omaha/google_update/generated_resources_ml.rc index b702ce6..3539d32 100644 Binary files a/omaha/google_update/generated_resources_ml.rc and b/omaha/google_update/generated_resources_ml.rc differ diff --git a/omaha/google_update/generated_resources_mr.rc b/omaha/google_update/generated_resources_mr.rc index b8bf1a5..a28e2e4 100644 Binary files a/omaha/google_update/generated_resources_mr.rc and b/omaha/google_update/generated_resources_mr.rc differ diff --git a/omaha/google_update/generated_resources_ms.rc b/omaha/google_update/generated_resources_ms.rc index 541c703..6ffdb5f 100644 Binary files a/omaha/google_update/generated_resources_ms.rc and b/omaha/google_update/generated_resources_ms.rc differ diff --git a/omaha/google_update/generated_resources_nl.rc b/omaha/google_update/generated_resources_nl.rc index 2bb60b7..f843956 100644 Binary files a/omaha/google_update/generated_resources_nl.rc and b/omaha/google_update/generated_resources_nl.rc differ diff --git a/omaha/google_update/generated_resources_no.rc b/omaha/google_update/generated_resources_no.rc index 06f98b4..e541fe8 100644 Binary files a/omaha/google_update/generated_resources_no.rc and b/omaha/google_update/generated_resources_no.rc differ diff --git a/omaha/google_update/generated_resources_or.rc b/omaha/google_update/generated_resources_or.rc index 88242e9..39641c9 100644 Binary files a/omaha/google_update/generated_resources_or.rc and b/omaha/google_update/generated_resources_or.rc differ diff --git a/omaha/google_update/generated_resources_pl.rc b/omaha/google_update/generated_resources_pl.rc index 0193115..a27c064 100644 Binary files a/omaha/google_update/generated_resources_pl.rc and b/omaha/google_update/generated_resources_pl.rc differ diff --git a/omaha/google_update/generated_resources_pt-BR.rc b/omaha/google_update/generated_resources_pt-BR.rc index b9c1aef..97f439f 100644 Binary files a/omaha/google_update/generated_resources_pt-BR.rc and b/omaha/google_update/generated_resources_pt-BR.rc differ diff --git a/omaha/google_update/generated_resources_pt-PT.rc b/omaha/google_update/generated_resources_pt-PT.rc index df6b223..cfcfffa 100644 Binary files a/omaha/google_update/generated_resources_pt-PT.rc and b/omaha/google_update/generated_resources_pt-PT.rc differ diff --git a/omaha/google_update/generated_resources_ro.rc b/omaha/google_update/generated_resources_ro.rc index e8ccc74..3ce0a43 100644 Binary files a/omaha/google_update/generated_resources_ro.rc and b/omaha/google_update/generated_resources_ro.rc differ diff --git a/omaha/google_update/generated_resources_ru.rc b/omaha/google_update/generated_resources_ru.rc index d2bd899..4b823d0 100644 Binary files a/omaha/google_update/generated_resources_ru.rc and b/omaha/google_update/generated_resources_ru.rc differ diff --git a/omaha/google_update/generated_resources_sk.rc b/omaha/google_update/generated_resources_sk.rc index 4f02548..4af6305 100644 Binary files a/omaha/google_update/generated_resources_sk.rc and b/omaha/google_update/generated_resources_sk.rc differ diff --git a/omaha/google_update/generated_resources_sl.rc b/omaha/google_update/generated_resources_sl.rc index be44431..369859b 100644 Binary files a/omaha/google_update/generated_resources_sl.rc and b/omaha/google_update/generated_resources_sl.rc differ diff --git a/omaha/google_update/generated_resources_sr.rc b/omaha/google_update/generated_resources_sr.rc index 890cd3c..a23270e 100644 Binary files a/omaha/google_update/generated_resources_sr.rc and b/omaha/google_update/generated_resources_sr.rc differ diff --git a/omaha/google_update/generated_resources_sv.rc b/omaha/google_update/generated_resources_sv.rc index fb1beef..a8899da 100644 Binary files a/omaha/google_update/generated_resources_sv.rc and b/omaha/google_update/generated_resources_sv.rc differ diff --git a/omaha/google_update/generated_resources_sw.rc b/omaha/google_update/generated_resources_sw.rc index ebe51b1..046fef0 100644 Binary files a/omaha/google_update/generated_resources_sw.rc and b/omaha/google_update/generated_resources_sw.rc differ diff --git a/omaha/google_update/generated_resources_ta.rc b/omaha/google_update/generated_resources_ta.rc index f8ad2b2..00e1377 100644 Binary files a/omaha/google_update/generated_resources_ta.rc and b/omaha/google_update/generated_resources_ta.rc differ diff --git a/omaha/google_update/generated_resources_te.rc b/omaha/google_update/generated_resources_te.rc index 7fcf7ed..e0ca62b 100644 Binary files a/omaha/google_update/generated_resources_te.rc and b/omaha/google_update/generated_resources_te.rc differ diff --git a/omaha/google_update/generated_resources_th.rc b/omaha/google_update/generated_resources_th.rc index 4f75099..2ff76c8 100644 Binary files a/omaha/google_update/generated_resources_th.rc and b/omaha/google_update/generated_resources_th.rc differ diff --git a/omaha/google_update/generated_resources_tr.rc b/omaha/google_update/generated_resources_tr.rc index da5234b..2f6284a 100644 Binary files a/omaha/google_update/generated_resources_tr.rc and b/omaha/google_update/generated_resources_tr.rc differ diff --git a/omaha/google_update/generated_resources_uk.rc b/omaha/google_update/generated_resources_uk.rc index 9f93de5..512c7f6 100644 Binary files a/omaha/google_update/generated_resources_uk.rc and b/omaha/google_update/generated_resources_uk.rc differ diff --git a/omaha/google_update/generated_resources_ur.rc b/omaha/google_update/generated_resources_ur.rc index d02115e..dc42fac 100644 Binary files a/omaha/google_update/generated_resources_ur.rc and b/omaha/google_update/generated_resources_ur.rc differ diff --git a/omaha/google_update/generated_resources_userdefault.rc b/omaha/google_update/generated_resources_userdefault.rc index b17bcab..0036520 100644 Binary files a/omaha/google_update/generated_resources_userdefault.rc and b/omaha/google_update/generated_resources_userdefault.rc differ diff --git a/omaha/google_update/generated_resources_vi.rc b/omaha/google_update/generated_resources_vi.rc index 2136404..17e73f8 100644 Binary files a/omaha/google_update/generated_resources_vi.rc and b/omaha/google_update/generated_resources_vi.rc differ diff --git a/omaha/google_update/generated_resources_zh-CN.rc b/omaha/google_update/generated_resources_zh-CN.rc index f28e0c9..0d8e730 100644 Binary files a/omaha/google_update/generated_resources_zh-CN.rc and b/omaha/google_update/generated_resources_zh-CN.rc differ diff --git a/omaha/google_update/generated_resources_zh-HK.rc b/omaha/google_update/generated_resources_zh-HK.rc index 0a80e81..b922f00 100644 Binary files a/omaha/google_update/generated_resources_zh-HK.rc and b/omaha/google_update/generated_resources_zh-HK.rc differ diff --git a/omaha/google_update/generated_resources_zh-TW.rc b/omaha/google_update/generated_resources_zh-TW.rc index aec1f7c..3c76622 100644 Binary files a/omaha/google_update/generated_resources_zh-TW.rc and b/omaha/google_update/generated_resources_zh-TW.rc differ diff --git a/omaha/google_update/precompile.h b/omaha/google_update/precompile.h deleted file mode 100644 index 92f91f8..0000000 --- a/omaha/google_update/precompile.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2008-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__ -#define OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__ - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#include -#include -#include - -#pragma warning(push) -// C4310: cast truncates constant value -#pragma warning(disable : 4310) -#include "base/basictypes.h" -#pragma warning(pop) - -#pragma strict_gs_check(on) - -#endif // OMAHA_GOOGLE_UPDATE_PRECOMPILE_H__ diff --git a/omaha/google_update/resource.rc b/omaha/google_update/resource.rc index a008c4d..ed31df5 100644 --- a/omaha/google_update/resource.rc +++ b/omaha/google_update/resource.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include #include "resource.h" LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US diff --git a/omaha/goopdate/app.cc b/omaha/goopdate/app.cc index dba77f8..b74c1f3 100644 --- a/omaha/goopdate/app.cc +++ b/omaha/goopdate/app.cc @@ -14,12 +14,11 @@ // ======================================================================== #include "omaha/goopdate/app.h" + #include "omaha/base/error.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/synchronized.h" #include "omaha/base/time.h" #include "omaha/common/config_manager.h" @@ -33,6 +32,7 @@ #include "omaha/goopdate/model.h" #include "omaha/goopdate/server_resource.h" #include "omaha/goopdate/string_formatter.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -59,11 +59,11 @@ App::App(const GUID& app_guid, bool is_update, AppBundle* app_bundle) installer_result_code_(0), installer_result_extra_code1_(0), post_install_action_(POST_INSTALL_ACTION_DEFAULT), - can_skip_signature_verification_(false), + source_url_index_(-1), + state_cancelled_(STATE_ERROR), previous_total_download_bytes_(0), num_bytes_downloaded_(0), - source_url_index_(-1), - state_cancelled_(STATE_ERROR) { + can_skip_signature_verification_(false) { ASSERT1(!::IsEqualGUID(GUID_NULL, app_guid_)); current_version_.reset(new AppVersion(this)); @@ -937,6 +937,12 @@ HRESULT App::CheckGroupPolicy() const { return S_OK; } +bool App::IsRollbackToTargetVersionAllowed() const { + __mutexScope(model()->lock()); + + return ConfigManager::IsRollbackToTargetVersionAllowed(app_guid_); +} + CString App::GetTargetVersionPrefix() const { __mutexScope(model()->lock()); diff --git a/omaha/goopdate/app.h b/omaha/goopdate/app.h index 8253393..e03a9bb 100644 --- a/omaha/goopdate/app.h +++ b/omaha/goopdate/app.h @@ -22,11 +22,10 @@ #include #include - +#include #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "goopdate/omaha3_idl.h" #include "omaha/base/browser_utils.h" #include "omaha/base/constants.h" @@ -332,9 +331,13 @@ class App : public ModelObject { // disabled by Group Policy. HRESULT CheckGroupPolicy() const; + // Returns whether the RollbackToTargetVersion policy has been set for the + // app. + bool IsRollbackToTargetVersionAllowed() const; + // Returns the target version prefix for the app, if the machine is joined to // a domain and has the corresponding group policy set. - CString App::GetTargetVersionPrefix() const; + CString GetTargetVersionPrefix() const; // Updates num bytes downloaded by adding newly downloaded bytes. void UpdateNumBytesDownloaded(uint64 num_bytes); @@ -404,10 +407,10 @@ class App : public ModelObject { int GetTimeDifferenceMs(TimeMetricType time_start_metric_type, TimeMetricType time_end_metric_type) const; - scoped_ptr app_state_; + std::unique_ptr app_state_; - scoped_ptr current_version_; - scoped_ptr next_version_; + std::unique_ptr current_version_; + std::unique_ptr next_version_; // Alias to the version of the app that is being modified. AppVersion* working_version_; @@ -478,10 +481,6 @@ class App : public ModelObject { // server_install_data_index_. CString server_install_data_; - // The packages of the app have been trusted by other means and the - // signature verification can be omitted. - bool can_skip_signature_verification_; - bool is_canceled_; ErrorContext error_context_; CString completion_message_; @@ -513,6 +512,10 @@ class App : public ModelObject { uint64 num_bytes_downloaded_; uint64 time_metrics_[TIME_METRICS_MAX]; + // The packages of the app have been trusted by other means and the + // signature verification can be omitted. + bool can_skip_signature_verification_; + DISALLOW_COPY_AND_ASSIGN(App); }; diff --git a/omaha/goopdate/app_bundle.cc b/omaha/goopdate/app_bundle.cc index 39d9acf..061f9bc 100644 --- a/omaha/goopdate/app_bundle.cc +++ b/omaha/goopdate/app_bundle.cc @@ -14,9 +14,10 @@ // ======================================================================== #include"omaha/goopdate/app_bundle.h" + #include #include -#include "omaha/base/debug.h" + #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/scope_guard.h" @@ -195,12 +196,12 @@ CString AppBundle::FetchAndResetLogText() { return event_log_text; } -void AppBundle::BuildPing(Ping** my_ping) { +void AppBundle::BuildPing(std::unique_ptr* my_ping) { CORE_LOG(L3, (_T("[AppBundle::BuildPing]"))); ASSERT1(model()->IsLockedByCaller()); ASSERT1(my_ping); - scoped_ptr ping( + std::unique_ptr ping( new Ping(is_machine_, session_id_, install_source_, request_id_)); for (size_t i = 0; i != apps_.size(); ++i) { @@ -215,14 +216,14 @@ void AppBundle::BuildPing(Ping** my_ping) { } } - *my_ping = ping.release(); + my_ping->reset(ping.release()); } HRESULT AppBundle::BuildAndPersistPing() { CORE_LOG(L3, (_T("[AppBundle::BuildAndPersistPing]"))); - scoped_ptr ping; - BuildPing(address(ping)); + std::unique_ptr ping; + BuildPing(&ping); return ping->PersistPing(); } @@ -236,10 +237,10 @@ HRESULT AppBundle::SendPingEventsAsync() { return S_OK; } - scoped_ptr ping; + std::unique_ptr ping; __mutexBlock(model()->lock()) { - BuildPing(address(ping)); + BuildPing(&ping); } CORE_LOG(L3, (_T("[AppBundle::SendPingEventsAsync][sending ping events]") @@ -254,7 +255,7 @@ HRESULT AppBundle::SendPingEventsAsync() { typedef StaticThreadPoolCallBack1 CB; Gate send_ping_events_gate; - scoped_ptr callback(new CB(&AppBundle::SendPingEvents, + std::unique_ptr callback(new CB(&AppBundle::SendPingEvents, internal::SendPingEventsParameters( ping.get(), token.GetHandle(), @@ -281,7 +282,7 @@ void AppBundle::SendPingEvents(internal::SendPingEventsParameters params) { _pAtlModule->Lock(); ON_SCOPE_EXIT_OBJ(*_pAtlModule, &CAtlModule::Unlock); - scoped_ptr ping(params.ping); + std::unique_ptr ping(params.ping); scoped_handle impersonation_token(params.impersonation_token); scoped_impersonation impersonate_user(get(impersonation_token)); @@ -726,7 +727,7 @@ HRESULT AppBundle::CreateUninstalledApp(const CString& app_id, App** app) { return hr; } - scoped_ptr local_app(new App(app_guid, true, this)); + std::unique_ptr local_app(new App(app_guid, true, this)); hr = AppManager::Instance()->ReadUninstalledAppPersistentData( local_app.get()); diff --git a/omaha/goopdate/app_bundle.h b/omaha/goopdate/app_bundle.h index c85e0a0..9803147 100644 --- a/omaha/goopdate/app_bundle.h +++ b/omaha/goopdate/app_bundle.h @@ -22,19 +22,19 @@ #include #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "goopdate/omaha3_idl.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/common/ping.h" #include "omaha/goopdate/com_wrapper_creator.h" #include "omaha/goopdate/model_object.h" #include "omaha/net/proxy_auth.h" -#include "third_party/bar/shared_ptr.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -81,7 +81,7 @@ struct SendPingEventsParameters { // depend on the bundle objects. class AppBundle : public ModelObject, - public enable_shared_from_this { + public std::enable_shared_from_this { public: AppBundle(bool is_machine, Model* model); virtual ~AppBundle(); @@ -187,7 +187,7 @@ class AppBundle fsm::AppBundleState* state); // Builds a new Ping object with all the Apps in the AppBundle. - void BuildPing(Ping** ping); + void BuildPing(std::unique_ptr* ping); // TODO(omaha): missing unit test. // Sends the ping if the applications in the bundle have accumulated @@ -238,7 +238,7 @@ class AppBundle // for debugging. UserWorkItem* user_work_item_; - scoped_ptr update_check_client_; + std::unique_ptr update_check_client_; // The apps in the bundle. Do not add to it directly; use AddApp() instead. std::vector apps_; @@ -248,7 +248,7 @@ class AppBundle // other pings. std::vector uninstalled_apps_; - scoped_ptr app_bundle_state_; + std::unique_ptr app_bundle_state_; // Impersonation and primary tokens set by the client. Typically only // set by the gupdatem service. The gupdatem service exposes a narrow diff --git a/omaha/goopdate/app_bundle_state_init.cc b/omaha/goopdate/app_bundle_state_init.cc index 7314cda..178fd67 100644 --- a/omaha/goopdate/app_bundle_state_init.cc +++ b/omaha/goopdate/app_bundle_state_init.cc @@ -115,8 +115,8 @@ HRESULT AppBundleStateInit::Initialize(AppBundle* app_bundle) { CString update_check_url; VERIFY1(SUCCEEDED( ConfigManager::Instance()->GetUpdateCheckUrl(&update_check_url))); - scoped_ptr web_service_client; - web_service_client.reset(new WebServicesClient(app_bundle->is_machine())); + auto web_service_client = std::make_unique( + app_bundle->is_machine()); hr = web_service_client->Initialize(update_check_url, HeadersVector(), true); if (FAILED(hr)) { CORE_LOG(LE, (_T("[Update check client init failed][0x%08x]"), hr)); diff --git a/omaha/goopdate/app_bundle_state_initialized.cc b/omaha/goopdate/app_bundle_state_initialized.cc index 5da58b3..00fddc1 100644 --- a/omaha/goopdate/app_bundle_state_initialized.cc +++ b/omaha/goopdate/app_bundle_state_initialized.cc @@ -14,11 +14,12 @@ // ======================================================================== #include "omaha/goopdate/app_bundle_state_initialized.h" + +#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/common/app_registry_utils.h" #include "omaha/common/config_manager.h" #include "omaha/common/goopdate_utils.h" @@ -28,6 +29,7 @@ #include "omaha/goopdate/app_bundle_state_stopped.h" #include "omaha/goopdate/app_manager.h" #include "omaha/goopdate/model.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -98,7 +100,7 @@ HRESULT AppBundleStateInitialized::CreateApp(AppBundle* app_bundle, return hr; } - scoped_ptr local_app(new App(app_guid, false, app_bundle)); + std::unique_ptr local_app(new App(app_guid, false, app_bundle)); hr = AddApp(app_bundle, local_app.get()); if (FAILED(hr)) { return hr; @@ -313,7 +315,7 @@ HRESULT AppBundleStateInitialized::AddInstalledApp(AppBundle* app_bundle, hr, app_id, app_bundle->is_machine())); } - scoped_ptr local_app(new App(app_guid, true, app_bundle)); + std::unique_ptr local_app(new App(app_guid, true, app_bundle)); local_app->set_external_updater_event(release(external_updater_event)); diff --git a/omaha/goopdate/app_bundle_unittest.cc b/omaha/goopdate/app_bundle_unittest.cc index c079dc3..aa6aefd 100644 --- a/omaha/goopdate/app_bundle_unittest.cc +++ b/omaha/goopdate/app_bundle_unittest.cc @@ -13,12 +13,13 @@ // limitations under the License. // ======================================================================== +#include "omaha/goopdate/app_bundle.h" + #include + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/thread_pool.h" #include "omaha/base/utils.h" #include "omaha/common/config_manager.h" @@ -36,6 +37,7 @@ #include "omaha/goopdate/worker.h" #include "omaha/goopdate/worker_mock.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -186,8 +188,8 @@ class AppBundleNoBundleTest : public testing::Test { } const bool is_machine_; - scoped_ptr worker_; - scoped_ptr model_; + std::unique_ptr worker_; + std::unique_ptr model_; private: Goopdate goopdate_; @@ -256,7 +258,7 @@ class AppBundleTest : public AppBundleNoBundleTest { return static_cast(app_bundle_->app_bundle_state_->state_); } - shared_ptr app_bundle_; + std::shared_ptr app_bundle_; private: DISALLOW_IMPLICIT_CONSTRUCTORS(AppBundleTest); @@ -368,7 +370,7 @@ TEST_F(AppBundleNoBundleUserTest, ConstructorAndDestructor) { EXPECT_CALL(*worker_, Lock()).WillOnce(Return(2)); EXPECT_CALL(*worker_, Unlock()).WillOnce(Return(1)); - shared_ptr app_bundle(model_->CreateAppBundle(is_machine_)); + std::shared_ptr app_bundle(model_->CreateAppBundle(is_machine_)); EXPECT_TRUE(app_bundle.get()); EXPECT_EQ(1, model_->GetNumberOfAppBundles()); EXPECT_EQ(app_bundle.get(), model_->GetAppBundle(0).get()); @@ -380,7 +382,7 @@ TEST_F(AppBundleNoBundleMachineTest, ConstructorAndDestructor) { EXPECT_CALL(*worker_, Lock()).WillOnce(Return(2)); EXPECT_CALL(*worker_, Unlock()).WillOnce(Return(1)); - shared_ptr app_bundle(model_->CreateAppBundle(is_machine_)); + std::shared_ptr app_bundle(model_->CreateAppBundle(is_machine_)); EXPECT_TRUE(app_bundle.get()); EXPECT_EQ(1, model_->GetNumberOfAppBundles()); EXPECT_EQ(app_bundle.get(), model_->GetAppBundle(0).get()); @@ -460,7 +462,7 @@ class AppBundlePopulatedRegistryTest : public AppBundleInitializedTest { AppManager::Instance()->ReadAppInstallTimeDiff(opposite_hive_app2); } - shared_ptr dummy_app_bundle_for_expected_apps_; + std::shared_ptr dummy_app_bundle_for_expected_apps_; LLock lock_; private: diff --git a/omaha/goopdate/app_command.h b/omaha/goopdate/app_command.h index bc3ac1d..fe4b4fd 100644 --- a/omaha/goopdate/app_command.h +++ b/omaha/goopdate/app_command.h @@ -17,13 +17,13 @@ #define OMAHA_GOOPDATE_APP_COMMAND_H__ #include +#include #include #include + #include "base/basictypes.h" #include "goopdate/omaha3_idl.h" -#include "omaha/base/scoped_any.h" #include "omaha/goopdate/app_command_formatter.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { @@ -99,7 +99,7 @@ class AppCommand { const bool capture_output_; const bool auto_run_on_os_upgrade_; - shared_ptr delegate_; + std::shared_ptr delegate_; // Tracks state of the currently running process. CComPtr completion_observer_; diff --git a/omaha/goopdate/app_command_completion_observer.cc b/omaha/goopdate/app_command_completion_observer.cc index cdbbeaf..34e2309 100644 --- a/omaha/goopdate/app_command_completion_observer.cc +++ b/omaha/goopdate/app_command_completion_observer.cc @@ -16,11 +16,10 @@ #include "omaha/goopdate/app_command_completion_observer.h" #include -#include "base/scoped_ptr.h" + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/common/const_cmd_line.h" #include "omaha/common/ping.h" @@ -36,7 +35,7 @@ AppCommandCompletionObserver::AppCommandCompletionObserver() HRESULT AppCommandCompletionObserver::Init( HANDLE process, HANDLE output, - const shared_ptr& delegate) { + const std::shared_ptr& delegate) { reset(process_, process); reset(output_pipe_, output); delegate_ = delegate; @@ -65,7 +64,7 @@ AppCommandCompletionObserver::~AppCommandCompletionObserver() { HRESULT AppCommandCompletionObserver::Start( HANDLE process, HANDLE output, - const shared_ptr& delegate, + const std::shared_ptr& delegate, AppCommandCompletionObserver** observer) { ASSERT1(process); ASSERT1(observer); @@ -77,9 +76,11 @@ HRESULT AppCommandCompletionObserver::Start( CComPtr local_observer; { - scoped_ptr > new_object; + std::unique_ptr> new_object; + CComObject* new_object_ptr = nullptr; HRESULT hr = CComObject::CreateInstance( - address(new_object)); + &new_object_ptr); + new_object.reset(new_object_ptr); if (FAILED(hr)) { CORE_LOG(LE, (_T("[failed to create AppCommandCompletionObserver]"), _T("[0x%08x]"), hr)); diff --git a/omaha/goopdate/app_command_completion_observer.h b/omaha/goopdate/app_command_completion_observer.h index b62c2c0..96fc646 100644 --- a/omaha/goopdate/app_command_completion_observer.h +++ b/omaha/goopdate/app_command_completion_observer.h @@ -17,12 +17,14 @@ #define OMAHA_GOOPDATE_APP_COMMAND_COMPLETION_OBSERVER_H__ #include +#include #include -#include "omaha/base/scoped_any.h" +#include + #include "omaha/base/synchronized.h" #include "omaha/common/ping_event.h" #include "goopdate/omaha3_idl.h" -#include "third_party/bar/shared_ptr.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -48,7 +50,7 @@ class ATL_NO_VTABLE AppCommandCompletionObserver // returned via |observer|. static HRESULT Start(HANDLE process, HANDLE output, - const shared_ptr& delegate, + const std::shared_ptr& delegate, AppCommandCompletionObserver** observer); // Returns the process status (one of @@ -80,7 +82,7 @@ class ATL_NO_VTABLE AppCommandCompletionObserver // Initializes the object properties and spins off the background thread. HRESULT Init(HANDLE process, HANDLE output, - const shared_ptr& delegate); + const std::shared_ptr& delegate); // Reads the child process's output for reporting to our client. void CaptureOutput(); @@ -99,7 +101,7 @@ class ATL_NO_VTABLE AppCommandCompletionObserver scoped_process process_; scoped_handle output_pipe_; - shared_ptr delegate_; + std::shared_ptr delegate_; scoped_handle thread_; diff --git a/omaha/goopdate/app_command_configuration.cc b/omaha/goopdate/app_command_configuration.cc index 4da3001..b36f07f 100644 --- a/omaha/goopdate/app_command_configuration.cc +++ b/omaha/goopdate/app_command_configuration.cc @@ -73,9 +73,9 @@ CString BuildAppCommandsPath(bool is_machine, const CString& app_guid) { } // namespace HRESULT AppCommandConfiguration::Load(const CString& app_guid, - bool is_machine, - const CString& command_id, - AppCommandConfiguration** configuration) { + bool is_machine, + const CString& command_id, + std::unique_ptr* configuration) { ASSERT1(configuration); CString command_line; @@ -139,7 +139,7 @@ HRESULT AppCommandConfiguration::Load(const CString& app_guid, run_as_user = 0; } - *configuration = new AppCommandConfiguration(app_guid, + configuration->reset(new AppCommandConfiguration(app_guid, is_machine, command_id, command_line, @@ -148,7 +148,7 @@ HRESULT AppCommandConfiguration::Load(const CString& app_guid, auto_run_on_os_upgrade != 0, reporting_id, run_as_user != 0, - capture_output != 0); + capture_output != 0)); return S_OK; } diff --git a/omaha/goopdate/app_command_configuration.h b/omaha/goopdate/app_command_configuration.h index 26a35ae..18fbfef 100644 --- a/omaha/goopdate/app_command_configuration.h +++ b/omaha/goopdate/app_command_configuration.h @@ -39,10 +39,12 @@ #ifndef OMAHA_GOOPDATE_APP_COMMAND_CONFIGURATION_H__ #define OMAHA_GOOPDATE_APP_COMMAND_CONFIGURATION_H__ -#include #include -#include +#include #include +#include +#include + #include "base/basictypes.h" namespace omaha { @@ -56,7 +58,7 @@ class AppCommandConfiguration { static HRESULT Load(const CString& app_guid, bool is_machine, const CString& command_id, - AppCommandConfiguration** configuration); + std::unique_ptr* configuration); AppCommand* Instantiate(const CString& session_id) const; diff --git a/omaha/goopdate/app_command_configuration_unittest.cc b/omaha/goopdate/app_command_configuration_unittest.cc index bc16bc4..3bbec29 100644 --- a/omaha/goopdate/app_command_configuration_unittest.cc +++ b/omaha/goopdate/app_command_configuration_unittest.cc @@ -13,17 +13,15 @@ // limitations under the License. // ======================================================================== -#include +#include "omaha/goopdate/app_command_configuration.h" + #include -#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" #include "omaha/base/file.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" -#include "omaha/goopdate/app_command_configuration.h" #include "omaha/goopdate/app_command_test_base.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -50,87 +48,87 @@ class AppCommandConfigurationTest : public AppCommandTestBase { typedef int(AppCommandConfiguration::*IntMember)(void) const; void TestValueMapping(const TCHAR* name, BoolMember mapped_member) { - scoped_ptr configuration; + std::unique_ptr configuration; CreateCommand(kAppGuid1, true, kCmdId1, kCmdLineExit0); SetCommandValue(kAppGuid1, true, kCmdId1, name, &kZero); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_FALSE((configuration.get()->*mapped_member)()); configuration.reset(); SetCommandValue(kAppGuid1, true, kCmdId1, name, &kOne); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_TRUE((configuration.get()->*mapped_member)()); configuration.reset(); SetCommandValue(kAppGuid1, true, kCmdId1, name, NULL); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_FALSE((configuration.get()->*mapped_member)()); } void TestValueMapping(const TCHAR* name, IntMember mapped_member) { - scoped_ptr configuration; + std::unique_ptr configuration; CreateCommand(kAppGuid1, true, kCmdId1, kCmdLineExit0); SetCommandValue(kAppGuid1, true, kCmdId1, name, &kZero); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_EQ(0, (configuration.get()->*mapped_member)()); configuration.reset(); SetCommandValue(kAppGuid1, true, kCmdId1, name, &kOne); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_EQ(1, (configuration.get()->*mapped_member)()); configuration.reset(); SetCommandValue(kAppGuid1, true, kCmdId1, name, &kTwo); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_EQ(2, (configuration.get()->*mapped_member)()); configuration.reset(); SetCommandValue(kAppGuid1, true, kCmdId1, name, NULL); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_EQ(0, (configuration.get()->*mapped_member)()); } }; TEST_F(AppCommandConfigurationTest, NoApp) { - scoped_ptr configuration; + std::unique_ptr configuration; ASSERT_HRESULT_FAILED(AppCommandConfiguration::Load( - kAppGuid1, false, kCmdId1, address(configuration))); + kAppGuid1, false, kCmdId1, &configuration)); } TEST_F(AppCommandConfigurationTest, NoCmd) { - scoped_ptr configuration; + std::unique_ptr configuration; CreateAppClientKey(kAppGuid1, false); CreateCommand(kAppGuid1, false, kCmdId1, kCmdLineExit0); ASSERT_HRESULT_FAILED(AppCommandConfiguration::Load( - kAppGuid1, false, kCmdId2, address(configuration))); + kAppGuid1, false, kCmdId2, &configuration)); } TEST_F(AppCommandConfigurationTest, WrongLevel) { - scoped_ptr configuration; + std::unique_ptr configuration; CreateAppClientKey(kAppGuid1, true); CreateCommand(kAppGuid1, true, kCmdId1, kCmdLineExit0); ASSERT_HRESULT_FAILED(AppCommandConfiguration::Load( - kAppGuid1, false, kCmdId1, address(configuration))); + kAppGuid1, false, kCmdId1, &configuration)); } TEST_F(AppCommandConfigurationTest, LoadCommand) { - scoped_ptr configuration; + std::unique_ptr configuration; CreateAppClientKey(kAppGuid1, true); CreateCommand(kAppGuid1, true, kCmdId1, kCmdLineExit0); ASSERT_HRESULT_SUCCEEDED(AppCommandConfiguration::Load( - kAppGuid1, true, kCmdId1, address(configuration))); + kAppGuid1, true, kCmdId1, &configuration)); ASSERT_EQ(kCmdLineExit0, configuration->command_line()); } diff --git a/omaha/goopdate/app_command_formatter.cc b/omaha/goopdate/app_command_formatter.cc index 83896df..bfcc094 100644 --- a/omaha/goopdate/app_command_formatter.cc +++ b/omaha/goopdate/app_command_formatter.cc @@ -19,7 +19,7 @@ #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/goopdate/app_command_formatter_unittest.cc b/omaha/goopdate/app_command_formatter_unittest.cc index 6f1996d..2d5b992 100644 --- a/omaha/goopdate/app_command_formatter_unittest.cc +++ b/omaha/goopdate/app_command_formatter_unittest.cc @@ -17,9 +17,9 @@ #include #include #include "base/basictypes.h" -#include "omaha/base/scoped_any.h" #include "omaha/goopdate/app_command_formatter.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -103,8 +103,8 @@ TEST(AppCommandFormatterTest, Interpolation) { parameters.push_back(_T("p3")); struct { - TCHAR* input; - TCHAR* output; + const TCHAR* input; + const TCHAR* output; } test_cases[] = { {_T("%1"), _T("p1")}, @@ -138,8 +138,8 @@ TEST(AppCommandFormatterTest, Interpolation) { TEST(AppCommandFormatterTest, ParameterQuoting) { struct { - TCHAR* input; - TCHAR* output; + const TCHAR* input; + const TCHAR* output; } test_cases[] = { // embedded \ and \\. {_T("a\\b\\\\c"), diff --git a/omaha/goopdate/app_command_model.cc b/omaha/goopdate/app_command_model.cc index 5077f36..190495b 100644 --- a/omaha/goopdate/app_command_model.cc +++ b/omaha/goopdate/app_command_model.cc @@ -15,15 +15,13 @@ #include "omaha/goopdate/app_command_model.h" -#include "OleAuto.h" +#include #include "base/file.h" #include "base/utils.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/system.h" #include "omaha/base/utils.h" #include "omaha/common/config_manager.h" @@ -35,6 +33,7 @@ #include "omaha/goopdate/app_command_configuration.h" #include "omaha/goopdate/google_app_command_verifier.h" #include "omaha/goopdate/model.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -53,12 +52,12 @@ HRESULT AppCommandModel::Load(App* app, ASSERT1(app); ASSERT1(app_command_model); - scoped_ptr configuration; + std::unique_ptr configuration; HRESULT hr = AppCommandConfiguration::Load(GuidToString(app->app_guid()), app->app_bundle()->is_machine(), cmd_id, - address(configuration)); + &configuration); if (FAILED(hr)) { return hr; } diff --git a/omaha/goopdate/app_command_model.h b/omaha/goopdate/app_command_model.h index ed8b7b8..b01bda4 100644 --- a/omaha/goopdate/app_command_model.h +++ b/omaha/goopdate/app_command_model.h @@ -23,8 +23,8 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "goopdate/omaha3_idl.h" #include "omaha/base/constants.h" #include "omaha/goopdate/app_bundle.h" // Required for com_wrapper_creator @@ -82,7 +82,7 @@ class AppCommandModel : public ModelObject { bool is_web_accessible() const; private: - scoped_ptr app_command_; + std::unique_ptr app_command_; DISALLOW_COPY_AND_ASSIGN(AppCommandModel); }; diff --git a/omaha/goopdate/app_command_unittest.cc b/omaha/goopdate/app_command_unittest.cc index f66cff9..22c57bc 100644 --- a/omaha/goopdate/app_command_unittest.cc +++ b/omaha/goopdate/app_command_unittest.cc @@ -13,22 +13,22 @@ // limitations under the License. // ======================================================================== +#include "omaha/goopdate/app_command.h" + #include -#include +#include #include #include #include #include -#include "base/scoped_ptr.h" + #include "base/utils.h" #include "omaha/base/app_util.h" #include "omaha/base/file.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" -#include "omaha/goopdate/app_command.h" #include "omaha/goopdate/app_command_verifier.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -42,13 +42,13 @@ const TCHAR* const kCmdLineExit0 = _T("cmd.exe /c \"exit 0\""); const TCHAR* const kCmdLineExit3 = _T("cmd.exe /c \"exit 3\""); const TCHAR* const kCmdLineExitX = _T("cmd.exe /c \"exit %1\""); const TCHAR* const kCmdLineSleep1 = - _T("cmd.exe /c \"ping.exe 1.1.1.1 -n 1 -w 1000 >NUL\""); + _T("cmd.exe /c \"ping.exe 2.2.2.2 -n 1 -w 1000 >NUL\""); const TCHAR* const kCmdLineEchoHelloWorldAscii = _T("cmd.exe /a /c \"echo Hello World\""); const TCHAR* const kCmdLineEchoHelloWorldUnicode = _T("cmd.exe /u /c \"echo Hello World\""); const TCHAR* const kCmdLineEchoWithSleep = - _T("cmd.exe /c \"echo Hello World& ping.exe 1.1.1.1 -n 1 -w 1000 >NUL & ") + _T("cmd.exe /c \"echo Hello World& ping.exe 2.2.2.2 -n 1 -w 1000 >NUL & ") _T("echo Goodbye World\""); const TCHAR* const kCmdId1 = _T("command 1"); diff --git a/omaha/goopdate/app_command_verifier.h b/omaha/goopdate/app_command_verifier.h index 62f85e2..266cdd9 100644 --- a/omaha/goopdate/app_command_verifier.h +++ b/omaha/goopdate/app_command_verifier.h @@ -16,7 +16,8 @@ #ifndef OMAHA_GOOPDATE_APP_COMMAND_VERIFIER_H__ #define OMAHA_GOOPDATE_APP_COMMAND_VERIFIER_H__ -#include +#include +#include #include "base/basictypes.h" namespace omaha { diff --git a/omaha/goopdate/app_manager.cc b/omaha/goopdate/app_manager.cc index ac13ec6..6184279 100644 --- a/omaha/goopdate/app_manager.cc +++ b/omaha/goopdate/app_manager.cc @@ -14,16 +14,17 @@ // ======================================================================== #include "omaha/goopdate/app_manager.h" -#include + #include +#include #include #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/const_object_names.h" #include "omaha/base/error.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/base/vistautil.h" @@ -58,31 +59,10 @@ int GetNumberOfDaysSince(int time) { return (now - time) / kSecondsPerDay; } -// Determines if an application is registered with Omaha. -class IsAppRegisteredFunc - : public std::unary_function { - public: - explicit IsAppRegisteredFunc(const CString& guid) - : is_registered_(false), - guid_(guid) {} - - bool is_registered() const { return is_registered_; } - - HRESULT operator() (const CString& guid) { - if (guid.CompareNoCase(guid_) == 0) { - is_registered_ = true; - } - return S_OK; - } - private: - CString guid_; - bool is_registered_; -}; - -// Enumerates all sub keys of the key and calls the functor for each of them, +// Enumerates all sub keys of the key and calls the function for each of them, // ignoring errors to ensure all keys are processed. -template -HRESULT EnumerateSubKeys(const TCHAR* key_name, T* functor) { +HRESULT EnumerateSubKeys(const TCHAR* key_name, + std::function fun) { RegKey client_key; HRESULT hr = client_key.Open(key_name, KEY_READ); if (FAILED(hr)) { @@ -94,7 +74,7 @@ HRESULT EnumerateSubKeys(const TCHAR* key_name, T* functor) { CString sub_key_name; hr = client_key.GetSubkeyNameAt(i, &sub_key_name); if (SUCCEEDED(hr)) { - (*functor)(sub_key_name); + fun(sub_key_name); } } @@ -103,109 +83,6 @@ HRESULT EnumerateSubKeys(const TCHAR* key_name, T* functor) { } // namespace -typedef bool (*AppPredictFunc)(const AppManager& app_manager, - const CString& app_id); - -bool IsUninstalledAppPredicate(const AppManager& app_manager, - const CString& app_id) { - return app_manager.IsAppUninstalled(app_id); -} - -bool IsAppOemInstalledAndEulaAcceptedPredicate(const AppManager& app_manager, - const CString& app_id) { - return app_manager.IsAppOemInstalledAndEulaAccepted(app_id); -} - -bool IsRegisteredAppPredicate(const AppManager& app_manager, - const CString& app_id) { - return app_manager.IsAppRegistered(app_id); -} - -// Accumulates app IDs for apps that satisfies the predicate. -class CollectProductsFunc - : public std::unary_function { - public: - CollectProductsFunc(const AppPredictFunc predicate, - const AppManager& app_manager, - AppIdVector* app_ids) - : predicate_(predicate), - app_manager_(app_manager), - app_ids_(app_ids) { - ASSERT1(app_ids); - } - - // Ignores errors and accumulates as many applications as possible. - HRESULT operator() (const CString& app_id) const { - if ((*predicate_)(app_manager_, app_id)) { - app_ids_->push_back(app_id); - } - - return S_OK; - } - - private: - const AppPredictFunc predicate_; - const AppManager& app_manager_; - AppIdVector* const app_ids_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(CollectProductsFunc); -}; - -// Runs application registration hooks registered under Omaha AppIds. -// Reads the Hook Clsid entry under Clients\{AppID}. CoCreates the CLSID. Calls -// IRegistrationUpdateHook::UpdateRegistry(). -class RunRegistrationUpdateHooksFunc - : public std::unary_function { - public: - explicit RunRegistrationUpdateHooksFunc(const AppManager& app_manager) - : app_manager_(app_manager) { - } - - HRESULT operator() (const CString& app_id) { - GUID app_guid = GUID_NULL; - HRESULT hr = StringToGuidSafe(app_id, &app_guid); - if (FAILED(hr)) { - return hr; - } - RegKey client_key; - hr = app_manager_.OpenClientKey(app_guid, &client_key); - if (FAILED(hr)) { - return hr; - } - - CString hook_clsid_str; - hr = client_key.GetValue(kRegValueUpdateHookClsid, &hook_clsid_str); - if (FAILED(hr)) { - return hr; - } - GUID hook_clsid = GUID_NULL; - hr = StringToGuidSafe(hook_clsid_str, &hook_clsid); - if (FAILED(hr)) { - return hr; - } - - CORE_LOG(L3, (_T("[Update Hook Clsid][%s][%s]"), app_id, hook_clsid_str)); - - CComPtr registration_hook; - hr = registration_hook.CoCreateInstance(hook_clsid); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[IRegistrationUpdateHook CoCreate failed][0x%x]"), hr)); - return hr; - } - - hr = registration_hook->UpdateRegistry(CComBSTR(app_id), - app_manager_.is_machine_); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[registration_hook UpdateRegistry failed][0x%x]"), hr)); - return hr; - } - - return S_OK; - } - - private: - const AppManager& app_manager_; -}; AppManager* AppManager::instance_ = NULL; @@ -282,15 +159,20 @@ bool AppManager::IsAppRegistered(const GUID& app_guid) const { // Vulnerable to a race condition with installers. To prevent this, acquire // GetRegistryStableStateLock(). bool AppManager::IsAppRegistered(const CString& app_id) const { - IsAppRegisteredFunc func(app_id); + bool is_registered = false; HRESULT hr = EnumerateSubKeys( ConfigManager::Instance()->registry_clients(is_machine_), - &func); + [&](const CString& subkey) { + if (subkey.CompareNoCase(app_id) == 0) { + is_registered = true; + } + }); + if (FAILED(hr)) { return false; } - return func.is_registered(); + return is_registered; } bool AppManager::IsAppUninstalled(const CString& app_id) const { @@ -341,55 +223,96 @@ bool AppManager::IsAppOemInstalledAndEulaAccepted(const CString& app_id) const { return RegKey::HasValue(GetClientStateKeyName(app_guid), kRegValueOemInstall); } +HRESULT AppManager::RunRegistrationUpdateHook(const CString& app_id) const { + GUID app_guid = GUID_NULL; + HRESULT hr = StringToGuidSafe(app_id, &app_guid); + if (FAILED(hr)) { + return hr; + } + RegKey client_key; + hr = OpenClientKey(app_guid, &client_key); + if (FAILED(hr)) { + return hr; + } + + CString hook_clsid_str; + hr = client_key.GetValue(kRegValueUpdateHookClsid, &hook_clsid_str); + if (FAILED(hr)) { + return hr; + } + GUID hook_clsid = GUID_NULL; + hr = StringToGuidSafe(hook_clsid_str, &hook_clsid); + if (FAILED(hr)) { + return hr; + } + + CORE_LOG(L3, (_T("[Update Hook Clsid][%s][%s]"), app_id, hook_clsid_str)); + + CComPtr registration_hook; + hr = registration_hook.CoCreateInstance(hook_clsid); + if (FAILED(hr)) { + CORE_LOG(LE, (_T("[IRegistrationUpdateHook CoCreate failed][0x%x]"), hr)); + return hr; + } + + hr = registration_hook->UpdateRegistry(CComBSTR(app_id), is_machine_); + if (FAILED(hr)) { + CORE_LOG(LE, (_T("[registration_hook UpdateRegistry failed][0x%x]"), hr)); + return hr; + } + + return S_OK; +} + + // Vulnerable to a race condition with installers. To prevent this, hold // GetRegistryStableStateLock() while calling this function and related // functions, such as ReadAppPersistentData(). HRESULT AppManager::GetRegisteredApps(AppIdVector* app_ids) const { ASSERT1(app_ids); - - CollectProductsFunc func(IsRegisteredAppPredicate, *this, app_ids); - return EnumerateSubKeys( ConfigManager::Instance()->registry_clients(is_machine_), - &func); + [&](const CString& subkey) { + if (this->IsAppRegistered(subkey)) { + app_ids->push_back(subkey); + } + }); } // Vulnerable to a race condition with installers. To prevent this, acquire // GetRegistryStableStateLock(). HRESULT AppManager::GetUninstalledApps(AppIdVector* app_ids) const { ASSERT1(app_ids); - - CollectProductsFunc func(IsUninstalledAppPredicate, *this, app_ids); - return EnumerateSubKeys( ConfigManager::Instance()->registry_client_state(is_machine_), - &func); + [&](const CString& subkey) { + if (this->IsAppUninstalled(subkey)) { + app_ids->push_back(subkey); + } + }); } HRESULT AppManager::GetOemInstalledAndEulaAcceptedApps( AppIdVector* app_ids) const { ASSERT1(app_ids); - - CollectProductsFunc func(IsAppOemInstalledAndEulaAcceptedPredicate, - *this, - app_ids); - return EnumerateSubKeys( ConfigManager::Instance()->registry_client_state(is_machine_), - &func); -} - -HRESULT AppManager::RunRegistrationUpdateHook(const CString& app_id) const { - return RunRegistrationUpdateHooksFunc(*this)(app_id); + [&](const CString& subkey) { + if (this->IsAppOemInstalledAndEulaAccepted(subkey)) { + app_ids->push_back(subkey); + } + }); } // Vulnerable to a race condition with installers. We think this is acceptable. // If there is a future requirement for greater consistency, acquire // GetRegistryStableStateLock(). HRESULT AppManager::RunAllRegistrationUpdateHooks() const { - RunRegistrationUpdateHooksFunc func(*this); const TCHAR* key(ConfigManager::Instance()->registry_clients(is_machine_)); - return EnumerateSubKeys(key, &func); + return EnumerateSubKeys(key, + [&](const CString& subkey) { + this->RunRegistrationUpdateHook(subkey); + }); } CString AppManager::GetClientKeyName(const GUID& app_guid) const { @@ -868,6 +791,7 @@ HRESULT AppManager::ReadUninstalledAppPersistentData(App* app) { // eulaaccepted (set/deleted) // browser // usagestats +// ping freshness // Sets eulaaccepted=0 if the app is not already registered and the app's EULA // has not been accepted. Deletes eulaaccepted if the EULA has been accepted. // Only call for initial or over-installs. Do not call for updates to avoid @@ -888,6 +812,17 @@ HRESULT AppManager::WritePreInstallData(const App& app) { return hr; } + // Initialize the ping freshness, if needed. For installs and over-installs, + // ping freshness must be available before sending a completion ping. + // Otherwise, the completion ping contains no ping_freshness, which makes + // impossible to do an accurate user count in the presence of system reimage. + if (!client_state_key.HasValue(kRegValuePingFreshness)) { + GUID ping_freshness = GUID_NULL; + VERIFY1(SUCCEEDED(::CoCreateGuid(&ping_freshness))); + client_state_key.SetValue(kRegValuePingFreshness, + GuidToString(ping_freshness)); + } + if (app.is_eula_accepted()) { hr = app_registry_utils::ClearAppEulaNotAccepted(is_machine_, app.app_guid_string()); @@ -1652,38 +1587,4 @@ HRESULT AppManager::RemoveClientState(const GUID& app_guid) { GuidToString(app_guid)); } -// TODO(omaha3): May not need these -#if 0 -// Writes 0.0.0.1 to pv. This value avoids any special cases, such as initial -// install rules, for 0.0.0.0, while being unlikely to be higher than the -// product's actual current version. -HRESULT AppManager::RegisterProduct(const GUID& product_guid, - const CString& product_name) { - const TCHAR* const kRegisterProductVersion = _T("0.0.0.1"); - - __mutexScope(GetRegistryStableStateLock()); - RegKey client_key; - HRESULT hr = client_key.Create(GetClientKeyName(GUID_NULL, product_guid)); - if (FAILED(hr)) { - return hr; - } - - hr = client_key.SetValue(kRegValueProductVersion, kRegisterProductVersion); - if (FAILED(hr)) { - return hr; - } - - // AppName is not a required parameter since it's only used for being able to - // easily tell what application is there when reading the registry. - VERIFY1(SUCCEEDED(client_key.SetValue(kRegValueAppName, product_name))); - - return S_OK; -} - -HRESULT AppManager::UnregisterProduct(const GUID& product_guid) { - __mutexScope(GetRegistryStableStateLock()); - return RegKey::DeleteKey(GetClientKeyName(GUID_NULL, product_guid), true); -} -#endif - } // namespace omaha diff --git a/omaha/goopdate/app_manager.h b/omaha/goopdate/app_manager.h index 526fc53..db3e380 100644 --- a/omaha/goopdate/app_manager.h +++ b/omaha/goopdate/app_manager.h @@ -208,12 +208,6 @@ class AppManager { // Omaha will not send day_of_install if it is 0. uint32 GetDayOfInstall(const GUID& app_guid) const; -#if 0 - HRESULT RegisterProduct(const GUID& product_guid, - const CString& product_name); - HRESULT UnregisterProduct(const GUID& product_guid); -#endif - bool IsAppRegistered(const CString& app_id) const; bool IsAppUninstalled(const CString& app_id) const; bool IsAppOemInstalledAndEulaAccepted(const CString& app_id) const; diff --git a/omaha/goopdate/app_manager_unittest.cc b/omaha/goopdate/app_manager_unittest.cc index 706c6a5..b1a47b9 100644 --- a/omaha/goopdate/app_manager_unittest.cc +++ b/omaha/goopdate/app_manager_unittest.cc @@ -13,14 +13,15 @@ // limitations under the License. // ======================================================================== -#include +#include "omaha/goopdate/app_manager.h" + +#include + #include "omaha/base/const_object_names.h" #include "omaha/base/error.h" #include "omaha/base/highres_timer-win32.h" #include "omaha/base/reg_key.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/thread.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" @@ -29,11 +30,11 @@ #include "omaha/common/app_registry_utils.h" #include "omaha/common/config_manager.h" #include "omaha/common/const_goopdate.h" -#include "omaha/goopdate/app_manager.h" #include "omaha/goopdate/app_unittest_base.h" #include "omaha/goopdate/worker.h" #include "omaha/setup/setup_google_update.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" using ::testing::_; using ::testing::Return; @@ -1242,7 +1243,7 @@ class AppManagerTestBase : public AppTestBaseWithRegistryOverride { // A second bundle is necessary because the same bundle cannot have the same // app in it more than once and many of these tests create an app to populate // the registry and another to read it. - shared_ptr dummy_app_bundle_for_app_creation_; + std::shared_ptr dummy_app_bundle_for_app_creation_; const GUID guid1_; @@ -1422,7 +1423,7 @@ void PingFreshnessTest(bool is_machine) { EXPECT_HRESULT_SUCCEEDED(StringToGuidSafe( _T("{21CD0965-0B0E-47cf-B421-2D191C16C0E2}"), &app_guid)); - scoped_ptr app_bundle; + std::unique_ptr app_bundle; { // AppBundle code expects the model to be locked. __mutexScope(Worker::Instance().model()->lock()); diff --git a/omaha/goopdate/app_state.h b/omaha/goopdate/app_state.h index b572bd0..fe6b4dc 100644 --- a/omaha/goopdate/app_state.h +++ b/omaha/goopdate/app_state.h @@ -18,8 +18,8 @@ #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/common/const_goopdate.h" #include "omaha/common/ping_event.h" #include "omaha/goopdate/installer_result_info.h" diff --git a/omaha/goopdate/app_state_checking_for_update.cc b/omaha/goopdate/app_state_checking_for_update.cc index 262de14..e2c77a0 100644 --- a/omaha/goopdate/app_state_checking_for_update.cc +++ b/omaha/goopdate/app_state_checking_for_update.cc @@ -156,6 +156,7 @@ void AppStateCheckingForUpdate::HandleUpdateAvailable(App* app, VERIFY1(SUCCEEDED(formatter.LoadString(IDS_UNKNOWN_APPLICATION, &error_message))); Error(app, ErrorContext(hr), error_message); + return; } const TCHAR* action = app->is_update() ? _T("update") : _T("install"); diff --git a/omaha/goopdate/app_unittest.cc b/omaha/goopdate/app_unittest.cc index 9ef8f00..f3f3609 100644 --- a/omaha/goopdate/app_unittest.cc +++ b/omaha/goopdate/app_unittest.cc @@ -68,11 +68,13 @@ class AppTest : public AppTestBaseWithRegistryOverride { update_response_.reset(xml::UpdateResponse::Create()); } - void AddAppResponse(const CString& status) { + void AddAppResponse(const CString& status, + const std::vector& data) { xml::response::App app; app.status = xml::response::kStatusOkValue; app.appid = kAppId1; app.update_check.status = status; + app.data = data; xml::response::Response response; @@ -85,7 +87,7 @@ class AppTest : public AppTestBaseWithRegistryOverride { } App* app_; - scoped_ptr update_response_; + std::unique_ptr update_response_; private: DISALLOW_COPY_AND_ASSIGN(AppTest); @@ -245,7 +247,8 @@ TEST_P(AppAutoUpdateTest, CheckGroupPolicy_ManualUpdatesDisabled) { TEST_F(AppInstallTest, PostUpdateCheck_NoUpdate) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusNoUpdate); + AddAppResponse(xml::response::kStatusNoUpdate, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_ERROR, app_->state()); @@ -254,7 +257,8 @@ TEST_F(AppInstallTest, PostUpdateCheck_NoUpdate) { TEST_F(AppInstallTest, PostUpdateCheck_UpdateAvailable) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -265,7 +269,8 @@ TEST_F(AppInstallTest, PostUpdateCheck_UpdateAvailable) { TEST_P(AppInstallTest, PostUpdateCheck_UpdateAvailable_InstallDisabled) { SetPolicy(kInstallPolicyApp1, kPolicyDisabled); SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -274,7 +279,8 @@ TEST_P(AppInstallTest, PostUpdateCheck_UpdateAvailable_InstallDisabled) { TEST_F(AppManualUpdateTest, PostUpdateCheck_NoUpdate) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusNoUpdate); + AddAppResponse(xml::response::kStatusNoUpdate, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_NO_UPDATE, app_->state()); @@ -283,7 +289,8 @@ TEST_F(AppManualUpdateTest, PostUpdateCheck_NoUpdate) { TEST_F(AppManualUpdateTest, PostUpdateCheck_UpdateAvailable) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -295,7 +302,8 @@ TEST_P(AppManualUpdateTest, PostUpdateCheck_UpdateAvailable_AllUpdatesDisabled) { SetPolicy(kUpdatePolicyApp1, kPolicyDisabled); SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -304,7 +312,8 @@ TEST_P(AppManualUpdateTest, TEST_F(AppAutoUpdateTest, PostUpdateCheck_NoUpdate) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusNoUpdate); + AddAppResponse(xml::response::kStatusNoUpdate, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_NO_UPDATE, app_->state()); @@ -313,7 +322,8 @@ TEST_F(AppAutoUpdateTest, PostUpdateCheck_NoUpdate) { TEST_F(AppAutoUpdateTest, PostUpdateCheck_UpdateAvailable) { SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -324,7 +334,38 @@ TEST_F(AppAutoUpdateTest, PostUpdateCheck_UpdateAvailable) { TEST_P(AppAutoUpdateTest, PostUpdateCheck_UpdateAvailable_AllUpdatesDisabled) { SetPolicy(kUpdatePolicyApp1, kPolicyDisabled); SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); - AddAppResponse(xml::response::kStatusOkValue); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); + + app_->PostUpdateCheck(S_OK, update_response_.get()); + EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); + EXPECT_EQ(S_OK, app_->error_code()); +} + +TEST_F(AppAutoUpdateTest, + PostUpdateCheck_UpdateAvailable_NonExistentInstallDataIndex) { + SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); + AddAppResponse(xml::response::kStatusOkValue, + std::vector()); + app_->put_serverInstallDataIndex(CComBSTR(_T("NonExistent"))); + + app_->PostUpdateCheck(S_OK, update_response_.get()); + EXPECT_EQ(STATE_ERROR, app_->state()); + EXPECT_EQ(GOOPDATE_E_INVALID_INSTALL_DATA_INDEX, app_->error_code()); +} + +TEST_F(AppAutoUpdateTest, + PostUpdateCheck_UpdateAvailable_ExistingInstallDataIndex) { + SetAppStateForUnitTest(app_, new fsm::AppStateCheckingForUpdate); + std::vector datas; + xml::response::Data data; + data.status = _T("ok"); + data.name = _T("install"); + data.install_data_index = _T("Existing"); + data.install_data = _T("{}"); + datas.push_back(data); + AddAppResponse(xml::response::kStatusOkValue, datas); + app_->put_serverInstallDataIndex(CComBSTR(_T("Existing"))); app_->PostUpdateCheck(S_OK, update_response_.get()); EXPECT_EQ(STATE_UPDATE_AVAILABLE, app_->state()); @@ -426,7 +467,7 @@ TEST_P(AppManualUpdateTest, QueueDownload_InstallDisabled) { EXPECT_EQ(S_OK, app_->error_code()); } -TEST_F(AppAutoUpdateTest, QueueDownload_AllUpdatesDisabled_NoPolicy) { +TEST_P(AppAutoUpdateTest, QueueDownload_AllUpdatesDisabled_NoPolicy) { SetAppStateForUnitTest(app_, new fsm::AppStateUpdateAvailable); app_->QueueDownload(); @@ -488,7 +529,7 @@ TEST_F(AppInstallTest, PreUpdateCheck_EulaAccepted) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -505,7 +546,7 @@ TEST_F(AppAutoUpdateTest, PreUpdateCheck_EulaAccepted) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -522,7 +563,7 @@ TEST_F(AppInstallTest, PreUpdateCheck_EulaNotAccepted_Online) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_FALSE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -542,7 +583,7 @@ TEST_F(AppInstallTest, PreUpdateCheck_EulaNotAccepted_Offline) { EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_FALSE)); EXPECT_SUCCEEDED(app_bundle_->put_offlineDirectory(CComBSTR(_T("foo")))); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -558,7 +599,7 @@ TEST_F(AppAutoUpdateTest, PreUpdateCheck_EulaNotAccepted) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_FALSE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -576,7 +617,7 @@ TEST_P(AppInstallTest, PreUpdateCheck_InstallDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -596,7 +637,7 @@ TEST_P(AppManualUpdateTest, PreUpdateCheck_InstallDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -616,7 +657,7 @@ TEST_P(AppAutoUpdateTest, PreUpdateCheck_InstallDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -636,7 +677,7 @@ TEST_P(AppInstallTest, PreUpdateCheck_InstallDisabledForDifferentApp) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -654,7 +695,7 @@ TEST_P(AppInstallTest, PreUpdateCheck_UpdateDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -672,7 +713,7 @@ TEST_P(AppManualUpdateTest, PreUpdateCheck_UpdateDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -696,7 +737,7 @@ TEST_P(AppAutoUpdateTest, PreUpdateCheck_UpdateDisabled) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -716,7 +757,7 @@ TEST_P(AppManualUpdateTest, PreUpdateCheck_UpdateDisabledForDifferentApp) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -736,7 +777,7 @@ TEST_P(AppAutoUpdateTest, PreUpdateCheck_UpdateDisabledForDifferentApp) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -756,7 +797,7 @@ TEST_P(AppInstallTest, PreUpdateCheck_ManualUpdatesOnly) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -774,7 +815,7 @@ TEST_P(AppManualUpdateTest, PreUpdateCheck_ManualUpdatesOnly) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), @@ -794,7 +835,7 @@ TEST_P(AppAutoUpdateTest, PreUpdateCheck_ManualUpdatesOnly) { SetAppStateForUnitTest(app_, new fsm::AppStateWaitingToCheckForUpdate); EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); - scoped_ptr update_request; + std::unique_ptr update_request; update_request.reset(xml::UpdateRequest::Create(is_machine_, _T("unittest_sessionid"), _T("unittest_instsource"), diff --git a/omaha/goopdate/app_unittest_base.h b/omaha/goopdate/app_unittest_base.h index 9a4e539..c8d2d29 100644 --- a/omaha/goopdate/app_unittest_base.h +++ b/omaha/goopdate/app_unittest_base.h @@ -20,8 +20,9 @@ #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" +#include "omaha/base/xml_utils.h" #include "omaha/common/const_group_policy.h" #include "omaha/goopdate/app_manager.h" #include "omaha/goopdate/app_bundle_state_initialized.h" @@ -92,7 +93,7 @@ class AppTestBase : public testing::Test { std::vector buffer(buffer_string.GetLength()); memcpy(&buffer.front(), buffer_string, buffer.size()); - scoped_ptr update_response( + std::unique_ptr update_response( xml::UpdateResponse::Create()); HRESULT hr = update_response->Deserialize(buffer); if (FAILED(hr)) { @@ -116,11 +117,11 @@ class AppTestBase : public testing::Test { CString hive_override_key_name_; - scoped_ptr mock_worker_; - scoped_ptr model_; + std::unique_ptr mock_worker_; + std::unique_ptr model_; Goopdate goopdate_; - shared_ptr app_bundle_; + std::shared_ptr app_bundle_; private: DISALLOW_COPY_AND_ASSIGN(AppTestBase); @@ -141,6 +142,13 @@ class AppTestBaseWithRegistryOverride virtual void SetUp() { AppTestBase::SetUp(); + // Registry redirection impacts the creation of the COM XML parser. + // This code instantiates the parser before registry redirection occurs. + { + CComPtr document; + EXPECT_SUCCEEDED(CoCreateSafeDOMDocument(&document)); + } + RegKey::DeleteKey(hive_override_key_name_); OverrideRegistryHives(hive_override_key_name_); } diff --git a/omaha/goopdate/app_version.cc b/omaha/goopdate/app_version.cc index c8439a9..21b145b 100644 --- a/omaha/goopdate/app_version.cc +++ b/omaha/goopdate/app_version.cc @@ -14,10 +14,11 @@ // ======================================================================== #include "omaha/goopdate/app_version.h" + #include + #include "omaha/base/debug.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/synchronized.h" #include "omaha/base/utils.h" #include "omaha/goopdate/file_hash.h" diff --git a/omaha/goopdate/app_version.h b/omaha/goopdate/app_version.h index 7b8f0a4..28dcf08 100644 --- a/omaha/goopdate/app_version.h +++ b/omaha/goopdate/app_version.h @@ -21,8 +21,8 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "goopdate/omaha3_idl.h" #include "omaha/base/constants.h" #include "omaha/common/install_manifest.h" @@ -78,7 +78,7 @@ class AppVersion : public ModelObject { // product version "pv". CString version_; - scoped_ptr install_manifest_; + std::unique_ptr install_manifest_; std::vector packages_; diff --git a/omaha/goopdate/app_version_unittest.cc b/omaha/goopdate/app_version_unittest.cc index e6eff36..e44b009 100644 --- a/omaha/goopdate/app_version_unittest.cc +++ b/omaha/goopdate/app_version_unittest.cc @@ -15,7 +15,7 @@ #include #include -#include "omaha/base/scoped_ptr_address.h" + #include "omaha/base/synchronized.h" #include "omaha/base/utils.h" #include "omaha/common/update3_utils.h" @@ -53,7 +53,7 @@ class AppVersionTest : public testing::Test { TEST_F(AppVersionTest, TestReadOnly) { IDummyUnknownImpl dummy_unknown; - scoped_ptr app_version; + std::unique_ptr app_version; EXPECT_SUCCEEDED(AppVersion::Create(&lock_, &dummy_unknown, true, @@ -89,7 +89,7 @@ TEST_F(AppVersionTest, TestReadOnly) { TEST_F(AppVersionTest, TestReadWrite) { IDummyUnknownImpl dummy_unknown; - scoped_ptr app_version; + std::unique_ptr app_version; EXPECT_SUCCEEDED(AppVersion::Create(&lock_, &dummy_unknown, false, diff --git a/omaha/goopdate/application_usage_data.h b/omaha/goopdate/application_usage_data.h index 718eed6..e55e62b 100644 --- a/omaha/goopdate/application_usage_data.h +++ b/omaha/goopdate/application_usage_data.h @@ -77,7 +77,7 @@ class ApplicationUsageData { bool check_low_integrity_; // Whether to check the low integrity registry // location. - DISALLOW_EVIL_CONSTRUCTORS(ApplicationUsageData); + DISALLOW_COPY_AND_ASSIGN(ApplicationUsageData); }; } // namespace omaha diff --git a/omaha/goopdate/broker_class_factory.h b/omaha/goopdate/broker_class_factory.h index 4d1776a..e0a1326 100644 --- a/omaha/goopdate/broker_class_factory.h +++ b/omaha/goopdate/broker_class_factory.h @@ -81,9 +81,6 @@ class BrokerClassFactory : public CComClassFactory { } }; -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) // This class is used for COM registration and class factory registration and // instantiation of the delegate brokers. The class itself is not @@ -131,7 +128,6 @@ class ATL_NO_VTABLE BrokerClassFactoryRegistrar DISALLOW_COPY_AND_ASSIGN(BrokerClassFactoryRegistrar); }; -#pragma warning(pop) extern TCHAR kOnDemandMachineBrokerProgId[]; extern TCHAR kUpdate3WebMachineBrokerProgId[]; diff --git a/omaha/goopdate/build.scons b/omaha/goopdate/build.scons index c8e771c..7faa79b 100644 --- a/omaha/goopdate/build.scons +++ b/omaha/goopdate/build.scons @@ -17,6 +17,7 @@ import omaha_version_utils +import os Import('env') @@ -25,7 +26,7 @@ def BuildCOMForwarder(cmd_line_switch, should_append_cmd_line): com_forwarder_env = env.Clone() - com_forwarder_env.FilterOut(CCFLAGS=['/GL', '/RTC1', '/GS']) + com_forwarder_env.FilterOut(CCFLAGS=['/GL', '/RTC1',]) com_forwarder_env.FilterOut(LINKFLAGS=['/LTCG']) should_append_string = 'FALSE' @@ -34,7 +35,6 @@ def BuildCOMForwarder(cmd_line_switch, com_forwarder_env.Append( CCFLAGS=[ - '/GS-', '/Zl', ], CPPDEFINES = [ @@ -74,18 +74,17 @@ def BuildCOMForwarder(cmd_line_switch, # Build the broker/legacy on-demand/WebPlugin forwarders. -BuildCOMForwarder('/broker', 'GoogleUpdateBroker', False) -BuildCOMForwarder('/ondemand', 'GoogleUpdateOnDemand', False) -BuildCOMForwarder('/pi', 'GoogleUpdateWebPlugin', True) +BuildCOMForwarder('/broker', 'BraveUpdateBroker', False) +BuildCOMForwarder('/ondemand', 'BraveUpdateOnDemand', False) +BuildCOMForwarder('/pi', 'BraveUpdateWebPlugin', True) def BuildCOMRegisterShell64(): com_register_shell_env = env.CloneAndMake64Bit() - com_register_shell_env.FilterOut(CCFLAGS=['/GL', '/RTC1', '/GS']) + com_register_shell_env.FilterOut(CCFLAGS=['/GL', '/RTC1',]) com_register_shell_env.FilterOut(LINKFLAGS=['/LTCG']) com_register_shell_env.Append( CCFLAGS=[ - '/GS-', '/Zl', ], LINKFLAGS=[ @@ -112,14 +111,22 @@ def BuildCOMRegisterShell64(): 'wtsapi32.lib', ], ) + if env.Bit('has_device_management'): + com_register_shell_env.Append( + LIBS=[ + '$LIB_DIR/dm_proto_64.lib', + '$LIB_DIR/libprotobuf_64.lib', + ], + ) + unsigned_exe = com_register_shell_env.ComponentProgram( - prog_name='GoogleUpdateComRegisterShell64_unsigned', + prog_name='BraveUpdateComRegisterShell64_unsigned', source= [ 'com_register_shell.cc', ] ) signed_exe = com_register_shell_env.DualSignedBinary( - target='GoogleUpdateComRegisterShell64.exe', + target='BraveUpdateComRegisterShell64.exe', source=unsigned_exe, ) env.Replicate('$STAGING_DIR', signed_exe) @@ -158,6 +165,7 @@ def BuildGoogleUpdateCOMProxy(midl_env, generated_idl): midl_env.Command(target_idl, 'omaha3_idl.idl', Copy('$TARGET', '$SOURCE')) midl_env.TypeLibrary(target_idl) else: + midl_env['MIDLFLAGS'] += [ '/win32' ] midl_outputs = midl_env.TypeLibrary('omaha3_idl.idl') # Save the .idl and the produced .tlb and .h files so we can provide @@ -173,10 +181,9 @@ def BuildGoogleUpdateCOMProxy(midl_env, generated_idl): 'omaha3_idl%s_i.c' % suffix, ] - midl_env.ComponentStaticLibrary( + midl_env.ComponentLibrary( 'omaha3_idl%s' % suffix, midl_lib_inputs, - use_pch_default=False ) generated_omaha3_idl = GenerateOmaha3IDLFile() @@ -193,6 +200,13 @@ def BuildGoogleUpdateHandlerDll(handler_env, '_USRDLL', '_WINDLL', ], + CCFLAGS = [ + '/wd4263', + '/wd4264', + '/wd4255', + '/wd4426', + '/wd5038', + ], CPPPATH = [ '$OBJ_ROOT', # Needed for generated files. ], @@ -210,13 +224,19 @@ def BuildGoogleUpdateHandlerDll(handler_env, 'wtsapi32.lib', ], ) + if handler_env.Bit('has_device_management'): + handler_env.Append( + LIBS = [ + handler_env.GetMultiarchLibName('dm_proto'), + handler_env.GetMultiarchLibName('libprotobuf'), + ], + ) + version_string = omaha_version_info.GetVersionString() prefix = omaha_version_info.filename_prefix - if prefix == 'TEST_': - handler_env['OBJPREFIX'] = handler_env.subst('test/$OBJPREFIX') - elif prefix: - raise Exception('ERROR: Unrecognized prefix "%s"' % prefix) + if prefix: + handler_env['OBJPREFIX'] = handler_env.subst(prefix + 'obj/$OBJPREFIX') handler_env.Append( CPPDEFINES = [ @@ -258,7 +278,6 @@ def BuildGoogleUpdateHandlerDll(handler_env, '$OBJ_ROOT/goopdate/google_update_ps.cc') inputs += handler_env.Object('omaha3_idl_datax_%s%s.obj' % (psname, suffix), '$OBJ_ROOT/goopdate/omaha3_idl_datax.c') - unsigned_dll = handler_env.ComponentLibrary( lib_name=target_name, source=inputs, @@ -284,6 +303,50 @@ for omaha_version_info in env['omaha_versions_info']: BuildGoogleUpdateHandlerDll(handler_env.CloneAndMake64Bit(), omaha_version_info, 0, 'psuser') +if env.Bit('has_device_management'): + # Compile the device management server protobufs. + proto_env = env.Clone() + proto_env.Append(PROTO_PATH = '$GOOGLE3') + proto_env.Append(CPP_OUT = '$TARGET_ROOT/proto_files') + proto_sources = [ + '$GOOGLE3/logs/proto/logs_annotations/logs_annotations.proto', + '$GOOGLE3/wireless/android/enterprise/devicemanagement/proto/' + + 'dm_api.proto', + '$GOOGLE3/net/proto2/proto/descriptor.proto', + ] + proto_outputs = proto_env.CompileProtoBuf(proto_sources) + + # Build the device management messages and protobuf library. + protobuf_src_dir = os.getenv('OMAHA_PROTOBUF_SRC_DIR', + '$GOOGLE3/third_party/protobuf/src') + proto_env.Append( + CCFLAGS=[ + '/wd4100', + '/wd4125', + '/wd4127', + '/wd4146', + '/wd4242', + '/wd4244', + '/wd4309', + '/wd4548', + '/wd4577', + '/wd4647', + '/wd4800', + '/wd4946', + '/wd4995', + '/wd4996', + ], + CPPPATH=[ + '$GOOGLE3', + protobuf_src_dir, + '$TARGET_ROOT/proto_files', + ], + ) + dm_proto_lib = proto_env.ComponentStaticLibraryMultiarch( + 'dm_proto', + proto_outputs + ['dm_messages.cc'], + ) + gd_env = env.Clone() # TODO(omaha3): Is it okay that other libs, such as common, do not define this. @@ -347,7 +410,6 @@ gd_inputs = [ 'model.cc', 'model_object.cc', 'ondemand.cc', - 'oneclick_process_launcher.cc', 'offline_utils.cc', 'string_formatter.cc', 'package.cc', @@ -363,6 +425,12 @@ gd_inputs = [ 'worker_metrics.cc', ] +if gd_env.Bit('has_device_management'): + gd_inputs += [ + 'dm_client.cc', + 'dm_storage.cc', + ] + # Compile the library. gd_env.ComponentStaticLibraryMultiarch(target_name, gd_inputs) @@ -371,14 +439,11 @@ gd_env.ComponentStaticLibraryMultiarch(target_name, gd_inputs) # Build Goopdate DLL # for omaha_version_info in env['omaha_versions_info']: - prefix = omaha_version_info.filename_prefix - temp_env = env.Clone(COMPONENT_STATIC=False) - if prefix == 'TEST_': - temp_env['OBJPREFIX'] = temp_env.subst('test/$OBJPREFIX') - elif prefix: - raise Exception('ERROR: Unrecognized prefix "%s"' % prefix) + prefix = omaha_version_info.filename_prefix + if prefix: + temp_env['OBJPREFIX'] = temp_env.subst(prefix + 'obj/$OBJPREFIX') # Add languages that have version resources but are not fully supported. translated_languages = omaha_version_utils.GetShellLanguagesForVersion( @@ -399,8 +464,10 @@ for omaha_version_info in env['omaha_versions_info']: '$LIB_DIR/client.lib', '$LIB_DIR/common.lib', '$LIB_DIR/core.lib', + '$LIB_DIR/crx_file.lib', '$LIB_DIR/google_update_recovery.lib', '$LIB_DIR/goopdate_lib.lib', + '$LIB_DIR/libprotobuf.lib', '$LIB_DIR/logging.lib', '$LIB_DIR/net.lib', '$LIB_DIR/omaha3_idl.lib', @@ -453,6 +520,12 @@ for omaha_version_info in env['omaha_versions_info']: '/DLANGUAGE_STRING=\\"en\\"', ], ) + if temp_env.Bit('has_device_management'): + temp_env.Append( + LIBS = [ + '$LIB_DIR/dm_proto.lib', + ], + ) resource_res = temp_env.RES( target=prefix + 'goopdate.res', @@ -481,8 +554,6 @@ for omaha_version_info in env['omaha_versions_info']: resource_res, version_res, ] - if env.Bit('use_precompiled_headers'): - inputs += temp_env.EnablePrecompile(target_name) for language in translated_languages: lang_base_name = 'goopdate_dll/generated_resources_' + language @@ -527,7 +598,6 @@ test_installer_env = env.Clone() test_installer_env.Append( CCFLAGS = [ '/wd4995', - '/FIgoogle_update/precompile.h', ], LIBS = [ 'delayimp.lib', diff --git a/omaha/goopdate/cocreate_async.cc b/omaha/goopdate/cocreate_async.cc index b98ea2b..7985452 100644 --- a/omaha/goopdate/cocreate_async.cc +++ b/omaha/goopdate/cocreate_async.cc @@ -17,7 +17,6 @@ #include "base/basictypes.h" #include "base/debug.h" #include "omaha/base/scope_guard.h" -#include "base/scoped_ptr_address.h" #include "omaha/base/system.h" #include "omaha/base/thread_pool_callback.h" #include "omaha/base/vistautil.h" @@ -44,8 +43,10 @@ STDMETHODIMP CoCreateAsync::createOmahaMachineServerAsync( } typedef CComObject ComObjectAsyncStatus; - scoped_ptr async_status; - HRESULT hr = ComObjectAsyncStatus::CreateInstance(address(async_status)); + std::unique_ptr async_status; + ComObjectAsyncStatus* async_status_obj = nullptr; + HRESULT hr = ComObjectAsyncStatus::CreateInstance(&async_status_obj); + async_status.reset(async_status_obj); if (FAILED(hr)) { return hr; } @@ -72,14 +73,13 @@ HRESULT CoCreateAsyncStatus::CreateOmahaMachineServerAsync( BOOL create_elevated) { // Create a thread pool work item for deferred execution of the CoCreate. The // thread pool owns this call back object. - typedef ThreadPoolCallBack2 CallBack; - scoped_ptr - callback(new CallBack(this, - &CoCreateAsyncStatus::CreateOmahaMachineServer, - origin_url, - create_elevated)); + BOOL>; + auto callback = std::make_unique(this, + &CoCreateAsyncStatus::CreateOmahaMachineServer, + origin_url, + create_elevated); HRESULT hr = Goopdate::Instance().QueueUserWorkItem(callback.get(), COINIT_MULTITHREADED, WT_EXECUTELONGFUNCTION); diff --git a/omaha/goopdate/cocreate_async.h b/omaha/goopdate/cocreate_async.h index b59f19a..cc2affe 100644 --- a/omaha/goopdate/cocreate_async.h +++ b/omaha/goopdate/cocreate_async.h @@ -29,10 +29,6 @@ namespace omaha { -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) - class ATL_NO_VTABLE CoCreateAsync : public CComObjectRootEx, public CComCoClass, @@ -107,8 +103,6 @@ class ATL_NO_VTABLE CoCreateAsyncStatus DISALLOW_COPY_AND_ASSIGN(CoCreateAsyncStatus); }; -#pragma warning(pop) - } // namespace omaha #endif // OMAHA_GOOPDATE_COCREATE_ASYNC_H_ diff --git a/omaha/goopdate/com_proxy.h b/omaha/goopdate/com_proxy.h index b4e4693..91e8a59 100644 --- a/omaha/goopdate/com_proxy.h +++ b/omaha/goopdate/com_proxy.h @@ -99,13 +99,6 @@ struct ComProxyMode { } }; -#pragma warning(push) - -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) - -// C4505: unreferenced IUnknown local functions have been removed -#pragma warning(disable : 4505) class ATL_NO_VTABLE ComProxy : public CComObjectRootEx, @@ -119,14 +112,10 @@ class ATL_NO_VTABLE ComProxy DECLARE_GET_CONTROLLING_UNKNOWN() DECLARE_REGISTRY_RESOURCEID_EX(IDR_COM_PROXY_RGS); -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) BEGIN_REGISTRY_MAP() REGMAP_ENTRY(_T("HKROOT"), ComProxyMode::hk_root()) REGMAP_ENTRY(_T("CLSID"), ComProxyMode::class_id()) END_REGISTRY_MAP() -#pragma warning(pop) BEGIN_COM_MAP(ComProxy) COM_INTERFACE_ENTRY(IUnknown) @@ -209,8 +198,6 @@ class ATL_NO_VTABLE ComProxy DISALLOW_COPY_AND_ASSIGN(ComProxy); }; -#pragma warning(pop) - class StdMarshalInfo : public IStdMarshalInfo { public: explicit StdMarshalInfo(bool is_machine) : is_machine_(is_machine) { diff --git a/omaha/goopdate/com_register_shell.cc b/omaha/goopdate/com_register_shell.cc index ad811bc..a151dd8 100644 --- a/omaha/goopdate/com_register_shell.cc +++ b/omaha/goopdate/com_register_shell.cc @@ -26,10 +26,10 @@ #include "omaha/base/logging.h" #include "omaha/base/path.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/utils.h" #include "omaha/common/const_cmd_line.h" #include "omaha/common/goopdate_utils.h" +#include "omaha/third_party/smartany/scoped_any.h" // GoogleUpdate.exe is running in 32-bit mode and it cannot directly load // 64-bit COM server DLL for register/unregister purpose. So create this diff --git a/omaha/goopdate/com_wrapper_creator.h b/omaha/goopdate/com_wrapper_creator.h index f367e13..6c4bad6 100644 --- a/omaha/goopdate/com_wrapper_creator.h +++ b/omaha/goopdate/com_wrapper_creator.h @@ -21,18 +21,17 @@ #include #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "base/scoped_ptr_address.h" #include "base/utils.h" #include "goopdate/omaha3_idl.h" #include "omaha/goopdate/model_object.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { class AppBundle; -typedef shared_ptr ControllingPtr; +using ControllingPtr = typedef std::shared_ptr; // Generalizes the creation of COM wrappers for a given class T. // It requires: @@ -49,8 +48,10 @@ class ComWrapper : public CComObjectRootEx { ASSERT1(IsModelLockedByCaller(t->model())); - scoped_ptr t_com_object; - HRESULT hr = TComObject::CreateInstance(address(t_com_object)); + std::unique_ptr t_com_object; + TComObject* com_object_ptr = nullptr; + HRESULT hr = TComObject::CreateInstance(&com_object_ptr); + t_com_object.reset(com_object_ptr); if (FAILED(hr)) { return hr; } diff --git a/omaha/goopdate/crash.cc b/omaha/goopdate/crash.cc index 05d8549..6978e09 100644 --- a/omaha/goopdate/crash.cc +++ b/omaha/goopdate/crash.cc @@ -43,7 +43,6 @@ #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/base/vistautil.h" @@ -55,6 +54,7 @@ #include "omaha/common/lang.h" #include "omaha/common/stats_uploader.h" #include "omaha/goopdate/goopdate_metrics.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/crash_generation/client_info.h" #include "third_party/breakpad/src/client/windows/sender/crash_report_sender.h" @@ -254,8 +254,8 @@ HRESULT CrashReporter::UploadCrash(bool is_out_of_process, std::wstring report_code; CrashReportSender sender(checkpoint_file_.GetString()); sender.set_max_reports_per_day(max_reports_per_day_); - CORE_LOG(L2, (_T("[Uploading crash report]") - _T("[%s][%s]"), crash_report_url_, crash_filename)); + OPT_LOG(L2, (_T("[Uploading crash report]") + _T("[%s][%s]"), crash_report_url_, crash_filename)); ASSERT1(!crash_report_url_.IsEmpty()); std::map crash_files; crash_files[L"upload_file_minidump"] = crash_filename.GetString(); @@ -286,7 +286,7 @@ HRESULT CrashReporter::UploadCrash(bool is_out_of_process, default: hr = E_FAIL; break; - }; + } // Continue the retry loop only when it could not contact the server. if (res != google_breakpad::RESULT_FAILED) { @@ -294,7 +294,7 @@ HRESULT CrashReporter::UploadCrash(bool is_out_of_process, } } - CORE_LOG(L2, (_T("[crash report code = %s]"), *report_id)); + OPT_LOG(L2, (_T("[crash report code = %s]"), *report_id)); CString product_name = GetProductNameForEventLogging(parameters); diff --git a/omaha/goopdate/crash_unittest.cc b/omaha/goopdate/crash_unittest.cc index 5963c2a..dd97979 100644 --- a/omaha/goopdate/crash_unittest.cc +++ b/omaha/goopdate/crash_unittest.cc @@ -21,7 +21,6 @@ #include "omaha/base/const_object_names.h" #include "omaha/base/error.h" #include "omaha/base/file.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/time.h" #include "omaha/base/user_info.h" #include "omaha/base/utils.h" @@ -32,6 +31,7 @@ #include "omaha/common/goopdate_utils.h" #include "omaha/goopdate/crash.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/handler/exception_handler.h" // TODO(omaha): Modify the tests to avoid writing files to the staging diff --git a/omaha/goopdate/cred_dialog.cc b/omaha/goopdate/cred_dialog.cc index e7d60f2..ec61990 100644 --- a/omaha/goopdate/cred_dialog.cc +++ b/omaha/goopdate/cred_dialog.cc @@ -13,6 +13,7 @@ // limitations under the License. // ======================================================================== +#include #include #include "omaha/base/debug.h" #include "omaha/base/logging.h" diff --git a/omaha/goopdate/cred_dialog.h b/omaha/goopdate/cred_dialog.h index 531e868..6a9f4c9 100644 --- a/omaha/goopdate/cred_dialog.h +++ b/omaha/goopdate/cred_dialog.h @@ -27,10 +27,6 @@ namespace omaha { -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) - class ATL_NO_VTABLE CredentialDialogBase : public CComObjectRootEx, public ICredentialDialog, @@ -182,8 +178,6 @@ inline HRESULT LaunchCredentialDialog( return hr; } -#pragma warning(pop) - } // namespace omaha #endif // OMAHA_GOOPDATE_CRED_DIALOG_H_ diff --git a/omaha/goopdate/current_state.cc b/omaha/goopdate/current_state.cc index b3ca663..8986fb0 100644 --- a/omaha/goopdate/current_state.cc +++ b/omaha/goopdate/current_state.cc @@ -14,6 +14,8 @@ // ======================================================================== #include "omaha/goopdate/current_state.h" +#include +#include #include #include "omaha/base/debug.h" #include "omaha/base/logging.h" @@ -117,7 +119,8 @@ STDMETHODIMP CurrentAppState::get_bytesDownloaded(ULONG* bytes_downloaded) { ASSERT1(bytes_downloaded); // Firefox does not support uint32... - if (bytes_downloaded_ > kint32max) { + if (bytes_downloaded_ > + static_cast(std::numeric_limits::max())) { return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); } *bytes_downloaded = static_cast(bytes_downloaded_); @@ -129,7 +132,8 @@ STDMETHODIMP CurrentAppState::get_totalBytesToDownload( ASSERT1(total_bytes_to_download); // Firefox does not support uint32... - if (total_bytes_to_download_ > kint32max) { + if (total_bytes_to_download_ > + static_cast(std::numeric_limits::max())) { return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW); } *total_bytes_to_download = static_cast(total_bytes_to_download_); diff --git a/omaha/goopdate/current_state.h b/omaha/goopdate/current_state.h index ac0e743..db5e684 100644 --- a/omaha/goopdate/current_state.h +++ b/omaha/goopdate/current_state.h @@ -21,8 +21,8 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "goopdate/omaha3_idl.h" #include "omaha/base/atlregmapex.h" #include "omaha/base/constants.h" @@ -74,9 +74,6 @@ class ATL_NO_VTABLE CurrentAppState DECLARE_REGISTRY_RESOURCEID_EX(IDR_INPROC_SERVER_RGS) - #pragma warning(push) - // C4640: construction of local static object is not thread-safe - #pragma warning(disable : 4640) BEGIN_REGISTRY_MAP() REGMAP_ENTRY(_T("HKROOT"), is_machine() ? _T("HKLM") : _T("HKCU")) REGMAP_ENTRY(_T("CLSID"), GetObjectCLSID()) @@ -105,7 +102,6 @@ class ATL_NO_VTABLE CurrentAppState PROP_DATA_ENTRY("PostInstallUrl", post_install_url_, VT_BSTR) PROP_DATA_ENTRY("PostInstallAction", post_install_action_, VT_I4) END_PROP_MAP() - #pragma warning(pop) // ICurrentState. STDMETHOD(get_stateValue)(LONG* state_value); diff --git a/omaha/goopdate/dm_client.cc b/omaha/goopdate/dm_client.cc new file mode 100644 index 0000000..596c755 --- /dev/null +++ b/omaha/goopdate/dm_client.cc @@ -0,0 +1,393 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_client.h" + +#include +#include +#include + +#include "omaha/base/app_util.h" +#include "omaha/base/constants.h" +#include "omaha/base/debug.h" +#include "omaha/base/logging.h" +#include "omaha/base/omaha_version.h" +#include "omaha/base/safe_format.h" +#include "omaha/base/string.h" +#include "omaha/base/system_info.h" +#include "omaha/common/config_manager.h" +#include "omaha/common/goopdate_utils.h" +#include "omaha/common/url_utils.h" +#include "omaha/goopdate/dm_messages.h" +#include "omaha/goopdate/dm_storage.h" +#include "omaha/net/network_config.h" +#include "omaha/net/network_request.h" +#include "omaha/net/simple_request.h" + +namespace omaha { +namespace dm_client { + +RegistrationState GetRegistrationState(DmStorage* dm_storage) { + ASSERT1(dm_storage); + + if (!dm_storage->GetDmToken().IsEmpty()) { + return kRegistered; + } + + return dm_storage->GetEnrollmentToken().IsEmpty() + ? kNotManaged + : kRegistrationPending; +} + +// Log categories are used within this function as follows: +// OPT: diagnostic messages to be included in the log file in release builds. +// REPORT: error messages to be included in the Windows Event Log. +HRESULT RegisterIfNeeded(DmStorage* dm_storage) { + ASSERT1(dm_storage); + OPT_LOG(L1, (_T("[DmClient::RegisterIfNeeded]"))); + + // No work to be done if the process is not running as an administrator, since + // we will not be able to persist anything. + if (!::IsUserAnAdmin()) { + OPT_LOG(L1, (_T("[RegisterIfNeeded][Process not Admin, exiting early]"))); + return S_FALSE; + } + + // No work to be done if a DM token was found. + CStringA dm_token = dm_storage->GetDmToken(); + if (!dm_token.IsEmpty()) { + OPT_LOG(L1, (_T("[Device is already registered]"))); + return S_FALSE; + } + + // No work to be done if no enrollment token was found. + CString enrollment_token = dm_storage->GetEnrollmentToken(); + if (enrollment_token.IsEmpty()) { + OPT_LOG(L1, (_T("[No enrollment token found]"))); + return S_FALSE; + } + + // Cannot register if no device ID was found. + CString device_id = dm_storage->GetDeviceId(); + if (device_id.IsEmpty()) { + REPORT_LOG(LE, (_T("[Device ID not found]"))); + return E_FAIL; + } + + // RegisterWithRequest owns the SimpleRequest being created here. + HRESULT hr = internal::RegisterWithRequest(new SimpleRequest, + enrollment_token, + device_id, + &dm_token); + if (FAILED(hr)) { + return hr; + } + + hr = dm_storage->StoreDmToken(dm_token); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[StoreDmToken failed][%#x]"), hr)); + return hr; + } + + OPT_LOG(L1, (_T("[Registration complete]"))); + + return S_OK; +} + +HRESULT RefreshPolicies() { + // No work to be done if the process is not running as an administrator, since + // we will not be able to persist anything. + if (!::IsUserAnAdmin()) { + REPORT_LOG(L1, (_T("[RefreshPolicies][Process not Admin, exiting early]"))); + return S_FALSE; + } + + DmStorage* const dm_storage = DmStorage::Instance(); + const CString dm_token = CString(dm_storage->GetDmToken()); + if (dm_token.IsEmpty()) { + REPORT_LOG(L1, (_T("[Skipping RefreshPolicies as there is no DMToken]"))); + return S_FALSE; + } + + const CString device_id = dm_storage->GetDeviceId(); + if (device_id.IsEmpty()) { + REPORT_LOG(LE, (_T("[Device ID not found]"))); + return E_FAIL; + } + + const CPath policy_responses_dir( + ConfigManager::Instance()->GetPolicyResponsesDir()); + CachedPolicyInfo info; + HRESULT hr = DmStorage::ReadCachedPolicyInfoFile(policy_responses_dir, &info); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[ReadCachedPolicyInfoFile failed][%#x]"), hr)); + // Not fatal, continue. + } + + // FetchPolicies owns the SimpleRequest being created here. + PolicyResponses responses; + hr = internal::FetchPolicies(new SimpleRequest, + dm_token, + device_id, + info, + &responses); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[FetchPolicies failed][%#x]"), hr)); + return hr; + } + + hr = DmStorage::PersistPolicies(policy_responses_dir, responses); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[PersistPolicies failed][%#x]"), hr)); + return hr; + } + + REPORT_LOG(L1, (_T("[RefreshPolicies complete]"))); + + return S_OK; +} + +namespace internal { + +HRESULT RegisterWithRequest(HttpRequestInterface* http_request, + const CString& enrollment_token, + const CString& device_id, + CStringA* dm_token) { + ASSERT1(http_request); + ASSERT1(dm_token); + + std::vector> query_params = { + {_T("request"), _T("register_policy_agent")}, + }; + + // Make the request payload. + CStringA payload = SerializeRegisterBrowserRequest( + WideToUtf8(app_util::GetHostName()), + CStringA("Windows"), + internal::GetOsVersion()); + if (payload.IsEmpty()) { + REPORT_LOG(LE, (_T("[SerializeRegisterBrowserRequest failed]"))); + return E_FAIL; + } + + std::vector response; + HRESULT hr = SendDeviceManagementRequest( + http_request, + payload, + internal::FormatEnrollmentTokenAuthorizationHeader(enrollment_token), + device_id, + std::move(query_params), + &response); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[SendDeviceManagementRequest failed][%#x]"), hr)); + return hr; + } + + hr = ParseDeviceRegisterResponse(response, dm_token); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[ParseDeviceRegisterResponse failed][%#x]"), hr)); + return hr; + } + + return S_OK; +} + +HRESULT FetchPolicies(HttpRequestInterface* http_request, + const CString& dm_token, + const CString& device_id, + const CachedPolicyInfo& info, + PolicyResponses* responses) { + ASSERT1(http_request); + ASSERT1(!dm_token.IsEmpty()); + ASSERT1(responses); + + std::vector> query_params = { + {_T("request"), _T("policy")}, + }; + + CStringA payload = SerializePolicyFetchRequest( + CStringA(kGoogleUpdateMachineLevelApps), + info); + if (payload.IsEmpty()) { + REPORT_LOG(LE, (_T("[SerializePolicyFetchRequest failed]"))); + return E_FAIL; + } + + std::vector response; + HRESULT hr = SendDeviceManagementRequest( + http_request, + payload, + FormatDMTokenAuthorizationHeader(dm_token), + device_id, + std::move(query_params), + &response); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[SendDeviceManagementRequest failed][%#x]"), hr)); + return hr; + } + + hr = ParseDevicePolicyResponse(response, + info, + dm_token, + device_id, + responses); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[ParseDeviceRegisterResponse failed][%#x]"), hr)); + return hr; + } + + return S_OK; +} + +HRESULT SendDeviceManagementRequest( + HttpRequestInterface* http_request, + const CStringA& payload, + const CString& authorization_header, + const CString& device_id, + std::vector> query_params, + std::vector* response) { + ASSERT1(http_request); + ASSERT1(response); + + // Get the network configuration. + NetworkConfig* network_config = NULL; + NetworkConfigManager& network_config_manager = + NetworkConfigManager::Instance(); + HRESULT hr = network_config_manager.GetUserNetworkConfig(&network_config); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[GetUserNetworkConfig failed][%#x]"), hr)); + return hr; + } + + // Create a network request and configure its headers. + std::unique_ptr request( + new NetworkRequest(network_config->session())); + request->AddHeader(_T("Authorization"), authorization_header); + + // Set it up + request->AddHttpRequest(http_request); + + // Form the request URL with query params. + CString url; + hr = ConfigManager::Instance()->GetDeviceManagementUrl(&url); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[GetDeviceManagementUrl failed][%#x]"), hr)); + return hr; + } + + query_params.emplace_back(_T("agent"), internal::GetAgent()); + query_params.emplace_back(_T("apptype"), _T("Chrome")); + query_params.emplace_back(_T("deviceid"), device_id); + query_params.emplace_back(_T("platform"), internal::GetPlatform()); + + hr = internal::AppendQueryParamsToUrl(query_params, &url); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[AppendQueryParamsToUrl failed][%#x]"), hr)); + return hr; + } + + hr = request->Post(url, payload, payload.GetLength(), response); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[NetworkRequest::Post failed][%#x, %s]"), hr, url)); + return hr; + } + + const int http_status_code = request->http_status_code(); + if (http_status_code != 200) { + REPORT_LOG(LE, (_T("[NetworkRequest::Post failed][status code %d]"), + http_status_code)); + CStringA error_message; + hr = ParseDeviceManagementResponseError(*response, &error_message); + if (SUCCEEDED(hr)) { + REPORT_LOG(LE, (_T("[Server returned: %S]"), error_message)); + } + return E_FAIL; + } + + return S_OK; +} + +CString GetAgent() { + CString agent; + SafeCStringFormat(&agent, _T("%s %s()"), kAppName, GetVersionString()); + return agent; +} + +CString GetPlatform() { + const DWORD architecture = SystemInfo::GetProcessorArchitecture(); + + int major_version = 0; + int minor_version = 0; + int service_pack_major = 0; + int service_pack_minor = 0; + if (!SystemInfo::GetSystemVersion(&major_version, &minor_version, + &service_pack_major, &service_pack_minor)) { + major_version = 0; + minor_version = 0; + } + + CString platform; + SafeCStringFormat(&platform, _T("Windows NT|%s|%d.%d.0"), + architecture == PROCESSOR_ARCHITECTURE_AMD64 ? + _T("x86_64") : + (architecture == PROCESSOR_ARCHITECTURE_INTEL ? + _T("x86") : + _T("")), + major_version, minor_version); + return platform; +} + +CStringA GetOsVersion() { + CString os_version; + CString service_pack; + + if (FAILED(goopdate_utils::GetOSInfo(&os_version, &service_pack))) { + return "0.0.0.0"; + } + return WideToUtf8(os_version); +} + +HRESULT AppendQueryParamsToUrl( + const std::vector>& query_params, + CString* url) { + ASSERT1(url); + CString query; + HRESULT hr = BuildQueryString(query_params, &query); + if (FAILED(hr)) { + return hr; + } + + CString result; + SafeCStringFormat(&result, _T("%s?%s"), *url, query); + *url = result; + return S_OK; +} + +CString FormatEnrollmentTokenAuthorizationHeader( + const CString& token) { + CString header_value; + SafeCStringFormat(&header_value, _T("GoogleEnrollmentToken token=%s"), token); + return header_value; +} + +CString FormatDMTokenAuthorizationHeader( + const CString& token) { + CString header_value; + SafeCStringFormat(&header_value, _T("GoogleDMToken token=%s"), token); + return header_value; +} + +} // namespace internal +} // namespace dm_client +} // namespace omaha diff --git a/omaha/goopdate/dm_client.h b/omaha/goopdate/dm_client.h new file mode 100644 index 0000000..ad9dff7 --- /dev/null +++ b/omaha/goopdate/dm_client.h @@ -0,0 +1,95 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef OMAHA_GOOPDATE_DM_CLIENT_H__ +#define OMAHA_GOOPDATE_DM_CLIENT_H__ + +#include +#include +#include +#include +#include "omaha/goopdate/dm_messages.h" + +namespace omaha { + +class DmStorage; +class HttpRequestInterface; + +namespace dm_client { + +// The policy type that supports getting the policies for all Machine +// applications from the DMServer. +const char kGoogleUpdateMachineLevelApps[] = "google/machine-level-apps"; + +enum RegistrationState { + // This client appears to not be managed. In particular, neither a device + // management token nor an enrollment token can be found. + kNotManaged, + + // This client has an enrollment token available, but is not yet registered + // for device management (i.e., no device management token can be found). + kRegistrationPending, + + // This client is registered for cloud management. + kRegistered, +}; + +// Returns the registration state for the machine. +RegistrationState GetRegistrationState(DmStorage* dm_storage); + +// Returns S_OK if registration takes place and succeeds, S_FALSE if +// registration was not needed (either it has already been done, or no +// enrollment token is found), or a failure HRESULT in case of error. +HRESULT RegisterIfNeeded(DmStorage* dm_storage); + +// Retrieve and persist locally the policies from the Device Management Server. +HRESULT RefreshPolicies(); + +namespace internal { + +HRESULT RegisterWithRequest(HttpRequestInterface* http_request, + const CString& enrollment_token, + const CString& device_id, + CStringA* dm_token); + +// Fetch policies from the DMServer. The policies are returned in |responses| +// containing elements in the following format: +// {policy_type}=>{SerializeToString-PolicyFetchResponse}. +HRESULT FetchPolicies(HttpRequestInterface* http_request, + const CString& dm_token, + const CString& device_id, + const CachedPolicyInfo& info, + PolicyResponses* responses); + +HRESULT SendDeviceManagementRequest( + HttpRequestInterface* http_request, + const CStringA& payload, + const CString& authorization_header, + const CString& device_id, + std::vector> query_params, + std::vector* response); +CString GetAgent(); +CString GetPlatform(); +CStringA GetOsVersion(); +HRESULT AppendQueryParamsToUrl( + const std::vector>& query_params, + CString* url); +CString FormatEnrollmentTokenAuthorizationHeader(const CString& token); +CString FormatDMTokenAuthorizationHeader(const CString& token); + +} // namespace internal +} // namespace dm_client +} // namespace omaha + +#endif // OMAHA_GOOPDATE_DM_CLIENT_H__ diff --git a/omaha/goopdate/dm_client_unittest.cc b/omaha/goopdate/dm_client_unittest.cc new file mode 100644 index 0000000..9b7a469 --- /dev/null +++ b/omaha/goopdate/dm_client_unittest.cc @@ -0,0 +1,779 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_client.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/basictypes.h" +#include "crypto/rsa_private_key.h" +#include "crypto/signature_creator.h" +#include "gtest/gtest-matchers.h" +#include "omaha/base/scope_guard.h" +#include "omaha/base/string.h" +#include "omaha/common/config_manager.h" +#include "omaha/goopdate/dm_storage.h" +#include "omaha/goopdate/dm_storage_test_utils.h" +#include "omaha/net/http_request.h" +#include "omaha/testing/unit_test.h" +#include "wireless/android/enterprise/devicemanagement/proto/dm_api.pb.h" + +using ::testing::_; +using ::testing::AllArgs; +using ::testing::HasSubstr; +using ::testing::Return; + +// An adapter for Google Mock's HasSubstr matcher that operates on a CString +// argument. +MATCHER_P(CStringHasSubstr, substr, "") { + return ::testing::Value(std::wstring(arg), HasSubstr(substr)); +} + +namespace omaha { +namespace dm_client { + +namespace { + +// Signing private key data (for testing only) in DER-encoded PKCS8 format. +const uint8_t kSigningPrivateKey[] = { + 0x30, 0x82, 0x01, 0x55, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, + 0x01, 0x3f, 0x30, 0x82, 0x01, 0x3b, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, + 0xd9, 0xcd, 0xca, 0xcd, 0xc3, 0xea, 0xbe, 0x72, 0x79, 0x1c, 0x29, 0x37, + 0x39, 0x99, 0x1f, 0xd4, 0xb3, 0x0e, 0xf0, 0x7b, 0x78, 0x77, 0x0e, 0x05, + 0x3b, 0x65, 0x34, 0x12, 0x62, 0xaf, 0xa6, 0x8d, 0x33, 0xce, 0x78, 0xf8, + 0x47, 0x05, 0x1d, 0x98, 0xaa, 0x1b, 0x1f, 0x50, 0x05, 0x5b, 0x3c, 0x19, + 0x3f, 0x80, 0x83, 0x63, 0x63, 0x3a, 0xec, 0xcb, 0x2e, 0x90, 0x4f, 0xf5, + 0x26, 0x76, 0xf1, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x40, 0x64, + 0x29, 0xc2, 0xd9, 0x6b, 0xfe, 0xf9, 0x84, 0x75, 0x73, 0xe0, 0xf4, 0x77, + 0xb5, 0x96, 0xb0, 0xdf, 0x83, 0xc0, 0x4e, 0x57, 0xf1, 0x10, 0x6e, 0x91, + 0x89, 0x12, 0x30, 0x5e, 0x57, 0xff, 0x14, 0x59, 0x5f, 0x18, 0x86, 0x4e, + 0x4b, 0x17, 0x56, 0xfc, 0x8d, 0x40, 0xdd, 0x74, 0x65, 0xd3, 0xff, 0x67, + 0x64, 0xcb, 0x9c, 0xb4, 0x14, 0x8a, 0x06, 0xb7, 0x13, 0x45, 0x94, 0x16, + 0x7d, 0x3f, 0xe1, 0x02, 0x21, 0x00, 0xf6, 0x0f, 0x31, 0x6d, 0x06, 0xcc, + 0x3b, 0xa0, 0x44, 0x1f, 0xf5, 0xc2, 0x45, 0x2b, 0x10, 0x6c, 0xf9, 0x6f, + 0x8f, 0x87, 0x3d, 0xc0, 0x3b, 0x55, 0x13, 0x37, 0x80, 0xcd, 0x9f, 0xe1, + 0xb7, 0xd9, 0x02, 0x21, 0x00, 0xe2, 0x9a, 0x5f, 0xbf, 0x95, 0x74, 0xb5, + 0x7a, 0x6a, 0xa6, 0x97, 0xbd, 0x75, 0x8c, 0x97, 0x18, 0x24, 0xd6, 0x09, + 0xcd, 0xdc, 0xb5, 0x94, 0xbf, 0xe2, 0x78, 0xaa, 0x20, 0x47, 0x9f, 0x68, + 0x5d, 0x02, 0x21, 0x00, 0xaf, 0x8f, 0x97, 0x8c, 0x5a, 0xd5, 0x4d, 0x95, + 0xc4, 0x05, 0xa9, 0xab, 0xba, 0xfe, 0x46, 0xf1, 0xf9, 0xe7, 0x07, 0x59, + 0x4f, 0x4d, 0xe1, 0x07, 0x8a, 0x76, 0x87, 0x88, 0x2f, 0x13, 0x35, 0xc1, + 0x02, 0x20, 0x24, 0xc3, 0xd9, 0x2f, 0x13, 0x47, 0x99, 0x3e, 0x20, 0x59, + 0xa1, 0x1a, 0xeb, 0x1c, 0x81, 0x53, 0x38, 0x7e, 0xc5, 0x9e, 0x71, 0xe5, + 0xc0, 0x19, 0x95, 0xdb, 0xef, 0xf6, 0x46, 0xc8, 0x95, 0x3d, 0x02, 0x21, + 0x00, 0xaa, 0xb1, 0xff, 0x8a, 0xa2, 0xb2, 0x2b, 0xef, 0x9a, 0x83, 0x3f, + 0xc5, 0xbc, 0xd4, 0x6a, 0x07, 0xe8, 0xc7, 0x0b, 0x2e, 0xd4, 0x0f, 0xf8, + 0x98, 0x68, 0xe1, 0x04, 0xa8, 0x92, 0xd0, 0x10, 0xaa, +}; + +// SHA256 signature of the public key corresponding to private key +// kSigningPrivateKey for "example.com" domain signed with +// kPolicyVerificationKey. +const uint8_t kSigningPublicKeySignature[] = { + 0x97, 0xEB, 0x13, 0xE6, 0x6C, 0xE2, 0x7A, 0x2F, 0xC6, 0x6E, 0x68, 0x8F, + 0xED, 0x5B, 0x51, 0x08, 0x27, 0xF0, 0xA5, 0x97, 0x20, 0xEE, 0xE2, 0x9B, + 0x5B, 0x63, 0xA5, 0x9C, 0xAE, 0x41, 0xFD, 0x34, 0xC4, 0x2E, 0xEB, 0x63, + 0x10, 0x80, 0x0C, 0x74, 0x77, 0x6E, 0x34, 0x1C, 0x1B, 0x3B, 0x8E, 0x2A, + 0x3A, 0x7F, 0xF9, 0x73, 0xB6, 0x2B, 0xB6, 0x45, 0xDB, 0x05, 0xE8, 0x5A, + 0x68, 0x36, 0x05, 0x3C, 0x62, 0x3A, 0x6C, 0x64, 0xDB, 0x0E, 0x61, 0xBD, + 0x29, 0x1C, 0x61, 0x4B, 0xE0, 0xDA, 0x07, 0xBA, 0x29, 0x81, 0xF0, 0x90, + 0x58, 0xB8, 0xBB, 0xF4, 0x69, 0xFF, 0x8F, 0x2B, 0x4A, 0x2D, 0x98, 0x51, + 0x37, 0xF5, 0x52, 0xCB, 0xE3, 0xC4, 0x6D, 0xEC, 0xEA, 0x32, 0x2D, 0xDD, + 0xD7, 0xFC, 0x43, 0xC6, 0x54, 0xE1, 0xC1, 0x66, 0x43, 0x37, 0x09, 0xE1, + 0xBF, 0xD1, 0x11, 0xFC, 0xDB, 0xBF, 0xDF, 0x66, 0x53, 0x8F, 0x38, 0x2D, + 0xAA, 0x89, 0xD2, 0x9F, 0x60, 0x90, 0xB7, 0x05, 0xC2, 0x20, 0x82, 0xE6, + 0xE0, 0x57, 0x55, 0xFF, 0x5F, 0xC1, 0x76, 0x66, 0x46, 0xF8, 0x67, 0xB8, + 0x8B, 0x81, 0x53, 0xA9, 0x8B, 0x48, 0x9E, 0x2A, 0xF9, 0x60, 0x57, 0xBA, + 0xD7, 0x52, 0x97, 0x53, 0xF0, 0x2F, 0x78, 0x68, 0x50, 0x18, 0x12, 0x00, + 0x5E, 0x8E, 0x2A, 0x62, 0x0D, 0x48, 0xA9, 0xB5, 0x6B, 0xBC, 0xA0, 0x52, + 0x53, 0xD7, 0x65, 0x23, 0xA4, 0xA5, 0xF5, 0x32, 0x49, 0x2D, 0xB2, 0x77, + 0x2C, 0x66, 0x97, 0xBA, 0x58, 0xE0, 0x16, 0x1C, 0x8C, 0x02, 0x5D, 0xE0, + 0x73, 0x2E, 0xDF, 0xB4, 0x2F, 0x4C, 0xA2, 0x11, 0x26, 0xC1, 0xAF, 0xAC, + 0x73, 0xBC, 0xB6, 0x98, 0xE0, 0x20, 0x61, 0x0E, 0x52, 0x4A, 0x6C, 0x80, + 0xB5, 0x0C, 0x10, 0x80, 0x09, 0x17, 0xF4, 0x9D, 0xFE, 0xB5, 0xFC, 0x63, + 0x9A, 0x80, 0x3F, 0x76, +}; + +// New signing private key data (for testing only) in DER-encoded PKCS8 format. +const uint8_t kNewSigningPrivateKey[] = { + 0x30, 0x82, 0x01, 0x54, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, + 0x01, 0x3e, 0x30, 0x82, 0x01, 0x3a, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, + 0x99, 0x98, 0x6b, 0x79, 0x5d, 0x38, 0x33, 0x79, 0x27, 0x0a, 0x2e, 0xb0, + 0x89, 0xba, 0xf8, 0xf6, 0x80, 0xde, 0xb0, 0x79, 0xf2, 0xd4, 0x6d, 0xf7, + 0x3c, 0xa3, 0x97, 0xf6, 0x4a, 0x3c, 0xa5, 0xcc, 0x40, 0x8a, 0xef, 0x59, + 0xaa, 0xc2, 0x82, 0x8f, 0xbc, 0x0d, 0x5b, 0x63, 0xc6, 0xaa, 0x72, 0xe2, + 0xf3, 0x57, 0xdd, 0x74, 0x00, 0xb0, 0x42, 0xd6, 0x27, 0xe7, 0x17, 0x61, + 0x0a, 0xdc, 0xc1, 0xf7, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x40, 0x34, + 0xcf, 0xc9, 0xb4, 0x73, 0x2f, 0x0d, 0xd3, 0xcc, 0x6e, 0x9d, 0xdb, 0x29, + 0xa0, 0x56, 0x56, 0x3b, 0xbd, 0x56, 0x24, 0xb8, 0x2f, 0xfe, 0x97, 0x92, + 0x0c, 0x16, 0x06, 0x23, 0x44, 0x73, 0x25, 0x1d, 0x65, 0xf4, 0xda, 0x77, + 0xe7, 0x91, 0x2e, 0x91, 0x05, 0x10, 0xc1, 0x1b, 0x39, 0x5e, 0xb2, 0xf7, + 0xbd, 0x14, 0x19, 0xcb, 0x6b, 0xc3, 0xa9, 0xe8, 0x91, 0xf7, 0xa7, 0xa9, + 0x90, 0x08, 0x51, 0x02, 0x21, 0x00, 0xcc, 0x9e, 0x03, 0x54, 0x8f, 0x24, + 0xde, 0x90, 0x25, 0xec, 0x21, 0xaf, 0xe6, 0x27, 0x2a, 0x16, 0x42, 0x74, + 0xda, 0xf8, 0x84, 0xc4, 0x8c, 0x1e, 0x86, 0x12, 0x04, 0x5c, 0x17, 0x01, + 0xea, 0x9d, 0x02, 0x21, 0x00, 0xc0, 0x2a, 0x6c, 0xe9, 0xa1, 0x1a, 0x41, + 0x11, 0x94, 0x50, 0xf7, 0x1a, 0xd3, 0xbc, 0xf3, 0xa2, 0xf8, 0x46, 0xbc, + 0x26, 0x77, 0x78, 0xef, 0xc0, 0x54, 0xec, 0x22, 0x3f, 0x2c, 0x57, 0xe0, + 0xa3, 0x02, 0x20, 0x31, 0xf2, 0xc8, 0xa1, 0x55, 0xa8, 0x0c, 0x64, 0x67, + 0xbd, 0x72, 0xa3, 0xbb, 0xad, 0x07, 0xcb, 0x13, 0x41, 0xef, 0x4a, 0x07, + 0x2e, 0xeb, 0x7d, 0x70, 0x00, 0xe9, 0xeb, 0x88, 0xfa, 0x40, 0xc9, 0x02, + 0x20, 0x3a, 0xe0, 0xc4, 0xde, 0x10, 0x6e, 0x6a, 0xe1, 0x68, 0x00, 0x26, + 0xb6, 0x21, 0x8a, 0x13, 0x5c, 0x2b, 0x96, 0x00, 0xb0, 0x08, 0x8b, 0x15, + 0x6a, 0x68, 0x9a, 0xb1, 0x23, 0x8a, 0x02, 0xa2, 0xe1, 0x02, 0x21, 0x00, + 0xa3, 0xf2, 0x2d, 0x55, 0xc1, 0x6d, 0x40, 0xfa, 0x1d, 0xf7, 0xba, 0x86, + 0xef, 0x50, 0x98, 0xfc, 0xee, 0x09, 0xcc, 0xe7, 0x22, 0xb9, 0x4e, 0x80, + 0x32, 0x1a, 0x6b, 0xb3, 0x5f, 0x35, 0xbd, 0xf3, +}; + +// SHA256 signature of the public key corresponding to private key +// kNewSigningPrivateKey for "example.com" domain signed with +// kPolicyVerificationKey. +const uint8_t kNewSigningPublicKeySignature[] = { + 0x70, 0xED, 0x27, 0x42, 0x34, 0x69, 0xB6, 0x47, 0x9E, 0x7C, 0xA0, 0xF0, + 0xE5, 0x0A, 0x49, 0x49, 0x00, 0xDA, 0xBC, 0x70, 0x01, 0xC5, 0x4B, 0xDB, + 0x47, 0xD5, 0xAF, 0xA1, 0xAD, 0xB7, 0xE4, 0xE1, 0xBD, 0x5A, 0x1C, 0x35, + 0x44, 0x5A, 0xAA, 0xDB, 0x27, 0xBA, 0xA4, 0xA9, 0xC8, 0xDD, 0xEC, 0xD6, + 0xEB, 0xFE, 0xDB, 0xE0, 0x03, 0x5C, 0xA6, 0x2E, 0x5A, 0xEC, 0x75, 0x79, + 0xB8, 0x5F, 0x0A, 0xEE, 0x05, 0xB2, 0x61, 0xDC, 0x58, 0xF0, 0xD1, 0xCB, + 0x7B, 0x2A, 0xDB, 0xC1, 0x7C, 0x60, 0xE6, 0x3E, 0x87, 0x02, 0x61, 0xE6, + 0x90, 0xFD, 0x54, 0x65, 0xC7, 0xFF, 0x74, 0x09, 0xD6, 0xAA, 0x8E, 0xDC, + 0x5B, 0xC8, 0x38, 0x0C, 0x84, 0x0E, 0x84, 0x2E, 0x37, 0x2A, 0x4B, 0xDE, + 0x31, 0x82, 0x76, 0x1E, 0x77, 0xA5, 0xC1, 0xD5, 0xED, 0xFF, 0xBC, 0xEA, + 0x91, 0xB7, 0xBC, 0xFF, 0x76, 0x23, 0xE2, 0x78, 0x63, 0x01, 0x47, 0x80, + 0x47, 0x1F, 0x3A, 0x49, 0xBF, 0x0D, 0xCF, 0x27, 0x70, 0x92, 0xBB, 0xEA, + 0xB3, 0x92, 0x70, 0xFF, 0x1E, 0x4B, 0x1B, 0xE0, 0x4E, 0x0C, 0x4C, 0x6B, + 0x5D, 0x77, 0x06, 0xBB, 0xFB, 0x9B, 0x0E, 0x55, 0xB8, 0x8A, 0xF2, 0x45, + 0xA9, 0xF3, 0x54, 0x3D, 0x0C, 0xAC, 0xA8, 0x15, 0xD2, 0x31, 0x8D, 0x97, + 0x08, 0x73, 0xC9, 0x0F, 0x1D, 0xDE, 0x10, 0x22, 0xC6, 0x55, 0x53, 0x7F, + 0x7C, 0x50, 0x16, 0x5A, 0x08, 0xCC, 0x1C, 0x53, 0x9B, 0x02, 0xB8, 0x80, + 0xB7, 0x46, 0xF5, 0xF1, 0xC7, 0x3D, 0x36, 0xBD, 0x26, 0x02, 0xDE, 0x10, + 0xAB, 0x5A, 0x03, 0xCD, 0x67, 0x00, 0x1C, 0x23, 0xC7, 0x13, 0xEE, 0x5D, + 0xAF, 0xC5, 0x1F, 0xE3, 0xA0, 0x54, 0xAC, 0xC2, 0xC9, 0x44, 0xD4, 0x4A, + 0x09, 0x8E, 0xEB, 0xAE, 0xCA, 0x08, 0x8A, 0x7F, 0x41, 0x7B, 0xD8, 0x2C, + 0xDD, 0x6F, 0x80, 0xC3, +}; + +const char kDomain[] = "example.com"; +const char kUsername[] = "username@example.com"; +const char kDmToken[] = "dm_token"; +const TCHAR kDeviceId[] = _T("device_id"); + +// A Google Mock matcher that returns true if a string contains a valid +// URL to the device management server with the required query parameters. +class IsValidRequestUrlMatcher + : public ::testing::MatcherInterface { + public: + IsValidRequestUrlMatcher( + std::vector> query_params) + : query_params_(std::move(query_params)) { + ConfigManager::Instance()->GetDeviceManagementUrl(&device_management_url_); + } + + virtual bool MatchAndExplain(const CString& arg, + ::testing::MatchResultListener* listener) const { + // Verify that the base of the URL is the device management server's + // endpoint. + int scan = 0; + CString url = arg.Tokenize(_T("?"), scan); + if (url != device_management_url_) { + *listener << "the base url is " << WideToUtf8(url); + return false; + } + + // Extract the query params from the URL. + std::map query_params; + CString param = arg.Tokenize(_T("&"), scan); + while (!param.IsEmpty()) { + int eq = param.Find('=', 0); + if (eq == -1) { + query_params[param] = CString(); + } else { + query_params[param.Left(eq)] = param.Right(param.GetLength() - eq - 1); + } + param = arg.Tokenize(_T("&"), scan); + } + + // Check that the required params are present. + for (const auto& query_param : query_params_) { + const TCHAR* p = query_param.first; + if (query_params.find(p) == query_params.end()) { + *listener << "the url is missing the \"" << WideToUtf8(p) + << "\" query parameter"; + return false; + } + + CString expected_param_value; + HRESULT hr = StringEscape(query_param.second, + false, + &expected_param_value); + if (FAILED(hr)) { + *listener << "failed to StringEscape \"" + << WideToUtf8(query_param.second) + << "\" query parameter"; + return false; + } + + if (query_params[p] != expected_param_value) { + *listener << "the actual request query parameter is \"" + << WideToUtf8(query_params[p]) << "\"" + << " and does not match the expected query parameter of \"" + << WideToUtf8(expected_param_value) << "\""; + return false; + } + } + + return true; + } + + virtual void DescribeTo(std::ostream* os) const { + *os << "string contains a valid device management request URL"; + } + + private: + const std::vector> query_params_; + CString device_management_url_; +}; + +// Returns an IsValidRequestUrl matcher, which takes a CString and matches if +// it is an URL leading to the device management server endpoint, and contains +// all the required query parameters in |query_params|. +::testing::Matcher IsValidRequestUrl( + std::vector> query_params) { + return ::testing::MakeMatcher( + new IsValidRequestUrlMatcher(std::move(query_params))); +} + +// A Google Mock matcher that returns true if a buffer contains a valid +// serialized RegisterBrowserRequest message. While the presence of each field +// in the request is checked, the exact value of each is not. +class IsRegisterBrowserRequestMatcher + : public ::testing::MatcherInterface& > { + public: + virtual bool MatchAndExplain( + const ::testing::tuple& buffer, + ::testing::MatchResultListener* listener) const { + enterprise_management::DeviceManagementRequest request; + if (!request.ParseFromArray( + ::testing::get<0>(buffer), + static_cast(::testing::get<1>(buffer)))) { + *listener << "parse failure"; + return false; + } + if (!request.has_register_browser_request()) { + *listener << "missing register_browser_request"; + return false; + } + const enterprise_management::RegisterBrowserRequest& register_request = + request.register_browser_request(); + if (!register_request.has_machine_name()) { + *listener << "missing register_browser_request.machine_name"; + return false; + } + if (!register_request.has_os_platform()) { + *listener << "missing register_browser_request.os_platform"; + return false; + } + if (!register_request.has_os_version()) { + *listener << "missing register_browser_request.os_version"; + return false; + } + return true; + } + + virtual void DescribeTo(std::ostream* os) const { + *os << "buffer contains a valid serialized RegisterBrowserRequest"; + } +}; + +// A Google Mock matcher that returns true if a buffer contains a valid +// serialized DevicePolicyRequest message. While the presence of each field +// in the request is checked, the exact value of each is not. +class IsFetchPoliciesRequestMatcher + : public ::testing::MatcherInterface& > { + public: + virtual bool MatchAndExplain( + const ::testing::tuple& buffer, + ::testing::MatchResultListener* listener) const { + enterprise_management::DeviceManagementRequest request; + if (!request.ParseFromArray( + ::testing::get<0>(buffer), + static_cast(::testing::get<1>(buffer)))) { + *listener << "parse failure"; + return false; + } + if (!request.has_policy_request()) { + *listener << "missing policy_request"; + return false; + } + if (!request.policy_request().requests_size()) { + *listener << "unexpected requests_size() == 0"; + return false; + } + const enterprise_management::PolicyFetchRequest& policy_request = + request.policy_request().requests(0); + if (!policy_request.has_policy_type()) { + *listener << "missing policy_request.has_policy_type"; + return false; + } + if (!policy_request.has_signature_type()) { + *listener << "missing policy_request.has_signature_type"; + return false; + } + if (!policy_request.has_verification_key_hash()) { + *listener << "missing policy_request.has_verification_key_hash"; + return false; + } + return true; + } + + + virtual void DescribeTo(std::ostream* os) const { + *os << "buffer contains a valid serialized DevicePolicyRequest"; + } +}; + +// Returns an IsRegisterBrowserRequest matcher, which takes a tuple of a pointer +// to a buffer and a buffer size. +::testing::Matcher& > +IsRegisterBrowserRequest() { + return ::testing::MakeMatcher(new IsRegisterBrowserRequestMatcher); +} + +// Returns an IsFetchPoliciesRequest matcher, which takes a tuple of a pointer +// to a buffer and a buffer size. +::testing::Matcher& > +IsFetchPoliciesRequest() { + return ::testing::MakeMatcher(new IsFetchPoliciesRequestMatcher); +} + +class MockHttpRequest : public HttpRequestInterface { + public: + MOCK_METHOD0(Close, HRESULT()); + MOCK_METHOD0(Send, HRESULT()); + MOCK_METHOD0(Cancel, HRESULT()); + MOCK_METHOD0(Pause, HRESULT()); + MOCK_METHOD0(Resume, HRESULT()); + MOCK_CONST_METHOD0(GetResponse, std::vector()); + MOCK_CONST_METHOD0(GetHttpStatusCode, int()); + MOCK_CONST_METHOD3(QueryHeadersString, + HRESULT(uint32 info_level, + const TCHAR* name, + CString* value)); + MOCK_CONST_METHOD0(GetResponseHeaders, CString()); + MOCK_CONST_METHOD0(ToString, CString()); + MOCK_METHOD1(set_session_handle, void(HINTERNET session_handle)); + MOCK_METHOD1(set_url, void(const CString& url)); + MOCK_METHOD2(set_request_buffer, void(const void* buffer, + size_t buffer_length)); + MOCK_METHOD1(set_proxy_configuration, void(const ProxyConfig& proxy_config)); + MOCK_METHOD1(set_filename, void(const CString& filename)); + MOCK_METHOD1(set_low_priority, void(bool low_priority)); + MOCK_METHOD1(set_callback, void(NetworkRequestCallback* callback)); + MOCK_METHOD1(set_additional_headers, void(const CString& additional_headers)); + MOCK_CONST_METHOD0(user_agent, CString()); + MOCK_METHOD1(set_user_agent, void(const CString& user_agent)); + MOCK_METHOD1(set_proxy_auth_config, void(const ProxyAuthConfig& config)); + MOCK_CONST_METHOD1(download_metrics, bool(DownloadMetrics* download_metrics)); +}; + +} // namespace + +// A test harness for testing DmClient request/response handling. +class DmClientRequestTest : public ::testing::Test { + protected: + DmClientRequestTest() {} + virtual ~DmClientRequestTest() {} + + // Populates |request| with a mock HttpRequest that behaves as if the server + // successfully processed a HTTP request, returning a HTTP response containing + // |response_data|. + // Note: always wrap calls to this with ASSERT_NO_FATAL_FAILURE. + template + void MakeSuccessHttpRequest(T response_data, MockHttpRequest** request) { + *request = new ::testing::NiceMock(); + + // The server responds with 200. + ON_CALL(**request, GetHttpStatusCode()) + .WillByDefault(Return(HTTP_STATUS_OK)); + + // And a valid response. + std::vector response; + ASSERT_NO_FATAL_FAILURE(MakeSuccessResponseBody(response_data, &response)); + ON_CALL(**request, GetResponse()).WillByDefault(Return(response)); + } + + struct KeyInfo { + const std::unique_ptr& signing_private_key; + const std::string& signing_public_key; + const std::string& signing_public_key_signature; + const std::unique_ptr& cached_signing_private_key; + }; + + struct FetchPoliciesInput { + const std::unique_ptr& key_info; + const PolicyResponses& responses; + }; + + void RunFetchPolicies(const std::unique_ptr& key_info, + CachedPolicyInfo* info) { + ASSERT_TRUE(info); + + PolicyResponsesMap expected_responses = { + {"google/chrome/machine-level-user", "test-data-chrome"}, + {"google/drive/machine-level-user", "test-data-drive"}, + {"google/earth/machine-level-user", "test-data-earth"}, + }; + + enterprise_management::PublicKeyVerificationData signed_data; + signed_data.set_new_public_key(key_info->signing_public_key); + signed_data.set_domain(kDomain); + + PolicyResponses input = {expected_responses, + signed_data.SerializeAsString()}; + FetchPoliciesInput fetch_input = {key_info, input}; + MockHttpRequest* mock_http_request = nullptr; + ASSERT_NO_FATAL_FAILURE(MakeSuccessHttpRequest(fetch_input, + &mock_http_request)); + + std::vector> query_params = { + {_T("request"), _T("policy")}, + {_T("agent"), internal::GetAgent()}, + {_T("apptype"), _T("Chrome")}, + {_T("deviceid"), kDeviceId}, + {_T("platform"), internal::GetPlatform()}, + }; + + // Expect the proper URL with query params. + EXPECT_CALL(*mock_http_request, + set_url(IsValidRequestUrl(std::move(query_params)))); + + // Expect that the request headers contain the DMToken. + EXPECT_CALL(*mock_http_request, + set_additional_headers( + CStringHasSubstr(_T("Authorization: GoogleDMToken ") + _T("token=dm_token")))); + + // Expect that the body of the request contains a well-formed fetch policies + // request. + EXPECT_CALL(*mock_http_request, set_request_buffer(_, _)) + .With(AllArgs(IsFetchPoliciesRequest())); + + // Fetch Policies should succeed, providing the expected PolicyResponses. + PolicyResponses responses; + ASSERT_HRESULT_SUCCEEDED(internal::FetchPolicies(mock_http_request, + CString(kDmToken), + kDeviceId, + *info, + &responses)); + ASSERT_TRUE(!responses.policy_info.empty()); + ASSERT_HRESULT_SUCCEEDED(GetCachedPolicyInfo(responses.policy_info, info)); + + EXPECT_EQ(expected_responses.size(), responses.responses.size()); + for (const auto& expected_response : expected_responses) { + enterprise_management::PolicyFetchResponse response; + const std::string& string_response = + responses.responses[expected_response.first.c_str()]; + EXPECT_TRUE(response.ParseFromString(string_response)); + + enterprise_management::PolicyData policy_data; + EXPECT_TRUE(policy_data.ParseFromString(response.policy_data())); + EXPECT_TRUE(policy_data.IsInitialized()); + EXPECT_TRUE(policy_data.has_policy_type()); + + EXPECT_STREQ(expected_response.first.c_str(), + policy_data.policy_type().c_str()); + EXPECT_STREQ(expected_response.second.c_str(), + policy_data.policy_value().c_str()); + } + } + + std::unique_ptr CreateKey( + const uint8_t* private_key, + size_t private_key_length, + std::string* rsa_public_key) { + std::vector input(private_key, private_key + private_key_length); + std::unique_ptr rsa_private_key( + crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(input)); + ASSERT1(rsa_private_key.get()); + + if (rsa_public_key) { + std::vector public_key; + ASSERT1(rsa_private_key->ExportPublicKey(&public_key)); + + *rsa_public_key = std::string( + reinterpret_cast(public_key.data()), + public_key.size()); + ASSERT1(rsa_public_key->length()); + } + + return std::move(rsa_private_key); + } + + private: + // Produces |key|'s signature over |data| and stores it in |signature|. + void SignData(const std::string& data, + crypto::RSAPrivateKey* key, + std::string* signature) { + std::unique_ptr signature_creator( + crypto::SignatureCreator::Create(key, CALG_SHA1)); + ASSERT_TRUE(signature_creator->Update( + reinterpret_cast(data.c_str()), data.size())); + std::vector signature_bytes; + ASSERT_TRUE(signature_creator->Final(&signature_bytes)); + signature->assign(reinterpret_cast(signature_bytes.data()), + signature_bytes.size()); + } + + void SignPolicyResponse(enterprise_management::PolicyFetchResponse* response, + const std::unique_ptr& key_info) { + ASSERT_TRUE(response); + ASSERT_TRUE(key_info->signing_private_key.get()); + + // Add the new public key and the corresponding verification key signature + // to the policy response. + response->set_new_public_key(key_info->signing_public_key); + response->set_new_public_key_verification_data_signature( + key_info->signing_public_key_signature); + + enterprise_management::PublicKeyVerificationData signed_data; + signed_data.set_new_public_key(key_info->signing_public_key); + signed_data.set_domain(kDomain); + response->set_new_public_key_verification_data( + signed_data.SerializeAsString()); + + // Add the PolicyData signature to the policy response. + SignData(response->policy_data(), + key_info->signing_private_key.get(), + response->mutable_policy_data_signature()); + + if (key_info->cached_signing_private_key.get()) { + // Use the cached private key to sign the new public key and add the + // signature to the policy response. + SignData(response->new_public_key(), + key_info->cached_signing_private_key.get(), + response->mutable_new_public_key_signature()); + } + } + + // Populates |body| with a valid serialized DeviceRegisterResponse. + // Note: always wrap calls to this with ASSERT_NO_FATAL_FAILURE. + void MakeSuccessResponseBody(const char* dm_token, std::vector* body) { + enterprise_management::DeviceManagementResponse dm_response; + dm_response.mutable_register_response()-> + set_device_management_token(dm_token); + std::string response_string; + ASSERT_TRUE(dm_response.SerializeToString(&response_string)); + body->assign(response_string.begin(), response_string.end()); + } + + // Populates |body| with a valid serialized DevicePolicyResponse. + // Note: always wrap calls to this with ASSERT_NO_FATAL_FAILURE. + void MakeSuccessResponseBody(const FetchPoliciesInput& fetch_input, + std::vector* body) { + const PolicyResponses& input = fetch_input.responses; + const PolicyResponsesMap& responses = input.responses; + + enterprise_management::DeviceManagementResponse dm_response; + + for (const auto& response : responses) { + enterprise_management::PolicyFetchResponse* policy_response = + dm_response.mutable_policy_response()->add_responses(); + enterprise_management::PolicyData policy_data; + policy_data.set_policy_type(response.first); + policy_data.set_policy_value(response.second); + policy_data.set_username(kUsername); + policy_data.set_request_token(kDmToken); + policy_data.set_device_id(CStringA(kDeviceId)); + policy_data.set_timestamp(time(NULL)); + policy_response->set_policy_data(policy_data.SerializeAsString()); + SignPolicyResponse(policy_response, fetch_input.key_info); + } + + std::string response_string; + ASSERT_TRUE(dm_response.SerializeToString(&response_string)); + body->assign(response_string.begin(), response_string.end()); + } + + DISALLOW_COPY_AND_ASSIGN(DmClientRequestTest); +}; + +// Test that DmClient can send a reasonable RegisterBrowserRequest and handle a +// corresponding DeviceRegisterResponse. +TEST_F(DmClientRequestTest, RegisterWithRequest) { + MockHttpRequest* mock_http_request = nullptr; + ASSERT_NO_FATAL_FAILURE(MakeSuccessHttpRequest(kDmToken, &mock_http_request)); + + std::vector> query_params = { + {_T("request"), _T("register_policy_agent")}, + {_T("agent"), internal::GetAgent()}, + {_T("apptype"), _T("Chrome")}, + {_T("deviceid"), kDeviceId}, + {_T("platform"), internal::GetPlatform()}, + }; + + // Expect the proper URL with query params. + EXPECT_CALL(*mock_http_request, + set_url(IsValidRequestUrl(std::move(query_params)))); + + // Expect that the request headers contain the enrollment token. + EXPECT_CALL(*mock_http_request, + set_additional_headers( + CStringHasSubstr(_T("Authorization: GoogleEnrollmentToken ") + _T("token=enrollment_token")))); + + // Expect that the body of the request contains a well-formed register browser + // request. + EXPECT_CALL(*mock_http_request, set_request_buffer(_, _)) + .With(AllArgs(IsRegisterBrowserRequest())); + + // Registration should succeed, providing the expected DMToken. + CStringA dm_token; + ASSERT_HRESULT_SUCCEEDED(internal::RegisterWithRequest(mock_http_request, + _T("enrollment_token"), + kDeviceId, + &dm_token)); + EXPECT_STREQ(dm_token.GetString(), kDmToken); +} + +// Test that DmClient can send a reasonable DevicePolicyRequest and handle a +// corresponding DevicePolicyResponse. +TEST_F(DmClientRequestTest, FetchPolicies) { + std::string signing_public_key; + const std::unique_ptr signing_private_key( + std::move(CreateKey(kSigningPrivateKey, + sizeof(kSigningPrivateKey), + &signing_public_key))); + const std::string signing_public_key_signature( + reinterpret_cast(kSigningPublicKeySignature), + sizeof(kSigningPublicKeySignature)); + const std::unique_ptr signing_key_info( + std::make_unique(KeyInfo{signing_private_key, + signing_public_key, + signing_public_key_signature, + nullptr})); + + std::string new_signing_public_key; + const std::unique_ptr new_signing_private_key( + std::move(CreateKey(kNewSigningPrivateKey, + sizeof(kNewSigningPrivateKey), + &new_signing_public_key))); + const std::string new_signing_public_key_signature( + reinterpret_cast(kNewSigningPublicKeySignature), + sizeof(kNewSigningPublicKeySignature)); + const std::unique_ptr new_signing_key_info( + std::make_unique(KeyInfo{new_signing_private_key, + new_signing_public_key, + new_signing_public_key_signature, + signing_private_key})); + + CachedPolicyInfo info; + + // The mock server will return PolicyData signed with kSigningPrivateKey, and + // a new public key corresponding to kSigningPrivateKey, signed with the + // hard-coded verification key. + RunFetchPolicies(signing_key_info, &info); + + // |info| was initialized in the previous run with the signing public key. Now + // the mock server will return PolicyData signed with kNewSigningPrivateKey, + // and a new public key corresponding to kNewSigningPrivateKey, signed with + // both the hard-coded verification key as well as with the previous private + // key kSigningPrivateKey. + RunFetchPolicies(new_signing_key_info, &info); +} + +class DmClientRegistryTest : public RegistryProtectedTest { +}; + +TEST_F(DmClientRegistryTest, GetRegistrationState) { + // No enrollment token. + { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kNotManaged); + } + + // Enrollment token without device management token. + { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(_T("enrollment_token"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), + kRegistrationPending); + } + + // Enrollment token and device management token. + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken("dm_token")); + { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(_T("enrollment_token"))); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kRegistered); + } + + // Device management token without enrollment token. + { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_EQ(GetRegistrationState(DmStorage::Instance()), kRegistered); + } +} + +TEST(DmClientTest, GetAgent) { + EXPECT_FALSE(internal::GetAgent().IsEmpty()); +} + +TEST(DmClientTest, GetPlatform) { + EXPECT_FALSE(internal::GetPlatform().IsEmpty()); +} + +TEST(DmClientTest, GetOsVersion) { + EXPECT_FALSE(internal::GetOsVersion().IsEmpty()); +} + +TEST(DmClientTest, AppendQueryParamsToUrl) { + static const TCHAR kUrl[] = _T("https://some.net/endpoint"); + std::vector> params = { + {_T("one"), _T("1")}, + {_T("2"), _T("two")}, + }; + + CString url(kUrl); + EXPECT_HRESULT_SUCCEEDED(internal::AppendQueryParamsToUrl(params, &url)); + EXPECT_EQ(url, CString(kUrl) + _T("?one=1&2=two")); +} + +TEST(DmClientTest, FormatEnrollmentTokenAuthorizationHeader) { + static const TCHAR kToken[] = _T("token"); + EXPECT_EQ(internal::FormatEnrollmentTokenAuthorizationHeader(kToken), + _T("GoogleEnrollmentToken token=token")); +} + +TEST(DmClientTest, FormatDMTokenAuthorizationHeader) { + static const TCHAR kToken[] = _T("token"); + EXPECT_EQ(internal::FormatDMTokenAuthorizationHeader(kToken), + _T("GoogleDMToken token=token")); +} + +} // namespace dm_client +} // namespace omaha diff --git a/omaha/goopdate/dm_messages.cc b/omaha/goopdate/dm_messages.cc new file mode 100644 index 0000000..515274f --- /dev/null +++ b/omaha/goopdate/dm_messages.cc @@ -0,0 +1,476 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_messages.h" + +#include +#include + +#include "crypto/signature_verifier_win.h" +#include "omaha/base/debug.h" +#include "omaha/base/logging.h" +#include "wireless/android/enterprise/devicemanagement/proto/dm_api.pb.h" + +namespace omaha { + +namespace { + +// Request signed policy blobs. kPolicyVerificationKeyHash and +// kPolicyVerificationKey need to be kept in sync with the corresponding values +// in Chromium's cloud_policy_constants.cc. +constexpr char kPolicyVerificationKeyHash[] = "1:356l7w"; +const uint8_t kPolicyVerificationKey[] = { + 0x30, 0x82, 0x01, 0x22, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, + 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0F, 0x00, + 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xA7, 0xB3, 0xF9, + 0x0D, 0xC7, 0xC7, 0x8D, 0x84, 0x3D, 0x4B, 0x80, 0xDD, 0x9A, 0x2F, 0xF8, + 0x69, 0xD4, 0xD1, 0x14, 0x5A, 0xCA, 0x04, 0x4B, 0x1C, 0xBC, 0x28, 0xEB, + 0x5E, 0x10, 0x01, 0x36, 0xFD, 0x81, 0xEB, 0xE4, 0x3C, 0x16, 0x40, 0xA5, + 0x8A, 0xE6, 0x08, 0xEE, 0xEF, 0x39, 0x1F, 0x6B, 0x10, 0x29, 0x50, 0x84, + 0xCE, 0xEE, 0x33, 0x5C, 0x48, 0x4A, 0x33, 0xB0, 0xC8, 0x8A, 0x66, 0x0D, + 0x10, 0x11, 0x9D, 0x6B, 0x55, 0x4C, 0x9A, 0x62, 0x40, 0x9A, 0xE2, 0xCA, + 0x21, 0x01, 0x1F, 0x10, 0x1E, 0x7B, 0xC6, 0x89, 0x94, 0xDA, 0x39, 0x69, + 0xBE, 0x27, 0x28, 0x50, 0x5E, 0xA2, 0x55, 0xB9, 0x12, 0x3C, 0x79, 0x6E, + 0xDF, 0x24, 0xBF, 0x34, 0x88, 0xF2, 0x5E, 0xD0, 0xC4, 0x06, 0xEE, 0x95, + 0x6D, 0xC2, 0x14, 0xBF, 0x51, 0x7E, 0x3F, 0x55, 0x10, 0x85, 0xCE, 0x33, + 0x8F, 0x02, 0x87, 0xFC, 0xD2, 0xDD, 0x42, 0xAF, 0x59, 0xBB, 0x69, 0x3D, + 0xBC, 0x77, 0x4B, 0x3F, 0xC7, 0x22, 0x0D, 0x5F, 0x72, 0xC7, 0x36, 0xB6, + 0x98, 0x3D, 0x03, 0xCD, 0x2F, 0x68, 0x61, 0xEE, 0xF4, 0x5A, 0xF5, 0x07, + 0xAE, 0xAE, 0x79, 0xD1, 0x1A, 0xB2, 0x38, 0xE0, 0xAB, 0x60, 0x5C, 0x0C, + 0x14, 0xFE, 0x44, 0x67, 0x2C, 0x8A, 0x08, 0x51, 0x9C, 0xCD, 0x3D, 0xDB, + 0x13, 0x04, 0x57, 0xC5, 0x85, 0xB6, 0x2A, 0x0F, 0x02, 0x46, 0x0D, 0x2D, + 0xCA, 0xE3, 0x3F, 0x84, 0x9E, 0x8B, 0x8A, 0x5F, 0xFC, 0x4D, 0xAA, 0xBE, + 0xBD, 0xE6, 0x64, 0x9F, 0x26, 0x9A, 0x2B, 0x97, 0x69, 0xA9, 0xBA, 0x0B, + 0xBD, 0x48, 0xE4, 0x81, 0x6B, 0xD4, 0x4B, 0x78, 0xE6, 0xAF, 0x95, 0x66, + 0xC1, 0x23, 0xDA, 0x23, 0x45, 0x36, 0x6E, 0x25, 0xF3, 0xC7, 0xC0, 0x61, + 0xFC, 0xEC, 0x66, 0x9D, 0x31, 0xD4, 0xD6, 0xB6, 0x36, 0xE3, 0x7F, 0x81, + 0x87, 0x02, 0x03, 0x01, 0x00, 0x01}; + +void SerializeToCStringA(const ::google::protobuf_opensource::Message& message, + CStringA* output) { + ASSERT1(output); + output->Empty(); + size_t byte_size = message.ByteSizeLong(); + if (byte_size > static_cast(std::numeric_limits::max())) { + return; + } + ::google::protobuf_opensource::uint8* buffer = + reinterpret_cast<::google::protobuf_opensource::uint8*>( + output->GetBufferSetLength(static_cast(byte_size))); + ::google::protobuf_opensource::uint8* end = + message.SerializeWithCachedSizesToArray(buffer); + output->ReleaseBufferSetLength(end - buffer); +} + +std::string GetPolicyVerificationKey() { + return std::string(reinterpret_cast(kPolicyVerificationKey), + sizeof(kPolicyVerificationKey)); +} + +bool VerifySignature(const std::string& data, + const std::string& key, + const std::string& signature, + ALG_ID algorithm_id) { + crypto::SignatureVerifierWin verifier; + if (!verifier.VerifyInit(algorithm_id, + reinterpret_cast(signature.data()), + signature.size(), + reinterpret_cast(key.data()), + key.size())) { + REPORT_LOG(LE, (_T("[VerifySignature][Invalid signature/key]"))); + return false; + } + + verifier.VerifyUpdate(reinterpret_cast(data.data()), + data.size()); + + return verifier.VerifyFinal(); +} + +// Verifies that the |new_public_key_verification_data_signature| verifies with +// the hardcoded |GetPolicyVerificationKey()| for the |new_public_key| in +// |fetch_response|. +bool CheckNewPublicKeyVerificationSignature( + const enterprise_management::PolicyFetchResponse& fetch_response) { + if (!fetch_response.has_new_public_key_verification_data() || + !fetch_response.has_new_public_key_verification_data_signature()) { + REPORT_LOG(LE, (_T("[CheckNewPublicKeyVerificationSignature]") + _T("[Policy missing new_public_key_verification_data or signature]"))); + return false; + } + + if (!VerifySignature( + fetch_response.new_public_key_verification_data(), + GetPolicyVerificationKey(), + fetch_response.new_public_key_verification_data_signature(), + CALG_SHA_256)) { + REPORT_LOG(LE, (_T("[CheckNewPublicKeyVerificationSignature]") + _T("[Signature verification failed]"))); + return false; + } + + return true; +} + +// We expect to return the cached public key for policy data validation, unless +// there is a new public key in the response, in which case we first validate +// the new public key and then return the new public key for the policy data +// validation. +HRESULT ValidateNewPublicKey( + const enterprise_management::PolicyFetchResponse& fetch_response, + const std::string& cached_public_key, + std::string* signature_key) { + ASSERT1(signature_key); + + if (!fetch_response.has_new_public_key_verification_data()) { + if (cached_public_key.empty()) { + REPORT_LOG(LE, (_T("[ValidateNewPublicKey]") + _T("[No public key cached or in response]"))); + return E_FAIL; + } + + *signature_key = cached_public_key; + return S_OK; + } + + // Validate new_public_key() against the hard-coded verification key. + if (!CheckNewPublicKeyVerificationSignature(fetch_response)) { + return E_FAIL; + } + + enterprise_management::PublicKeyVerificationData public_key_data; + + if (!public_key_data.ParseFromString( + fetch_response.new_public_key_verification_data())) { + REPORT_LOG(LE, (_T("[ValidateNewPublicKey][Failed to deserialize key]"))); + return E_FAIL; + } + + // Also validate new_public_key() against the cached_public_key, if the + // latter exists. + if (!cached_public_key.empty()) { + if (!fetch_response.has_new_public_key_signature() || + !VerifySignature(public_key_data.new_public_key(), + cached_public_key, + fetch_response.new_public_key_signature(), + CALG_SHA1)) { + REPORT_LOG(LE, (_T("[ValidateNewPublicKey]") + _T("[Verification against cached public key failed]"))); + return E_FAIL; + } + } + + // Now that the new public key has been successfully verified, we rotate to + // use it for future policy data validation. + *signature_key = public_key_data.new_public_key(); + + return S_OK; +} + +HRESULT ValidateDMToken(const enterprise_management::PolicyData& policy_data, + const CString& dm_token) { + if (!policy_data.has_request_token()) { + REPORT_LOG(LW, (_T("[ValidateDMToken][No DMToken in PolicyData]"))); + return E_FAIL; + } + + CString received_token(policy_data.request_token().c_str()); + if (dm_token.CompareNoCase(received_token)) { + REPORT_LOG(LE, (_T("[ValidateDMToken][Unexpected DMToken]") + _T("[Expected][%s][Got][%s]"), dm_token, received_token)); + return E_FAIL; + } + + return S_OK; +} + +HRESULT ValidateDeviceId(const enterprise_management::PolicyData& policy_data, + const CString& device_id) { + if (!policy_data.has_device_id()) { + REPORT_LOG(LW, (_T("[ValidateDeviceId][No Device Id in PolicyData]"))); + return E_FAIL; + } + + CString received_id(policy_data.device_id().c_str()); + if (device_id.CompareNoCase(received_id)) { + REPORT_LOG(LE, (_T("[ValidateDeviceId][Unexpected Device Id]") + _T("[Expected][%s][Got][%s]"), device_id, received_id)); + return E_FAIL; + } + + return S_OK; +} + +HRESULT ValidateTimestamp(const enterprise_management::PolicyData& policy_data, + const int64_t cached_timestamp) { + if (!policy_data.has_timestamp()) { + REPORT_LOG(LW, (_T("[ValidateTimestamp][No timestamp in PolicyData]"))); + return E_FAIL; + } + + if (policy_data.timestamp() < cached_timestamp) { + REPORT_LOG(LE, (_T("[ValidateTimestamp]") + _T("[Unexpected timestamp older than cached timestamp]"))); + return E_FAIL; + } + + return S_OK; +} + +HRESULT ValidatePolicy( + const enterprise_management::PolicyFetchResponse& fetch_response, + const std::string& signature_key) { + if (!fetch_response.has_policy_data_signature() || + !VerifySignature(fetch_response.policy_data(), + signature_key, + fetch_response.policy_data_signature(), + CALG_SHA1)) { + REPORT_LOG(LE, (_T("[ValidatePolicy]") + _T("[Failed to verify the signature on policy_data()]"))); + return E_FAIL; + } + + return S_OK; +} + +} // namespace + +HRESULT GetCachedPolicyInfo(const std::string& raw_response, + CachedPolicyInfo* info) { + ASSERT1(info); + + *info = {}; + + enterprise_management::PolicyFetchResponse response; + enterprise_management::PolicyData policy_data; + enterprise_management::PublicKeyVerificationData verification_data; + if (raw_response.empty() || + !response.ParseFromString(raw_response) || + !policy_data.ParseFromString(response.policy_data()) || + !policy_data.has_timestamp() || + !response.has_new_public_key_verification_data() || + !verification_data.ParseFromString( + response.new_public_key_verification_data())) { + return E_UNEXPECTED; + } + + info->key = verification_data.new_public_key(); + if (verification_data.has_new_public_key_version()) { + info->is_version_valid = true; + info->version = verification_data.new_public_key_version(); + } + info->timestamp = policy_data.timestamp(); + + return S_OK; +} + +CStringA SerializeRegisterBrowserRequest(const CStringA& machine_name, + const CStringA& os_platform, + const CStringA& os_version) { + enterprise_management::DeviceManagementRequest dm_request; + + ::enterprise_management::RegisterBrowserRequest* request = + dm_request.mutable_register_browser_request(); + request->set_machine_name(machine_name, machine_name.GetLength()); + request->set_os_platform(os_platform, os_platform.GetLength()); + request->set_os_version(os_version, os_version.GetLength()); + + CStringA result; + SerializeToCStringA(dm_request, &result); + return result; +} + +CStringA SerializePolicyFetchRequest(const CStringA& policy_type, + const CachedPolicyInfo& info) { + enterprise_management::DeviceManagementRequest policy_request; + + enterprise_management::PolicyFetchRequest* policy_fetch_request = + policy_request.mutable_policy_request()->add_requests(); + policy_fetch_request->set_policy_type(policy_type); + policy_fetch_request->set_signature_type( + enterprise_management::PolicyFetchRequest::SHA1_RSA); + policy_fetch_request->set_verification_key_hash(kPolicyVerificationKeyHash); + + if (info.is_version_valid) { + policy_fetch_request->set_public_key_version(info.version); + } + + CStringA result; + SerializeToCStringA(policy_request, &result); + return result; +} + +HRESULT ParseDeviceRegisterResponse(const std::vector& response, + CStringA* dm_token) { + ASSERT1(dm_token); + enterprise_management::DeviceManagementResponse dm_response; + + if (response.size() > static_cast(std::numeric_limits::max())) { + return E_FAIL; + } + + if (!dm_response.ParseFromArray(response.data(), + static_cast(response.size()))) { + return E_FAIL; + } + + if (!dm_response.has_register_response()) { + return E_FAIL; + } + + if (!dm_response.register_response().has_device_management_token()) { + return E_FAIL; + } + + const ::std::string& token = + dm_response.register_response().device_management_token(); + if (token.size() > static_cast(std::numeric_limits::max())) { + return E_FAIL; + } + dm_token->SetString(token.data(), static_cast(token.size())); + + return S_OK; +} + +HRESULT ParseDevicePolicyResponse(const std::vector& dm_response_array, + const CachedPolicyInfo& info, + const CString& dm_token, + const CString& device_id, + PolicyResponses* responses_out) { + ASSERT1(responses_out); + + enterprise_management::DeviceManagementResponse dm_response; + + if (dm_response_array.size() > + static_cast(std::numeric_limits::max())) { + return E_FAIL; + } + + if (!dm_response.ParseFromArray(dm_response_array.data(), + static_cast(dm_response_array.size()))) { + return E_FAIL; + } + + if (!dm_response.has_policy_response() || + dm_response.policy_response().responses_size() == 0) { + return E_FAIL; + } + + const enterprise_management::DevicePolicyResponse& policy_response = + dm_response.policy_response(); + const enterprise_management::PolicyFetchResponse& fetch_response = + policy_response.responses(0); + + std::string signature_key; + HRESULT hr = ValidateNewPublicKey(fetch_response, info.key, &signature_key); + if (FAILED(hr)) { + return hr; + } + + enterprise_management::PolicyData fetch_policy_data; + if (!fetch_policy_data.ParseFromString(fetch_response.policy_data())) { + REPORT_LOG(LW, (_T("[ParseDevicePolicyResponse][Invalid PolicyData]"))); + return E_FAIL; + } + + hr = ValidateDMToken(fetch_policy_data, dm_token); + if (FAILED(hr)) { + return hr; + } + + hr = ValidateDeviceId(fetch_policy_data, device_id); + if (FAILED(hr)) { + return hr; + } + + hr = ValidateTimestamp(fetch_policy_data, info.timestamp); + if (FAILED(hr)) { + return hr; + } + + std::string policy_info; + if (!fetch_response.SerializeToString(&policy_info)) { + return E_UNEXPECTED; + } + responses_out->policy_info = std::move(policy_info); + + PolicyResponsesMap responses; + for (int i = 0; i < policy_response.responses_size(); ++i) { + const enterprise_management::PolicyFetchResponse& response = + policy_response.responses(i); + enterprise_management::PolicyData policy_data; + if (!policy_data.ParseFromString(response.policy_data()) || + !policy_data.IsInitialized() || + !policy_data.has_policy_type()) { + REPORT_LOG(LW, (_T("Ignoring invalid PolicyData"))); + continue; + } + + const std::string& type = policy_data.policy_type(); + if (responses.find(type) != responses.end()) { + REPORT_LOG(LW, (_T("Duplicate PolicyFetchResponse for type: %S"), + type.c_str())); + continue; + } + + std::string policy_fetch_response; + if (!response.SerializeToString(&policy_fetch_response)) { + REPORT_LOG(LW, (_T("Failed to serialize response for type: %S"), + type.c_str())); + continue; + } + + hr = ValidatePolicy(response, signature_key); + if (FAILED(hr)) { + REPORT_LOG(LW, + (_T("[ParseDevicePolicyResponse][Failed ValidatePolicy][%d][%#x]"), + info.version, hr)); + continue; + } + + responses[type] = std::move(policy_fetch_response); + } + + responses_out->responses = std::move(responses); + return S_OK; +} + +HRESULT ParseDeviceManagementResponseError(const std::vector& response, + CStringA* error_message) { + ASSERT1(error_message); + enterprise_management::DeviceManagementResponse dm_response; + + if (response.size() > static_cast(std::numeric_limits::max())) { + return E_FAIL; + } + + if (!dm_response.ParseFromArray(response.data(), + static_cast(response.size()))) { + return E_FAIL; + } + + if (!dm_response.has_error_message()) { + return S_FALSE; + } + + const ::std::string& message = dm_response.error_message(); + if (message.size() > static_cast(std::numeric_limits::max())) { + return E_FAIL; + } + error_message->SetString(message.data(), static_cast(message.size())); + + return S_OK; +} + +} // namespace omaha diff --git a/omaha/goopdate/dm_messages.h b/omaha/goopdate/dm_messages.h new file mode 100644 index 0000000..60a7ef8 --- /dev/null +++ b/omaha/goopdate/dm_messages.h @@ -0,0 +1,69 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef OMAHA_GOOPDATE_DM_MESSAGES_H__ +#define OMAHA_GOOPDATE_DM_MESSAGES_H__ + +#include +#include +#include +#include +#include + +#include "base/basictypes.h" + +namespace omaha { + +// Maps policy types to their corresponding serialized PolicyFetchResponses. +using PolicyResponsesMap = std::map; +struct PolicyResponses { + PolicyResponsesMap responses; + std::string policy_info; +}; + +struct CachedPolicyInfo { + std::string key; + bool is_version_valid = false; + int32_t version = -1; + int64_t timestamp = 0; +}; + +HRESULT GetCachedPolicyInfo(const std::string& raw_response, + CachedPolicyInfo* info); + +CStringA SerializeRegisterBrowserRequest(const CStringA& machine_name, + const CStringA& os_platform, + const CStringA& os_version); + +CStringA SerializePolicyFetchRequest(const CStringA& policy_type, + const CachedPolicyInfo& info); + +HRESULT ParseDeviceRegisterResponse(const std::vector& response, + CStringA* dm_token); + +// Parses the policies from the DMServer, and return the PolicyFetchResponses in +// |responses|. |responses| contains elements in the following format: +// {policy_type}=>{SerializeToString-PolicyFetchResponse}. +HRESULT ParseDevicePolicyResponse(const std::vector& dm_response_array, + const CachedPolicyInfo& info, + const CString& dm_token, + const CString& device_id, + PolicyResponses* responses_out); + +HRESULT ParseDeviceManagementResponseError(const std::vector& response, + CStringA* error_message); + +} // namespace omaha + +#endif // OMAHA_GOOPDATE_DM_MESSAGES_H__ diff --git a/omaha/goopdate/dm_storage.cc b/omaha/goopdate/dm_storage.cc new file mode 100644 index 0000000..a3032e9 --- /dev/null +++ b/omaha/goopdate/dm_storage.cc @@ -0,0 +1,414 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_storage.h" + +#include +#include + +#include "omaha/base/const_utils.h" +#include "omaha/base/debug.h" +#include "omaha/base/file.h" +#include "omaha/base/logging.h" +#include "omaha/base/path.h" +#include "omaha/base/reg_key.h" +#include "omaha/base/safe_format.h" +#include "omaha/base/string.h" +#include "omaha/base/utils.h" +#include "omaha/common/app_registry_utils.h" +#include "omaha/common/config_manager.h" +#include "omaha/common/const_goopdate.h" +#include "omaha/common/const_group_policy.h" + +namespace omaha { + +namespace { + +// Returns an enrollment token stored in Omaha's ClientState key, or an empty +// string if not present or in case of failure. +CString LoadEnrollmentTokenFromInstall() { + CString value; + HRESULT hr = RegKey::GetValue( + app_registry_utils::GetAppClientStateKey(true /* is_machine */, + kGoogleUpdateAppId), + kRegValueCloudManagementEnrollmentToken, + &value); + return SUCCEEDED(hr) ? value : CString(); +} + +// Returns an enrollment token provisioned to the computer via Group Policy, or +// an empty string if not set or in case of failure. +CString LoadEnrollmentTokenFromCompanyPolicy() { + return ConfigManager::Instance()->GetCloudManagementEnrollmentToken(); +} + +#if defined(HAS_LEGACY_DM_CLIENT) + +// Returns an enrollment token provisioned to the computer via Group Policy for +// an install of Google Chrome, or an empty string if not set or in case of +// failure. +CString LoadEnrollmentTokenFromLegacyPolicy() { + CString value; + HRESULT hr = RegKey::GetValue(kRegKeyLegacyGroupPolicy, + kRegValueCloudManagementEnrollmentTokenPolicy, + &value); + return SUCCEEDED(hr) ? value : CString(); +} + +// Returns an enrollment token provisioned to the computer via Group Policy for +// an install of Google Chrome in a deprecated location used by old versions of +// Chrome, or an empty string if not set or in case of failure. +CString LoadEnrollmentTokenFromOldLegacyPolicy() { + CString value; + HRESULT hr = RegKey::GetValue( + kRegKeyLegacyGroupPolicy, + kRegValueMachineLevelUserCloudPolicyEnrollmentToken, + &value); + return SUCCEEDED(hr) ? value : CString(); +} + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +// Returns the device management token found in the registry key |path|, or an +// empty string if not set or in case of failure. +CStringA LoadDmTokenFromKey(const TCHAR* path) { + ASSERT1(path); + RegKey key; + HRESULT hr = key.Open(path, KEY_QUERY_VALUE); + if (FAILED(hr)) { + return CStringA(); + } + + byte* value = NULL; + size_t byte_count = 0; + DWORD type = REG_NONE; + hr = key.GetValue(kRegValueDmToken, &value, &byte_count, &type); + std::unique_ptr safe_value(value); + if (FAILED(hr) || type != REG_BINARY || byte_count == 0 || + byte_count > 4096 /* kMaxDMTokenLength */ ) { + return CStringA(); + } + return CStringA(reinterpret_cast(value), static_cast(byte_count)); +} + +// Stores |dm_token| in the registry key |path|. +HRESULT StoreDmTokenInKey(const CStringA& dm_token, const TCHAR* path) { + ASSERT1(path); + RegKey key; + HRESULT hr = key.Create(path, NULL /* reg_class */, + REG_OPTION_NON_VOLATILE /* options */, + KEY_SET_VALUE); + if (FAILED(hr)) { + return hr; + } + + hr = key.SetValue(kRegValueDmToken, + reinterpret_cast(dm_token.GetString()), + dm_token.GetLength(), REG_BINARY); + return hr; +} + +struct IgnoreCaseCompare { + bool operator() (const CString& a, const CString& b) const { + return a.CompareNoCase(b) < 0; + } +}; + +HRESULT DeleteObsoletePolicies( + const CPath& policy_responses_dir, + const std::set& policy_types_base64) { + std::vector files; + HRESULT hr = FindFiles(policy_responses_dir, _T("*"), &files); + if (FAILED(hr)) { + return hr; + } + + for (const auto& file : files) { + if (file == _T(".") || + file == _T("..") || + !file.CompareNoCase(kCachedPolicyInfoFileName) || + policy_types_base64.count(file)) { + continue; + } + + CPath path = policy_responses_dir; + VERIFY1(path.Append(file)); + REPORT_LOG(L1, (_T("[DeleteObsoletePolicies][Deleting][%s]"), path)); + VERIFY1(SUCCEEDED(DeleteBeforeOrAfterReboot(path))); + } + + return S_OK; +} + +HRESULT WriteToFile(const CPath& filename, const char* buf, const size_t len) { + ASSERT1(buf); + ASSERT1(len); + + File file; + HRESULT hr = file.Open(filename, true, false); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[WriteToFile][Failed Open][%s][%#x]"), filename, hr)); + return hr; + } + + uint32_t bytes_written = 0; + hr = file.WriteAt(0, + reinterpret_cast(buf), + static_cast(len), + 0, + &bytes_written); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[WriteToFile][Failed Write][%s][%#x]"), filename, hr)); + return hr; + } + + ASSERT1(bytes_written == len); + return file.SetLength(bytes_written, false); +} + +} // namespace + +DmStorage* DmStorage::instance_ = NULL; + +// There should not be any contention on creation because only GoopdateImpl +// should create DmStorage during its initialization. +HRESULT DmStorage::CreateInstance(const CString& enrollment_token) { + ASSERT1(!instance_); + + DmStorage* instance = new DmStorage(enrollment_token); + if (!instance) { + return E_OUTOFMEMORY; + } + + instance_ = instance; + return S_OK; +} + +void DmStorage::DeleteInstance() { + delete instance_; + instance_ = NULL; +} + +DmStorage* DmStorage::Instance() { + ASSERT1(instance_); + return instance_; +} + +CString DmStorage::GetEnrollmentToken() { + if (enrollment_token_source_ == kETokenSourceNone) { + LoadEnrollmentTokenFromStorage(); + } + ASSERT1((enrollment_token_source_ == kETokenSourceNone) == + enrollment_token_.IsEmpty()); + return enrollment_token_; +} + +HRESULT DmStorage::StoreRuntimeEnrollmentTokenForInstall() { + if (enrollment_token_source_ != kETokenSourceRuntime) { + return S_FALSE; + } + HRESULT hr = RegKey::SetValue( + app_registry_utils::GetAppClientStateKey(true /* is_machine */, + kGoogleUpdateAppId), + kRegValueCloudManagementEnrollmentToken, + enrollment_token_); + if (FAILED(hr)) { + OPT_LOG(LE, (_T("[StoreRuntimeEnrollmentTokenForInstall failed][%#x]"), + hr)); + } + return hr; +} + +CStringA DmStorage::GetDmToken() { + if (dm_token_source_ == kDmTokenSourceNone) { + LoadDmTokenFromStorage(); + } + ASSERT1((dm_token_source_ == kDmTokenSourceNone) == dm_token_.IsEmpty()); + return dm_token_; +} + +HRESULT DmStorage::StoreDmToken(const CStringA& dm_token) { + HRESULT hr = StoreDmTokenInKey(dm_token, kRegKeyCompanyEnrollment); + if (SUCCEEDED(hr)) { + dm_token_ = dm_token; + dm_token_source_ = kDmTokenSourceCompany; +#if defined(HAS_LEGACY_DM_CLIENT) + hr = StoreDmTokenInKey(dm_token, kRegKeyLegacyEnrollment); +#endif + } + return hr; +} + +CString DmStorage::GetDeviceId() { + if (device_id_.IsEmpty()) { + LoadDeviceIdFromStorage(); + } + return device_id_; +} + +HRESULT DmStorage::PersistPolicies(const CPath& policy_responses_dir, + const PolicyResponses& responses) { + if (!responses.policy_info.empty()) { + CPath policy_info_file(policy_responses_dir); + policy_info_file.Append(kCachedPolicyInfoFileName); + HRESULT hr = WriteToFile(policy_info_file, + responses.policy_info.c_str(), + responses.policy_info.length()); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[PersistPolicies][WriteToFile failed][%s][%#x]"), + policy_info_file, hr)); + } + } + + std::set policy_types_base64; + + for (const auto& response : responses.responses) { + CStringA encoded_policy_response_dirname; + Base64Escape(response.first.c_str(), + static_cast(response.first.length()), + &encoded_policy_response_dirname, + true); + + CString dirname(encoded_policy_response_dirname); + policy_types_base64.emplace(dirname); + CPath policy_response_dir(policy_responses_dir); + policy_response_dir.Append(dirname); + HRESULT hr = CreateDir(policy_response_dir, NULL); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[PersistPolicies][Failed to create dir][%s][%#x]"), + policy_response_dir, hr)); + continue; + } + + CPath policy_response_file(policy_response_dir); + policy_response_file.Append(kPolicyResponseFileName); + + const char* policy_fetch_response = response.second.c_str(); + const size_t len = response.second.length(); + hr = WriteToFile(policy_response_file, policy_fetch_response, len); + if (FAILED(hr)) { + REPORT_LOG(LW, (_T("[PersistPolicies][WriteToFile failed][%s][%#x]"), + policy_response_file, hr)); + continue; + } + } + + VERIFY1(SUCCEEDED(DeleteObsoletePolicies(policy_responses_dir, + policy_types_base64))); + return S_OK; +} + +HRESULT DmStorage::ReadCachedPolicyInfoFile(const CPath& policy_responses_dir, + CachedPolicyInfo* info) { + ASSERT1(info); + + CPath policy_info_file(policy_responses_dir); + policy_info_file.Append(kCachedPolicyInfoFileName); + + if (!File::Exists(policy_info_file)) { + return S_FALSE; + } + + std::vector data; + HRESULT hr = ReadEntireFileShareMode(policy_info_file, + 0, + FILE_SHARE_READ, + &data); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[ReadCachedPolicyInfoFile][Read failed][%s][%#x]"), + policy_info_file, hr)); + return hr; + } + + hr = GetCachedPolicyInfo(std::string(reinterpret_cast(&data[0]), + data.size()), + info); + if (FAILED(hr)) { + REPORT_LOG(LE, (_T("[ReadCachedPolicyInfoFile]") + _T("[GetCachedPolicyInfo failed][%s][%#x]"), + policy_info_file, hr)); + return hr; + } + + return S_OK; +} + +DmStorage::DmStorage(const CString& runtime_enrollment_token) + : runtime_enrollment_token_(runtime_enrollment_token), + enrollment_token_source_(kETokenSourceNone), + dm_token_source_(kDmTokenSourceNone) { +} + +void DmStorage::LoadEnrollmentTokenFromStorage() { + // Load from most to least preferred, stopping when one is found. + enrollment_token_ = LoadEnrollmentTokenFromCompanyPolicy(); + if (!enrollment_token_.IsEmpty()) { + enrollment_token_source_ = kETokenSourceCompanyPolicy; + return; + } + +#if defined(HAS_LEGACY_DM_CLIENT) + enrollment_token_ = LoadEnrollmentTokenFromLegacyPolicy(); + if (!enrollment_token_.IsEmpty()) { + enrollment_token_source_ = kETokenSourceLegacyPolicy; + return; + } + + enrollment_token_ = LoadEnrollmentTokenFromOldLegacyPolicy(); + if (!enrollment_token_.IsEmpty()) { + enrollment_token_source_ = kETokenSourceOldLegacyPolicy; + return; + } +#endif // defined(HAS_LEGACY_DM_CLIENT) + + if (!runtime_enrollment_token_.IsEmpty()) { + enrollment_token_ = runtime_enrollment_token_; + enrollment_token_source_ = kETokenSourceRuntime; + return; + } + + enrollment_token_ = LoadEnrollmentTokenFromInstall(); + if (!enrollment_token_.IsEmpty()) { + enrollment_token_source_ = kETokenSourceInstall; + } +} + +void DmStorage::LoadDmTokenFromStorage() { + // Load from most to least preferred, stopping when one is found. + dm_token_ = LoadDmTokenFromKey(kRegKeyCompanyEnrollment); + if (!dm_token_.IsEmpty()) { + dm_token_source_ = kDmTokenSourceCompany; + return; + } + +#if defined(HAS_LEGACY_DM_CLIENT) + dm_token_ = LoadDmTokenFromKey(kRegKeyLegacyEnrollment); + if (!dm_token_.IsEmpty()) { + dm_token_source_ = kDmTokenSourceLegacy; + } +#endif // defined(HAS_LEGACY_DM_CLIENT) +} + +void DmStorage::LoadDeviceIdFromStorage() { + RegKey key; + HRESULT hr = key.Open(kRegKeyCryptography, KEY_QUERY_VALUE); + if (SUCCEEDED(hr)) { + hr = key.GetValue(kRegValueMachineGuid, &device_id_); + } + if (FAILED(hr)) { + device_id_.Empty(); + } +} + +} // namespace omaha diff --git a/omaha/goopdate/dm_storage.h b/omaha/goopdate/dm_storage.h new file mode 100644 index 0000000..97af8ff --- /dev/null +++ b/omaha/goopdate/dm_storage.h @@ -0,0 +1,163 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef OMAHA_GOOPDATE_DM_STORAGE_H__ +#define OMAHA_GOOPDATE_DM_STORAGE_H__ + +#include +#include +#include + +#include "base/basictypes.h" +#include "omaha/base/constants.h" +#include "omaha/goopdate/dm_messages.h" + +namespace omaha { + +// This is the standard name for the file that PersistPolicies() uses for each +// {policy_type} that it receives from the DMServer. +const TCHAR kPolicyResponseFileName[] = _T("PolicyFetchResponse"); + +// This is the standard name for the file that PersistPolicies() uses to store +// a PolicyFetchResponse received from the DMServer during the previous request. +// The data within the PolicyFetchResponse, such as the public key, version, and +// timestamp are used for subsequent requests and validations of DMServer +// responses. +const TCHAR kCachedPolicyInfoFileName[] = _T("CachedPolicyInfo"); + +// A handler for storage related to cloud-based device management of Omaha. This +// class provides access to an enrollment token, a device management token, and +// a device identifier. +class DmStorage { + public: + // The possible sources of an enrollment token, sorted by decreasing + // precedence. + enum EnrollmentTokenSource { + kETokenSourceNone, + kETokenSourceCompanyPolicy, +#if defined(HAS_LEGACY_DM_CLIENT) + kETokenSourceLegacyPolicy, + kETokenSourceOldLegacyPolicy, +#endif // defined(HAS_LEGACY_DM_CLIENT) + kETokenSourceRuntime, + kETokenSourceInstall, + }; + + static HRESULT CreateInstance(const CString& enrollment_token); + static void DeleteInstance(); + + static DmStorage* Instance(); + + // Returns the current enrollment token, reading from sources as-needed to + // find one. Returns an empty string if no enrollment token is found. + CString GetEnrollmentToken(); + + // Returns the origin of the current enrollment token, or kETokenSourceNone if + // none has been found. + EnrollmentTokenSource enrollment_token_source() const { + return enrollment_token_source_; + } + + // Writes the instance's enrollment token if it was provided at runtime into + // Omaha's ClientState key so that it is available for subsequent runs. + // Returns S_FALSE if the instance's enrollment token was not provided at + // runtime. + HRESULT StoreRuntimeEnrollmentTokenForInstall(); + + // Returns the device management token, reading from sources as-needed to find + // one. Returns an empty string if no device management token is found. + CStringA GetDmToken(); + + // Writes |dm_token| into the registry. + HRESULT StoreDmToken(const CStringA& dm_token); + + // Returns the device identifier, or an empty string in case of error. + CString GetDeviceId(); + + // Persists each PolicyFetchResponse in |responses| into a subdirectory within + // |policy_responses_dir|. Each PolicyFetchResponse is stored within a + // subdirectory named {Base64Encoded{policy_type}}, with a fixed file name of + // "PolicyFetchResponse", where the file contents are + // {SerializeToString-PolicyFetchResponse}}. + // + // Also, if |responses.policy_info| has data, we persist the data + // (a PolicyFetchResponse) into a file with a fixed file name of + // "CachedPolicyInfo". The PolicyFetchResponse (the new public key, version, + // and timestamp) is used in subsequent policy fetches. + // + // Each file is opened in exclusive mode. If we are unable to open or write to + // files, the caller is expected to try again later. For instance, if UA is + // calling us, UA will retry at the next UA interval. + // + // Client applications could use ::FindFirstChangeNotificationW on the + // subdirectory corresponding to their respective policy_type to watch for + // changes. They can then read and apply the policies within this file. + // To minimize the number of notifications for existing PolicyFetchResponse + // files, the files are first modified in-place if the response includes them, + // and then the files that do not have a corresponding response are deleted. + static HRESULT PersistPolicies(const CPath& policy_responses_dir, + const PolicyResponses& responses); + + // Returns the public key information within the PolicyFetchResponse in + // |policy_responses_dir|\CachedPolicyInfo. + static HRESULT ReadCachedPolicyInfoFile(const CPath& policy_responses_dir, + CachedPolicyInfo* info); + + private: + // Constructs an instance with a runtime-provided enrollment token (e.g., one + // obtained via the etoken extra arg). + explicit DmStorage(const CString& runtime_enrollment_token); + + // The possible sources of a device management token, sorted by decreasing + // precedence. + enum DmTokenSource { + kDmTokenSourceNone, + kDmTokenSourceCompany, +#if defined(HAS_LEGACY_DM_CLIENT) + kDmTokenSourceLegacy, +#endif // defined(HAS_LEGACY_DM_CLIENT) + }; + + void LoadEnrollmentTokenFromStorage(); + void LoadDmTokenFromStorage(); + void LoadDeviceIdFromStorage(); + + // An enrollment token provided on the command line at runtime. + const CString runtime_enrollment_token_; + + // The active enrollment token. + CString enrollment_token_; + + // The active device management token. + CStringA dm_token_; + + // The device identifier. + CString device_id_; + + // The origin of the current enrollment token. + EnrollmentTokenSource enrollment_token_source_; + + // The origin of the current device management token. + DmTokenSource dm_token_source_; + + static DmStorage* instance_; + + friend class DmStorageTest; + + DISALLOW_COPY_AND_ASSIGN(DmStorage); +}; + +} // namespace omaha + +#endif // OMAHA_GOOPDATE_DM_STORAGE_H__ diff --git a/omaha/goopdate/dm_storage_test_utils.cc b/omaha/goopdate/dm_storage_test_utils.cc new file mode 100644 index 0000000..05d6da5 --- /dev/null +++ b/omaha/goopdate/dm_storage_test_utils.cc @@ -0,0 +1,87 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_storage_test_utils.h" + +#include "omaha/base/constants.h" +#include "omaha/base/reg_key.h" +#include "omaha/common/app_registry_utils.h" +#include "omaha/common/const_goopdate.h" +#include "omaha/common/const_group_policy.h" +#include "omaha/testing/unit_test.h" + +namespace omaha { + +namespace { + +void SetBinaryValue(const TCHAR* path, + const TCHAR* value_name, + const CStringA& data) { + RegKey key; + ASSERT_HRESULT_SUCCEEDED(key.Create(path, NULL, REG_OPTION_NON_VOLATILE, + KEY_SET_VALUE)); + ASSERT_HRESULT_SUCCEEDED( + key.SetValue(value_name, + reinterpret_cast(data.GetString()), + data.GetLength(), REG_BINARY)); +} + +} // namespace + +void WriteInstallToken(const TCHAR* enrollment_token) { + ASSERT_HRESULT_SUCCEEDED(RegKey::SetValue( + app_registry_utils::GetAppClientStateKey(true /* is_machine */, + kGoogleUpdateAppId), + kRegValueCloudManagementEnrollmentToken, + enrollment_token)); +} + +void WriteCompanyPolicyToken(const TCHAR* enrollment_token) { + ASSERT_HRESULT_SUCCEEDED(RegKey::SetValue( + kRegKeyCloudManagementGroupPolicy, + kRegValueEnrollmentToken, + enrollment_token)); +} + +void WriteCompanyDmToken(const char* dm_token) { + ASSERT_NO_FATAL_FAILURE(SetBinaryValue(kRegKeyCompanyEnrollment, + kRegValueDmToken, + dm_token)); +} + +#if defined(HAS_LEGACY_DM_CLIENT) + +void WriteLegacyPolicyToken(const TCHAR* enrollment_token) { + ASSERT_HRESULT_SUCCEEDED(RegKey::SetValue( + kRegKeyLegacyGroupPolicy, + kRegValueCloudManagementEnrollmentTokenPolicy, + enrollment_token)); +} + +void WriteOldLegacyPolicyToken(const TCHAR* enrollment_token) { + ASSERT_HRESULT_SUCCEEDED(RegKey::SetValue( + kRegKeyLegacyGroupPolicy, + kRegValueMachineLevelUserCloudPolicyEnrollmentToken, + enrollment_token)); +} + +void WriteLegacyDmToken(const char* dm_token) { + ASSERT_NO_FATAL_FAILURE(SetBinaryValue(kRegKeyLegacyEnrollment, + kRegValueDmToken, + dm_token)); +} + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +} // namespace diff --git a/omaha/goopdate/dm_storage_test_utils.h b/omaha/goopdate/dm_storage_test_utils.h new file mode 100644 index 0000000..a191a03 --- /dev/null +++ b/omaha/goopdate/dm_storage_test_utils.h @@ -0,0 +1,33 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +namespace omaha { + +// Test helper functions for writing enrollment and device management tokens +// into various locations in the Windows registry. All functions use Google +// Test ASSERTs, and must therefore be wrapped in ASSERT_NO_FATAL_FAILURE. + +void WriteInstallToken(const TCHAR* enrollment_token); +void WriteCompanyPolicyToken(const TCHAR* enrollment_token); +void WriteCompanyDmToken(const char* dm_token); + +#if defined(HAS_LEGACY_DM_CLIENT) +void WriteLegacyPolicyToken(const TCHAR* enrollment_token); +void WriteOldLegacyPolicyToken(const TCHAR* enrollment_token); +void WriteLegacyDmToken(const char* dm_token); +#endif // defined(HAS_LEGACY_DM_CLIENT) + +} // namespace omaha diff --git a/omaha/goopdate/dm_storage_unittest.cc b/omaha/goopdate/dm_storage_unittest.cc new file mode 100644 index 0000000..8830c4a --- /dev/null +++ b/omaha/goopdate/dm_storage_unittest.cc @@ -0,0 +1,293 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "omaha/goopdate/dm_storage.h" + +#include "omaha/base/app_util.h" +#include "omaha/base/file.h" +#include "omaha/base/path.h" +#include "omaha/base/scope_guard.h" +#include "omaha/base/string.h" +#include "omaha/base/utils.h" +#include "omaha/goopdate/dm_storage_test_utils.h" +#include "omaha/testing/unit_test.h" + +namespace omaha { + +class DmStorageTest : public RegistryProtectedTest { + protected: + static const TCHAR kETRuntime[]; + static const TCHAR kETInstall[]; + static const TCHAR kETCompanyPolicy[]; + static const char kDmTCompany[]; + +#if defined(HAS_LEGACY_DM_CLIENT) + static const TCHAR kETLegacyPolicy[]; + static const TCHAR kETOldLegacyPolicy[]; + static const char kDmTLegacy[]; +#endif // defined(HAS_LEGACY_DM_CLIENT) + + DmStorage* NewDmStorage(const CString& enrollment_token) { + return new DmStorage(enrollment_token); + } + + CPath GetPolicyResponseFilePath(const CPath& policy_responses_dir, + const std::string& policy_type) { + CStringA encoded_policy_response_dirname; + Base64Escape(policy_type.c_str(), + static_cast(policy_type.length()), + &encoded_policy_response_dirname, + true); + + CPath policy_response_file(policy_responses_dir); + policy_response_file.Append(CString(encoded_policy_response_dirname)); + policy_response_file.Append(kPolicyResponseFileName); + return policy_response_file; + } + + void CheckFileContentsMatch(const CPath& file_path, + const std::string& expected_contents) { + std::vector raw_contents; + ASSERT_HRESULT_SUCCEEDED(ReadEntireFileShareMode( + file_path, 0, FILE_SHARE_READ, &raw_contents)); + std::string contents(reinterpret_cast(&raw_contents[0]), + raw_contents.size()); + + ASSERT_STREQ(expected_contents.c_str(), contents.c_str()); + } + + void VerifyPolicies(const CPath& policy_responses_dir, + const PolicyResponses& expected_responses) { + if (!expected_responses.policy_info.empty()) { + CPath policy_info_file(policy_responses_dir); + policy_info_file.Append(kCachedPolicyInfoFileName); + CheckFileContentsMatch(policy_info_file, expected_responses.policy_info); + } + + for (const auto& expected_response : expected_responses.responses) { + CPath policy_response_file = GetPolicyResponseFilePath( + policy_responses_dir, expected_response.first); + + CheckFileContentsMatch(policy_response_file, expected_response.second); + } + } +}; + +const TCHAR DmStorageTest::kETRuntime[] = _T("runtime"); +const TCHAR DmStorageTest::kETInstall[] = _T("install"); +const TCHAR DmStorageTest::kETCompanyPolicy[] = _T("company_policy"); +const char DmStorageTest::kDmTCompany[] = "company"; +#if defined(HAS_LEGACY_DM_CLIENT) +const TCHAR DmStorageTest::kETLegacyPolicy[] = _T("legacy_policy"); +const TCHAR DmStorageTest::kETOldLegacyPolicy[] = _T("old_legacy_policy"); +const char DmStorageTest::kDmTLegacy[] = "legacy"; +#endif // defined(HAS_LEGACY_DM_CLIENT) + +// Test that empty strings are returned when the registry holds nothing. +TEST_F(DmStorageTest, NoEnrollmentToken) { + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetEnrollmentToken(), CString()); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceNone); +} + +// Test the individual sources. +TEST_F(DmStorageTest, EnrollmentTokenFromRuntime) { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETRuntime); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceRuntime); +} + +TEST_F(DmStorageTest, EnrollmentTokenFromInstall) { + ASSERT_NO_FATAL_FAILURE(WriteInstallToken(kETInstall)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETInstall); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceInstall); +} + +TEST_F(DmStorageTest, EnrollmentTokenFromCompanyPolicy) { + ASSERT_NO_FATAL_FAILURE(WriteCompanyPolicyToken(kETCompanyPolicy)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETCompanyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceCompanyPolicy); +} + +#if defined(HAS_LEGACY_DM_CLIENT) + +TEST_F(DmStorageTest, EnrollmentTokenFromLegacyPolicy) { + ASSERT_NO_FATAL_FAILURE(WriteLegacyPolicyToken(kETLegacyPolicy)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETLegacyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceLegacyPolicy); +} + +TEST_F(DmStorageTest, EnrollmentTokenFromOldLegacyPolicy) { + ASSERT_NO_FATAL_FAILURE(WriteOldLegacyPolicyToken(kETOldLegacyPolicy)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETOldLegacyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceOldLegacyPolicy); +} + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +TEST_F(DmStorageTest, EnrollmentTokenPrecedence) { + // Add the sources from lowest to highest priority. + ASSERT_NO_FATAL_FAILURE(WriteInstallToken(kETInstall)); + { + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETInstall); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceInstall); + } + { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETRuntime); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceRuntime); + } +#if defined(HAS_LEGACY_DM_CLIENT) + ASSERT_NO_FATAL_FAILURE(WriteOldLegacyPolicyToken(kETOldLegacyPolicy)); + { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETOldLegacyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceOldLegacyPolicy); + } + ASSERT_NO_FATAL_FAILURE(WriteLegacyPolicyToken(kETLegacyPolicy)); + { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETLegacyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceLegacyPolicy); + } +#endif // defined(HAS_LEGACY_DM_CLIENT) + ASSERT_NO_FATAL_FAILURE(WriteCompanyPolicyToken(kETCompanyPolicy)); + { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETCompanyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceCompanyPolicy); + } +} + +TEST_F(DmStorageTest, RuntimeEnrollmentTokenForInstall) { + { + std::unique_ptr dm_storage(NewDmStorage(kETRuntime)); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETRuntime); + EXPECT_EQ(dm_storage->StoreRuntimeEnrollmentTokenForInstall(), S_OK); + } + + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETRuntime); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceInstall); +} + +TEST_F(DmStorageTest, PolicyEnrollmentTokenForInstall) { + { + ASSERT_NO_FATAL_FAILURE(WriteCompanyPolicyToken(kETCompanyPolicy)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->StoreRuntimeEnrollmentTokenForInstall(), S_FALSE); + } + + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_STREQ(dm_storage->GetEnrollmentToken(), kETCompanyPolicy); + EXPECT_EQ(dm_storage->enrollment_token_source(), + DmStorage::kETokenSourceCompanyPolicy); +} + +TEST_F(DmStorageTest, NoDmToken) { + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetDmToken(), CStringA()); +} + +TEST_F(DmStorageTest, DmTokenFromCompany) { + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kDmTCompany)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetDmToken(), kDmTCompany); +} + +#if defined(HAS_LEGACY_DM_CLIENT) + +TEST_F(DmStorageTest, DmTokenFromLegacy) { + ASSERT_NO_FATAL_FAILURE(WriteLegacyDmToken(kDmTLegacy)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetDmToken(), kDmTLegacy); +} + +#endif // defined(HAS_LEGACY_DM_CLIENT) + +TEST_F(DmStorageTest, DmTokenPrecedence) { + // Add the sources from lowest to highest priority. +#if defined(HAS_LEGACY_DM_CLIENT) + ASSERT_NO_FATAL_FAILURE(WriteLegacyDmToken(kDmTLegacy)); + { + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetDmToken(), kDmTLegacy); + } +#endif // defined(HAS_LEGACY_DM_CLIENT) + + ASSERT_NO_FATAL_FAILURE(WriteCompanyDmToken(kDmTCompany)); + std::unique_ptr dm_storage(NewDmStorage((CString()))); + EXPECT_EQ(dm_storage->GetDmToken(), kDmTCompany); +} + +TEST_F(DmStorageTest, PersistPolicies) { + PolicyResponsesMap old_responses = { + {"google/chrome/machine-level-user", "test-data-chrome"}, + {"google/drive/machine-level-user", "test-data-drive"}, + {"google/earth/machine-level-user", "test-data-earth"}, + }; + + const CPath policy_responses_dir = CPath(ConcatenatePath( + app_util::GetCurrentModuleDirectory(), + _T("Policies"))); + + PolicyResponses expected_old_responses = {old_responses, ""}; + ASSERT_HRESULT_SUCCEEDED(DmStorage::PersistPolicies(policy_responses_dir, + expected_old_responses)); + VerifyPolicies(policy_responses_dir, expected_old_responses); + + PolicyResponsesMap new_responses = { + {"google/chrome/machine-level-user", "test-data-chr"}, // Shorter data. + // {"google/drive/machine-level-user", "test-data-drive"}, // Obsolete. + {"google/earth/machine-level-user", + "test-data-earth-foo-bar-baz-foo-bar-baz-foo-bar-baz"}, // Longer data. + {"google/newdrive/machine-level-user", "test-data-newdrive"}, // New. + }; + + PolicyResponses expected_new_responses = {new_responses, "expected data"}; + ASSERT_HRESULT_SUCCEEDED(DmStorage::PersistPolicies(policy_responses_dir, + expected_new_responses)); + VerifyPolicies(policy_responses_dir, expected_new_responses); + EXPECT_FALSE(GetPolicyResponseFilePath( + policy_responses_dir, "google/drive/machine-level-user").FileExists()); + + EXPECT_HRESULT_SUCCEEDED(DeleteDirectory(policy_responses_dir)); +} + +// This test must access the true registry, so it doesn't use the DmStorageTest +// fixture. +TEST(DmStorageDeviceIdTest, GetDeviceId) { + EXPECT_HRESULT_SUCCEEDED(DmStorage::CreateInstance(CString())); + ON_SCOPE_EXIT(DmStorage::DeleteInstance); + EXPECT_FALSE(DmStorage::Instance()->GetDeviceId().IsEmpty()); +} + +} // namespace omaha diff --git a/omaha/goopdate/download_manager.cc b/omaha/goopdate/download_manager.cc index ddadae3..3695a34 100644 --- a/omaha/goopdate/download_manager.cc +++ b/omaha/goopdate/download_manager.cc @@ -39,6 +39,7 @@ #include "omaha/base/synchronized.h" #include "omaha/base/user_rights.h" #include "omaha/base/utils.h" +#include "omaha/common/brave_stats_updater.h" #include "omaha/common/config_manager.h" #include "omaha/common/const_goopdate.h" #include "omaha/goopdate/model.h" @@ -276,6 +277,9 @@ HRESULT DownloadManager::DownloadApp(App* app) { } if (SUCCEEDED(hr)) { + omaha::BraveSendStatsPing(_T("download-complete"), app->app_guid_string(), + app->referral_id(), + app_version->app()->next_version()->version()); app->DownloadComplete(); app->MarkReadyToInstall(); } else { @@ -584,7 +588,7 @@ HRESULT DownloadManager::CreateStateForApp(App* app, State** state) { network_request->set_proxy_auth_config( app->app_bundle()->GetProxyAuthConfig()); - scoped_ptr state_ptr(new State(app, network_request)); + std::unique_ptr state_ptr(new State(app, network_request)); __mutexBlock(lock()) { download_state_.push_back(state_ptr.release()); diff --git a/omaha/goopdate/download_manager.h b/omaha/goopdate/download_manager.h index 1c9c879..fa59ac0 100644 --- a/omaha/goopdate/download_manager.h +++ b/omaha/goopdate/download_manager.h @@ -18,9 +18,10 @@ #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" namespace omaha { @@ -109,9 +110,9 @@ class DownloadManager : public DownloadManagerInterface { // Not owned by this object. App* app_; - scoped_ptr network_request_; + std::unique_ptr network_request_; - DISALLOW_EVIL_CONSTRUCTORS(State); + DISALLOW_COPY_AND_ASSIGN(State); }; // Creates a download state corresponding to the app. The state object is @@ -151,10 +152,10 @@ class DownloadManager : public DownloadManagerInterface { std::vector download_state_; - scoped_ptr package_cache_; + std::unique_ptr package_cache_; friend class DownloadManagerTest; - DISALLOW_EVIL_CONSTRUCTORS(DownloadManager); + DISALLOW_COPY_AND_ASSIGN(DownloadManager); }; } // namespace omaha diff --git a/omaha/goopdate/download_manager_unittest.cc b/omaha/goopdate/download_manager_unittest.cc index 5ff7961..3b35df6 100644 --- a/omaha/goopdate/download_manager_unittest.cc +++ b/omaha/goopdate/download_manager_unittest.cc @@ -15,15 +15,14 @@ // TODO(omaha): why so many dependencies for this unit test? -#include #include +#include + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/signatures.h" #include "omaha/base/thread_pool.h" #include "omaha/base/timer.h" @@ -37,6 +36,7 @@ #include "omaha/goopdate/download_manager.h" #include "omaha/goopdate/file_hash.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" using ::testing::_; using ::testing::Return; @@ -81,7 +81,7 @@ class DownloadAppWorkItem : public UserWorkItem { DownloadManager* download_manager_; App* app_; - DISALLOW_EVIL_CONSTRUCTORS(DownloadAppWorkItem); + DISALLOW_COPY_AND_ASSIGN(DownloadAppWorkItem); }; bool FileHashesEqual(const FileHash& hash1, const FileHash& hash2) { @@ -129,7 +129,7 @@ class DownloadManagerTest : public AppTestBase { } const CString cache_path_; - scoped_ptr download_manager_; + std::unique_ptr download_manager_; }; @@ -400,7 +400,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_Concurrent) { app = app_bundle_->GetApp(i); SetAppStateWaitingToDownload(app); - scoped_ptr work_item( + std::unique_ptr work_item( new DownloadAppWorkItem(download_manager_.get(), app)); // WT_EXECUTELONGFUNCTION causes the thread pool to use multiple threads. @@ -535,7 +535,7 @@ TEST_F(DownloadManagerUserTest, DISABLED_DownloadApp_Cancel) { app = app_bundle_->GetApp(i); SetAppStateWaitingToDownload(app); - scoped_ptr work_item( + std::unique_ptr work_item( new DownloadAppWorkItem(download_manager_.get(), app)); ASSERT_HRESULT_SUCCEEDED(thread_pool.QueueUserWorkItem( @@ -758,7 +758,7 @@ TEST_F(DownloadManagerUserTest, DownloadApp_FileAlreadyInCache) { EXPECT_LT(0, app->GetDownloadTimeMs()); // Create the second app bundle. - shared_ptr app_bundle2(model_->CreateAppBundle(false)); + std::shared_ptr app_bundle2(model_->CreateAppBundle(false)); EXPECT_SUCCEEDED(app_bundle2->put_displayName(CComBSTR(_T("My Bundle")))); EXPECT_SUCCEEDED(app_bundle2->put_displayLanguage(CComBSTR(_T("en")))); EXPECT_SUCCEEDED(app_bundle2->initialize()); diff --git a/omaha/goopdate/google_update.cc b/omaha/goopdate/google_update.cc index 0d9a02f..0b3e5af 100644 --- a/omaha/goopdate/google_update.cc +++ b/omaha/goopdate/google_update.cc @@ -31,7 +31,6 @@ #include "omaha/goopdate/google_update3.h" #include "omaha/goopdate/omaha3_idl_datax.h" #include "omaha/goopdate/ondemand.h" -#include "omaha/goopdate/oneclick_process_launcher.h" #include "omaha/goopdate/process_launcher.h" #include "omaha/goopdate/update3web.h" #include "omaha/goopdate/worker.h" @@ -53,16 +52,12 @@ BEGIN_OBJECT_MAP(object_map_broker_machine_mode) OBJECT_ENTRY(__uuidof(OnDemandMachineAppsClass), OnDemandMachineBroker) OBJECT_ENTRY(__uuidof(GoogleUpdate3WebMachineClass), Update3WebMachineBroker) OBJECT_ENTRY(__uuidof(CoCreateAsyncClass), CoCreateAsync) - OBJECT_ENTRY(__uuidof(OneClickMachineProcessLauncherClass), - OneClickProcessLauncher) END_OBJECT_MAP() BEGIN_OBJECT_MAP(object_map_ondemand_user_mode) OBJECT_ENTRY(__uuidof(GoogleUpdate3WebUserClass), Update3WebUser) OBJECT_ENTRY(__uuidof(OnDemandUserAppsClass), OnDemandUser) OBJECT_ENTRY(__uuidof(CredentialDialogUserClass), CredentialDialogUser) - OBJECT_ENTRY(__uuidof(OneClickUserProcessLauncherClass), - OneClickProcessLauncher) END_OBJECT_MAP() BEGIN_OBJECT_MAP(object_map_ondemand_machine_mode) diff --git a/omaha/goopdate/google_update.h b/omaha/goopdate/google_update.h index cfd9351..e609e75 100644 --- a/omaha/goopdate/google_update.h +++ b/omaha/goopdate/google_update.h @@ -21,7 +21,7 @@ #include #include -#include "base/scoped_ptr.h" + #include "goopdate/omaha3_idl.h" #include "omaha/base/debug.h" #include "omaha/base/logging.h" @@ -95,10 +95,10 @@ class GoogleUpdate : public CAtlExeModuleT { HRESULT RegisterOrUnregisterExe(bool is_register); static HRESULT RegisterOrUnregisterExe(void* data, bool is_register); - ComServerMode mode_; bool is_machine_; + ComServerMode mode_; - DISALLOW_EVIL_CONSTRUCTORS(GoogleUpdate); + DISALLOW_COPY_AND_ASSIGN(GoogleUpdate); }; } // namespace omaha diff --git a/omaha/goopdate/google_update3.h b/omaha/goopdate/google_update3.h index 4546805..5c04342 100644 --- a/omaha/goopdate/google_update3.h +++ b/omaha/goopdate/google_update3.h @@ -19,9 +19,10 @@ #include #include #include +#include #include + #include "goopdate/omaha3_idl.h" -#include "base/scoped_ptr.h" #include "omaha/base/atlregmapex.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" @@ -33,7 +34,6 @@ #include "omaha/goopdate/model.h" #include "omaha/goopdate/non_localized_resource.h" #include "omaha/goopdate/worker.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { @@ -47,12 +47,6 @@ struct Update3COMClassMode { static const TCHAR* const hk_root() { return hkroot; } }; -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) -// C4505: unreferenced IUnknown local functions have been removed -#pragma warning(disable : 4505) - template class ATL_NO_VTABLE Update3COMClass : public CComObjectRootEx, @@ -129,7 +123,7 @@ class ATL_NO_VTABLE Update3COMClass if (index < 0 || static_cast(index) >= num_app_bundles) { return HRESULT_FROM_WIN32(ERROR_INVALID_INDEX); } - shared_ptr app_bundle(model()->GetAppBundle(index)); + std::shared_ptr app_bundle(model()->GetAppBundle(index)); return AppBundleWrapper::Create(app_bundle->controlling_ptr(), app_bundle.get(), app_bundle_wrapper); @@ -146,7 +140,7 @@ class ATL_NO_VTABLE Update3COMClass __mutexScope(model()->lock()); - shared_ptr app_bundle(model()->CreateAppBundle(T::is_machine())); + std::shared_ptr app_bundle(model()->CreateAppBundle(T::is_machine())); return AppBundleWrapper::Create(app_bundle->controlling_ptr(), app_bundle.get(), app_bundle_wrapper); @@ -183,7 +177,7 @@ class ATL_NO_VTABLE Update3COMClass } if (!instance->model()) { - omaha::interlocked_exchange_pointer(&instance->model_, + omaha::interlocked_exchange_pointer(&instance->model_, Worker::Instance().model()); } ASSERT1(instance->model()); @@ -201,8 +195,6 @@ class ATL_NO_VTABLE Update3COMClass DISALLOW_COPY_AND_ASSIGN(Update3COMClass); }; -#pragma warning(pop) - extern TCHAR kHKRootUser[]; extern TCHAR kHKRootMachine[]; extern TCHAR kHKRootService[]; diff --git a/omaha/goopdate/google_update_proxy.h b/omaha/goopdate/google_update_proxy.h deleted file mode 100644 index 6b39a47..0000000 --- a/omaha/goopdate/google_update_proxy.h +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Defines SharedMemoryProxy to encapsulate marshaling and unmarshaling of -// IGoogleUpdate3 and other interface pointers across process boundaries. -// -// TODO(omaha): seems possible to make it general purpose and move it to common. -#ifndef OMAHA_GOOPDATE_GOOGLE_UPDATE_PROXY_H__ -#define OMAHA_GOOPDATE_GOOGLE_UPDATE_PROXY_H__ - -#include -#include -#include "base/basictypes.h" -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/shared_memory_ptr.h" -#include "omaha/base/utils.h" -#include "omaha/base/vistautil.h" - -namespace omaha { - -// Constants -const size_t kMaxSizeInterfaceMarshalData = 256; -const TCHAR* const kBrowserHttpRequestShareName = _T("IBrowserRequest2_"); - -struct InterfaceMarshalData { - void InitializeSharedData(const CString&) { - SetZero(data_); - size_ = 0; - } - size_t size_; - uint8 data_[kMaxSizeInterfaceMarshalData]; -}; - -class SharedMemoryAttributes { - public: - SharedMemoryAttributes(const TCHAR* shared_memory_name, - const CSecurityDesc& security_attributes) - : shared_memory_name_(shared_memory_name), - security_attributes_(security_attributes) { - } - const CString& GetSharedMemoryName() { return shared_memory_name_; } - LPSECURITY_ATTRIBUTES GetSecurityAttributes() { - return &security_attributes_; - } - - private: - CString shared_memory_name_; - CSecurityAttributes security_attributes_; - DISALLOW_EVIL_CONSTRUCTORS(SharedMemoryAttributes); -}; - -extern SharedMemoryAttributes low_integrity_attributes; -extern SharedMemoryAttributes high_integrity_attributes; - -template -class SharedMemoryProxy { - public: - SharedMemoryProxy(bool read_only, SharedMemoryAttributes* attributes) - : shared_memory_ptr_(attributes->GetSharedMemoryName(), - attributes->GetSecurityAttributes(), - NULL, - read_only) { - CORE_LOG(L3, (_T("[SharedMemoryProxy::SharedMemoryProxy]"))); - } - - ~SharedMemoryProxy() { - CORE_LOG(L3, (_T("[SharedMemoryProxy::~SharedMemoryProxy]"))); - } - - HRESULT GetObject(InterfaceType** interface_ptr) { - ASSERT1(interface_ptr); - ASSERT1(*interface_ptr == NULL); - - CORE_LOG(L3, (_T("[SharedMemoryProxy::GetObject]"))); - - return UnmarshalInterface(interface_ptr); - } - - HRESULT RegisterObject(InterfaceType* interface_ptr) { - ASSERT1(interface_ptr); - CORE_LOG(L3, (_T("[SharedMemoryProxy::RegisterObject]"))); - - return MarshalInterface(interface_ptr); - } - - HRESULT RevokeObject() { - CORE_LOG(L3, (_T("[SharedMemoryProxy::RevokeObject]"))); - - if (!shared_memory_ptr_) { - OPT_LOG(LEVEL_ERROR, (_T("[Shared memory ptr error]"))); - return GOOPDATE_E_INVALID_SHARED_MEMORY_PTR; - } - - shared_memory_ptr_->size_ = 0; - SetZero(shared_memory_ptr_->data_); - - return S_OK; - } - - private: - // Helpers. - HRESULT MarshalInterface(InterfaceType* interface_ptr) { - CORE_LOG(L3, (_T("[SharedMemoryProxy::MarshalInterface]"))); - - if (!shared_memory_ptr_) { - OPT_LOG(LEVEL_ERROR, (_T("[Shared memory ptr error]"))); - return GOOPDATE_E_INVALID_SHARED_MEMORY_PTR; - } - - // Marshal the interface. - scoped_hglobal hglobal(::GlobalAlloc(GHND, 0)); - if (!valid(hglobal)) { - OPT_LOG(LEVEL_ERROR, (_T("[GlobalAlloc failed]"))); - return E_OUTOFMEMORY; - } - - CComPtr stream; - HRESULT hr = ::CreateStreamOnHGlobal(get(hglobal), false, &stream); - if (FAILED(hr)) { - OPT_LOG(LEVEL_ERROR, (_T("[CreateStreamOnHGlobal failed][0x%08x]"), hr)); - return hr; - } - - // MSHLFLAGS_TABLEWEAK results in CO_E_OBJNOTREG if unmarshaling multiple - // times, so using MSHLFLAGS_TABLESTRONG. - hr = ::CoMarshalInterface(stream, - __uuidof(InterfaceType), - interface_ptr, - MSHCTX_LOCAL, - NULL, - MSHLFLAGS_TABLESTRONG); - if (FAILED(hr)) { - OPT_LOG(LEVEL_ERROR, (_T("[CoMarshalInterface failed][0x%08x]"), hr)); - return hr; - } - - // Copy out the marshaled data. - STATSTG stat = {0}; - hr = stream->Stat(&stat, STATFLAG_NONAME); - if (FAILED(hr)) { - OPT_LOG(LEVEL_ERROR, (_T("[IStream::Stat failed][0x%08x]"), hr)); - return hr; - } - int64 size = static_cast(stat.cbSize.QuadPart); - if (!size || size > kMaxSizeInterfaceMarshalData) { - OPT_LOG(LEVEL_ERROR, (_T("[Bad size][%I64d]"), size)); - return GOOPDATE_E_INVALID_INTERFACE_MARSHAL_SIZE; - } - - byte* data = reinterpret_cast(::GlobalLock(get(hglobal))); - if (!data) { - return HRESULTFromLastError(); - } - memcpy(shared_memory_ptr_->data_, data, stat.cbSize.LowPart); - shared_memory_ptr_->size_ = stat.cbSize.LowPart; - - ::GlobalUnlock(get(hglobal)); - - return S_OK; - } - - HRESULT UnmarshalInterface(InterfaceType** interface_ptr) { - CORE_LOG(L3, (_T("[SharedMemoryProxy::UnmarshalInterface]"))); - - if (!shared_memory_ptr_) { - OPT_LOG(LEVEL_ERROR, (_T("[Shared memory ptr error]"))); - return GOOPDATE_E_INVALID_SHARED_MEMORY_PTR; - } - - size_t size = shared_memory_ptr_->size_; - if (!size || size > kMaxSizeInterfaceMarshalData) { - CORE_LOG(LEVEL_ERROR, (_T("[bad size][%d]"), size)); - return GOOPDATE_E_INVALID_INTERFACE_MARSHAL_SIZE; - } - - // Unmarshal the interface. - scoped_hglobal hglobal(::GlobalAlloc(GPTR, size)); - if (!valid(hglobal)) { - OPT_LOG(LEVEL_ERROR, (_T("[GlobalAlloc failed]"))); - return E_OUTOFMEMORY; - } - memcpy(get(hglobal), shared_memory_ptr_->data_, size); - - CComPtr stream; - HRESULT hr = ::CreateStreamOnHGlobal(get(hglobal), false, &stream); - if (FAILED(hr)) { - OPT_LOG(LEVEL_ERROR, (_T("[CreateStreamOnHGlobal failed][0x%08x]"), hr)); - return hr; - } - - hr = ::CoUnmarshalInterface(stream, - __uuidof(InterfaceType), - reinterpret_cast(interface_ptr)); - if (FAILED(hr)) { - OPT_LOG(LEVEL_ERROR, (_T("[CoUnmarshalInterface failed][0x%08x]"), hr)); - return hr; - } - - return S_OK; - } - - SharedMemoryPtr shared_memory_ptr_; - DISALLOW_EVIL_CONSTRUCTORS(SharedMemoryProxy); -}; - -} // namespace omaha - -#endif // OMAHA_GOOPDATE_GOOGLE_UPDATE_PROXY_H__ - diff --git a/omaha/goopdate/goopdate.cc b/omaha/goopdate/goopdate.cc index 47d5e38..7010264 100644 --- a/omaha/goopdate/goopdate.cc +++ b/omaha/goopdate/goopdate.cc @@ -43,9 +43,10 @@ // -Embedding #include "omaha/goopdate/goopdate.h" + #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" #include "omaha/base/const_object_names.h" #include "omaha/base/crash_if_specific_error.h" @@ -57,8 +58,6 @@ #include "omaha/base/proc_utils.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/system_info.h" #include "omaha/base/utils.h" #include "omaha/base/vistautil.h" @@ -89,13 +88,19 @@ #include "omaha/goopdate/goopdate_internal.h" #include "omaha/goopdate/goopdate_metrics.h" #include "omaha/goopdate/resource_manager.h" -#include "omaha/net/net_diags.h" #include "omaha/service/service_main.h" #include "omaha/setup/setup_google_update.h" #include "omaha/setup/setup_service.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "third_party/breakpad/src/client/windows/sender/crash_report_sender.h" #include "third_party/breakpad/src/client/windows/handler/exception_handler.h" +#if defined(HAS_DEVICE_MANAGEMENT) +#include "omaha/common/event_logger.h" +#include "omaha/goopdate/dm_client.h" +#include "omaha/goopdate/dm_storage.h" +#endif + using google_breakpad::CustomInfoEntry; namespace omaha { @@ -129,7 +134,6 @@ bool CheckRegisteredVersion(const CString& version, case COMMANDLINE_MODE_NOARGS: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_INSTALL: @@ -173,6 +177,28 @@ bool CheckRegisteredVersion(const CString& version, } #endif +#if defined(HAS_DEVICE_MANAGEMENT) + +// Writes an error event to the Windows event log with the given |event_id| and +// |description| and |hresult| in the event text. +void LogErrorWithHResult(int event_id, + const CString& description, + HRESULT hresult) { + GoogleUpdateLogEvent log_event(EVENTLOG_ERROR_TYPE, event_id, + true /* is_machine */); + log_event.set_event_desc(description); + + // |hresult| may be S_OK for cases where no external error instigated the + // logging of this event. + CString text; + SafeCStringFormat(&text, _T("HRESULT = %#x"), hresult); + log_event.set_event_text(text); + + log_event.WriteEvent(); +} + +#endif // defined(HAS_DEVICE_MANAGEMENT) + } // namespace namespace detail { @@ -279,6 +305,14 @@ class GoopdateImpl { HRESULT InstallExceptionHandler(); +#if defined(HAS_DEVICE_MANAGEMENT) + + // Returns a success HRESULT on noop, success, or non-fatal failure. Returns + // a failure HRESULT if registration was mandatory and failed. + HRESULT RegisterForDeviceManagement(); + +#endif // defined(HAS_DEVICE_MANAGEMENT) + // Called by operator new or operator new[] when they cannot satisfy // a request for additional storage. static void OutOfMemoryHandler(); @@ -301,12 +335,12 @@ class GoopdateImpl { // Language identifier for the current user locale. CString user_default_language_id_; - scoped_ptr exception_handler_; - scoped_ptr thread_pool_; + std::unique_ptr exception_handler_; + std::unique_ptr thread_pool_; Goopdate* goopdate_; - DISALLOW_EVIL_CONSTRUCTORS(GoopdateImpl); + DISALLOW_COPY_AND_ASSIGN(GoopdateImpl); }; GoopdateImpl::GoopdateImpl(Goopdate* goopdate, bool is_local_system) @@ -364,6 +398,10 @@ GoopdateImpl::~GoopdateImpl() { Stop(); +#if defined(HAS_DEVICE_MANAGEMENT) + DmStorage::DeleteInstance(); +#endif + // Bug 994348 does not repro anymore. // If the assert fires, clean up the key, and fix the code if we have unit // tests or application code that create the key. @@ -719,6 +757,12 @@ HRESULT GoopdateImpl::ExecuteMode(bool* has_ui_been_displayed) { VERIFY1(SUCCEEDED(SetBackgroundPriorityIfNeeded(mode))); +#if defined(HAS_DEVICE_MANAGEMENT) + // Reference the DmStorage instance here so the singleton can be created + // before use. + VERIFY1(SUCCEEDED(DmStorage::CreateInstance(args_.extra.enrollment_token))); +#endif + #pragma warning(push) // C4061: enumerator 'xxx' in switch of enum 'yyy' is not explicitly handled by // a case label. @@ -808,9 +852,6 @@ HRESULT GoopdateImpl::ExecuteMode(bool* has_ui_been_displayed) { case COMMANDLINE_MODE_CODE_RED_CHECK: return HandleCodeRedCheck(); - case COMMANDLINE_MODE_NETDIAGS: - return NetDiags().Main(); - case COMMANDLINE_MODE_REGISTER_PRODUCT: // TODO(omaha3): Eliminate the need for this mode. return E_FAIL; @@ -936,7 +977,6 @@ bool GoopdateImpl::ShouldCheckShutdownEvent(CommandLineMode mode) { case COMMANDLINE_MODE_NOARGS: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_RECOVER: @@ -952,6 +992,7 @@ bool GoopdateImpl::ShouldCheckShutdownEvent(CommandLineMode mode) { case COMMANDLINE_MODE_PING: case COMMANDLINE_MODE_HEALTH_CHECK: case COMMANDLINE_MODE_REGISTER_MSI_HELPER: + case COMMANDLINE_MODE_UA: return false; // Modes that should honor shutdown. @@ -964,7 +1005,6 @@ bool GoopdateImpl::ShouldCheckShutdownEvent(CommandLineMode mode) { case COMMANDLINE_MODE_MEDIUM_SERVICE: case COMMANDLINE_MODE_HANDOFF_INSTALL: - case COMMANDLINE_MODE_UA: case COMMANDLINE_MODE_UNINSTALL: return true; @@ -1016,7 +1056,6 @@ HRESULT GoopdateImpl::LoadResourceDllIfNecessary(CommandLineMode mode, case COMMANDLINE_MODE_CORE: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_WEBPLUGIN: @@ -1132,6 +1171,26 @@ HRESULT GoopdateImpl::DoInstall(bool* has_ui_been_displayed) { } HRESULT hr = S_OK; +#if defined(HAS_DEVICE_MANAGEMENT) + if (is_machine_) { + hr = RegisterForDeviceManagement(); + if (FAILED(hr)) { + return hr; // Mandatory registration failed. + } + + // TODO(ganesh): It is desirable to separate the execution paths of + // installs/updates and policy fetch. Once we have the Firebase Messaging + // feature solidified, we can move the policy fetch logic over there. + hr = dm_client::RefreshPolicies(); + if (FAILED(hr)) { + OPT_LOG(LE, (_T("[RefreshPolicies failed][%#x]"), hr)); + LogErrorWithHResult(kRefreshPoliciesFailedEventId, + _T("Device management policy refresh failed"), + hr); + } + } +#endif // defined(HAS_DEVICE_MANAGEMENT) + if (args_.is_oem_set) { hr = OemInstall(!args_.is_silent_set, // is_interactive !args_.extra.runtime_only, // is_app_install @@ -1260,6 +1319,39 @@ HRESULT GoopdateImpl::DoUpdateAllApps(bool* has_ui_been_displayed ) { OPT_LOG(L1, (_T("[GoopdateImpl::DoUpdateAllApps]"))); ASSERT1(has_ui_been_displayed); + HRESULT hr = S_OK; +#if defined(HAS_DEVICE_MANAGEMENT) + // Make a best-effort attempt to register during UA processing to handle the + // following cases: + // - The network could not be used during installation on account of + // NOGOOGLEUPDATEPING. + // - Non-mandatory registration failed during installation. + // - An enrollment token was provisioned to the machine via Group Policy after + // installation. + // TODO(ganesh): It is desirable to separate the execution paths of + // installs/updates and policy fetch. Once we have the Firebase Messaging + // feature solidified, we can move the policy fetch logic over there. + if (is_machine_) { + hr = dm_client::RegisterIfNeeded(DmStorage::Instance()); + if (FAILED(hr)) { + OPT_LOG(LE, (_T("[Registration failed][%#x]"), hr)); + // Emit to the Event Log. The entry will include details by way of + // logging at the LC_REPORT category within dm_client. + LogErrorWithHResult(kEnrollmentFailedEventId, + _T("Device management enrollment failed"), + hr); + } else { + hr = dm_client::RefreshPolicies(); + if (FAILED(hr)) { + OPT_LOG(LE, (_T("[RefreshPolicies failed][%#x]"), hr)); + LogErrorWithHResult(kRefreshPoliciesFailedEventId, + _T("Device management policy refresh failed"), + hr); + } + } + } +#endif // defined(HAS_DEVICE_MANAGEMENT) + bool is_interactive_update = !args_.is_silent_set; // TODO(omaha3): Interactive is used as an indication of an on-demand request. @@ -1278,7 +1370,7 @@ HRESULT GoopdateImpl::DoUpdateAllApps(bool* has_ui_been_displayed ) { // TODO(omaha): Consider moving InitializeClientSecurity calls inside // install_apps.cc or maybe to update3_utils::CreateGoogleUpdate3Class(). - HRESULT hr = InitializeClientSecurity(); + hr = InitializeClientSecurity(); if (FAILED(hr)) { ASSERT1(false); return is_interactive_update ? hr : S_OK; @@ -1473,7 +1565,6 @@ bool GoopdateImpl::ShouldSetBackgroundPriority(CommandLineMode mode) { case COMMANDLINE_MODE_NOARGS: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_RECOVER: case COMMANDLINE_MODE_SERVICE_REGISTER: @@ -1532,9 +1623,71 @@ HRESULT GoopdateImpl::InstallExceptionHandler() { return OmahaExceptionHandler::Create(is_machine_, custom_info_map, - address(exception_handler_)); + &exception_handler_); +} + +#if defined(HAS_DEVICE_MANAGEMENT) + +HRESULT GoopdateImpl::RegisterForDeviceManagement() { + ASSERT1(args_.mode == COMMANDLINE_MODE_INSTALL); + ASSERT1(is_machine_); + + if (args_.is_oem_set) { + // TODO(b/117412382): Consider storing an enrollment token provided via + // extra args (DmStorage::StoreRuntimeEnrollmentTokenForInstall) so that + // registration can take place when the OEM ping is sent. + return S_FALSE; + } + + DmStorage* const dm_storage = DmStorage::Instance(); + const bool is_enrollment_mandatory = + ConfigManager::Instance()->IsCloudManagementEnrollmentMandatory(); + + if (args_.is_enterprise_set && + dm_client::GetRegistrationState(dm_storage) == + dm_client::kRegistrationPending) { + if (is_enrollment_mandatory) { + LogErrorWithHResult(kEnrollmentRequiresNetworkEventId, + _T("Mandatory device management enrollment ") + _T("incompatible with NOGOOGLEUPDATEPING"), + S_OK); + return E_FAIL; + } + // If the enrollment token was provided via extra args, write the token to + // the registry for use in subsequent registration attempts during + // UpdateApps processing. + dm_storage->StoreRuntimeEnrollmentTokenForInstall(); + return S_FALSE; + } + + HRESULT hr = dm_client::RegisterIfNeeded(dm_storage); + + // Exit early if no work was needed. + if (hr == S_FALSE) { + return hr; + } + + // If the enrollment token was provided via extra args, write the token to the + // registry for use in subsequent registration attempts. + dm_storage->StoreRuntimeEnrollmentTokenForInstall(); + + if (SUCCEEDED(hr)) { + return hr; + } + OPT_LOG(LE, (_T("[Registration failed][%#x]"), hr)); + + // Emit to the Event Log. The entry will include details by way of + // logging at the LC_REPORT category within dm_client. + LogErrorWithHResult(kEnrollmentFailedEventId, + _T("Device management enrollment failed"), + hr); + + // Bubble the failure HRESULT up if enrollment was mandatory. + return is_enrollment_mandatory ? hr : S_FALSE; } +#endif // defined(HAS_DEVICE_MANAGEMENT) + void GoopdateImpl::OutOfMemoryHandler() { ::RaiseException(EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, @@ -1750,7 +1903,6 @@ bool IsMachineProcess(CommandLineMode mode, // in the wild. case COMMANDLINE_MODE_NOARGS: case COMMANDLINE_MODE_UNKNOWN: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: default: return is_running_from_official_machine_directory; @@ -1776,7 +1928,6 @@ bool CanDisplayUi(CommandLineMode mode, bool is_silent) { case COMMANDLINE_MODE_SERVICE: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_UPDATE: diff --git a/omaha/goopdate/goopdate.h b/omaha/goopdate/goopdate.h index ed28ea8..e90b653 100644 --- a/omaha/goopdate/goopdate.h +++ b/omaha/goopdate/goopdate.h @@ -19,8 +19,9 @@ #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/thread_pool.h" namespace omaha { @@ -59,9 +60,9 @@ class Goopdate { static Goopdate* instance_; // Uses pimpl idiom to minimize dependencies on implementation details. - scoped_ptr impl_; + std::unique_ptr impl_; - DISALLOW_EVIL_CONSTRUCTORS(Goopdate); + DISALLOW_COPY_AND_ASSIGN(Goopdate); }; } // namespace omaha diff --git a/omaha/goopdate/goopdate.rc b/omaha/goopdate/goopdate.rc index 3fb4006..f2c5cdc 100644 --- a/omaha/goopdate/goopdate.rc +++ b/omaha/goopdate/goopdate.rc @@ -16,7 +16,7 @@ // TODO(omaha3): Figure out what category of resources this file includes and // rename it and non_localized_resource.h. Is it DLL resources? -#include +#include #include "omaha/goopdate/non_localized_resource.h" LANGUAGE LANG_NEUTRAL, SUBLANG_DEFAULT @@ -32,5 +32,4 @@ IDR_GOOGLE_UPDATE3_SERVICE_APPID REGISTRY "omaha/base/generic_reg_file_appid.rg 1 TYPELIB "goopdate\\omaha3_idl.tlb" IDB_CHROME BITMAP "omaha/goopdate/resources/chrome.bmp" -IDR_MARQUEE AVI "omaha/goopdate/resources/marquee.avi" diff --git a/omaha/goopdate/goopdate_unittest.cc b/omaha/goopdate/goopdate_unittest.cc index a97782d..bca7d16 100644 --- a/omaha/goopdate/goopdate_unittest.cc +++ b/omaha/goopdate/goopdate_unittest.cc @@ -720,7 +720,6 @@ static void EnsureUnitTestUpdatedWithNewModes() { case COMMANDLINE_MODE_SERVICE: case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_REPORTCRASH: case COMMANDLINE_MODE_INSTALL: @@ -761,7 +760,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_MachineDirOnly) { } EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_REGSERVER)); EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_UNREGSERVER)); - EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_NETDIAGS)); EXPECT_TRUE(FromMachineDirHelper(COMMANDLINE_MODE_CRASH)); // TODO(omaha): Change to machine. EXPECT_FALSE(FromMachineDirHelper(COMMANDLINE_MODE_REPORTCRASH)); @@ -811,7 +809,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_IsLocalSystemOnly) { EXPECT_TRUE(IsLocalSystemHelper(COMMANDLINE_MODE_SERVICE)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_REGSERVER)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_UNREGSERVER)); - EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_NETDIAGS)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_CRASH)); EXPECT_FALSE(IsLocalSystemHelper(COMMANDLINE_MODE_REPORTCRASH)); { @@ -860,7 +857,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_MachineOverrideOnly) { } EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_REGSERVER)); EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_UNREGSERVER)); - EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_NETDIAGS)); EXPECT_FALSE(MachineOverrideHelper(COMMANDLINE_MODE_CRASH)); EXPECT_TRUE(MachineOverrideHelper(COMMANDLINE_MODE_REPORTCRASH)); { @@ -912,7 +908,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_NeedsAdminFalseOnly) { } EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_REGSERVER)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_UNREGSERVER)); - EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_NETDIAGS)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_CRASH)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_REPORTCRASH)); EXPECT_FALSE(NeedsAdminFalseHelper(COMMANDLINE_MODE_INSTALL)); @@ -952,7 +947,6 @@ TEST_F(GoopdateIsMachineProcessTest, IsMachineProcess_NeedsAdminTrueOnly) { } EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_REGSERVER)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_UNREGSERVER)); - EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_NETDIAGS)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_CRASH)); EXPECT_FALSE(NeedsAdminTrueHelper(COMMANDLINE_MODE_REPORTCRASH)); EXPECT_TRUE(NeedsAdminTrueHelper(COMMANDLINE_MODE_INSTALL)); diff --git a/omaha/goopdate/goopdate_version.rc b/omaha/goopdate/goopdate_version.rc index e2f94c9..31b63d1 100644 --- a/omaha/goopdate/goopdate_version.rc +++ b/omaha/goopdate/goopdate_version.rc @@ -15,7 +15,7 @@ // // This file contains the unlocalized goopdate DLL version resources. -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -49,7 +49,6 @@ BEGIN VALUE "FileDescription", OMAHA_APP_NAME_ANSI VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", OMAHA_COPYRIGHT_STRING_ENGLISH VALUE "OriginalFilename", MAIN_DLL_BASE_NAME_ANSI ".dll" VALUE "ProductName", OMAHA_APP_NAME_ANSI VALUE "ProductVersion", VERSION_NUMBER_STRING diff --git a/omaha/goopdate/install_manager.cc b/omaha/goopdate/install_manager.cc index e31872f..f922b9d 100644 --- a/omaha/goopdate/install_manager.cc +++ b/omaha/goopdate/install_manager.cc @@ -23,6 +23,7 @@ #include "omaha/base/scope_guard.h" #include "omaha/base/synchronized.h" #include "omaha/base/utils.h" +#include "omaha/common/brave_stats_updater.h" #include "omaha/common/config_manager.h" #include "omaha/common/const_cmd_line.h" #include "omaha/common/install_manifest.h" @@ -119,6 +120,9 @@ void InstallManager::InstallApp(App* app, const CString& dir) { HANDLE primary_token(app->app_bundle()->primary_token()); + omaha::BraveSendStatsPing(_T("installer-run"), app->app_guid_string(), + app->referral_id(), next_version->version()); + HRESULT hr = InstallApp(is_machine_, primary_token, current_version_string, diff --git a/omaha/goopdate/install_manager.h b/omaha/goopdate/install_manager.h index 3bfa248..4f711c5 100644 --- a/omaha/goopdate/install_manager.h +++ b/omaha/goopdate/install_manager.h @@ -21,8 +21,9 @@ #include #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/thread_pool.h" namespace omaha { @@ -76,7 +77,7 @@ class InstallManager : public InstallManagerInterface { // Base path where verified application packages are copied before install. CString install_working_dir_; - scoped_ptr installer_wrapper_; + std::unique_ptr installer_wrapper_; friend class InstallManagerInstallAppTest; diff --git a/omaha/goopdate/install_manager_unittest.cc b/omaha/goopdate/install_manager_unittest.cc index 3ad09e5..ddc17e6 100644 --- a/omaha/goopdate/install_manager_unittest.cc +++ b/omaha/goopdate/install_manager_unittest.cc @@ -13,16 +13,17 @@ // limitations under the License. // ======================================================================== +#include "omaha/goopdate/install_manager.h" + #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/shell.h" #include "omaha/base/synchronized.h" #include "omaha/base/system.h" @@ -38,7 +39,6 @@ #include "omaha/goopdate/app_state_waiting_to_install.h" #include "omaha/goopdate/app_unittest_base.h" #include "omaha/goopdate/installer_wrapper.h" -#include "omaha/goopdate/install_manager.h" #include "omaha/testing/unit_test.h" using ::testing::_; @@ -95,7 +95,7 @@ const TCHAR kMsiLogFormat[] = _T("%s.log"); // brand, InstallTime, DayOfInstall, DayOfLastActivity, DayOfLastRollCall, and // LastCheckSuccess are automatically populated. -const int kNumAutoPopulatedValues = 6; +const int kNumAutoPopulatedValues = 7; FileHash CreateFileHash(const CString& sha1, const CString& sha256) { FileHash hash; @@ -266,7 +266,7 @@ class InstallManagerInstallAppTest : public AppTestBase { app, result_info); } - scoped_ptr installer_wrapper_; + std::unique_ptr installer_wrapper_; App* app_; diff --git a/omaha/goopdate/installer_wrapper.cc b/omaha/goopdate/installer_wrapper.cc index 5ffcb71..fa4f41f 100644 --- a/omaha/goopdate/installer_wrapper.cc +++ b/omaha/goopdate/installer_wrapper.cc @@ -26,7 +26,6 @@ #include "omaha/base/process.h" #include "omaha/base/safe_format.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/synchronized.h" #include "omaha/base/system_info.h" diff --git a/omaha/goopdate/installer_wrapper.h b/omaha/goopdate/installer_wrapper.h index 0f68ca3..f7855c4 100644 --- a/omaha/goopdate/installer_wrapper.h +++ b/omaha/goopdate/installer_wrapper.h @@ -23,8 +23,8 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/synchronized.h" #include "omaha/goopdate/installer_result_info.h" diff --git a/omaha/goopdate/installer_wrapper_unittest.cc b/omaha/goopdate/installer_wrapper_unittest.cc index 8069dbd..919eadd 100644 --- a/omaha/goopdate/installer_wrapper_unittest.cc +++ b/omaha/goopdate/installer_wrapper_unittest.cc @@ -13,16 +13,18 @@ // limitations under the License. // ======================================================================== +#include "omaha/goopdate/installer_wrapper.h" + #include #include -#include "base/scoped_ptr.h" +#include + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/process.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/shell.h" #include "omaha/base/system.h" #include "omaha/base/timer.h" @@ -32,7 +34,6 @@ #include "omaha/common/const_goopdate.h" #include "omaha/common/install_manifest.h" #include "omaha/goopdate/app_manager.h" -#include "omaha/goopdate/installer_wrapper.h" #include "omaha/goopdate/model.h" #include "omaha/goopdate/resource_manager.h" #include "omaha/testing/unit_test.h" @@ -409,7 +410,7 @@ class InstallerWrapperTest : public testing::Test { static const int kOtherInstaller = InstallerWrapper::CUSTOM_INSTALLER; bool is_machine_; - scoped_ptr iw_; + std::unique_ptr iw_; // Used as an argument to various functions. InstallerResultInfo result_info_; diff --git a/omaha/goopdate/job_observer.h b/omaha/goopdate/job_observer.h index 5369360..d2d04df 100644 --- a/omaha/goopdate/job_observer.h +++ b/omaha/goopdate/job_observer.h @@ -22,7 +22,7 @@ #include #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/utils.h" #include "omaha/client/install_apps.h" #include "goopdate/omaha3_idl.h" diff --git a/omaha/goopdate/model.cc b/omaha/goopdate/model.cc index c0fffa8..d64f515 100644 --- a/omaha/goopdate/model.cc +++ b/omaha/goopdate/model.cc @@ -14,8 +14,9 @@ // ======================================================================== #include "omaha/goopdate/model.h" + #include -#include + #include "omaha/base/debug.h" #include "omaha/base/logging.h" #include "omaha/goopdate/worker.h" @@ -39,10 +40,10 @@ Model::~Model() { worker_ = NULL; } -shared_ptr Model::CreateAppBundle(bool is_machine) { +std::shared_ptr Model::CreateAppBundle(bool is_machine) { __mutexScope(lock_); - shared_ptr app_bundle(new AppBundle(is_machine, this)); + std::shared_ptr app_bundle(new AppBundle(is_machine, this)); app_bundles_.push_back(AppBundleWeakPtr(app_bundle)); const int lock_count(worker_->Lock()); @@ -60,7 +61,7 @@ void Model::CleanupExpiredAppBundles() { typedef std::vector::iterator Iterator; Iterator it = remove_if(app_bundles_.begin(), app_bundles_.end(), - std::mem_fun_ref(&AppBundleWeakPtr::expired)); + [](AppBundleWeakPtr ptr) { return ptr.expired(); }); const size_t num_bundles = distance(it, app_bundles_.end()); @@ -78,7 +79,7 @@ size_t Model::GetNumberOfAppBundles() const { return app_bundles_.size(); } -shared_ptr Model::GetAppBundle(size_t index) const { +std::shared_ptr Model::GetAppBundle(size_t index) const { __mutexScope(lock_); ASSERT1(!app_bundles_[index].expired()); return app_bundles_[index].lock(); diff --git a/omaha/goopdate/model.h b/omaha/goopdate/model.h index d789a94..b764921 100644 --- a/omaha/goopdate/model.h +++ b/omaha/goopdate/model.h @@ -23,17 +23,17 @@ #endif #include +#include #include + #include "base/basictypes.h" #include "base/debug.h" -#include "base/scoped_ptr.h" #include "base/synchronized.h" #include "omaha/goopdate/app.h" #include "omaha/goopdate/app_bundle.h" #include "omaha/goopdate/app_version.h" #include "omaha/goopdate/current_state.h" #include "omaha/goopdate/package.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { @@ -52,14 +52,14 @@ class Model { } // Creates an AppBundle object in the model. - shared_ptr CreateAppBundle(bool is_machine); + std::shared_ptr CreateAppBundle(bool is_machine); // Removes the AppBundle objects that have no outstanding strong references. void CleanupExpiredAppBundles(); size_t GetNumberOfAppBundles() const; - shared_ptr GetAppBundle(size_t index) const; + std::shared_ptr GetAppBundle(size_t index) const; // Initiates an update check for all apps in the bundle. HRESULT CheckForUpdate(AppBundle* app_bundle); @@ -88,7 +88,7 @@ class Model { const CString& version) const; private: - typedef weak_ptr AppBundleWeakPtr; + using AppBundleWeakPtr = std::weak_ptr; // Serializes access to the model objects. Consider replacing with SWMR lock. LLock lock_; diff --git a/omaha/goopdate/non_localized_resource.h b/omaha/goopdate/non_localized_resource.h index 35080dc..3bcec6b 100644 --- a/omaha/goopdate/non_localized_resource.h +++ b/omaha/goopdate/non_localized_resource.h @@ -24,6 +24,5 @@ #define IDR_GOOGLE_UPDATE3_SERVICE_APPID 2009 #define IDB_CHROME 2100 -#define IDR_MARQUEE 2102 #endif // OMAHA_GOOPDATE_NON_LOCALIZED_RESOURCE_H_ diff --git a/omaha/goopdate/offline_utils_unittest.cc b/omaha/goopdate/offline_utils_unittest.cc index 0ff9147..bdf50d6 100644 --- a/omaha/goopdate/offline_utils_unittest.cc +++ b/omaha/goopdate/offline_utils_unittest.cc @@ -14,7 +14,9 @@ // ======================================================================== #include "omaha/goopdate/offline_utils.h" + #include + #include "omaha/base/app_util.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" @@ -113,7 +115,7 @@ void ParseAndCheck(const TCHAR* source_manifest_extension, EXPECT_SUCCEEDED(File::Copy(source_manifest_path, target_manifest_path, true)); - scoped_ptr update_response( + std::unique_ptr update_response( xml::UpdateResponse::Create()); EXPECT_SUCCEEDED(offline_utils::ParseOfflineManifest( kAppId1, @@ -178,7 +180,7 @@ TEST(OfflineUtilsTest, ParseOfflineManifest_v2_Success) { } TEST(OfflineUtilsTest, ParseOfflineManifest_FileDoesNotExist) { - scoped_ptr update_response( + std::unique_ptr update_response( xml::UpdateResponse::Create()); EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), offline_utils::ParseOfflineManifest( diff --git a/omaha/goopdate/omaha3_idl.idl b/omaha/goopdate/omaha3_idl.idl index 7fc1378..2e3d188 100644 --- a/omaha/goopdate/omaha3_idl.idl +++ b/omaha/goopdate/omaha3_idl.idl @@ -109,7 +109,7 @@ enum AppCommandStatus { [ object, dual, - uuid(76607e7e-c0ff-4dd3-b134-7fc3724ee66a), + uuid(7CB305B1-4D45-4668-AD91-677F87BED305), helpstring("IGoogleUpdate3 Interface"), pointer_default(unique) ] @@ -132,7 +132,7 @@ interface IGoogleUpdate3 : IDispatch { [ object, dual, - uuid(9a527c99-02cb-49eb-a14f-225c25cb76dc), + uuid(1985533F-9B0F-490A-85C5-24F316E66FB2), helpstring("IAppBundle Interface"), pointer_default(unique) ] @@ -243,7 +243,7 @@ interface IAppBundle : IDispatch { [ object, dual, - uuid(2ea2902f-31b3-45fe-a27a-62bb796e74c0), + uuid(A4BCDF52-2179-4C77-8C5F-B8095712B563), helpstring("IApp Interface"), pointer_default(unique) ] @@ -316,7 +316,7 @@ interface IApp : IDispatch { [ object, dual, - uuid(90861d48-51c0-46ec-9b4f-b32dba5fe6f6), + uuid(A147722A-5568-4B84-B401-86D744470CBF), helpstring("IApp2 Interface"), pointer_default(unique) ] @@ -328,7 +328,7 @@ interface IApp2 : IApp { [ object, dual, - uuid(ab158438-2643-41a5-a576-1edfe7a10114), + uuid(4842EC21-0860-45B5-99F0-A1E6E7C11561), helpstring("IAppCommand Interface"), pointer_default(unique) ] @@ -351,7 +351,7 @@ interface IAppCommand : IDispatch { [ object, dual, - uuid(20b6b554-b345-4deb-9075-04cbfac85492), + uuid(C11C073F-E6D0-4EF7-897B-AAF52498CD2F), helpstring("IAppCommand2 Interface"), pointer_default(unique) ] @@ -362,7 +362,7 @@ interface IAppCommand2 : IAppCommand { [ object, dual, - uuid(6f5a84a3-867a-47bb-848b-a4cd8ffa8fce), + uuid(F234546B-DACD-4374-97CF-7BADFAB76766), helpstring("IAppVersion Interface"), pointer_default(unique) ] @@ -383,7 +383,7 @@ interface IAppVersion : IDispatch { [ object, dual, - uuid(593e29d1-4adf-4f5d-ade8-a0836155c8a3), + uuid(C663DEBB-F082-4971-9F6E-35DE45C96F4E), helpstring("IPackage Interface"), pointer_default(unique) ] @@ -406,7 +406,7 @@ interface IPackage : IDispatch { [ object, dual, - uuid(9df22aa7-720e-4216-9cb4-727781edac1a), + uuid(E6836CFF-5949-44BC-B6BE-9C8C48DD8D97), helpstring("ICurrentState Interface"), pointer_default(unique) ] @@ -498,7 +498,7 @@ interface ICurrentState : IDispatch { [ object, dual, - uuid(9f2f5f08-a28f-414f-8fe5-31d77b2af211), + uuid(48B5E6B2-9383-4B1E-AAE7-720C4779ABA6), helpstring("IRegistrationUpdateHook Interface"), pointer_default(unique), ] @@ -508,7 +508,7 @@ interface IRegistrationUpdateHook : IDispatch { [ object, - uuid(a3c270b9-98bd-4998-91a4-3f11adad0377), + uuid(660130E8-74E4-4821-A6FD-4E9A86E06470), helpstring("ICredentialDialog Interface"), pointer_default(unique), ] @@ -529,7 +529,7 @@ interface ICredentialDialog : IUnknown { [ object, dual, - uuid(c90fc75b-9bdc-47aa-9f3c-59f416c91aef), + uuid(C9190589-ECEC-43F8-8AEC-62496BB87B26), helpstring("IGoogleUpdate3Web Interface"), pointer_default(unique), ] @@ -539,7 +539,7 @@ interface IGoogleUpdate3Web : IDispatch { [ object, - uuid(d8f0740e-8970-44e4-ad03-46394ba7d3e7), + uuid(24D704AD-AC42-49F2-BB4F-68BA77C98E91), helpstring("IGoogleUpdate3WebSecurity Interface"), pointer_default(unique), ] @@ -550,7 +550,7 @@ interface IGoogleUpdate3WebSecurity : IUnknown { [ object, dual, - uuid(3aaa8bbc-dc93-49d9-9b87-c8ded3b2bb40), + uuid(852A0F87-D117-4B7C-ABA9-2F76D91BCB9D), helpstring("IAppBundleWeb Interface"), pointer_default(unique), ] @@ -589,7 +589,7 @@ interface IAppBundleWeb : IDispatch { [ object, dual, - uuid(973d746a-1df2-404a-b66b-ea632417866f), + uuid(FB43AAD0-DDBA-4D01-A3E0-FAB100E7926B), helpstring("IAppWeb Interface"), pointer_default(unique), ] @@ -618,7 +618,7 @@ interface IAppWeb : IDispatch { [ object, dual, - uuid(c0be1521-7935-42e6-b606-058a559910ba), + uuid(19F4616B-B7DD-4B3F-8084-C81C5C77AAA4), helpstring("IAppCommandWeb Interface"), pointer_default(unique) ] @@ -641,7 +641,7 @@ interface IAppCommandWeb : IDispatch { [ object, dual, - uuid(afc15738-2cc4-4aac-9b19-c1831428d04f), + uuid(35A4470F-5EEC-4715-A2DC-6AA9F8E21183), helpstring("IAppVersionWeb Interface"), pointer_default(unique) ] @@ -661,7 +661,7 @@ interface IAppVersionWeb : IDispatch { [ object, dual, - uuid(4dafb7ab-e8d8-4003-87b8-678e15b4c221), + uuid(7A24060E-533F-4962-9E15-34BD82555FA7), helpstring("ICoCreateAsyncStatus Interface"), pointer_default(unique) ] @@ -673,7 +673,7 @@ interface ICoCreateAsyncStatus : IDispatch { [ object, - uuid(7fbb29e7-6703-4624-ad84-c8500f57c5c4), + uuid(DD84E356-3D21-44C8-83DD-6BEEC22FA427), helpstring("ICoCreateAsync Interface"), pointer_default(unique) ] @@ -690,7 +690,7 @@ interface ICoCreateAsync : IUnknown { [ object, - uuid(791df12c-01ff-43a1-a3d7-5b1b98a9248a), + uuid(AAE4AD28-500D-43BA-9F54-730CA146C190), oleautomation, nonextensible, pointer_default(unique) @@ -723,7 +723,7 @@ interface IBrowserHttpRequest2 : IUnknown { [ object, oleautomation, - uuid(28839a52-cddf-4c7c-ac21-b1c4fc1be7ef), + uuid(70E5ECF5-2CA7-4019-9B23-916789A13C2C), helpstring("Google Update IProcessLauncher Interface"), pointer_default(unique) ] @@ -749,7 +749,7 @@ interface IProcessLauncher : IUnknown { [ object, oleautomation, - uuid(addddf17-7ad2-4ea1-86d7-ffb8d5972baf), + uuid(D5627FC9-E2F0-484B-89A4-5DACFE7FAAD3), helpstring("Google Update IProcessLauncher2 Interface"), pointer_default(unique) ] @@ -769,18 +769,6 @@ interface IProcessLauncher2 : IProcessLauncher { [out] ULONG_PTR* stdout_handle); }; -[ - object, - oleautomation, - uuid(4d3a05b9-5ef2-46f9-a4fe-81b01637ed47), - helpstring("Google Update IOneClickProcessLauncher Interface"), - pointer_default(unique) -] -interface IOneClickProcessLauncher : IUnknown { - HRESULT LaunchAppCommand([in, string] const WCHAR* app_guid, - [in, string] const WCHAR* cmd_id); -}; - typedef enum { COMPLETION_CODE_SUCCESS = 1, COMPLETION_CODE_SUCCESS_CLOSE_UI, @@ -797,7 +785,7 @@ typedef enum { [ object, oleautomation, - uuid(cd858925-6866-4f02-b9e9-b5b08e353be7), + uuid(8504FB26-FC3E-4C1C-9C94-46EC93E6BA63), helpstring("GoogleUpdate UI-specific events Interface"), pointer_default(unique) ] @@ -826,7 +814,7 @@ interface IProgressWndEvents : IUnknown { [ object, oleautomation, - uuid(ff612905-d787-4f53-ab5e-5ab5971b10a7), + uuid(7CFC4E00-1C9D-443D-B5BE-CEEEAC1443AF), helpstring("IJobObserver Interface"), pointer_default(unique) ] @@ -847,18 +835,21 @@ interface IJobObserver : IUnknown { [ object, oleautomation, - uuid(edccf840-a0a4-4d10-82f4-4f60f848ea56), + uuid(91B050A9-5A49-4249-A8C8-B4390961A912), helpstring("IJobObserver2 Interface"), pointer_default(unique) ] interface IJobObserver2 : IUnknown { + // @param time_remaining_ms Remaining install time. + // @param pos Current install progress in percentage from 0 to 100. -1 + // indicates unknown. HRESULT OnInstalling2([in] int time_remaining_ms, [in] int pos); }; [ object, oleautomation, - uuid(a62c03e7-56ef-4109-a920-d3c06665223e), + uuid(4C929BFE-4FA4-488D-B1E2-82ECD6F076C8), helpstring("IGoogleUpdate Interface"), pointer_default(unique) ] @@ -878,7 +869,7 @@ interface IGoogleUpdate : IUnknown { [ object, oleautomation, - uuid(857a3d7a-6b13-45f3-a19b-75870d0c2823), + uuid(10479D64-2C5F-46CD-9BC8-FD04FF4D02D8), helpstring("Google Update Core Interface"), pointer_default(unique) ] @@ -899,7 +890,7 @@ interface IGoogleUpdateCore : IUnknown // END Legacy google_update_idl interfaces. [ - uuid(5e3de9e9-0248-4fab-ac1c-01b86cf9790e), + uuid(6FF4F468-0B5A-4878-ACEB-86263DAAD877), version(1.0), helpstring("Omaha 3.0 Type Library") ] @@ -927,7 +918,7 @@ library GoogleUpdate3Lib { interface ICoCreateAsyncStatus; [ - uuid(cec92c56-68e4-4494-ba79-eb3a71ad8473), + uuid(2CF4A521-EC1E-4075-A20B-5DE3E5B89B1B), helpstring("GoogleUpdate3 Class for per-user applications") ] coclass GoogleUpdate3UserClass { @@ -935,7 +926,7 @@ library GoogleUpdate3Lib { } [ - uuid(edc2caa1-2001-4835-a04a-565a5cde5f7f), + uuid(08F15E98-0442-45D3-82F1-F67495CC51EB), helpstring("GoogleUpdate3 Service Class for machine applications") ] coclass GoogleUpdate3ServiceClass { @@ -943,7 +934,7 @@ library GoogleUpdate3Lib { } [ - uuid(b5bae3dd-809e-4be3-a421-f5d3f17a03db), + uuid(2F78AECB-0A7F-4474-89D5-C325293DE960), helpstring("GoogleUpdate3Web for user applications") ] coclass GoogleUpdate3WebUserClass { @@ -951,7 +942,7 @@ library GoogleUpdate3Lib { } [ - uuid(31e52f9c-5dba-4a20-b7d4-4ade46fbf9e9), + uuid(00B16F95-319A-4F01-AC81-CE69B8F4E387), helpstring("Pass-through broker for the GoogleUpdate3WebServiceClass") ] coclass GoogleUpdate3WebMachineClass { @@ -959,7 +950,7 @@ library GoogleUpdate3Lib { } [ - uuid(2e119b1c-8a13-4e21-92c2-1b34cab1f028), + uuid(3A9D7221-2278-41DD-930B-C2356B7D3725), helpstring("GoogleUpdate3Web") ] coclass GoogleUpdate3WebServiceClass { @@ -967,7 +958,7 @@ library GoogleUpdate3Lib { } [ - uuid(0e2ee4d0-7ef1-45d0-aae8-2506c0ba649c), + uuid(66CE3D6C-0B35-4F78-AC77-39728A75CB75), helpstring("Fallback mechanism if GoogleUpdate3WebServiceClass fails") ] coclass GoogleUpdate3WebMachineFallbackClass { @@ -975,7 +966,7 @@ library GoogleUpdate3Lib { } [ - uuid(733eb758-7cf0-4927-a3b9-75eb28490613), + uuid(06B74C04-E813-4DD4-A972-172836EFA8D6), helpstring("CurrentStateUserClass") ] coclass CurrentStateUserClass { @@ -983,7 +974,7 @@ library GoogleUpdate3Lib { } [ - uuid(dad290ab-07df-443d-9a5a-4434474353ed), + uuid(BC03C0E4-1528-4299-89B2-419644FA48AC), helpstring("CurrentStateMachineClass") ] coclass CurrentStateMachineClass { @@ -991,7 +982,7 @@ library GoogleUpdate3Lib { } [ - uuid(5e79da64-77df-4c1f-9184-c6b5f035e3d9), + uuid(8F6D9FE5-6ED3-43A3-80D2-EA8766D65352), helpstring("CoCreateAsyncClass") ] coclass CoCreateAsyncClass { @@ -999,7 +990,7 @@ library GoogleUpdate3Lib { } [ - uuid(a663a8e3-b533-4153-8ef6-3c5823de9280), + uuid(4C738ABE-2ED7-4BF6-B668-046DC1A72C00), helpstring("CredentialDialogUserClass") ] coclass CredentialDialogUserClass { @@ -1007,7 +998,7 @@ library GoogleUpdate3Lib { } [ - uuid(341390f2-6214-4981-a2ae-738205e73590), + uuid(B5D1924F-CB80-47AA-8DEC-5E0854A42A73), helpstring("CredentialDialogMachineClass") ] coclass CredentialDialogMachineClass { @@ -1033,7 +1024,7 @@ library GoogleUpdate3Lib { // BEGIN Legacy google_update_idl coclasses. [ - uuid(f235f88c-3de7-4195-a0e9-105ba38344cc), + uuid(4C3BA8F3-1264-4BDB-BB2D-CA44734AD00D), helpstring("ProcessLauncherClass Class") ] coclass ProcessLauncherClass { @@ -1041,23 +1032,7 @@ library GoogleUpdate3Lib { } [ - uuid(bb42bfd1-b0eb-449c-8882-fb810c2738d0), - helpstring("OneClickUserProcessLauncherClass Class") - ] - coclass OneClickUserProcessLauncherClass { - [default] interface IOneClickProcessLauncher; - } - - [ - uuid(5457eff7-c0b3-4672-a6b4-58f93951f1e0), - helpstring("OneClickMachineProcessLauncherClass Class") - ] - coclass OneClickMachineProcessLauncherClass { - [default] interface IOneClickProcessLauncher; - } - - [ - uuid(660baf72-a9ef-4fb1-81ae-9395ca6c39cf), + uuid(6DA8171A-7CEC-4E45-BDED-9F287AD7C854), helpstring("OnDemand updates for per-user applications.") ] coclass OnDemandUserAppsClass { @@ -1065,7 +1040,7 @@ library GoogleUpdate3Lib { } [ - uuid(0dd31efc-0cf5-4ec5-9799-f1a8819acea4), + uuid(28C83F57-E4C0-4B54-B187-585C51EE8F9C), helpstring("OnDemand pass-through broker for machine applications.") ] coclass OnDemandMachineAppsClass { @@ -1073,7 +1048,7 @@ library GoogleUpdate3Lib { } [ - uuid(19c06b1a-7202-40b4-9903-62927d08f943), + uuid(D7D7525F-5DF4-4C9D-8781-C02F39F973E6), helpstring("OnDemand updates for per-machine applications.") ] coclass OnDemandMachineAppsServiceClass { @@ -1081,7 +1056,7 @@ library GoogleUpdate3Lib { } [ - uuid(107e2437-bfe7-4e17-91d9-2866e1373e00), + uuid(3282EB12-D954-4FD2-A2E1-C942C8745C65), helpstring("Fallback for if OnDemandMachineAppsServiceClass fails.") ] coclass OnDemandMachineAppsFallbackClass { @@ -1089,7 +1064,7 @@ library GoogleUpdate3Lib { } [ - uuid(b0f72540-f2a8-4027-aac8-a39deb0470ad), + uuid(3AD2D487-D166-4160-8E36-1AE505233A55), helpstring("GoogleUpdateCore Class") ] coclass GoogleUpdateCoreClass @@ -1098,7 +1073,7 @@ library GoogleUpdate3Lib { } [ - uuid(b15e7b58-2a81-4f3e-8381-f5db7d3a1f84), + uuid(F7FF255A-A593-41BD-A69B-E05D72B72756), helpstring("GoogleUpdateCore Machine Class") ] coclass GoogleUpdateCoreMachineClass diff --git a/omaha/goopdate/omaha_customization_goopdate_apis_unittest.cc b/omaha/goopdate/omaha_customization_goopdate_apis_unittest.cc index 10b73a0..d6db836 100644 --- a/omaha/goopdate/omaha_customization_goopdate_apis_unittest.cc +++ b/omaha/goopdate/omaha_customization_goopdate_apis_unittest.cc @@ -508,42 +508,6 @@ TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, EXPECT_TRUE(!help_file_); } -TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, - OneClickUserProcessLauncherClass) { - EXPECT_GU_ID_EQ(_T("{51F9E8EF-59D7-475b-A106-C7EA6F30C119}"), - __uuidof(OneClickUserProcessLauncherClass)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("OneClickUserProcessLauncherClass"))); - EXPECT_STREQ(_T("OneClickUserProcessLauncherClass Class"), - item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, - IOneClickProcessLauncher) { - EXPECT_GU_ID_EQ(_T("{5CCCB0EF-7073-4516-8028-4C628D0C8AAB}"), - __uuidof(IOneClickProcessLauncher)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("IOneClickProcessLauncher"))); - EXPECT_STREQ(_T("Google Update IOneClickProcessLauncher Interface"), - item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - -TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, - OneClickMachineProcessLauncherClass) { - EXPECT_GU_ID_EQ(_T("{AAD4AE2E-D834-46d4-8B09-490FAC9C722B}"), - __uuidof(OneClickMachineProcessLauncherClass)); - - EXPECT_SUCCEEDED(GetDocumentation(_T("OneClickMachineProcessLauncherClass"))); - EXPECT_STREQ(_T("OneClickMachineProcessLauncherClass Class"), - item_doc_string_); - EXPECT_EQ(0, help_context_); - EXPECT_TRUE(!help_file_); -} - TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, OnDemandUserAppsClass) { EXPECT_GU_ID_EQ(_T("{2F0E2680-9FF5-43c0-B76E-114A56E93598}"), @@ -616,7 +580,7 @@ TEST_GU_INT_F(OmahaCustomizationGoopdateComInterfaceTest, // Verifies there are no new interfaces in the TypeLib. TEST_F(OmahaCustomizationGoopdateComInterfaceTest, VerifyNoNewInterfaces) { - EXPECT_EQ(39, type_lib_->GetTypeInfoCount()) + EXPECT_EQ(36, type_lib_->GetTypeInfoCount()) << _T("A new interface may have been added. If so, add the interface to ") << _T("to kIIDsToRegister, and add test(s) for new interface(s)."); } diff --git a/omaha/goopdate/ondemand.h b/omaha/goopdate/ondemand.h index 5a3a115..7c034b1 100644 --- a/omaha/goopdate/ondemand.h +++ b/omaha/goopdate/ondemand.h @@ -21,9 +21,10 @@ #include #include #include +#include + #include "base/basictypes.h" #include "base/debug.h" -#include "base/scoped_ptr.h" #include "omaha/base/atlregmapex.h" #include "omaha/base/constants.h" #include "omaha/base/preprocessor_fun.h" @@ -79,10 +80,6 @@ HRESULT DoOnDemand(bool is_machine, } // namespace internal -#pragma warning(push) - -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) template class ATL_NO_VTABLE OnDemand @@ -179,7 +176,7 @@ class ATL_NO_VTABLE OnDemand // impersonation and primary tokens. typedef StaticThreadPoolCallBack1 Callback; Gate on_demand_gate; - scoped_ptr callback( + std::unique_ptr callback( new Callback(&OnDemand::DoOnDemandInternal, internal::OnDemandParameters( guid, @@ -284,8 +281,6 @@ typedef OnDemand OnDemandUser; typedef OnDemand OnDemandMachineFallback; typedef OnDemand OnDemandService; -#pragma warning(pop) - } // namespace omaha #endif // OMAHA_GOOPDATE_ONDEMAND_H_ diff --git a/omaha/goopdate/oneclick_process_launcher.cc b/omaha/goopdate/oneclick_process_launcher.cc deleted file mode 100644 index 50ba1d6..0000000 --- a/omaha/goopdate/oneclick_process_launcher.cc +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#include "omaha/goopdate/oneclick_process_launcher.h" - -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_ptr_address.h" -#include "omaha/goopdate/app_command.h" -#include "omaha/goopdate/app_command_configuration.h" - -namespace omaha { - -OneClickProcessLauncher::OneClickProcessLauncher() {} - -OneClickProcessLauncher::~OneClickProcessLauncher() {} - -STDMETHODIMP OneClickProcessLauncher::LaunchAppCommand( - const WCHAR* app_guid, const WCHAR* cmd_id) { - ASSERT1(app_guid); - ASSERT1(cmd_id); - - if (!app_guid || !cmd_id) { - return E_INVALIDARG; - } - - CORE_LOG(L3, (_T("[OneClickProcessLauncher::LaunchAppCommand]") - _T("[app %s][cmd %s]"), app_guid, cmd_id)); - - // Allocate a session ID for the ping that this call will generate. - // TODO(omaha3): Are there any situations where this control can be - // instantiated outside of the context of an Update3Web/OneClick - // webpage? If not, we should consider adding a function to - // OneClickProcessLauncher() to modify the session ID it uses. - CString session_id; - GetGuid(&session_id); - - scoped_ptr configuration; - HRESULT hr = AppCommandConfiguration::Load(app_guid, - is_machine(), - cmd_id, - address(configuration)); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[failed to load command configuration][0x%x]"), hr)); - return hr; - } - - if (!configuration->is_web_accessible()) { - return E_ACCESSDENIED; - } - - if (!is_machine()) { - // Execute directly at medium integrity for user-level mode - scoped_process process; - scoped_ptr app_command(configuration->Instantiate(session_id)); - return app_command->Execute(NULL, std::vector(), address(process)); - } - - // Elevate to high integrity for machine-level mode - CComPtr process_launcher; - hr = process_launcher.CoCreateInstance(__uuidof(ProcessLauncherClass)); - if (FAILED(hr)) { - return hr; - } - - ULONG_PTR phandle = NULL; - DWORD process_id = ::GetCurrentProcessId(); - - hr = process_launcher->LaunchCmdElevated( - app_guid, cmd_id, process_id, &phandle); - - if (SUCCEEDED(hr)) { - ::CloseHandle(reinterpret_cast(phandle)); - } - - return hr; -} - -} // namespace omaha diff --git a/omaha/goopdate/oneclick_process_launcher.h b/omaha/goopdate/oneclick_process_launcher.h deleted file mode 100644 index 86a6000..0000000 --- a/omaha/goopdate/oneclick_process_launcher.h +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_GOOPDATE_ONECLICK_PROCESS_LAUNCHER_H__ -#define OMAHA_GOOPDATE_ONECLICK_PROCESS_LAUNCHER_H__ - -#include -#include -#include "base/basictypes.h" -#include "goopdate/omaha3_idl.h" -#include "omaha/base/atlregmapex.h" -#include "omaha/common/const_goopdate.h" -#include "omaha/common/goopdate_utils.h" -#include "omaha/goopdate/non_localized_resource.h" - -namespace omaha { - -const TCHAR* const kOneClickProcessLauncherTlbVersion = _T("1.0"); -const TCHAR* const kOneClickProcessLauncherDescription = - _T(SHORT_COMPANY_NAME_ANSI) _T(".OneClickProcessLauncher"); - -class ATL_NO_VTABLE OneClickProcessLauncher - : public CComObjectRootEx, - public CComCoClass, - public IOneClickProcessLauncher { - public: - OneClickProcessLauncher(); - virtual ~OneClickProcessLauncher(); - - DECLARE_NOT_AGGREGATABLE(OneClickProcessLauncher) - DECLARE_PROTECT_FINAL_CONSTRUCT() - - DECLARE_REGISTRY_RESOURCEID_EX(IDR_LOCAL_SERVER_IE_LOW_RGS) - - #pragma warning(push) - // C4640: construction of local static object is not thread-safe - #pragma warning(disable : 4640) - BEGIN_REGISTRY_MAP() - REGMAP_ENTRY(_T("HKROOT"), goopdate_utils::GetHKRoot()) - REGMAP_MODULE2(_T("MODULE"), - is_machine() ? kOmahaBrokerFileName : kOmahaOnDemandFileName) - REGMAP_ENTRY(_T("VERSION"), kOneClickProcessLauncherTlbVersion) - REGMAP_ENTRY(_T("PROGID"), - is_machine() ? - kProgIDOneClickProcessLauncherMachine : - kProgIDOneClickProcessLauncherUser) - REGMAP_ENTRY(_T("DESCRIPTION"), kOneClickProcessLauncherDescription) - REGMAP_UUID(_T("CLSID"), - is_machine() ? - __uuidof(OneClickMachineProcessLauncherClass) : - __uuidof(OneClickUserProcessLauncherClass)) - END_REGISTRY_MAP() - #pragma warning(pop) - - // C4505: unreferenced IUnknown local functions have been removed - #pragma warning(disable : 4505) - BEGIN_COM_MAP(OneClickProcessLauncher) - COM_INTERFACE_ENTRY(IOneClickProcessLauncher) - END_COM_MAP() - - STDMETHOD(LaunchAppCommand)(const WCHAR* app_guid, - const WCHAR* cmd_id); - - private: - static bool is_machine() { - return goopdate_utils::IsRunningFromOfficialGoopdateDir(true); - } - - DISALLOW_COPY_AND_ASSIGN(OneClickProcessLauncher); -}; // class OneClickProcessLauncher - -} // namespace omaha - -#endif // OMAHA_GOOPDATE_ONECLICK_PROCESS_LAUNCHER_H__ diff --git a/omaha/goopdate/package.cc b/omaha/goopdate/package.cc index 02175bd..5a504a5 100644 --- a/omaha/goopdate/package.cc +++ b/omaha/goopdate/package.cc @@ -14,9 +14,9 @@ // ======================================================================== #include "omaha/goopdate/package.h" + #include "omaha/base/debug.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/synchronized.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" diff --git a/omaha/goopdate/package_cache.cc b/omaha/goopdate/package_cache.cc index 78ee01d..2fa8ac4 100644 --- a/omaha/goopdate/package_cache.cc +++ b/omaha/goopdate/package_cache.cc @@ -14,8 +14,11 @@ // ======================================================================== #include "omaha/goopdate/package_cache.h" + #include +#include #include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/file.h" diff --git a/omaha/goopdate/package_cache.h b/omaha/goopdate/package_cache.h index 8995ba5..b1352ad 100644 --- a/omaha/goopdate/package_cache.h +++ b/omaha/goopdate/package_cache.h @@ -38,7 +38,7 @@ class PackageCache { const CString& version, const CString& package_name) : app_id_(app_id), - version_(version.IsEmpty() ? _T("0.0.0.0") : version), + version_(version.IsEmpty() ? CString(_T("0.0.0.0")) : version), package_name_(package_name) {} CString app_id() const { return app_id_; } diff --git a/omaha/goopdate/process_launcher.h b/omaha/goopdate/process_launcher.h index 30bfc88..3df3a4b 100644 --- a/omaha/goopdate/process_launcher.h +++ b/omaha/goopdate/process_launcher.h @@ -55,9 +55,6 @@ class ATL_NO_VTABLE ProcessLauncher DECLARE_REGISTRY_RESOURCEID_EX(IDR_LOCAL_SERVER_RGS) - #pragma warning(push) - // C4640: construction of local static object is not thread-safe - #pragma warning(disable : 4640) BEGIN_REGISTRY_MAP() REGMAP_ENTRY(_T("HKROOT"), goopdate_utils::GetHKRoot()) REGMAP_MODULE2(_T("MODULE"), kOmahaOnDemandFileName) @@ -66,10 +63,7 @@ class ATL_NO_VTABLE ProcessLauncher REGMAP_ENTRY(_T("DESCRIPTION"), kProcessWorkerDescription) REGMAP_UUID(_T("CLSID"), __uuidof(ProcessLauncherClass)) END_REGISTRY_MAP() - #pragma warning(pop) - // C4505: unreferenced IUnknown local functions have been removed - #pragma warning(disable : 4505) BEGIN_COM_MAP(ProcessLauncher) COM_INTERFACE_ENTRY(IProcessLauncher2) COM_INTERFACE_ENTRY(IProcessLauncher) @@ -95,7 +89,7 @@ class ATL_NO_VTABLE ProcessLauncher ULONG_PTR* stdout_handle); private: - DISALLOW_EVIL_CONSTRUCTORS(ProcessLauncher); + DISALLOW_COPY_AND_ASSIGN(ProcessLauncher); }; } // namespace omaha diff --git a/omaha/goopdate/resource_manager.h b/omaha/goopdate/resource_manager.h index 66348ba..40cfd3a 100644 --- a/omaha/goopdate/resource_manager.h +++ b/omaha/goopdate/resource_manager.h @@ -85,7 +85,7 @@ class ResourceManager { friend class ResourceManagerTest; - DISALLOW_EVIL_CONSTRUCTORS(ResourceManager); + DISALLOW_COPY_AND_ASSIGN(ResourceManager); }; } // namespace omaha diff --git a/omaha/goopdate/resources/build.scons b/omaha/goopdate/resources/build.scons index ed99f53..4db2216 100644 --- a/omaha/goopdate/resources/build.scons +++ b/omaha/goopdate/resources/build.scons @@ -18,21 +18,9 @@ Import('env') local_env = env.Clone( - PRECOMPILE_STOPFILE = '', - PRECOMPILE_BUILDER = '', COMPONENT_STATIC = False, ) -# We disable runtime stack check to avoid increasing the code size. -# There is a compiler pragma to programmatically disable the stack checks -# but for some reason it did not work. -local_env.FilterOut(CPPFLAGS = ['/GS']) - -# Disable stack checks for VC80. Stack checks are on by default. -if local_env['msc_ver'] >= 1400: - local_env['CCFLAGS'] += ['/GS-'] - - for omaha_version_info in local_env['omaha_versions_info']: prefix = omaha_version_info.filename_prefix @@ -52,11 +40,13 @@ for omaha_version_info in local_env['omaha_versions_info']: '$OBJ_ROOT/goopdate', # Needed for the tlb ], LINKFLAGS = [ - '/NODEFAULTLIB', '/ENTRY:DllEntry', '/MERGE:.rdata=.text', '/BASE:0x19000000', ], + LIBS = [ + lang_env['crt_libs'][lang_env.Bit('debug')], + ] ) # Avoid conflicts in obj targets diff --git a/omaha/goopdate/resources/chrome.bmp b/omaha/goopdate/resources/chrome.bmp index 1201d65..bfde16d 100644 Binary files a/omaha/goopdate/resources/chrome.bmp and b/omaha/goopdate/resources/chrome.bmp differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_am.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_am.rc index 536d555..b5cf69a 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_am.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_am.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ar.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ar.rc index be5b72f..2f151f8 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ar.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ar.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_bg.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_bg.rc index 70247f9..5d4573c 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_bg.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_bg.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_bn.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_bn.rc index d51b155..6bfce84 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_bn.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_bn.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ca.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ca.rc index 15dcf7a..9d76f19 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ca.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ca.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_cs.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_cs.rc index 2c3833e..4dfc4d5 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_cs.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_cs.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_da.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_da.rc index a6ee391..b228f79 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_da.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_da.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_de.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_de.rc index b624965..61d5070 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_de.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_de.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_el.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_el.rc index 50913e8..3305f8c 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_el.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_el.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_en-GB.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_en-GB.rc index 5e31fd2..77a13d3 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_en-GB.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_en-GB.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_en.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_en.rc index 4133c1c..68848bd 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_en.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_en.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_es-419.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_es-419.rc index b595e14..cd8ecd3 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_es-419.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_es-419.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_es.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_es.rc index 8880958..7c2857b 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_es.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_es.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_et.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_et.rc index 1614f41..8af6fb9 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_et.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_et.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_fi.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_fi.rc index dfd56ba..08e89b7 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_fi.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_fi.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_fil.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_fil.rc index a82b588..a8bf08b 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_fil.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_fil.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_fr.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_fr.rc index 18f5493..a85a492 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_fr.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_fr.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_gu.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_gu.rc index df36d49..6019d53 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_gu.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_gu.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_hi.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_hi.rc index 8be4fee..8cff208 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_hi.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_hi.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_hr.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_hr.rc index d742c46..6bb5715 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_hr.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_hr.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_hu.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_hu.rc index 827891d..181c8d1 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_hu.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_hu.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_id.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_id.rc index 684a379..d860e5f 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_id.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_id.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_is.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_is.rc index 757fc50..347bca6 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_is.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_is.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_it.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_it.rc index f68283e..044343d 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_it.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_it.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_iw.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_iw.rc index 38806f3..c29a140 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_iw.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_iw.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ja.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ja.rc index 0646256..e77160c 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ja.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ja.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_kn.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_kn.rc index a3b160d..38a3c2b 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_kn.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_kn.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ko.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ko.rc index ae8a9dc..006c852 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ko.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ko.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_lt.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_lt.rc index 804782a..20ae693 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_lt.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_lt.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_lv.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_lv.rc index f50b1f9..a2275af 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_lv.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_lv.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ml.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ml.rc index 1e54285..eb7c628 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ml.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ml.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_mr.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_mr.rc index b17588c..4ae3252 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_mr.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_mr.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_nl.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_nl.rc index e4d2626..6742e6f 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_nl.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_nl.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_no.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_no.rc index b3b64d5..cf7dee8 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_no.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_no.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_or.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_or.rc index 91473b3..1ff87ce 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_or.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_or.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_pl.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_pl.rc index 24dca43..52f0a29 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_pl.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_pl.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-BR.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-BR.rc index 1ed0a43..bf05ad1 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-BR.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-BR.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-PT.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-PT.rc index 7039162..7ebe3a7 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-PT.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_pt-PT.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ro.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ro.rc index 11194ca..4358738 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ro.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ro.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ru.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ru.rc index 1315ac5..2c40ca2 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ru.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ru.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_sk.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_sk.rc index 9942cc9..162a88c 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_sk.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_sk.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_sl.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_sl.rc index 22c6fbe..a4287af 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_sl.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_sl.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_sr.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_sr.rc index 8f60172..f3bfac1 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_sr.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_sr.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_sv.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_sv.rc index a3b6e6a..c21a297 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_sv.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_sv.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_sw.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_sw.rc index 27d8dcf..f486b8b 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_sw.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_sw.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ta.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ta.rc index 8fc1bdb..e9dda59 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ta.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ta.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_te.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_te.rc index 1a3483c..c2b294c 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_te.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_te.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_tr.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_tr.rc index e672ee9..82a5a1a 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_tr.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_tr.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_ur.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_ur.rc index f99f5c7..27d39ec 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_ur.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_ur.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_userdefault.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_userdefault.rc index 2d90d74..92ae98e 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_userdefault.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_userdefault.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_vi.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_vi.rc index e334ce6..b95988a 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_vi.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_vi.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-CN.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-CN.rc index 8142a97..f472c52 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-CN.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-CN.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-HK.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-HK.rc index d1b87a2..486e911 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-HK.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-HK.rc differ diff --git a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-TW.rc b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-TW.rc index d3e30d6..adc4b4a 100644 Binary files a/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-TW.rc and b/omaha/goopdate/resources/goopdate_dll/generated_resources_zh-TW.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_am.rc b/omaha/goopdate/resources/goopdateres/generated_resources_am.rc index 342c07b..4f56a08 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_am.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_am.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ar.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ar.rc index 15cb94e..6ad6513 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ar.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ar.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_bg.rc b/omaha/goopdate/resources/goopdateres/generated_resources_bg.rc index b8c0d4e..038681b 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_bg.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_bg.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_bn.rc b/omaha/goopdate/resources/goopdateres/generated_resources_bn.rc index ab346d6..1fbc9cf 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_bn.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_bn.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ca.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ca.rc index 6a22058..b008dc7 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ca.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ca.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_cs.rc b/omaha/goopdate/resources/goopdateres/generated_resources_cs.rc index 20a218d..13dc80f 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_cs.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_cs.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_da.rc b/omaha/goopdate/resources/goopdateres/generated_resources_da.rc index 92a6ce9..89fffcc 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_da.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_da.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_de.rc b/omaha/goopdate/resources/goopdateres/generated_resources_de.rc index 2ff71ab..8e91ac4 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_de.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_de.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_el.rc b/omaha/goopdate/resources/goopdateres/generated_resources_el.rc index f99ca73..ad50e28 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_el.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_el.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_en-GB.rc b/omaha/goopdate/resources/goopdateres/generated_resources_en-GB.rc index 1189211..95e8681 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_en-GB.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_en-GB.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_en.rc b/omaha/goopdate/resources/goopdateres/generated_resources_en.rc index 41daaf0..bd0df53 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_en.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_en.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_es-419.rc b/omaha/goopdate/resources/goopdateres/generated_resources_es-419.rc index 6eb5fbb..797aca3 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_es-419.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_es-419.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_es.rc b/omaha/goopdate/resources/goopdateres/generated_resources_es.rc index 6914825..3ea18d0 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_es.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_es.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_et.rc b/omaha/goopdate/resources/goopdateres/generated_resources_et.rc index f2df15b..b1da465 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_et.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_et.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_fa.rc b/omaha/goopdate/resources/goopdateres/generated_resources_fa.rc index ca426fe..a46834c 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_fa.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_fa.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_fi.rc b/omaha/goopdate/resources/goopdateres/generated_resources_fi.rc index 91d3d26..9efde0b 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_fi.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_fi.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_fil.rc b/omaha/goopdate/resources/goopdateres/generated_resources_fil.rc index 8090c96..98c6446 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_fil.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_fil.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_fr.rc b/omaha/goopdate/resources/goopdateres/generated_resources_fr.rc index 3bc137b..9e3e89a 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_fr.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_fr.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_gu.rc b/omaha/goopdate/resources/goopdateres/generated_resources_gu.rc index d8540b1..6009ef9 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_gu.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_gu.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_hi.rc b/omaha/goopdate/resources/goopdateres/generated_resources_hi.rc index aca8bc3..98c7605 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_hi.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_hi.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_hr.rc b/omaha/goopdate/resources/goopdateres/generated_resources_hr.rc index f6b20d3..196bc92 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_hr.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_hr.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_hu.rc b/omaha/goopdate/resources/goopdateres/generated_resources_hu.rc index 8f7f17c..16f9f97 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_hu.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_hu.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_id.rc b/omaha/goopdate/resources/goopdateres/generated_resources_id.rc index fb7b384..f1084e1 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_id.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_id.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_is.rc b/omaha/goopdate/resources/goopdateres/generated_resources_is.rc index ff5c015..d867fe4 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_is.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_is.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_it.rc b/omaha/goopdate/resources/goopdateres/generated_resources_it.rc index 8ea10bf..084b5d4 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_it.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_it.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_iw.rc b/omaha/goopdate/resources/goopdateres/generated_resources_iw.rc index 1af1dd8..3146756 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_iw.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_iw.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ja.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ja.rc index cb7d5c0..d23632b 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ja.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ja.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_kn.rc b/omaha/goopdate/resources/goopdateres/generated_resources_kn.rc index 1083de6..960c03d 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_kn.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_kn.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ko.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ko.rc index f65a649..2e11dbc 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ko.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ko.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_lt.rc b/omaha/goopdate/resources/goopdateres/generated_resources_lt.rc index 403ecc8..da74db8 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_lt.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_lt.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_lv.rc b/omaha/goopdate/resources/goopdateres/generated_resources_lv.rc index c80a116..a744a3d 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_lv.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_lv.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ml.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ml.rc index 09bfb60..53432f9 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ml.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ml.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_mr.rc b/omaha/goopdate/resources/goopdateres/generated_resources_mr.rc index c08dca4..d8b743e 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_mr.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_mr.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ms.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ms.rc index 1680aee..8fb0f3a 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ms.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ms.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_nl.rc b/omaha/goopdate/resources/goopdateres/generated_resources_nl.rc index 83b7b8e..14ddcc6 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_nl.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_nl.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_no.rc b/omaha/goopdate/resources/goopdateres/generated_resources_no.rc index 69d8637..3debdfc 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_no.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_no.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_pl.rc b/omaha/goopdate/resources/goopdateres/generated_resources_pl.rc index 381843e..29f6822 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_pl.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_pl.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_pt-BR.rc b/omaha/goopdate/resources/goopdateres/generated_resources_pt-BR.rc index bebd5ed..ef0973a 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_pt-BR.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_pt-BR.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_pt-PT.rc b/omaha/goopdate/resources/goopdateres/generated_resources_pt-PT.rc index 0f658e1..f0beb52 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_pt-PT.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_pt-PT.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ro.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ro.rc index 144b6f4..f846caf 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ro.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ro.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ru.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ru.rc index 66645e1..30dba19 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ru.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ru.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_sk.rc b/omaha/goopdate/resources/goopdateres/generated_resources_sk.rc index 6c34c30..c6200fb 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_sk.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_sk.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_sl.rc b/omaha/goopdate/resources/goopdateres/generated_resources_sl.rc index 4d69911..26b66a6 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_sl.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_sl.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_sr.rc b/omaha/goopdate/resources/goopdateres/generated_resources_sr.rc index 56cab25..113cb29 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_sr.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_sr.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_sv.rc b/omaha/goopdate/resources/goopdateres/generated_resources_sv.rc index 7ab8f07..99c843d 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_sv.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_sv.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_sw.rc b/omaha/goopdate/resources/goopdateres/generated_resources_sw.rc index 6853ede..f4046c4 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_sw.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_sw.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ta.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ta.rc index 957eda8..0025fe5 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ta.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ta.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_te.rc b/omaha/goopdate/resources/goopdateres/generated_resources_te.rc index 18f3a8c..8da9e44 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_te.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_te.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_th.rc b/omaha/goopdate/resources/goopdateres/generated_resources_th.rc index 0f59644..34d6ed1 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_th.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_th.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_tr.rc b/omaha/goopdate/resources/goopdateres/generated_resources_tr.rc index 4579eda..2f9034c 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_tr.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_tr.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_uk.rc b/omaha/goopdate/resources/goopdateres/generated_resources_uk.rc index 4c7b347..7c71d87 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_uk.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_uk.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_ur.rc b/omaha/goopdate/resources/goopdateres/generated_resources_ur.rc index 39d7537..2df8095 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_ur.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_ur.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_vi.rc b/omaha/goopdate/resources/goopdateres/generated_resources_vi.rc index ebd56e1..9a04c1b 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_vi.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_vi.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_zh-CN.rc b/omaha/goopdate/resources/goopdateres/generated_resources_zh-CN.rc index 31b89dc..9bc53a9 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_zh-CN.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_zh-CN.rc differ diff --git a/omaha/goopdate/resources/goopdateres/generated_resources_zh-TW.rc b/omaha/goopdate/resources/goopdateres/generated_resources_zh-TW.rc index 432dba2..13f3ecc 100644 Binary files a/omaha/goopdate/resources/goopdateres/generated_resources_zh-TW.rc and b/omaha/goopdate/resources/goopdateres/generated_resources_zh-TW.rc differ diff --git a/omaha/goopdate/resources/goopdateres/goopdate.grh b/omaha/goopdate/resources/goopdateres/goopdate.grh index 4772e71..0fa27cd 100644 --- a/omaha/goopdate/resources/goopdateres/goopdate.grh +++ b/omaha/goopdate/resources/goopdateres/goopdate.grh @@ -109,7 +109,6 @@ #define IDC_BUTTON1 2004 #define IDC_BUTTON2 2005 #define IDC_PROGRESS 2006 -#define IDC_MARQUEE 2007 #define IDC_INSTALLER_STATE_TEXT 2008 #define IDC_INFO_TEXT 2009 #define IDC_PAUSE_RESUME_TEXT 2010 diff --git a/omaha/goopdate/resources/marquee.avi b/omaha/goopdate/resources/marquee.avi deleted file mode 100644 index 4d513b3..0000000 Binary files a/omaha/goopdate/resources/marquee.avi and /dev/null differ diff --git a/omaha/goopdate/string_formatter.h b/omaha/goopdate/string_formatter.h index 374d516..1ab13c1 100644 --- a/omaha/goopdate/string_formatter.h +++ b/omaha/goopdate/string_formatter.h @@ -37,7 +37,7 @@ class StringFormatter { private: CString language_; - DISALLOW_EVIL_CONSTRUCTORS(StringFormatter); + DISALLOW_COPY_AND_ASSIGN(StringFormatter); }; } // namespace omaha diff --git a/omaha/goopdate/string_formatter_unittest.cc b/omaha/goopdate/string_formatter_unittest.cc index a0acde4..bbe62e0 100644 --- a/omaha/goopdate/string_formatter_unittest.cc +++ b/omaha/goopdate/string_formatter_unittest.cc @@ -13,13 +13,13 @@ // limitations under the License. // ======================================================================== -#include "base/scoped_ptr.h" +#include "omaha/goopdate/string_formatter.h" + #include "omaha/base/app_util.h" #include "omaha/base/string.h" #include "omaha/common/lang.h" #include "omaha/goopdate/resource_manager.h" #include "omaha/goopdate/server_resource.h" -#include "omaha/goopdate/string_formatter.h" #include "omaha/testing/unit_test.h" using ::testing::_; @@ -77,7 +77,7 @@ TEST_F(StringFormatterTest, FormatMessageTest) { StringFormatter formatter_de(_T("de")); EXPECT_HRESULT_SUCCEEDED( formatter_de.FormatMessage(&format_result, IDS_CLOSE)); - EXPECT_STREQ(_T("Schließen"), format_result); // NOLINT + EXPECT_STREQ(_T("Schlie\u00dfen"), format_result); // NOLINT StringFormatter formatter_fr(_T("fr")); EXPECT_HRESULT_SUCCEEDED( diff --git a/omaha/goopdate/test_omaha_exe_installer.cc b/omaha/goopdate/test_omaha_exe_installer.cc index e338d27..6ee350b 100644 --- a/omaha/goopdate/test_omaha_exe_installer.cc +++ b/omaha/goopdate/test_omaha_exe_installer.cc @@ -51,18 +51,20 @@ // directory in the Omaha server config, and the Omaha metainstaller should be // tagged with the "installdataindex" that corresponding to that .bat file. +#include #include #include -#include + #include + #include "base/basictypes.h" #include "omaha/base/app_util.h" #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/process.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/common/const_cmd_line.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace { @@ -102,8 +104,8 @@ int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR cmd_line, int) { return E_INVALIDARG; } - CPath data_file = - GetInstallerDataFilename(argument_list[argument_count - 1]); + CPath data_file( + GetInstallerDataFilename(argument_list[argument_count - 1])); data_file.UnquoteSpaces(); CPath bat_file; diff --git a/omaha/goopdate/update3web.h b/omaha/goopdate/update3web.h index d3e1d3f..7d4dfe9 100644 --- a/omaha/goopdate/update3web.h +++ b/omaha/goopdate/update3web.h @@ -37,10 +37,6 @@ namespace omaha { -#pragma warning(push) -// Construction of local static object is not thread-safe -#pragma warning(disable:4640) - class ATL_NO_VTABLE Update3WebBase : public CComObjectRootEx, public IDispatchImpl Update3WebUser; typedef Update3Web Update3WebMachineFallback; typedef Update3Web Update3WebService; -#pragma warning(pop) - } // namespace omaha #endif // OMAHA_GOOPDATE_UPDATE3WEB_H_ diff --git a/omaha/goopdate/update_request_utils.cc b/omaha/goopdate/update_request_utils.cc index c4f910c..0ef8e3f 100644 --- a/omaha/goopdate/update_request_utils.cc +++ b/omaha/goopdate/update_request_utils.cc @@ -90,6 +90,8 @@ void BuildRequest(const App* app, request_app.update_check.is_update_disabled = FAILED(app->CheckGroupPolicy()); request_app.update_check.tt_token = app->tt_token(); + request_app.update_check.is_rollback_allowed = + app->IsRollbackToTargetVersionAllowed(); request_app.update_check.target_version_prefix = app->GetTargetVersionPrefix(); } diff --git a/omaha/goopdate/update_request_utils_unittest.cc b/omaha/goopdate/update_request_utils_unittest.cc index 89408af..8787c7c 100644 --- a/omaha/goopdate/update_request_utils_unittest.cc +++ b/omaha/goopdate/update_request_utils_unittest.cc @@ -65,7 +65,7 @@ class UpdateRequestUtilsTest : public AppTestBaseWithRegistryOverride { } App* app_; - scoped_ptr update_request_; + std::unique_ptr update_request_; private: DISALLOW_COPY_AND_ASSIGN(UpdateRequestUtilsTest); @@ -172,6 +172,31 @@ TEST_P(UpdateRequestUtilsTest, update_check.target_version_prefix); } +TEST_P(UpdateRequestUtilsTest, + BuildRequest_UpdateCheck_GroupPolicy_RollbackToTargetVersion) { + EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); + + EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, + kRegValueIsEnrolledToDomain, + IsDomain() ? 1UL : 0UL)); + + const TCHAR* const kRollbackToTargetVersionApp1 = + _T("RollbackToTargetVersion") APP_ID1; + RegKey::SetValue(kRegKeyGoopdateGroupPolicy, + kRollbackToTargetVersionApp1, + 1UL); + + BuildRequest(app_, true, update_request_.get()); + + const xml::request::Request& request = update_request_->request(); + ASSERT_EQ(1, request.apps.size()); + + const xml::request::App& app = request.apps[0]; + const xml::request::UpdateCheck& update_check = app.update_check; + EXPECT_TRUE(update_check.is_valid); + EXPECT_EQ(IsDomain() ? true : false, update_check.is_rollback_allowed); +} + TEST_F(UpdateRequestUtilsTest, BuildRequest_DoNotPickUpDidRunValueWhenNotDoingUpdateCheck) { EXPECT_SUCCEEDED(app_->put_isEulaAccepted(VARIANT_TRUE)); diff --git a/omaha/goopdate/update_response_utils_unittest.cc b/omaha/goopdate/update_response_utils_unittest.cc index dcc4bc2..2c6aec3 100644 --- a/omaha/goopdate/update_response_utils_unittest.cc +++ b/omaha/goopdate/update_response_utils_unittest.cc @@ -13,14 +13,14 @@ // limitations under the License. // ======================================================================== -#include "base/scoped_ptr.h" +#include "omaha/goopdate/update_response_utils.h" + #include "omaha/base/app_util.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" #include "omaha/base/system_info.h" #include "omaha/goopdate/app_unittest_base.h" #include "omaha/goopdate/resource_manager.h" -#include "omaha/goopdate/update_response_utils.h" #include "omaha/testing/unit_test.h" namespace omaha { @@ -86,7 +86,7 @@ class UpdateResponseUtilsGetResultTest : public testing::Test { ResourceManager::Delete(); } - scoped_ptr update_response_; + std::unique_ptr update_response_; }; class UpdateResponseUtilsTest : public AppTestBase, diff --git a/omaha/goopdate/worker.cc b/omaha/goopdate/worker.cc index 6bdf927..b584b24 100644 --- a/omaha/goopdate/worker.cc +++ b/omaha/goopdate/worker.cc @@ -15,8 +15,11 @@ #include "omaha/goopdate/worker.h" #include "omaha/goopdate/worker_internal.h" + #include #include +#include + #include "omaha/base/app_util.h" #include "omaha/base/const_object_names.h" #include "omaha/base/debug.h" @@ -416,7 +419,7 @@ HRESULT Worker::CheckForUpdateAsync(AppBundle* app_bundle) { ASSERT1(app_bundle); ASSERT1(model_->IsLockedByCaller()); - shared_ptr shared_bundle(app_bundle->controlling_ptr()); + std::shared_ptr shared_bundle(app_bundle->controlling_ptr()); HRESULT hr = QueueDeferredFunctionCall0(shared_bundle, &Worker::CheckForUpdate); if (FAILED(hr)) { @@ -431,7 +434,7 @@ HRESULT Worker::CheckForUpdateAsync(AppBundle* app_bundle) { return S_OK; } -void Worker::CheckForUpdate(shared_ptr app_bundle) { +void Worker::CheckForUpdate(std::shared_ptr app_bundle) { CORE_LOG(L3, (_T("[Worker::CheckForUpdate][0x%p]"), app_bundle.get())); ASSERT1(app_bundle.get()); @@ -463,13 +466,13 @@ void Worker::CheckForUpdateHelper(AppBundle* app_bundle, return; } - scoped_ptr update_request( + std::unique_ptr update_request( xml::UpdateRequest::Create(is_machine_, app_bundle->session_id(), app_bundle->install_source(), app_bundle->origin_url())); - scoped_ptr update_response( + std::unique_ptr update_response( xml::UpdateResponse::Create()); CallAsSelfAndImpersonate2(this, @@ -526,7 +529,7 @@ HRESULT Worker::DownloadAsync(AppBundle* app_bundle) { ASSERT1(app_bundle); ASSERT1(model_->IsLockedByCaller()); - shared_ptr shared_bundle(app_bundle->controlling_ptr()); + std::shared_ptr shared_bundle(app_bundle->controlling_ptr()); HRESULT hr = QueueDeferredFunctionCall0(shared_bundle, &Worker::Download); if (FAILED(hr)) { return hr; @@ -540,7 +543,7 @@ HRESULT Worker::DownloadAsync(AppBundle* app_bundle) { return S_OK; } -void Worker::Download(shared_ptr app_bundle) { +void Worker::Download(std::shared_ptr app_bundle) { CORE_LOG(L3, (_T("[Worker::Download][0x%p]"), app_bundle.get())); ASSERT1(app_bundle.get()); @@ -581,7 +584,7 @@ HRESULT Worker::DownloadAndInstallAsync(AppBundle* app_bundle) { ASSERT1(app_bundle); ASSERT1(model_->IsLockedByCaller()); - shared_ptr shared_bundle(app_bundle->controlling_ptr()); + std::shared_ptr shared_bundle(app_bundle->controlling_ptr()); HRESULT hr = QueueDeferredFunctionCall0(shared_bundle, &Worker::DownloadAndInstall); if (FAILED(hr)) { @@ -599,7 +602,7 @@ HRESULT Worker::DownloadAndInstallAsync(AppBundle* app_bundle) { return S_OK; } -void Worker::DownloadAndInstall(shared_ptr app_bundle) { +void Worker::DownloadAndInstall(std::shared_ptr app_bundle) { CORE_LOG(L3, (_T("[Worker::DownloadAndInstall][0x%p]"), app_bundle.get())); ASSERT1(app_bundle.get()); @@ -672,7 +675,7 @@ HRESULT Worker::UpdateAllAppsAsync(AppBundle* app_bundle) { ASSERT1(app_bundle); ASSERT1(model_->IsLockedByCaller()); - shared_ptr shared_bundle(app_bundle->controlling_ptr()); + std::shared_ptr shared_bundle(app_bundle->controlling_ptr()); HRESULT hr = QueueDeferredFunctionCall0(shared_bundle, &Worker::UpdateAllApps); if (FAILED(hr)) { @@ -688,7 +691,7 @@ HRESULT Worker::UpdateAllAppsAsync(AppBundle* app_bundle) { } // Runs through all steps regardless of error. App state machine handles errors. -void Worker::UpdateAllApps(shared_ptr app_bundle) { +void Worker::UpdateAllApps(std::shared_ptr app_bundle) { CORE_LOG(L3, (_T("[Worker::UpdateAllApps][0x%p]"), app_bundle.get())); ASSERT1(app_bundle.get()); @@ -722,7 +725,7 @@ HRESULT Worker::DownloadPackageAsync(Package* package) { ASSERT1(package); ASSERT1(model_->IsLockedByCaller()); - shared_ptr shared_bundle = + std::shared_ptr shared_bundle = package->app_version()->app()->app_bundle()->controlling_ptr(); CORE_LOG(L3, (_T("[Worker::DownloadPackageAsync][0x%p][0x%p]"), shared_bundle.get(), package)); @@ -740,7 +743,7 @@ HRESULT Worker::DownloadPackageAsync(Package* package) { return S_OK; } -void Worker::DownloadPackage(shared_ptr app_bundle, +void Worker::DownloadPackage(std::shared_ptr app_bundle, Package* package) { CORE_LOG(L3, (_T("[Worker::DownloadPackage][0x%p][0x%p]"), app_bundle.get(), package)); @@ -957,7 +960,9 @@ HRESULT Worker::DoUpdateCheck(AppBundle* app_bundle, HighresTimer update_check_timer; // This is a blocking call on the network. - HRESULT hr = app_bundle->update_check_client()->Send(update_request, + const bool is_foreground = app_bundle->priority() == INSTALL_PRIORITY_HIGH; + HRESULT hr = app_bundle->update_check_client()->Send(is_foreground, + update_request, update_response); CORE_LOG(L3, (_T("[Update check HTTP trace][%s]"), @@ -1038,15 +1043,15 @@ void Worker::PersistRetryAfter(int retry_after_sec) const { // Creates a thread pool work item for deferred execution of deferred_function. // The thread pool owns this callback object. HRESULT Worker::QueueDeferredFunctionCall0( - shared_ptr app_bundle, - void (Worker::*deferred_function)(shared_ptr)) { + std::shared_ptr app_bundle, + void (Worker::*deferred_function)(std::shared_ptr)) { ASSERT1(app_bundle.get()); ASSERT1(deferred_function); - typedef ThreadPoolCallBack1 > Callback; - scoped_ptr callback(new Callback(this, + using Callback = ThreadPoolCallBack1 >; + auto callback = std::make_unique(this, deferred_function, - app_bundle)); + app_bundle); HRESULT hr = Goopdate::Instance().QueueUserWorkItem(callback.get(), COINIT_MULTITHREADED, WT_EXECUTELONGFUNCTION); @@ -1063,17 +1068,17 @@ HRESULT Worker::QueueDeferredFunctionCall0( // The thread pool owns this callback object. template HRESULT Worker::QueueDeferredFunctionCall1( - shared_ptr app_bundle, + std::shared_ptr app_bundle, P1 p1, - void (Worker::*deferred_function)(shared_ptr, P1)) { + void (Worker::*deferred_function)(std::shared_ptr, P1)) { ASSERT1(app_bundle.get()); ASSERT1(deferred_function); - typedef ThreadPoolCallBack2, P1> Callback; - scoped_ptr callback(new Callback(this, + using Callback = ThreadPoolCallBack2, P1>; + auto callback = std::make_unique(this, deferred_function, app_bundle, - p1)); + p1); HRESULT hr = Goopdate::Instance().QueueUserWorkItem(callback.get(), COINIT_MULTITHREADED, WT_EXECUTELONGFUNCTION); diff --git a/omaha/goopdate/worker.h b/omaha/goopdate/worker.h index b4f77b1..4c4630f 100644 --- a/omaha/goopdate/worker.h +++ b/omaha/goopdate/worker.h @@ -18,13 +18,13 @@ #include #include +#include + #include "base/basictypes.h" #include "omaha/base/program_instance.h" -#include "base/scoped_ptr.h" #include "omaha/base/shutdown_callback.h" #include "omaha/base/shutdown_handler.h" #include "omaha/base/wtl_atlapp_wrapper.h" -#include "third_party/bar/shared_ptr.h" namespace omaha { @@ -132,11 +132,11 @@ class Worker : public WorkerModelInterface, public ShutdownCallback { // These functions execute code in the thread pool. They hold an outstanding // reference to the application bundle to prevent the application bundle // object from being deleted before the functions complete. - void CheckForUpdate(shared_ptr app_bundle); - void Download(shared_ptr app_bundle); - void DownloadAndInstall(shared_ptr app_bundle); - void DownloadPackage(shared_ptr app_bundle, Package* package); - void UpdateAllApps(shared_ptr app_bundle); + void CheckForUpdate(std::shared_ptr app_bundle); + void Download(std::shared_ptr app_bundle); + void DownloadAndInstall(std::shared_ptr app_bundle); + void DownloadPackage(std::shared_ptr app_bundle, Package* package); + void UpdateAllApps(std::shared_ptr app_bundle); // These functions do the work for the corresponding functions but do not call // CompleteAsyncCall(). @@ -164,14 +164,14 @@ class Worker : public WorkerModelInterface, public ShutdownCallback { void PersistRetryAfter(int retry_after_sec) const; HRESULT QueueDeferredFunctionCall0( - shared_ptr app_bundle, - void (Worker::*deferred_function)(shared_ptr)); + std::shared_ptr app_bundle, + void (Worker::*deferred_function)(std::shared_ptr)); template HRESULT QueueDeferredFunctionCall1( - shared_ptr app_bundle, + std::shared_ptr app_bundle, P1 p1, - void (Worker::*deferred_function)(shared_ptr, P1)); + void (Worker::*deferred_function)(std::shared_ptr, P1)); void WriteEventLog(int event_type, int event_id, @@ -181,12 +181,12 @@ class Worker : public WorkerModelInterface, public ShutdownCallback { bool is_machine_; int lock_count_; HRESULT single_instance_hr_; - scoped_ptr single_instance_; - scoped_ptr reactor_; - scoped_ptr shutdown_handler_; - scoped_ptr model_; - scoped_ptr download_manager_; - scoped_ptr install_manager_; + std::unique_ptr single_instance_; + std::unique_ptr reactor_; + std::unique_ptr shutdown_handler_; + std::unique_ptr model_; + std::unique_ptr download_manager_; + std::unique_ptr install_manager_; CMessageLoop message_loop_; diff --git a/omaha/goopdate/worker_unittest.cc b/omaha/goopdate/worker_unittest.cc index b91600c..0881b30 100644 --- a/omaha/goopdate/worker_unittest.cc +++ b/omaha/goopdate/worker_unittest.cc @@ -13,9 +13,11 @@ // limitations under the License. // ======================================================================== +#include "omaha/goopdate/worker.h" + +#include #include -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/const_addresses.h" #include "omaha/common/config_manager.h" @@ -31,7 +33,6 @@ #include "omaha/goopdate/installer_result_info.h" #include "omaha/goopdate/model.h" #include "omaha/goopdate/resource_manager.h" -#include "omaha/goopdate/worker.h" #include "omaha/goopdate/worker_internal.h" #include "omaha/goopdate/worker_metrics.h" #include "omaha/testing/unit_test.h" @@ -93,6 +94,7 @@ void SetAppStateReadyToInstall(App* app) { } typedef HRESULT WebServiceClientSendMethod( + bool is_foreground, const xml::UpdateRequest* update_request, xml::UpdateResponse* update_response); @@ -102,7 +104,7 @@ class WebServiceClientSendAction : public ::testing::ActionInterface { public: virtual HRESULT Perform(const ArgumentTuple& args) { - xml::UpdateResponse* response = std::tr1::get<1>(args); + xml::UpdateResponse* response = std::get<2>(args); xml::response::Response r; // Omaha expects |elapsed_days| to be in range. So set it to a valid @@ -119,11 +121,13 @@ ::testing::Action WebServiceClientSend() { class MockWebServicesClient : public WebServicesClientInterface { public: - MOCK_METHOD2(Send, - HRESULT(const xml::UpdateRequest* update_request, + MOCK_METHOD3(Send, + HRESULT(bool is_foreground, + const xml::UpdateRequest* update_request, xml::UpdateResponse* update_response)); - MOCK_METHOD2(SendString, - HRESULT(const CString* request_string, + MOCK_METHOD3(SendString, + HRESULT(bool is_foreground, + const CString* request_string, xml::UpdateResponse* update_response)); MOCK_METHOD0(Cancel, void()); @@ -310,7 +314,7 @@ class WorkerWithBundleTest : public WorkerTest { WorkerTest::TearDown(); } - shared_ptr app_bundle_; + std::shared_ptr app_bundle_; private: DISALLOW_COPY_AND_ASSIGN(WorkerWithBundleTest); @@ -387,7 +391,7 @@ class WorkerMockedManagersTest : public WorkerWithTwoAppsTest { }; TEST_F(WorkerMockedManagersTest, CheckForUpdateAsync) { - EXPECT_CALL(*mock_web_services_client_, Send(_, _)) + EXPECT_CALL(*mock_web_services_client_, Send(_, _, _)) .Times(1).WillOnce(WebServiceClientSend()); ON_CALL(*mock_web_services_client_, http_trace()) .WillByDefault(Return(_T(""))); @@ -565,7 +569,7 @@ TEST_F(WorkerMockedManagersTest, DownloadAsync_Then_DownloadAndInstallAsync) { } TEST_F(WorkerMockedManagersTest, UpdateAllAppsAsync) { - EXPECT_CALL(*mock_web_services_client_, Send(_, _)) + EXPECT_CALL(*mock_web_services_client_, Send(_, _, _)) .Times(1).WillOnce(WebServiceClientSend()); ON_CALL(*mock_web_services_client_, http_trace()) .WillByDefault(Return(_T(""))); diff --git a/omaha/hammer-brave.bat b/omaha/hammer-brave.bat new file mode 100644 index 0000000..71a1df2 --- /dev/null +++ b/omaha/hammer-brave.bat @@ -0,0 +1,130 @@ +@echo off + +:: Hammer does not need this variable but the unit +:: tests do. +set OMAHA_PSEXEC_DIR=%ProgramFiles(x86)%\pstools + +:: Set VS environment variables. +call "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsamd64_x86.bat" + +setlocal + +rem -- Set all environment variables used by Hammer and Omaha. -- + +:: VS2003/VC71 is 1310 (not supported by the current build). +:: VS2005/VC80 is 1400 (not supported by the current build). +:: VS2008/VC90 is 1500 (not supported by the current build). +:: VS2010/VC10 is 1600 (not supported by the current build). +:: VS2012/VC11 is 1700 (not supported by the current build). +:: VS2013/VC12 is 1800. +:: VS2015/VC14 is 1900. +:: VS2017/VC14.1 is 1910. +:: VS2019/VC16.0 is 1920. + +if "%VisualStudioVersion%"=="" goto error_no_vc +if "%VisualStudioVersion%"=="12.0" goto vc120 +if "%VisualStudioVersion%"=="14.0" goto vc140 +if "%VisualStudioVersion%"=="15.0" goto vc141 +if "%VisualStudioVersion%"=="16.0" goto vc160 +goto error_vc_not_supported + +:vc120 +set OMAHA_MSC_VER=1800 +goto set_env_variables + +:vc140 +set OMAHA_MSC_VER=1900 +goto set_env_variables + +:vc141 +set OMAHA_MSC_VER=1910 +goto set_env_variables + +:vc160 +set OMAHA_MSC_VER=1920 +goto set_env_variables + +:set_env_variables + +:: Set signtool arguments +set SIGNTOOL_ARGS="sign /t http://timestamp.digicert.com /fd sha256 /sm" + +:: Change these variables to match the local build environment. + +:: Directory where the Go programming language toolchain is installed. +set GOROOT=C:\Go + +:: Directory where AtlServer files are. +set OMAHA_ATL_SERVER_DIR=c:\atl\ + +:: This will depend on your OS. If this version of the .Net framework came with +:: the OS, then set it to the framework directory +:: (something like C:\Windows\Microsoft.NET\Framework\v2.0.50727). +:: Otherwise, set it to the directory where the .NET framework is installed. +set OMAHA_NET_DIR=%WINDIR%\Microsoft.NET\Framework\v2.0.50727 + +:: This directory is needed to find mage.exe tool, which is the .Net manifest +:: generating tool. This tool ships as part of the Windows SDK. +:: However, newer versions of mage.exe can't targer older versions of .Net +:: framework. If there is a need for the click-once application to run on older +:: versions of the .Net framework, then an older version of the Windows SDK +:: needs to be installed and this environment variable point to that directory. +set OMAHA_NETFX_TOOLS_DIR=%ProgramFiles(x86)%\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools + +:: This directory is needed to find protoc.exe, which is the protocol buffer +:: compiler. From the release page https://github.com/google/protobuf/releases, +:: download the zip file protoc-$VERSION-win32.zip. It contains the protoc +:: binary. Unzip the contents under C:\protobuf. +set OMAHA_PROTOBUF_BIN_DIR=C:\protobuf\bin + +:: This directory is needed to find the protocol buffer source files. From the +:: release page https://github.com/google/protobuf/releases, download the zip +:: file protobuf-cpp-$VERSION.zip. Unzip the "src" sub-directory contents to +:: C:\protobuf\src. +set OMAHA_PROTOBUF_SRC_DIR=C:\protobuf\src + +:: Directory where Python (python.exe) is installed. +set OMAHA_PYTHON_DIR=C:\Python27 + +:: Directory in WiX where candle.exe and light.exe are installed. +set OMAHA_WIX_DIR=%ProgramFiles(x86)%\WiX Toolset v3.11\bin + +:: Root directory of the WTL installation. +set OMAHA_WTL_DIR=C:\wtl\ + +set OMAHA_PLATFORM_SDK_DIR=%WindowsSdkDir%\ +set OMAHA_WINDOWS_SDK_10_0_VERSION=%WindowsSDKVersion:~0,-1% + +:: Directory which includes the sign.exe tool for Authenticode signing. +set OMAHA_SIGNTOOL_SDK_DIR="%WindowsSdkVerBinPath%\x86" +set PYTHONPATH=%OMAHA_PYTHON_DIR% + +:: Directory of Scons (http://www.scons.org/). +set SCONS_DIR=C:\Python27\Lib\site-packages\scons-1.3.1 + +:: Directory of the Google's Software Construction Toolkit. +set SCT_DIR=C:\swtoolkit + +set PROXY_CLSID_TARGET=%~dp0proxy_clsids.txt +set CUSTOMIZATION_UT_TARGET=%~dp0common\omaha_customization_proxy_clsid.h + +rem Force Hammer to use Python 2.7 +set PYTHON_TO_USE=python_27 +call "%SCT_DIR%\hammer.bat" %* + +if /i {%1} == {-c} ( + del /q /f "%PROXY_CLSID_TARGET%" 2> NUL + del /q /f "%CUSTOMIZATION_UT_TARGET%" 2> NUL +) + +goto end + +:error_no_vc +echo VisualStudioVersion variable is not set. Have you run vcvarsall.bat before running this script? +goto end + +:error_vc_not_supported +echo Visual Studio version %VisualStudioVersion% is not supported. +goto end + +:end diff --git a/omaha/hammer.bat b/omaha/hammer.bat index 928e77c..b839b0e 100644 --- a/omaha/hammer.bat +++ b/omaha/hammer.bat @@ -15,10 +15,14 @@ rem -- Set all environment variables used by Hammer and Omaha. -- :: VS2012/VC11 is 1700 (not supported by the current build). :: VS2013/VC12 is 1800. :: VS2015/VC14 is 1900. +:: VS2017/VC14.1 is 1910. +:: VS2019/VC16.0 is 1920. if "%VisualStudioVersion%"=="" goto error_no_vc if "%VisualStudioVersion%"=="12.0" goto vc120 if "%VisualStudioVersion%"=="14.0" goto vc140 +if "%VisualStudioVersion%"=="15.0" goto vc141 +if "%VisualStudioVersion%"=="16.0" goto vc160 goto error_vc_not_supported :vc120 @@ -29,6 +33,14 @@ goto set_env_variables set OMAHA_MSC_VER=1900 goto set_env_variables +:vc141 +set OMAHA_MSC_VER=1910 +goto set_env_variables + +:vc160 +set OMAHA_MSC_VER=1920 +goto set_env_variables + :set_env_variables :: Change these variables to match the local build environment. @@ -66,10 +78,10 @@ set OMAHA_PROTOBUF_BIN_DIR=C:\protobuf\bin set OMAHA_PROTOBUF_SRC_DIR=C:\protobuf\src :: Directory where Python (python.exe) is installed. -set OMAHA_PYTHON_DIR=C:\Python24 +set OMAHA_PYTHON_DIR=C:\Python27 :: Directory in WiX where candle.exe and light.exe are installed. -set OMAHA_WIX_DIR=%ProgramFiles(x86)%\WiX Toolset v3.10\bin +set OMAHA_WIX_DIR=%WIX%\bin :: Root directory of the WTL installation. set OMAHA_WTL_DIR=C:\wtl\files @@ -78,11 +90,11 @@ set OMAHA_PLATFORM_SDK_DIR=%WindowsSdkDir%\ set OMAHA_WINDOWS_SDK_10_0_VERSION=%WindowsSDKVersion:~0,-1% :: Directory which includes the sign.exe tool for Authenticode signing. -set OMAHA_SIGNTOOL_SDK_DIR=%WindowsSdkDir%\bin\x86 +set OMAHA_SIGNTOOL_SDK_DIR="%WindowsSdkVerBinPath%\x86" set PYTHONPATH=%OMAHA_PYTHON_DIR% :: Directory of Scons (http://www.scons.org/). -set SCONS_DIR=C:\Python24\Lib\site-packages\scons-1.3.1 +set SCONS_DIR=C:\Python27\Lib\site-packages\scons-1.3.1 :: Directory of the Google's Software Construction Toolkit. set SCT_DIR=C:\swtoolkit @@ -90,9 +102,8 @@ set SCT_DIR=C:\swtoolkit set PROXY_CLSID_TARGET=%~dp0proxy_clsids.txt set CUSTOMIZATION_UT_TARGET=%~dp0common\omaha_customization_proxy_clsid.h -rem Force Hammer to use Python 2.4. (The default of Python 2.6 exposes some -rem bugs in Scons 1.2, which we currently use.) -set PYTHON_TO_USE=python_24 +rem Force Hammer to use Python 2.7 +set PYTHON_TO_USE=python_27 call "%SCT_DIR%\hammer.bat" %* if /i {%1} == {-c} ( diff --git a/omaha/installers/build.scons b/omaha/installers/build.scons index f7bd6ce..61b6826 100644 --- a/omaha/installers/build.scons +++ b/omaha/installers/build.scons @@ -118,7 +118,7 @@ def _GenerateDeploymentForOneLanguage(omaha_version_info, language): def _BuildSetup(omaha_versions_info, is_repair = False): # Build the meta-installer for each version. - _PRODUCT_NAME = 'GoogleUpdate' + _PRODUCT_NAME = 'BraveUpdate' for omaha_version_info in omaha_versions_info: prefix = omaha_version_info.filename_prefix @@ -210,7 +210,7 @@ if not env.Bit('official_installers'): '$TARGET_ROOT/clickonce_deployment/bin/', '$STAGING_DIR', ], - source='$OBJ_ROOT/installers/GoogleUpdateSetup.exe', + source='$OBJ_ROOT/installers/BraveUpdateSetup.exe', ) # Build the repair installer. diff --git a/omaha/installers/tag_meta_installers.py b/omaha/installers/tag_meta_installers.py index 59315f0..c166515 100644 --- a/omaha/installers/tag_meta_installers.py +++ b/omaha/installers/tag_meta_installers.py @@ -71,8 +71,8 @@ def ReadBundleInstallerFile(installers_txt_filename): for line in installers_txt_file.readlines(): line = line.strip() if len(line) and not line.startswith('#'): - (exe_name, needs_admin, language, browser, usage, bundle_apps) =\ - eval(line) + (exe_name, needs_admin, language, browser, usage, + bundle_apps) = eval(line) bundle = Bundle(exe_name, needs_admin, language, browser, usage, installers_txt_filename, bundle_apps) @@ -120,20 +120,15 @@ def SetOutputFileNames(file_name, apps, output_dir): """ # Determine the language. - file = os.path.basename(file_name) - if file.startswith('TEST_'): - test = True - else: - test = False - for (lang, apps_lang) in apps.iteritems(): # Get the output filename and set it on the application. for app in apps_lang: output_path = BuildOutputDirectory(output_dir, lang, app) - path = os.path.join(output_path, GetOutputFileName(test, app.name, lang)) + path = os.path.join(output_path, GetOutputFileName( + os.path.basename(file_name), app.name, lang)) app.output_file_name = path -def GetOutputFileName(test, name, lang): +def GetOutputFileName(file, name, lang): """Creates the output file name based on the language and the name of the app. Args: test: Whether the input file name starts with TEST. @@ -142,8 +137,8 @@ def GetOutputFileName(test, name, lang): Returns: The output filename """ - if test: - file_name = 'Tagged_TEST_%sSetup_%s.exe' % (name, lang) + if file.startswith(('TEST_', 'TEST2_')): + file_name = 'Tagged_%s_%sSetup_%s.exe' % (file.split('_', 1)[0], name, lang) else: file_name = 'Tagged_%sSetup_%s.exe' % (name, lang) return file_name @@ -163,8 +158,8 @@ def BuildTagStringForBundle(bundle): first_app = False (guid, name, ap) = app display_name = UrlEncodeString(name) - args += 'appguid=%s&appname=%s&needsadmin=%s' % \ - (guid, display_name, bundle.needs_admin) + args += 'appguid=%s&appname=%s&needsadmin=%s' % ( + guid, display_name, bundle.needs_admin) if ap: args += '&ap=%s' % ap @@ -186,10 +181,9 @@ def TagOneFile(file, app, applytag_exe_name): """ tag_string = BuildTagStringForBundle(app) - output_path = app.output_file_name + out_path = app.output_file_name if not os.path.exists(file): - print 'Could not find file %s required for creating %s' % \ - (file, output_path) + print 'Could not find file %s required for creating %s' % (file, out_path) return False arguments = [applytag_exe_name, @@ -214,8 +208,8 @@ def GetAllSetupExeInDirectory(dir): ret_files = [] files = os.listdir(dir) for file in files: - regex = re.compile('^TEST_GoogleUpdateSetup_.*.exe$|' - '^GoogleUpdateSetup_.*.exe$') + regex = re.compile('^TEST_BraveUpdateSetup_.*.exe$|' + '^BraveUpdateSetup_.*.exe$') if not regex.match(file): continue ret_files.append(file) @@ -245,8 +239,8 @@ def PrintUsage(): print 'For an example of the take a look at' print '#/installers/googlegears_installer.txt' print '' - print 'tag_meta_installers.py \ - ' + print ('tag_meta_installers.py ' + '') def main(): if len(sys.argv) != 5: diff --git a/omaha/installers/tagged_installer.py b/omaha/installers/tagged_installer.py index 19752a2..d41538f 100644 --- a/omaha/installers/tagged_installer.py +++ b/omaha/installers/tagged_installer.py @@ -28,19 +28,10 @@ def TagOneBundle(env, bundle, untagged_binary_path, output_dir): indx = bundle.output_file_name.find('installers') relative_filepath = bundle.output_file_name[indx+len('installers')+1:] - tag_exe = '$TESTS_DIR/ApplyTag.exe' - - tag_output = env.Command( + return env.OmahaTagExe( target='%s/%s' % (output_dir, relative_filepath), source=untagged_binary_path, - action='%s $SOURCES $TARGET %s append' % ( - env.File(tag_exe).abspath, tag_str) - ) - - # Add extra (hidden) dependency plus a dependency on the tag executable. - env.Depends(tag_output, [bundle.installers_txt_filename, tag_exe]) - - return tag_output + tag=tag_str) def _ReadAllBundleInstallerFiles(installers_txt_files_path): diff --git a/omaha/internal/grit/README.md b/omaha/internal/grit/README.md index 6d445d5..dfafc71 100644 --- a/omaha/internal/grit/README.md +++ b/omaha/internal/grit/README.md @@ -1,5 +1,5 @@ -The GRIT source files here are provided for reference purposes or for developers -who would like to change the UI strings, then use GRIT to localize the +The GRIT source files here are provided for reference purposes or for developers +who would like to change the UI strings, then use GRIT to localize the resource files. These files don't build as part of this source tree. diff --git a/omaha/internal/tools/ApplyTag.exe b/omaha/internal/tools/ApplyTag.exe new file mode 100644 index 0000000..8957713 Binary files /dev/null and b/omaha/internal/tools/ApplyTag.exe differ diff --git a/omaha/main.scons b/omaha/main.scons index bd3f505..ea5ee9e 100644 --- a/omaha/main.scons +++ b/omaha/main.scons @@ -65,19 +65,19 @@ _is_google_update_build = False # These values must be changed when customizing open source Omaha. # You may also wish to replace the language-neutral constants in the individual # *generated_resources_*.rc files with localized strings. -_FULL_COMPANY_NAME = 'OmahaCompanyName Inc.' -_SHORT_COMPANY_NAME = 'OmahaCompanyName' +_FULL_COMPANY_NAME = 'BraveSoftware Inc.' +_SHORT_COMPANY_NAME = 'BraveSoftware' _PRODUCT_NAME = 'Update' -_COMPANY_DOMAIN_BASE = 'google' +_COMPANY_DOMAIN_BASE = 'brave' _COMPANY_DOMAIN = _COMPANY_DOMAIN_BASE + '.com' -_MAIN_EXE_BASE_NAME = 'GoogleUpdate' +_MAIN_EXE_BASE_NAME = 'BraveUpdate' # TODO(omaha): Use this throughout the build files where goopdate and # goopdateres are referenced. _MAIN_DLL_BASE_NAME = 'goopdate' -# "Google Inc." must not be removed from the copyright string. This literal also +# "Google LLC" must not be removed from the copyright string. This literal also # appears as LegalCopyright in the VERSIONINFO section of .rc files. # TODO(omaha): Use this variable in .wxs files, etc. -_OMAHA_COPYRIGHT_STRING_ENGLISH = 'Copyright 2007-2010 Google Inc.' +_OMAHA_COPYRIGHT_STRING_ENGLISH = '' # TODO(omaha): Allow open source Omaha to be built without the Recovery MSI, @@ -88,28 +88,26 @@ _OMAHA_COPYRIGHT_STRING_ENGLISH = 'Copyright 2007-2010 Google Inc.' # TODO(omaha3): Allow open source Omaha to be built without support for # Omaha 2's COM APIs. -# The hash comes from the Thumbprint item in the Details tab of the file -# properties for the public key .cer file. -# Omaha and Chrome certificate: sha256 (12/15/2015 to 12/16/2018). -_BUILD_SERVER_CERTIFICATE_HASH = '5a9272ce76a9415a4a3a5002a2589a049312aa40' - # # End vendor-specific constants. # # Reads the value of OMAHA_MSC_VER to determine which compiler/toolchain to use. # The set of expected values are in omaha_version_utils. -# Defaults to VC140 if the environment variable is not specified. -_msc_ver = int(os.getenv('OMAHA_MSC_VER', "1900")) - -_default_sdk_dir = ('$THIRD_PARTY/%s/files' % - {omaha_version_utils.VC140:'windows_sdk/windows_sdk_10', +# Defaults to VC160 (Visual Studio 2019) if the environment variable is not +# specified. +_msc_ver = int(os.getenv('OMAHA_MSC_VER', "1920")) + +_sdk_dir = os.getenv('WindowsSdkDir', os.getenv('OMAHA_PLATFORM_SDK_DIR')) +if (_sdk_dir is None): + _sdk_dir = ('$THIRD_PARTY/%s/files' % + { omaha_version_utils.VC160:'windows_sdk/windows_sdk_10', + omaha_version_utils.VC150:'windows_sdk/windows_sdk_10', + omaha_version_utils.VC140:'windows_sdk/windows_sdk_10', omaha_version_utils.VC120:'windows_sdk_8_1', omaha_version_utils.VC100:'platformsdk_vc_10_0', omaha_version_utils.VC80:'platformsdk/v6_1' }[_msc_ver]) -_sdk_dir = os.getenv('OMAHA_PLATFORM_SDK_DIR', _default_sdk_dir) - _sdk_version = os.getenv('OMAHA_WINDOWS_SDK_10_0_VERSION', None) _atl_server_dir = os.getenv('OMAHA_ATL_SERVER_DIR', @@ -130,13 +128,17 @@ win_env = Environment( tools=[ 'component_setup', 'target_platform_windows', - { omaha_version_utils.VC140:'windows_vc14_0', + { omaha_version_utils.VC160:'windows_vc16_0_host64_x86', + omaha_version_utils.VC150:'windows_vc15_0_host64_x86', + omaha_version_utils.VC140:'windows_vc14_0', omaha_version_utils.VC120:'windows_vc12_0', omaha_version_utils.VC100:'windows_vc10_0', omaha_version_utils.VC80:'target_platform_windows' }[_msc_ver], 'masm', # Use 'masm' to override the 'as' tool currently # used by default in 'target_platform_windows' - { omaha_version_utils.VC140:'atlmfc_vc14_0', + { omaha_version_utils.VC160:'atlmfc_vc16_0', + omaha_version_utils.VC150:'atlmfc_vc15_0', + omaha_version_utils.VC140:'atlmfc_vc14_0', omaha_version_utils.VC120:'atlmfc_vc12_0', omaha_version_utils.VC100:'atlmfc_vc10_0', omaha_version_utils.VC80:'atlmfc_vc80' }[_msc_ver], @@ -145,7 +147,6 @@ win_env = Environment( 'omaha_builders', ], msc_ver = _msc_ver, - build_server_certificate_hash = _BUILD_SERVER_CERTIFICATE_HASH, # Visual Studio 2008 does not ship the sign tool. Use the sign tool from # the Platform SDK. This must come after the 'code_signing' tool is used. @@ -157,10 +158,10 @@ win_env = Environment( win_env['ENV']['GOROOT'] = os.getenv('GOROOT', win_env.subst('$MAIN_DIR') + '\\..\\third_party\\go\\files') +win_env['ENV']['LocalAppData'] = os.getenv('LocalAppData') # Append paths for supporting tools such as uuidgen.exe and mage.exe. -win_env.AppendENVPath('PATH', (_sdk_dir + '\\bin\\' + - ('', 'x86')[_msc_ver >= omaha_version_utils.VC120])) +win_env.AppendENVPath('PATH', (os.environ['WindowsSdkVerBinPath'] + '\\x86\\')) win_env.AppendENVPath('PATH', os.getenv('OMAHA_NETFX_TOOLS_DIR')) # Remove this value because it conflicts with a #define @@ -284,10 +285,11 @@ AddOption( # Declare various boolean states. DeclareBit('is_google_update_build', 'True if building Google Update') -DeclareBit('use_precompiled_headers', 'Use precompiled headers in build') DeclareBit('official_installers', 'Building using checked-in binaries') DeclareBit('build_server', 'Running on the build server') DeclareBit('build_two_versions', 'Build second version for self-update testing') +DeclareBit('build_three_versions', 'Build a second and a third version for' + 'self-update testing') DeclareBit('test_certificate', 'Files will be signed with the test certificate') DeclareBit('bin', 'Building from pre-built binaries') DeclareBit('min', 'Building minimal set of projects') @@ -297,6 +299,8 @@ DeclareBit('no-tests', 'Do not build the unit tests') DeclareBit('x64', 'Build 64 bit code') DeclareBit('analysis', 'Turns on static analysis') DeclareBit('suppress_light_validation', 'Suppress WiX Linker ICE validation') +DeclareBit('has_device_management', + 'True if including cloud-based device management') # Build official installers if --official_installers is on the command line. win_env.SetBitFromOption('official_installers', False) @@ -307,6 +311,9 @@ win_env.SetBitFromOption('build_server', False) # Build two versions if --build_two_versions is on the command line. win_env.SetBitFromOption('build_two_versions', False) +# Build three versions if --build_three_versions is on the command line. +win_env.SetBitFromOption('build_three_versions', False) + # Store new versions of pre-built binaries if --bin is on the command line. win_env.SetBitFromOption('bin', False) @@ -325,16 +332,22 @@ win_env.SetBitFromOption('no-tests', False) # Set if this is a Google build, otherwise, it is an open source build. if _is_google_update_build: win_env.SetBits('is_google_update_build') + # Ordinarily, presence of device management integration is only for Google + # Update builds. It can be configured independently in case a forker wishes + # to provide their own device management server. + win_env.SetBits('has_device_management') -# Build all directories and two versions if this is the build server. if win_env.Bit('build_server'): win_env.SetBits('all') - win_env.SetBits('build_two_versions') -# Make sure 'all' overrides 'min'. +# 'all' overrides 'min'. if win_env.Bit('all'): win_env.ClearBits('min') +# 'build_three_versions' overrides 'build_two_versions'. +if win_env.Bit('build_three_versions'): + win_env.ClearBits('build_two_versions') + # Allow use of command-line-specified certificates to sign with, but # only if we're not on the build server. if not win_env.Bit('build_server'): @@ -367,39 +380,26 @@ win_env.SetBitFromOption('analysis', False) # non-interactive account or a non-Admin account: http://goo.gl/UyDzeP. win_env.SetBitFromOption('suppress_light_validation', False) -# The precompiled headers are to be used as an optional build speed up -# build facility. Individual compilation units in the project must build with -# or without precompiled headers. Building without precompiled headers is sort -# of meaningless, since all the time we should build with it. However, -# eliminating the dependency is desirable from a few reasons: -# 1. making sure the files in the project include all the definitions they need -# 2. creating different precompile headers if needed. -# 3. making sure the precompile headers do not add to the size bloat. -# There are two current limitations with the current setup. -# First, due to pushing the warning level to W4 and WAll, we rely on the -# common precompile.h to properly turn off the warnings inside system and -# library code. -# Second, to override the ATLASSERT, a file must be included before any of -# the atl headers. To do this on a case by case basis is impractical and -# error prone. -# Therefore, when building with precompile headers off, the code is -# building on W3 and it is not taking over the ATL asserts. -win_env.SetBitFromOption('use_precompiled_headers', True) - -if win_env.Bit('use_precompiled_headers'): - print 'Using precompiled headers.' - - # # Set up version info. # +# If specified on the command line, either two or three successive versions +# of the build targets could be produced by the build script. Such versions +# are useful for creating A/B experiments to test the update paths from +# current version to future versions and assess the quality of releases. omaha_version_info = omaha_version_utils.OmahaVersionInfo('VERSION') omaha_versions_info = [omaha_version_info] - if win_env.Bit('build_two_versions'): omaha_test_version_info = copy.deepcopy(omaha_version_info) - omaha_test_version_info.MakeTestVersion() + omaha_test_version_info.MakeTestVersion(delta=1, prefix='TEST_') omaha_versions_info.append(omaha_test_version_info) +elif win_env.Bit('build_three_versions'): + omaha_test_version_info = copy.deepcopy(omaha_version_info) + omaha_test_version_info.MakeTestVersion(delta=1, prefix='TEST_') + omaha_versions_info.append(omaha_test_version_info) + omaha_test_2_version_info = copy.deepcopy(omaha_version_info) + omaha_test_2_version_info.MakeTestVersion(delta=2, prefix='TEST2_') + omaha_versions_info.append(omaha_test_2_version_info) # Print the version(s) being built. print 'Building versions: %s' % ', '.join( @@ -417,6 +417,17 @@ if _is_google_update_build: RCFLAGS = ['/DGOOGLE_UPDATE_BUILD=1'], ) +if win_env.Bit('has_device_management'): + win_env.Append( + CPPDEFINES = ['HAS_DEVICE_MANAGEMENT'], + ) + if _is_google_update_build: + # Google Update includes integration specific to Google Chrome, which + # should not be present in other forks of Omaha. + win_env.Append( + CPPDEFINES = ['HAS_LEGACY_DM_CLIENT'], + ) + # Make sure python.exe can be located. win_env.AppendENVPath('PATH', os.environ['OMAHA_PYTHON_DIR']) @@ -429,27 +440,35 @@ if _msc_ver >= omaha_version_utils.VC120: # VS2015 has a set of new libraries as part of the universal CRT. win_env['crt_libs'] = (['libcmt', 'libcpmt'], ['libcmtd', 'libcpmtd']) if _msc_ver >= omaha_version_utils.VC140: - win_env['crt_libs'] = (['libcmt', 'libcpmt', 'libvcruntime', 'libucrt'], - ['libcmtd', 'libcpmtd', 'libvcruntimed', 'libucrtd']) + win_env['crt_libs'] = ( + ['libconcrt', 'libcmt', 'libcpmt', 'libvcruntime', 'libucrt'], + ['libconcrtd', 'libcmtd', 'libcpmtd', 'libvcruntimed', 'libucrtd']) + +win_env.FilterOut(CCFLAGS=['/W3']) win_env.AppendUnique( - # Add windows specific compiler flags. + # Add Windows specific compiler flags. CCFLAGS = [ '/arch:IA32', ('', '/analyze:WX-')[win_env.Bit('analysis')], - '/nologo', '/c', - '/Zc:forScope', - '/Zc:threadSafeInit-', + '/D_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES=1', + '/D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1', + '/D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1', '/D_HAS_EXCEPTIONS=0', + '/D_USING_V110_SDK71_', '/DCOMPILER_MSVC', '/DSTL_MSVC', '/GR-', - '/D_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES=1', - '/D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1', - '/D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1', - '/WX', # warnings as errors - '/d2Zi+', # better debugging support for optimized code + '/GS', + '/nologo', + '/permissive-', + '/std:c++17', + '/W4', + '/Wall', + '/WX', # warnings as errors + '/Zc:twoPhase-', # avoids an ICE in service/service_main.h with 16.1.0. + '/Zo', # better debugging support for optimized code # # Disable the following level 4 warnings below. @@ -461,6 +480,7 @@ win_env.AppendUnique( # # Disable the pedantic warnings below. # + '/wd4091', # 'typedef': ignored on left of when no variable is declared '/wd4191', # unsafe conversion from 'type of expression' to # 'type required' '/wd4217', # member template functions cannot be used for @@ -473,14 +493,16 @@ win_env.AppendUnique( '/wd4510', # default constructor could not be generated '/wd4512', # assignment operator could not be generated '/wd4514', # unreferenced inline function has been removed + '/wd4548', # expression before comma has no effect '/wd4555', # expression has no effect + '/wd4577', # 'noexcept' used with no exception handling mode specified; + # termination on exception is not guaranteed. '/wd4605', # '...' specified on current command line, but was not # specified when precompiled header was built. '/wd4610', # struct can never be instantiated '/wd4619', # there is no warning number 'number' '/wd4623', # default constructor could not be generated... '/wd4625', # copy constructor could not be generated... - '/wd4640', # construction of local static object is not thread-safe '/wd4626', # assignment operator could not be generated... '/wd4668', # not defined as a preprocessor macro, replacing with '0'. '/wd4710', # function not inlined @@ -489,13 +511,22 @@ win_env.AppendUnique( '/wd4755', # Conversion rules for arithmetic operations in the # comparison at mean that one branch cannot be executed # in an inlined function. + '/wd4768', # __declspec attributes before linkage specification are + # ignored + '/wd4774', # format string expected in argument is not a string literal '/wd4777', # format string 'requires an argument of type... '/wd4820', # bytes padding added after construct 'member_name' - '/wd4091', # 'typedef': ignored on left of when no variable is declared + '/wd4840', # non-portable use of class as an arg to a variadic function + '/wd4986', # exception specification doesn't match previous declaration '/wd4987', # nonstandard extension used: 'throw (...) '/wd4995', # name was marked as #pragma deprecated '/wd4996', # 'function': was declared deprecated - + '/wd5032', # detected #pragma warning(push) with no corresponding + # #pragma warning(pop) - due to a WinSDK bug in winioctl.h. + '/wd5038', # data member '' will be initialized after data member '' + '/wd5042', # function declarations at block scope cannot be specified + # 'inline' in standard C++ + '/wd5045', # Compiler will insert Spectre mitigation for memory load # # Disable static analysis warnings. # @@ -512,12 +543,17 @@ win_env.AppendUnique( '$MAIN_DIR', '$MAIN_DIR/third_party/chrome/files/src', '$THIRD_PARTY/breakpad/src', + '$THIRD_PARTY/googletest/googlemock/include', + '$THIRD_PARTY/googletest/googletest/include', + '$THIRD_PARTY/libzip/lib', ], # Defines for windows environment. CPPDEFINES = [ 'PSAPI_VERSION=1', - 'WINVER=0X0500', + # Use _WIN32_WINNT_WIN7 (0x0601) + 'WINVER=0x0601', + '_WIN32_WINNT=0x0601', 'WIN32', '_WINDOWS', 'UNICODE', '_UNICODE', 'WIN32_LEAN_AND_MEAN', @@ -537,6 +573,7 @@ win_env.AppendUnique( '_ATL_XP_TARGETING', '_SECURE_ATL=1', '_WTL_NO_CSTRING', # WTL uses ATL CString instead. + 'ZIP_STATIC', # '_ATL_NO_CONNECTION_POINTS', # '_ATL_NO_DOCHOSTUIHANDLER', @@ -548,7 +585,8 @@ win_env.AppendUnique( # Windows XP. Therefore, the code needs to gracefully handle the # cases where some of the functionality enabled by the platform SDK # headers is not available. - 'DNTDDI_VERSION=NTDDI_WINXPSP3', + # Use NTDDI_WIN7 (0x06010000) + 'NTDDI_VERSION=0x06010000', # don't define min and max in windef.h 'NOMINMAX', @@ -579,8 +617,6 @@ win_env.AppendUnique( omaha_version_info.update_plugin_version), 'UPDATE_PLUGIN_FILENAME=_T(\\"%s\\")' % ( omaha_version_info.update_plugin_filename), - 'BHO_NAME=_T(\\"%s\\")' % omaha_version_utils.GetBHO_NAME(), - 'BHO_FILENAME=_T(\\"%s\\")' % omaha_version_info.bho_filename, 'CRASH_HANDLER_NAME=_T(\\"%s\\")' % omaha_version_utils.GetCRASH_HANDLER_NAME(), @@ -589,6 +625,7 @@ win_env.AppendUnique( # for the CRX Verifier protocol buffers code. 'GOOGLE_PROTOBUF_NO_RTTI', + 'GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP', ], # Link in some windows libraries. @@ -630,17 +667,6 @@ win_env.AppendUnique( ], ) -if _is_google_update_build: - win_env.AppendUnique(CPPPATH = [ - '$THIRD_PARTY/gmock/include', - '$THIRD_PARTY/gtest/include', - ]) -else: - win_env.AppendUnique(CPPPATH = [ - '$THIRD_PARTY/googletest/googlemock/include', - '$THIRD_PARTY/googletest/googletest/include', - ]) - if _msc_ver >= omaha_version_utils.VC140: win_env.AppendUnique( CCFLAGS = [ @@ -669,7 +695,7 @@ if _msc_ver >= omaha_version_utils.VC120 and not win_env.Bit('build_server'): win_env.AppendUnique( # Forces writes to the program database (PDB) file to allow otherwise, # for some reason, optimized builds fail when run with -j option. - CCFLAGS = ['/FS', '/MP'] + CCFLAGS = ['/FS', ] ) # Allow verification of these settings in the build log. @@ -746,7 +772,7 @@ _official_installers_dirs = [ ] _extra_dirs = [ - 'enterprise', + #'enterprise', 'standalone', ] @@ -834,8 +860,6 @@ windows_optimized_env.AppendUnique( CCFLAGS = [ '/O1', # Optimize for small size. '/Oy-', # Disable frame pointer omission. - '/GS', - '/FD', '/GL', # Global optimization goes with link flag '/LTCG' '/MT', ], diff --git a/omaha/mi_exe_stub/build.scons b/omaha/mi_exe_stub/build.scons index e2d2c32..bebc86f 100644 --- a/omaha/mi_exe_stub/build.scons +++ b/omaha/mi_exe_stub/build.scons @@ -18,13 +18,11 @@ Import('env') env.BuildSConscript('x86_encoder') for omaha_version_info in env['omaha_versions_info']: - prefix = omaha_version_info.filename_prefix temp_env = env.Clone() - if prefix == 'TEST_': - temp_env['OBJPREFIX'] = temp_env.subst('test/$OBJPREFIX') - elif prefix: - raise Exception('ERROR: Unrecognized prefix "%s"' % prefix) + prefix = omaha_version_info.filename_prefix + if prefix: + temp_env['OBJPREFIX'] = temp_env.subst(prefix + 'obj/$OBJPREFIX') temp_env.Append( CPPDEFINES = [ @@ -37,15 +35,24 @@ for omaha_version_info in env['omaha_versions_info']: CCFLAGS = [ '/D_SECURE_SCL=1', '/EHsc', - '/FI$MAIN_DIR/mi_exe_stub/ptrdiff_t.h', ], LIBS = [ + '$LIB_DIR/base.lib', + '$LIB_DIR/common.lib', + '$LIB_DIR/net.lib', + '$LIB_DIR/security.lib', 'lzma', 'mi_exe_stub_lib', temp_env['atls_libs'][temp_env.Bit('debug')], temp_env['crt_libs'][temp_env.Bit('debug')], + 'crypt32.lib', + 'iphlpapi.lib', + 'netapi32.lib', + 'psapi.lib', 'shlwapi', + 'userenv.lib', 'version', + 'wtsapi32.lib', ], RCFLAGS = [ '/DVERSION_MAJOR=%d' % omaha_version_info.version_major, @@ -94,8 +101,4 @@ local_inputs = [ '../base/extractor.cc', ] -# Precompiled headers cannot be used because debug builds must link against -# base.lib due to base/ inclusions in precompile.h. -local_env.ComponentStaticLibrary('mi_exe_stub_lib', - local_inputs, - use_pch_default=False) +local_env.ComponentLibrary('mi_exe_stub_lib', local_inputs) diff --git a/omaha/mi_exe_stub/mi.cc b/omaha/mi_exe_stub/mi.cc index 28ca6b2..ed0e337 100644 --- a/omaha/mi_exe_stub/mi.cc +++ b/omaha/mi_exe_stub/mi.cc @@ -29,8 +29,10 @@ #pragma warning(push) // C4917: a GUID can only be associated with a class, interface or namespace. -#pragma warning(disable : 4917) +// C5038: data member '' will be initialized after data member '' +#pragma warning(disable : 4917 5038) #include +#include #pragma warning(pop) #include @@ -38,14 +40,13 @@ #include #include #include -#include +#include #pragma warning(push) // C4310: cast truncates constant value #pragma warning(disable : 4310) #include "base/basictypes.h" #pragma warning(pop) -#include "base/scoped_ptr.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" #include "omaha/base/extractor.h" @@ -53,13 +54,16 @@ // C4244: conversion from 'type1' to 'type2', possible loss of data #pragma warning(disable : 4244) #pragma warning(pop) -#include "omaha/base/scoped_any.h" + #include "omaha/base/system_info.h" #include "omaha/base/utils.h" +#include "omaha/common/brave_referral_code_utils.h" +#include "omaha/common/brave_stats_updater.h" #include "omaha/common/const_cmd_line.h" #include "omaha/mi_exe_stub/process.h" #include "omaha/mi_exe_stub/mi.grh" #include "omaha/mi_exe_stub/tar.h" +#include "omaha/third_party/smartany/scoped_any.h" extern "C" { #include "third_party/lzma/files/C/Bcj2.h" #include "third_party/lzma/files/C/LzmaDec.h" @@ -110,7 +114,7 @@ char* ReadTag(TagExtractor* extractor) { return NULL; } - scoped_array tag_buffer(new char[tag_buffer_size]); + std::unique_ptr tag_buffer(new char[tag_buffer_size]); if (!tag_buffer.get()) { return NULL; } @@ -150,11 +154,26 @@ char* ExtractTag(const TCHAR* module_file_name) { return ret; } +char* GetTag(HINSTANCE instance) { + // Get this module file name. + TCHAR module_file_name[MAX_PATH] = {}; + DWORD len = ::GetModuleFileName(instance, + module_file_name, + arraysize(module_file_name)); + if (len == 0 || len >= arraysize(module_file_name)) { + _ASSERTE(false); + return NULL; + } + + return ExtractTag(module_file_name); +} + class MetaInstaller { public: - MetaInstaller(HINSTANCE instance, LPCSTR cmd_line) + MetaInstaller(HINSTANCE instance, LPCSTR cmd_line, LPCTSTR referral_code) : instance_(instance), cmd_line_(cmd_line), + referral_code_(referral_code), exit_code_(0) { } @@ -203,7 +222,7 @@ class MetaInstaller { CString command_line(exe_path_); ::PathQuoteSpaces(CStrBuf(command_line, MAX_PATH)); - scoped_array tag(GetTag()); + std::unique_ptr tag(GetTag(instance_)); if (cmd_line_.IsEmpty()) { // Run-by-user case. if (!tag.get()) { @@ -212,10 +231,32 @@ class MetaInstaller { HandleError(hr); return hr; } - SafeCStringAppendCmdLine(&command_line, _T(" /%s %s /%s"), - kCmdLineInstallSource, - kCmdLineInstallSource_TaggedMetainstaller, - kCmdLineInstall); + + const CString original_tag(tag.get()); + CString silent_tag; + silent_tag.Format(_T("&%s"), kCmdLineSilent); + const int silent_tag_len = silent_tag.GetLength(); + // If tag has silent tag, append \silent \install to command line. + // Also silent tag is removed from tag list and assign it to |tag| + // buffer again. silent tag isn't recognized by brave updater. + if (original_tag.Right(silent_tag_len).CompareNoCase(silent_tag) == 0) { + const CString revised_tag = + original_tag.Left(original_tag.GetLength() - silent_tag_len); + const int revised_tag_len = revised_tag.GetLength(); + char *new_tag_buffer = new char[revised_tag_len + 1]; + strncpy(new_tag_buffer, tag.get(), revised_tag_len); + new_tag_buffer[revised_tag_len] = NULL; + tag.reset(new_tag_buffer); + + SafeCStringAppendCmdLine(&command_line, _T(" /%s /%s"), + kCmdLineSilent, + kCmdLineInstall); + } else { + SafeCStringAppendCmdLine(&command_line, _T(" /%s %s /%s"), + kCmdLineInstallSource, + kCmdLineInstallSource_TaggedMetainstaller, + kCmdLineInstall); + } } else { SafeCStringAppendCmdLine(&command_line, _T(" %s"), cmd_line_); @@ -224,8 +265,9 @@ class MetaInstaller { const bool should_append_tag = !RemoveIgnoreTagSwitch(&command_line); if (should_append_tag && tag.get()) { - SafeCStringAppendCmdLine(&command_line, _T(" \"%s\""), - CString(tag.get())); + CString tag_with_referral_code(tag.get()); + tag_with_referral_code.AppendFormat(_T("&referral=%s"), referral_code_); + SafeCStringAppendCmdLine(&command_line, _T(" \"%s\""), tag_with_referral_code); } RunAndWait(command_line, &exit_code_); @@ -442,20 +484,6 @@ class MetaInstaller { return true; } - char* GetTag() const { - // Get this module file name. - TCHAR module_file_name[MAX_PATH] = {}; - DWORD len = ::GetModuleFileName(instance_, - module_file_name, - arraysize(module_file_name)); - if (len == 0 || len >= arraysize(module_file_name)) { - _ASSERTE(false); - return NULL; - } - - return ExtractTag(module_file_name); - } - static CString GetFilespec(const CString& path) { int pos = path.ReverseFind('\\'); if (pos >= 0) { @@ -525,7 +553,7 @@ class MetaInstaller { packed_buffer += sizeof(unpacked_size_64); packed_size -= sizeof(unpacked_size_64); - scoped_array unpacked_buffer(new uint8[unpacked_size]); + std::unique_ptr unpacked_buffer(new uint8[unpacked_size]); ELzmaStatus status = static_cast(0); SRes result = LzmaDec_DecodeToBuf( @@ -561,7 +589,7 @@ class MetaInstaller { uint32 stream3_size = *reinterpret_cast(p); p += sizeof(uint32); // NOLINT - scoped_array output_buffer(new uint8[original_size]); + std::unique_ptr output_buffer(new uint8[original_size]); if (SZ_OK != Bcj2_Decode(p, stream0_size, p + stream0_size, @@ -588,6 +616,7 @@ class MetaInstaller { HINSTANCE instance_; CString cmd_line_; CString exe_path_; + CString referral_code_; DWORD exit_code_; CSimpleArray files_to_delete_; CString temp_dir_; @@ -633,6 +662,79 @@ HRESULT HandleError(HRESULT result) { return result; } +CString ReadAppGuidFromTag(HINSTANCE hInstance) { + std::unique_ptr tag(omaha::GetTag(hInstance)); + const CString original_tag(tag.get()); + + CString app_guid; + const CString app_guid_prefix = _T("appguid="); + int appguid_start = original_tag.Find(app_guid_prefix); + if (appguid_start != -1) { + appguid_start += app_guid_prefix.GetLength(); + int appguid_end = original_tag.Find(_T("&"), appguid_start); + if (appguid_end != -1) { + app_guid = original_tag.Mid(appguid_start, appguid_end - appguid_start); + } + } + + return app_guid; +} + +HRESULT StorePathToRegForPromoCode(LPSTR lpCmdLine) { + // This stub installer can be executed twice by internally when user allowed + // to run installer in admin mode. In this case, copied with changed filename + // |kOmahaMetainstallerFileName| at tempdir is used. + // In that case, command line is not empty. + // So, we can only get original file name when this run is user initiated. + if (!CString(lpCmdLine).IsEmpty()) + return S_OK; + + TCHAR module_file_name[MAX_PATH] = {}; + DWORD len = ::GetModuleFileName(NULL, + module_file_name, + arraysize(module_file_name)); + if (len == 0 || len >= arraysize(module_file_name)) { + _ASSERTE(false); + return NULL; + } + + HKEY key; + DWORD dw; + if (RegCreateKeyEx(HKEY_CURRENT_USER, + _T("Software\\BraveSoftware\\Promo"), + 0, + NULL, + REG_OPTION_NON_VOLATILE, + KEY_WRITE, + NULL, &key, &dw) != S_OK) { + return S_OK; + } + + if (RegSetValueEx(key, + _T("StubInstallerPath"), + NULL, + REG_SZ, + reinterpret_cast(module_file_name), + (lstrlen(module_file_name) + 1) * sizeof(TCHAR)) != S_OK) { + return S_OK; + } + + RegCloseKey(key); + return S_OK; +} + +CString GetReferralCodeFromModuleFileName() { + TCHAR module_file_name[MAX_PATH] = {}; + DWORD len = + ::GetModuleFileName(NULL, module_file_name, arraysize(module_file_name)); + if (len == 0 || len >= arraysize(module_file_name)) { + _ASSERTE(false); + return _T("none"); + } + + return omaha::GetReferralCode(module_file_name); +} + } // namespace } // namespace omaha @@ -651,8 +753,16 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, int) { return omaha::HandleError(hr); } - omaha::MetaInstaller mi(hInstance, lpCmdLine); + omaha::StorePathToRegForPromoCode(lpCmdLine); + + const CString referral_code = omaha::GetReferralCodeFromModuleFileName(); + if (CString(lpCmdLine).IsEmpty()) { + const CString app_guid = omaha::ReadAppGuidFromTag(hInstance); + hr = omaha::BraveSendStatsPing(_T("startup"), app_guid, referral_code, + _T("")); + } + + omaha::MetaInstaller mi(hInstance, lpCmdLine, referral_code); int result = mi.ExtractAndRun(); return result; } - diff --git a/omaha/mi_exe_stub/mi.rc b/omaha/mi_exe_stub/mi.rc index eacfb8f..7addf46 100644 --- a/omaha/mi_exe_stub/mi.rc +++ b/omaha/mi_exe_stub/mi.rc @@ -16,8 +16,6 @@ // This file contains the unlocalized metainstaller resources. #include -#include -#include #include "resource.h" LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -54,7 +52,6 @@ BEGIN VALUE "FileDescription", OMAHA_APP_NAME_ANSI " Setup" VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI " Setup" - VALUE "LegalCopyright", OMAHA_COPYRIGHT_STRING_ENGLISH VALUE "OriginalFilename", MAIN_EXE_BASE_NAME_ANSI "Setup.exe" VALUE "ProductName", OMAHA_APP_NAME_ANSI VALUE "ProductVersion", VERSION_NUMBER_STRING @@ -80,5 +77,5 @@ END // Special external requirement. LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL -#define IDR_GOOGLEUPDATE 1 -IDR_GOOGLEUPDATE GOOGLEUPDATE { 1L } +#define IDR_BRAVEUPDATE 1 +IDR_BRAVEUPDATE BRAVEUPDATE { 1L } diff --git a/omaha/mi_exe_stub/mi_generated_resources_am.rc b/omaha/mi_exe_stub/mi_generated_resources_am.rc index 8cded9e..d48b9fa 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_am.rc and b/omaha/mi_exe_stub/mi_generated_resources_am.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ar.rc b/omaha/mi_exe_stub/mi_generated_resources_ar.rc index eac9b57..a084896 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ar.rc and b/omaha/mi_exe_stub/mi_generated_resources_ar.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_bg.rc b/omaha/mi_exe_stub/mi_generated_resources_bg.rc index 9988a0f..94e1f90 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_bg.rc and b/omaha/mi_exe_stub/mi_generated_resources_bg.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_bn.rc b/omaha/mi_exe_stub/mi_generated_resources_bn.rc index a0a3aa9..a2ff7d0 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_bn.rc and b/omaha/mi_exe_stub/mi_generated_resources_bn.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ca.rc b/omaha/mi_exe_stub/mi_generated_resources_ca.rc index 68590e8..d0a3944 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ca.rc and b/omaha/mi_exe_stub/mi_generated_resources_ca.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_cs.rc b/omaha/mi_exe_stub/mi_generated_resources_cs.rc index 0f9d46f..eb62b7a 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_cs.rc and b/omaha/mi_exe_stub/mi_generated_resources_cs.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_da.rc b/omaha/mi_exe_stub/mi_generated_resources_da.rc index 7f89668..047b56c 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_da.rc and b/omaha/mi_exe_stub/mi_generated_resources_da.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_de.rc b/omaha/mi_exe_stub/mi_generated_resources_de.rc index 0e18946..9cb4ca4 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_de.rc and b/omaha/mi_exe_stub/mi_generated_resources_de.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_el.rc b/omaha/mi_exe_stub/mi_generated_resources_el.rc index 887c645..2a3c2c3 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_el.rc and b/omaha/mi_exe_stub/mi_generated_resources_el.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_en-GB.rc b/omaha/mi_exe_stub/mi_generated_resources_en-GB.rc index 77e5443..680daf7 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_en-GB.rc and b/omaha/mi_exe_stub/mi_generated_resources_en-GB.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_en.rc b/omaha/mi_exe_stub/mi_generated_resources_en.rc index a387c9a..483b043 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_en.rc and b/omaha/mi_exe_stub/mi_generated_resources_en.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_es-419.rc b/omaha/mi_exe_stub/mi_generated_resources_es-419.rc index 86012eb..2d1bbf5 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_es-419.rc and b/omaha/mi_exe_stub/mi_generated_resources_es-419.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_es.rc b/omaha/mi_exe_stub/mi_generated_resources_es.rc index 4c713b5..8addcb2 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_es.rc and b/omaha/mi_exe_stub/mi_generated_resources_es.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_et.rc b/omaha/mi_exe_stub/mi_generated_resources_et.rc index de09d55..944e0f5 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_et.rc and b/omaha/mi_exe_stub/mi_generated_resources_et.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_fa.rc b/omaha/mi_exe_stub/mi_generated_resources_fa.rc index 2c906ca..a0f9ca7 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_fa.rc and b/omaha/mi_exe_stub/mi_generated_resources_fa.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_fi.rc b/omaha/mi_exe_stub/mi_generated_resources_fi.rc index 354838a..a57fb8f 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_fi.rc and b/omaha/mi_exe_stub/mi_generated_resources_fi.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_fil.rc b/omaha/mi_exe_stub/mi_generated_resources_fil.rc index 497638e..4c7a4b7 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_fil.rc and b/omaha/mi_exe_stub/mi_generated_resources_fil.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_fr.rc b/omaha/mi_exe_stub/mi_generated_resources_fr.rc index d044f85..6fec08d 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_fr.rc and b/omaha/mi_exe_stub/mi_generated_resources_fr.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_gu.rc b/omaha/mi_exe_stub/mi_generated_resources_gu.rc index 58766cb..cb80ef8 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_gu.rc and b/omaha/mi_exe_stub/mi_generated_resources_gu.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_hi.rc b/omaha/mi_exe_stub/mi_generated_resources_hi.rc index 13a0354..043a6cf 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_hi.rc and b/omaha/mi_exe_stub/mi_generated_resources_hi.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_hr.rc b/omaha/mi_exe_stub/mi_generated_resources_hr.rc index 4d4db4a..7c4d1f3 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_hr.rc and b/omaha/mi_exe_stub/mi_generated_resources_hr.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_hu.rc b/omaha/mi_exe_stub/mi_generated_resources_hu.rc index 6a8fb02..71a31f0 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_hu.rc and b/omaha/mi_exe_stub/mi_generated_resources_hu.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_id.rc b/omaha/mi_exe_stub/mi_generated_resources_id.rc index 0405ab0..170b1fc 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_id.rc and b/omaha/mi_exe_stub/mi_generated_resources_id.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_is.rc b/omaha/mi_exe_stub/mi_generated_resources_is.rc index 311cae3..5950a7f 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_is.rc and b/omaha/mi_exe_stub/mi_generated_resources_is.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_it.rc b/omaha/mi_exe_stub/mi_generated_resources_it.rc index c79f9f7..543d85f 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_it.rc and b/omaha/mi_exe_stub/mi_generated_resources_it.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_iw.rc b/omaha/mi_exe_stub/mi_generated_resources_iw.rc index 247a636..97baf4e 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_iw.rc and b/omaha/mi_exe_stub/mi_generated_resources_iw.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ja.rc b/omaha/mi_exe_stub/mi_generated_resources_ja.rc index 4c2ef5a..6598cda 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ja.rc and b/omaha/mi_exe_stub/mi_generated_resources_ja.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_kn.rc b/omaha/mi_exe_stub/mi_generated_resources_kn.rc index a15c748..5d842b7 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_kn.rc and b/omaha/mi_exe_stub/mi_generated_resources_kn.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ko.rc b/omaha/mi_exe_stub/mi_generated_resources_ko.rc index af43051..ab8d715 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ko.rc and b/omaha/mi_exe_stub/mi_generated_resources_ko.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_lt.rc b/omaha/mi_exe_stub/mi_generated_resources_lt.rc index df7d700..eb8a6f6 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_lt.rc and b/omaha/mi_exe_stub/mi_generated_resources_lt.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_lv.rc b/omaha/mi_exe_stub/mi_generated_resources_lv.rc index 3b976ee..b319605 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_lv.rc and b/omaha/mi_exe_stub/mi_generated_resources_lv.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ml.rc b/omaha/mi_exe_stub/mi_generated_resources_ml.rc index 49a125c..93db176 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ml.rc and b/omaha/mi_exe_stub/mi_generated_resources_ml.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_mr.rc b/omaha/mi_exe_stub/mi_generated_resources_mr.rc index df5e294..91aacc4 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_mr.rc and b/omaha/mi_exe_stub/mi_generated_resources_mr.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ms.rc b/omaha/mi_exe_stub/mi_generated_resources_ms.rc index 24be004..870f7fb 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ms.rc and b/omaha/mi_exe_stub/mi_generated_resources_ms.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_nl.rc b/omaha/mi_exe_stub/mi_generated_resources_nl.rc index 1f05e67..e1f80b8 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_nl.rc and b/omaha/mi_exe_stub/mi_generated_resources_nl.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_no.rc b/omaha/mi_exe_stub/mi_generated_resources_no.rc index 140a7d6..c9c82a0 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_no.rc and b/omaha/mi_exe_stub/mi_generated_resources_no.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_pl.rc b/omaha/mi_exe_stub/mi_generated_resources_pl.rc index aa0a0dc..ae938fa 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_pl.rc and b/omaha/mi_exe_stub/mi_generated_resources_pl.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_pt-BR.rc b/omaha/mi_exe_stub/mi_generated_resources_pt-BR.rc index 6fe4eb5..4ed106a 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_pt-BR.rc and b/omaha/mi_exe_stub/mi_generated_resources_pt-BR.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_pt-PT.rc b/omaha/mi_exe_stub/mi_generated_resources_pt-PT.rc index ada4f8c..2e0a14c 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_pt-PT.rc and b/omaha/mi_exe_stub/mi_generated_resources_pt-PT.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ro.rc b/omaha/mi_exe_stub/mi_generated_resources_ro.rc index fdff05d..37fd340 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ro.rc and b/omaha/mi_exe_stub/mi_generated_resources_ro.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ru.rc b/omaha/mi_exe_stub/mi_generated_resources_ru.rc index 49e1312..d57619d 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ru.rc and b/omaha/mi_exe_stub/mi_generated_resources_ru.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_sk.rc b/omaha/mi_exe_stub/mi_generated_resources_sk.rc index c88d9e9..397b6a0 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_sk.rc and b/omaha/mi_exe_stub/mi_generated_resources_sk.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_sl.rc b/omaha/mi_exe_stub/mi_generated_resources_sl.rc index ab1dfd1..2a4fc76 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_sl.rc and b/omaha/mi_exe_stub/mi_generated_resources_sl.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_sr.rc b/omaha/mi_exe_stub/mi_generated_resources_sr.rc index 5b5662b..7eec2df 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_sr.rc and b/omaha/mi_exe_stub/mi_generated_resources_sr.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_sv.rc b/omaha/mi_exe_stub/mi_generated_resources_sv.rc index 6e87308..347c277 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_sv.rc and b/omaha/mi_exe_stub/mi_generated_resources_sv.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_sw.rc b/omaha/mi_exe_stub/mi_generated_resources_sw.rc index b1104e7..ff337c3 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_sw.rc and b/omaha/mi_exe_stub/mi_generated_resources_sw.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ta.rc b/omaha/mi_exe_stub/mi_generated_resources_ta.rc index 3f1c8d1..bf6b427 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ta.rc and b/omaha/mi_exe_stub/mi_generated_resources_ta.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_te.rc b/omaha/mi_exe_stub/mi_generated_resources_te.rc index e77731f..68b8467 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_te.rc and b/omaha/mi_exe_stub/mi_generated_resources_te.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_th.rc b/omaha/mi_exe_stub/mi_generated_resources_th.rc index 4f03211..594a8c6 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_th.rc and b/omaha/mi_exe_stub/mi_generated_resources_th.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_tr.rc b/omaha/mi_exe_stub/mi_generated_resources_tr.rc index 4f58021..ee50a9c 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_tr.rc and b/omaha/mi_exe_stub/mi_generated_resources_tr.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_uk.rc b/omaha/mi_exe_stub/mi_generated_resources_uk.rc index 28d6564..4ece612 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_uk.rc and b/omaha/mi_exe_stub/mi_generated_resources_uk.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_ur.rc b/omaha/mi_exe_stub/mi_generated_resources_ur.rc index 8ff25ef..6a7bccf 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_ur.rc and b/omaha/mi_exe_stub/mi_generated_resources_ur.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_vi.rc b/omaha/mi_exe_stub/mi_generated_resources_vi.rc index 5d2fb0c..5d2ed85 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_vi.rc and b/omaha/mi_exe_stub/mi_generated_resources_vi.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_zh-CN.rc b/omaha/mi_exe_stub/mi_generated_resources_zh-CN.rc index a572f46..bc28965 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_zh-CN.rc and b/omaha/mi_exe_stub/mi_generated_resources_zh-CN.rc differ diff --git a/omaha/mi_exe_stub/mi_generated_resources_zh-TW.rc b/omaha/mi_exe_stub/mi_generated_resources_zh-TW.rc index c25d897..5d0e7c7 100644 Binary files a/omaha/mi_exe_stub/mi_generated_resources_zh-TW.rc and b/omaha/mi_exe_stub/mi_generated_resources_zh-TW.rc differ diff --git a/omaha/mi_exe_stub/ptrdiff_t.h b/omaha/mi_exe_stub/ptrdiff_t.h deleted file mode 100644 index a9c653b..0000000 --- a/omaha/mi_exe_stub/ptrdiff_t.h +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2006-2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// The WDK CRT headers do not define ptrdiff_t, which is used by -// scoped_array. - -#ifndef OMAHA_MI_EXE_STUB_PTRDIFF_H_ -#define OMAHA_MI_EXE_STUB_PTRDIFF_H_ - -namespace std { - -#ifdef _WIN64 -typedef __int64 ptrdiff_t; -#else -typedef int ptrdiff_t; -#endif - -} // namespace std - -#endif // OMAHA_MI_EXE_STUB_PTRDIFF_H_ diff --git a/omaha/mi_exe_stub/tar.h b/omaha/mi_exe_stub/tar.h index 1731d9b..6c89782 100644 --- a/omaha/mi_exe_stub/tar.h +++ b/omaha/mi_exe_stub/tar.h @@ -65,8 +65,8 @@ class Tar { bool ExtractToDir(); private: - HANDLE file_handle_; CString target_directory_name_; + HANDLE file_handle_; bool delete_when_done_; CSimpleArray files_to_delete_; TarFileCallback callback_; diff --git a/omaha/mi_exe_stub/x86_encoder/bcj.cc b/omaha/mi_exe_stub/x86_encoder/bcj.cc index fe254ac..a198e7d 100644 --- a/omaha/mi_exe_stub/x86_encoder/bcj.cc +++ b/omaha/mi_exe_stub/x86_encoder/bcj.cc @@ -17,9 +17,9 @@ #include #include +#include #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "third_party/smartany/scoped_any.h" extern "C" { @@ -46,7 +46,7 @@ int wmain(int argc, WCHAR* argv[], WCHAR* env[]) { } DWORD file_size = static_cast(file_size_data.QuadPart); - scoped_array buffer(new uint8[file_size]); + std::unique_ptr buffer(new uint8[file_size]); DWORD bytes_read = 0; if (!::ReadFile(get(file), buffer.get(), file_size, &bytes_read, NULL) || bytes_read != file_size) { diff --git a/omaha/mi_exe_stub/x86_encoder/bcj2.cc b/omaha/mi_exe_stub/x86_encoder/bcj2.cc index 1fc3daf..af9ccbb 100644 --- a/omaha/mi_exe_stub/x86_encoder/bcj2.cc +++ b/omaha/mi_exe_stub/x86_encoder/bcj2.cc @@ -15,13 +15,13 @@ // // BCJ encodes a file to increase its compressibility. +#include +#include #include #include #include -#include #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/mi_exe_stub/x86_encoder/bcj2_encoder.h" #include "third_party/smartany/scoped_any.h" @@ -45,7 +45,7 @@ int wmain(int argc, WCHAR* argv[], WCHAR* env[]) { } DWORD file_size = static_cast(file_size_data.QuadPart); - scoped_array buffer(new uint8[file_size]); + std::unique_ptr buffer(new uint8[file_size]); DWORD bytes_read = 0; if (!::ReadFile(get(file), buffer.get(), file_size, &bytes_read, NULL) || bytes_read != file_size) { @@ -76,7 +76,7 @@ int wmain(int argc, WCHAR* argv[], WCHAR* env[]) { } size_t buffer_remaining = output_buffer_length; - scoped_array output_buffer(new uint8[output_buffer_length]); + std::unique_ptr output_buffer(new uint8[output_buffer_length]); uint8* p = output_buffer.get(); *reinterpret_cast(p) = bytes_read; p += sizeof(uint32); // NOLINT diff --git a/omaha/mi_exe_stub/x86_encoder/build.scons b/omaha/mi_exe_stub/x86_encoder/build.scons index 993986a..d3d74c3 100644 --- a/omaha/mi_exe_stub/x86_encoder/build.scons +++ b/omaha/mi_exe_stub/x86_encoder/build.scons @@ -45,7 +45,7 @@ bin_env.Append( ], ) -bin_env.ComponentTool( +bin_env.ComponentProgram( prog_name='bcj', source=[ 'bcj.cc', @@ -56,7 +56,7 @@ bjc2_env = bin_env.Clone() bjc2_env.Append( LIBS=[ bcj2_lib ], ) -bjc2_env.ComponentTool( +bjc2_env.ComponentProgram( prog_name='bcj2', source=[ 'bcj2.cc', diff --git a/omaha/mi_exe_stub/x86_encoder/range_encoder.h b/omaha/mi_exe_stub/x86_encoder/range_encoder.h index a4485b1..cb32007 100644 --- a/omaha/mi_exe_stub/x86_encoder/range_encoder.h +++ b/omaha/mi_exe_stub/x86_encoder/range_encoder.h @@ -47,14 +47,14 @@ class RangeEncoder { void set_range(uint32 range) { range_ = range; } private: + std::string* output_; + uint8 cache_; uint32 cache_size_; uint64 low_; uint32 range_; - std::string* output_; - DISALLOW_COPY_AND_ASSIGN(RangeEncoder); }; diff --git a/omaha/net/bind_status_callback.cc b/omaha/net/bind_status_callback.cc deleted file mode 100644 index 43a5ab8..0000000 --- a/omaha/net/bind_status_callback.cc +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// IBindStatusCallback interface. - -#include "omaha/net/bind_status_callback.h" -#include -#include "omaha/base/debug.h" -#include "omaha/base/error.h" -#include "omaha/base/logging.h" -#include "omaha/base/utils.h" - -namespace omaha { - -HRESULT QueryHttpInfo(IWinInetHttpInfo* http_info, DWORD query, CString* info) { - CORE_LOG(L3, (_T("[QueryHttpInfo][%d]"), query)); - ASSERT1(http_info); - ASSERT1(query); - ASSERT1(info); - - info->Empty(); - DWORD size = 0; - DWORD flags = 0; - HRESULT hr = http_info->QueryInfo(query, 0, &size, &flags, 0); - CORE_LOG(L3, (_T("[http_info->QueryInfo][0x%x][%d]"), hr, size)); - if (FAILED(hr)) { - return hr; - } - - CStringA buf; - hr = http_info->QueryInfo(query, CStrBufA(buf, size), &size, &flags, 0); - CORE_LOG(L3, (_T("[http_info->QueryInfo][0x%x][%d]"), hr, size)); - if (FAILED(hr)) { - return hr; - } - - CORE_LOG(L3, (_T("[QueryHttpInfo success][%d][%s]"), query, CA2T(buf))); - *info = buf; - return S_OK; -} - -BindStatusCallback::BindStatusCallback() - : http_verb_(BINDVERB_GET), - post_data_byte_count_(0), - response_code_(0) { -} - -HRESULT BindStatusCallback::Send(BSTR url, - BSTR post_data, - BSTR request_headers, - VARIANT response_headers_needed, - VARIANT* response_headers, - DWORD* response_code, - BSTR* cache_filename) { - if (!url || !*url || !response_code || !cache_filename) { - return E_INVALIDARG; - } - - *response_code = 0; - *cache_filename = NULL; - - if (V_VT(&response_headers_needed) != VT_EMPTY) { - if ((V_VT(&response_headers_needed) != (VT_ARRAY | VT_UI4)) || - !response_headers) { - return E_INVALIDARG; - } - V_VT(response_headers) = VT_NULL; - response_headers_needed_ = response_headers_needed.parray; - if (!response_headers_needed_.GetCount()) { - return E_INVALIDARG; - } - } - - request_headers_ = request_headers; - if (!post_data) { - http_verb_ = BINDVERB_GET; - } else { - http_verb_ = BINDVERB_POST; - post_data_byte_count_ = ::SysStringByteLen(post_data); - reset(post_data_, ::GlobalAlloc(GPTR, post_data_byte_count_)); - if (!post_data_) { - HRESULT hr = HRESULTFromLastError(); - CORE_LOG(LE, (_T("[::GlobalAlloc failed][0x%x]"), hr)); - return hr; - } - - memcpy(get(post_data_), post_data, post_data_byte_count_); - } - - CComPtr bsc(this); - CString filename; - HRESULT hr = ::URLDownloadToCacheFile(NULL, - url, - CStrBuf(filename, MAX_PATH), - MAX_PATH, - 0, - bsc); - - if (response_headers) { - response_headers_.Detach(response_headers); - } - *response_code = response_code_; - - CORE_LOG(L2, (_T("[URLDownloadToCacheFile][0x%x][%s]"), hr, url)); - if (FAILED(hr)) { - return hr; - } - - ASSERT1(!filename.IsEmpty()); - CORE_LOG(L2, (_T("[BindStatusCallback::Send][cache file][%s]"), filename)); - *cache_filename = filename.AllocSysString(); - return hr; -} - -// IBindStatusCallback methods. - -STDMETHODIMP BindStatusCallback::OnStartBinding(DWORD, IBinding* binding) { - __mutexScope(lock_); - binding_git_.Attach(binding); - return S_OK; -} - -STDMETHODIMP BindStatusCallback::GetPriority(LONG* priority) { - UNREFERENCED_PARAMETER(priority); - return E_NOTIMPL; -} - -STDMETHODIMP BindStatusCallback::OnLowResource(DWORD) { - return E_NOTIMPL; -} - -STDMETHODIMP BindStatusCallback::OnProgress(ULONG, ULONG, ULONG, LPCWSTR) { - return E_NOTIMPL; -} - -STDMETHODIMP BindStatusCallback::OnStopBinding(HRESULT, LPCWSTR) { - CComPtr binding; - - __mutexBlock(lock_) { - if (!binding_git_) { - return S_OK; - } - - HRESULT hr = binding_git_.CopyTo(&binding); - VERIFY1(SUCCEEDED(binding_git_.Revoke())); - if (FAILED(hr)) { - CORE_LOG(LW, (_T("[binding_git_.CopyTo failed][0x%x]"), hr)); - return S_OK; - } - } - - CComQIPtr http_info(binding); - if (!http_info) { - return S_OK; - } - - CString response_code_buf; - if (SUCCEEDED(QueryHttpInfo(http_info, - HTTP_QUERY_STATUS_CODE, - &response_code_buf)) && - !response_code_buf.IsEmpty()) { - response_code_ = _ttoi(response_code_buf); - } - - if (!response_headers_needed_) { - return S_OK; - } - int count = response_headers_needed_.GetCount(); - ASSERT1(count > 0); - int lower_bound = response_headers_needed_.GetLowerBound(); - int upper_bound = response_headers_needed_.GetUpperBound(); - - CComSafeArray response_array(count, lower_bound); - for (int i = lower_bound; i <= upper_bound; ++i) { - CString response_header_buf; - QueryHttpInfo(http_info, response_headers_needed_[i], &response_header_buf); - response_array[i] = response_header_buf.AllocSysString(); - } - - V_VT(&response_headers_) = VT_ARRAY | VT_BSTR; - V_ARRAY(&response_headers_) = response_array.Detach(); - return S_OK; -} - -STDMETHODIMP BindStatusCallback::GetBindInfo(DWORD* flags, BINDINFO* info) { - ASSERT1(flags); - ASSERT1(info); - *flags = 0; - - // Set up the BINDINFO data structure. - info->cbSize = sizeof(*info); - info->dwBindVerb = http_verb_; - info->szExtraInfo = NULL; - - // Initialize the STGMEDIUM. - SetZero(info->stgmedData); - info->grfBindInfoF = 0; - info->szCustomVerb = NULL; - - switch (http_verb_) { - case BINDVERB_POST: - if (post_data_) { - // Fill the STGMEDIUM with the data to post. Certain versions of Urlmon - // require TYMED_GLOBAL with GMEM_FIXED. - info->stgmedData.tymed = TYMED_HGLOBAL; - info->stgmedData.hGlobal = get(post_data_); - - // The documentation for GetBindInfo() indicates that the method could - // be called multiple times for the same request. We do not want to - // allocate global memory for each of those times. So we maintain - // ownership of the global memory, and pass a reference to it each time. - // The HGLOBAL is released on BindStatusCallback destruction. Hence we - // set pUnkForRelease to our IUnknown ptr. - info->stgmedData.pUnkForRelease = - static_cast(this); - AddRef(); - - info->cbstgmedData = post_data_byte_count_; - } - return S_OK; - - case BINDVERB_GET: - return S_OK; - - case BINDVERB_PUT: - case BINDVERB_CUSTOM: - default: - ASSERT1(false); - return E_FAIL; - } -} - -STDMETHODIMP BindStatusCallback::OnDataAvailable(DWORD, - DWORD, - FORMATETC*, - STGMEDIUM*) { - // The documentation does not explicitly say that E_NOTIMPL can be returned - // for this method. So we return S_OK. - return S_OK; -} - -STDMETHODIMP BindStatusCallback::OnObjectAvailable(REFIID, IUnknown*) { - // The documentation does not explicitly say that E_NOTIMPL can be returned - // for this method. So we return S_OK. - return S_OK; -} - -STDMETHODIMP BindStatusCallback::BeginningTransaction(LPCWSTR, - LPCWSTR, - DWORD, - LPWSTR* request_headers) { - if (!request_headers) { - return E_INVALIDARG; - } - *request_headers = NULL; - - if (request_headers_.IsEmpty()) { - return S_OK; - } - - int request_headers_size = request_headers_.GetLength() + 1; - TCHAR* additional_headers = static_cast( - ::CoTaskMemAlloc(request_headers_size * sizeof(TCHAR))); - if (!additional_headers) { - return E_OUTOFMEMORY; - } - - _tcscpy_s(additional_headers, request_headers_size, request_headers_); - *request_headers = additional_headers; - - return S_OK; -} - -STDMETHODIMP BindStatusCallback::OnResponse(DWORD response_code, - LPCWSTR response_headers, - LPCWSTR request_headers, - LPWSTR* additional_headers) { - CORE_LOG(L1, (_T("[OnResponse [%d][%s]"), response_code, response_headers)); - UNREFERENCED_PARAMETER(response_code); - UNREFERENCED_PARAMETER(response_headers); - UNREFERENCED_PARAMETER(request_headers); - if (!additional_headers) { - return E_INVALIDARG; - } - - *additional_headers = NULL; - return S_OK; -} - -HRESULT BindStatusCallback::Cancel() { - CComPtr binding; - - __mutexBlock(lock_) { - if (!binding_git_) { - return S_OK; - } - - HRESULT hr = binding_git_.CopyTo(&binding); - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[binding_git_.CopyTo failed][0x%x]"), hr)); - return hr; - } - } - - return binding->Abort(); -} - -} // namespace omaha - diff --git a/omaha/net/bind_status_callback.h b/omaha/net/bind_status_callback.h deleted file mode 100644 index 3afb72c..0000000 --- a/omaha/net/bind_status_callback.h +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// IBindStatusCallback interface. Support for HTTP POST. - -#ifndef OMAHA_NET_BIND_STATUS_CALLBACK_H__ -#define OMAHA_NET_BIND_STATUS_CALLBACK_H__ - -#include -#include -#include -#include -#include -#include -#include "omaha/base/scoped_any.h" -#include "omaha/base/synchronized.h" - -namespace omaha { - -class ATL_NO_VTABLE BindStatusCallback - : public CComObjectRootEx, - public IBindStatusCallback, - public IHttpNegotiate { - public: - HRESULT Send(BSTR url, - BSTR post_data, - BSTR request_headers, - VARIANT response_headers_needed, - VARIANT* response_headers, - DWORD* response_code, - BSTR* cache_filename); - - HRESULT Cancel(); - - // C4505: unreferenced IUnknown local functions have been removed - #pragma warning(disable : 4505) - BEGIN_COM_MAP(BindStatusCallback) - COM_INTERFACE_ENTRY(IBindStatusCallback) - COM_INTERFACE_ENTRY(IHttpNegotiate) - END_COM_MAP() - - // IBindStatusCallback methods. - STDMETHODIMP OnStartBinding(DWORD reserved, IBinding* binding); - STDMETHODIMP GetPriority(LONG* priority); - STDMETHODIMP OnLowResource(DWORD reserved); - STDMETHODIMP OnProgress(ULONG, ULONG, ULONG, LPCWSTR); - STDMETHODIMP OnStopBinding(HRESULT, LPCWSTR); - STDMETHODIMP GetBindInfo(DWORD* bindf_flags, BINDINFO* bind_info); - STDMETHODIMP OnDataAvailable(DWORD, DWORD, FORMATETC*, STGMEDIUM*); - STDMETHODIMP OnObjectAvailable(REFIID, IUnknown*); - - // IHttpNegotiate methods - STDMETHODIMP BeginningTransaction(LPCWSTR url, - LPCWSTR request_headers, - DWORD reserved, - LPWSTR* additional_headers); - STDMETHODIMP OnResponse(DWORD response_code, - LPCWSTR response_headers, - LPCWSTR request_headers, - LPWSTR* additional_request_headers); - - protected: - BindStatusCallback(); - virtual ~BindStatusCallback() {} - - private: - LLock lock_; - BINDVERB http_verb_; - scoped_hglobal post_data_; - DWORD post_data_byte_count_; - CString request_headers_; - CComSafeArray response_headers_needed_; - CComVariant response_headers_; - DWORD response_code_; - CComGITPtr binding_git_; -}; - -} // namespace omaha - -#endif // OMAHA_NET_BIND_STATUS_CALLBACK_H__ - diff --git a/omaha/net/bits_job_callback.cc b/omaha/net/bits_job_callback.cc index 02943cb..ba8d014 100644 --- a/omaha/net/bits_job_callback.cc +++ b/omaha/net/bits_job_callback.cc @@ -29,7 +29,7 @@ HRESULT BitsJobCallback::Create(BitsRequest* bits_request, ASSERT1(bits_job_callback); *bits_job_callback = NULL; - scoped_ptr > callback_obj( + std::unique_ptr> callback_obj( new CComObjectNoLock); if (callback_obj == NULL) { return E_OUTOFMEMORY; diff --git a/omaha/net/bits_job_callback.h b/omaha/net/bits_job_callback.h index eb3a9cb..78821e5 100644 --- a/omaha/net/bits_job_callback.h +++ b/omaha/net/bits_job_callback.h @@ -57,7 +57,7 @@ class ATL_NO_VTABLE BitsJobCallback BitsRequest* bits_request_; LLock lock_; - DISALLOW_EVIL_CONSTRUCTORS(BitsJobCallback); + DISALLOW_COPY_AND_ASSIGN(BitsJobCallback); }; } // namespace omaha diff --git a/omaha/net/bits_request.cc b/omaha/net/bits_request.cc index 95aae57..af2b118 100644 --- a/omaha/net/bits_request.cc +++ b/omaha/net/bits_request.cc @@ -31,7 +31,8 @@ #include #include #include -#include +#include +#include #include "omaha/base/const_addresses.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" @@ -88,9 +89,9 @@ BitsRequest::BitsRequest() minimum_retry_delay_(-1), no_progress_timeout_(-1), current_auth_scheme_(0), + creds_set_scheme_unknown_(false), bits_request_callback_(NULL), - last_progress_report_tick_(0), - creds_set_scheme_unknown_(false) { + last_progress_report_tick_(0) { GetBitsManager(&bits_manager_); // Creates a auto-reset event for BITS job change notifications. @@ -297,7 +298,10 @@ HRESULT BitsRequest::CreateOrOpenJob(const TCHAR* display_name, // Try to find if we already have the job in the BITS queue. // By convention, the display name of the job is the same as the file name. CComPtr job; - hr = FindBitsJobIf(std::bind2nd(JobDisplayNameEqual(), display_name), + hr = FindBitsJobIf([display_name](CComPtr in_job) { + return IsEqualBitsJobDisplayName(in_job, + display_name); + }, bits_manager, &job); if (SUCCEEDED(hr)) { @@ -857,10 +861,11 @@ DownloadMetrics BitsRequest::MakeDownloadMetrics(HRESULT hr) const { download_metrics.error = error; BG_JOB_PROGRESS progress = {0}; if (SUCCEEDED(request_state_->bits_job->GetProgress(&progress))) { - download_metrics.downloaded_bytes = progress.BytesTransferred <= kint64max ? - static_cast(progress.BytesTransferred) : -1; + constexpr auto kMaxBytes = std::numeric_limits::max(); + download_metrics.downloaded_bytes = progress.BytesTransferred <= kMaxBytes ? + static_cast(progress.BytesTransferred) : -1; - download_metrics.total_bytes = progress.BytesTotal <= kint64max ? + download_metrics.total_bytes = progress.BytesTotal <= kMaxBytes ? static_cast(progress.BytesTotal) : -1; } download_metrics.download_time_ms = diff --git a/omaha/net/bits_request.h b/omaha/net/bits_request.h index 296122b..7acf323 100644 --- a/omaha/net/bits_request.h +++ b/omaha/net/bits_request.h @@ -28,9 +28,10 @@ #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/synchronized.h" #include "omaha/base/utils.h" #include "omaha/net/http_request.h" @@ -222,7 +223,7 @@ class BitsRequest : public HttpRequestInterface { int http_status_code; CComPtr bits_job; GUID bits_job_id; - scoped_ptr download_metrics; + std::unique_ptr download_metrics; uint64 request_begin_ms; uint64 request_end_ms; }; @@ -256,7 +257,7 @@ class BitsRequest : public HttpRequestInterface { BitsJobCallback* bits_request_callback_; uint32 last_progress_report_tick_; - scoped_ptr request_state_; + std::unique_ptr request_state_; // See http://b/1189928 CComPtr bits_manager_; @@ -266,7 +267,7 @@ class BitsRequest : public HttpRequestInterface { // BitsRequest. static const int kJobProgressReportMinimumIntervalMs = 200; - DISALLOW_EVIL_CONSTRUCTORS(BitsRequest); + DISALLOW_COPY_AND_ASSIGN(BitsRequest); }; } // namespace omaha diff --git a/omaha/net/bits_utils.cc b/omaha/net/bits_utils.cc index f56b66b..a2a56d6 100644 --- a/omaha/net/bits_utils.cc +++ b/omaha/net/bits_utils.cc @@ -45,8 +45,7 @@ HRESULT GetBitsManager(IBackgroundCopyManager** bits_manager) { return S_OK; } -bool JobLocalNameEqual::operator()(IBackgroundCopyJob* job, - const TCHAR* name) const { +bool IsEqualBitsJobLocalName(IBackgroundCopyJob* job, const TCHAR* name) { ASSERT1(job); ASSERT1(name); CComPtr files; @@ -71,8 +70,7 @@ bool JobLocalNameEqual::operator()(IBackgroundCopyJob* job, return false; } -bool JobDisplayNameEqual::operator()(IBackgroundCopyJob* job, - const TCHAR* name) const { +bool IsEqualBitsJobDisplayName(IBackgroundCopyJob* job, const TCHAR* name) { ASSERT1(job); ASSERT1(name); scoped_ptr_cotask display_name; diff --git a/omaha/net/bits_utils.h b/omaha/net/bits_utils.h index e30ac17..fca84bf 100644 --- a/omaha/net/bits_utils.h +++ b/omaha/net/bits_utils.h @@ -20,26 +20,17 @@ #include #include #include -#include namespace omaha { // Gets the instance of BITS manager. HRESULT GetBitsManager(IBackgroundCopyManager** bits_manager); -// Compares the local name of a job. -struct JobLocalNameEqual - : public std::binary_function { +// Compares the local name of a BITS job. +bool IsEqualBitsJobLocalName(IBackgroundCopyJob* job, const TCHAR* name); - bool operator()(IBackgroundCopyJob* job, const TCHAR* local_name) const; -}; - -// Compares the display name of a job. -struct JobDisplayNameEqual - : public std::binary_function { - - bool operator()(IBackgroundCopyJob* job, const TCHAR* local_name) const; -}; +// Compares the display name of a BITS job. +bool IsEqualBitsJobDisplayName(IBackgroundCopyJob* job, const TCHAR* name); // Finds a job that matches the given predicate. // TODO(omaha): do we need to search across all users? diff --git a/omaha/net/build.scons b/omaha/net/build.scons index 97e23d1..5a1af86 100644 --- a/omaha/net/build.scons +++ b/omaha/net/build.scons @@ -29,7 +29,6 @@ local_env.Append( ) inputs = [ - 'bind_status_callback.cc', 'bits_request.cc', 'bits_job_callback.cc', 'bits_utils.cc', @@ -39,7 +38,6 @@ inputs = [ 'detector.cc', 'http_client.cc', 'simple_request.cc', - 'net_diags.cc', 'net_utils.cc', 'network_config.cc', 'network_request.cc', diff --git a/omaha/net/cup_ecdsa_pubkey.1.h b/omaha/net/cup_ecdsa_pubkey.1.h new file mode 100644 index 0000000..d0c87e9 --- /dev/null +++ b/omaha/net/cup_ecdsa_pubkey.1.h @@ -0,0 +1,31 @@ +// Copyright 2018 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ======================================================================== +// +// CUP-ECDSA public keys consist of a byte array, 66 bytes long, containing: +// * The key ID (one byte) +// * The public key in X9.62 uncompressed encoding (65 bytes): +// * Uncompressed header byte (0x04) +// * Gx coordinate (256-bit integer, big-endian) +// * Gy coordinate (256-bit integer, big-endian) +{0x01, +0x04, +0x6a, 0x13, 0xc5, 0xf6, 0xb7, 0x28, 0xad, 0x94, +0xbf, 0x77, 0x84, 0xc6, 0x95, 0x82, 0x09, 0x9b, +0xab, 0x02, 0xed, 0x27, 0x97, 0x5d, 0x58, 0x43, +0x3c, 0x85, 0x70, 0x13, 0x5a, 0xeb, 0xb1, 0xf3, +0x62, 0xb3, 0x21, 0x43, 0x47, 0x26, 0x2e, 0x18, +0x7e, 0x27, 0xc4, 0xbb, 0x5a, 0x9f, 0x0e, 0xe0, +0x57, 0xa8, 0x2b, 0x51, 0xb0, 0x9b, 0x77, 0x12, +0x93, 0x6e, 0x2d, 0xdd, 0xc0, 0x2a, 0x97, 0x66}; diff --git a/omaha/net/cup_ecdsa_pubkey.8.h b/omaha/net/cup_ecdsa_pubkey.8.h new file mode 100644 index 0000000..9156ab4 --- /dev/null +++ b/omaha/net/cup_ecdsa_pubkey.8.h @@ -0,0 +1,31 @@ +// Copyright 2018 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ======================================================================== +// +// CUP-ECDSA public keys consist of a byte array, 66 bytes long, containing: +// * The key ID (one byte) +// * The public key in X9.62 uncompressed encoding (65 bytes): +// * Uncompressed header byte (0x04) +// * Gx coordinate (256-bit integer, big-endian) +// * Gy coordinate (256-bit integer, big-endian) +{0x08, +0x04, +0xf8, 0x9d, 0xa2, 0x0a, 0x97, 0xe4, 0xf2, 0x54, +0xe1, 0x72, 0xe2, 0x94, 0x3f, 0x34, 0xda, 0x55, +0xc5, 0x23, 0x84, 0xd4, 0x77, 0x01, 0x81, 0xca, +0xfa, 0xd4, 0xde, 0x94, 0x67, 0x47, 0xbf, 0x21, +0x86, 0xc7, 0xb4, 0x4f, 0xec, 0x1a, 0x61, 0x61, +0x23, 0xe6, 0xa4, 0x7e, 0x8f, 0xe1, 0x5a, 0xfb, +0xd9, 0xa9, 0x34, 0x5b, 0x56, 0xb4, 0x6d, 0x6e, +0x79, 0x3b, 0xd1, 0xd6, 0xda, 0x8c, 0xf7, 0xad}; diff --git a/omaha/net/cup_ecdsa_pubkey.9.h b/omaha/net/cup_ecdsa_pubkey.9.h new file mode 100644 index 0000000..309c504 --- /dev/null +++ b/omaha/net/cup_ecdsa_pubkey.9.h @@ -0,0 +1,31 @@ +// Copyright 2019 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ======================================================================== +// +// CUP-ECDSA public keys consist of a byte array, 66 bytes long, containing: +// * The key ID (one byte) +// * The public key in X9.62 uncompressed encoding (65 bytes): +// * Uncompressed header byte (0x04) +// * Gx coordinate (256-bit integer, big-endian) +// * Gy coordinate (256-bit integer, big-endian) +{0x09, +0x04, +0xb1, 0x5c, 0x15, 0x32, 0x62, 0x09, 0x69, 0x60, +0x63, 0x92, 0xd4, 0xb1, 0xf6, 0x6d, 0x49, 0xad, +0x95, 0x98, 0x06, 0xf3, 0x26, 0x6e, 0xca, 0xc6, +0x19, 0x03, 0xe1, 0x49, 0xc0, 0xed, 0x6a, 0x8f, +0x83, 0x96, 0x80, 0xfc, 0xef, 0x56, 0x26, 0x11, +0xeb, 0xa7, 0x01, 0xa4, 0x2f, 0x44, 0xc6, 0x60, +0x0e, 0x1d, 0x67, 0x09, 0xa5, 0xa4, 0x54, 0x6e, +0xb0, 0xa3, 0xbe, 0x7e, 0xc8, 0x36, 0xca, 0x0c}; diff --git a/omaha/net/cup_ecdsa_request.cc b/omaha/net/cup_ecdsa_request.cc index 6b59a93..d144ae6 100644 --- a/omaha/net/cup_ecdsa_request.cc +++ b/omaha/net/cup_ecdsa_request.cc @@ -42,7 +42,7 @@ namespace omaha { namespace internal { const uint8 CupEcdsaRequestImpl::kCupProductionPublicKey[] = -#include "omaha/net/cup_ecdsa_pubkey.7.h" +#include "omaha/net/cup_ecdsa_pubkey.1.h" ; // NOLINT const uint8 CupEcdsaRequestImpl::kCupTestPublicKey[] = diff --git a/omaha/net/cup_ecdsa_request.h b/omaha/net/cup_ecdsa_request.h index f8fc66a..55dc7bb 100644 --- a/omaha/net/cup_ecdsa_request.h +++ b/omaha/net/cup_ecdsa_request.h @@ -22,8 +22,8 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/net/http_request.h" namespace omaha { @@ -93,7 +93,7 @@ class CupEcdsaRequest : public HttpRequestInterface { private: friend class CupEcdsaRequestTest; - scoped_ptr impl_; + std::unique_ptr impl_; DISALLOW_COPY_AND_ASSIGN(CupEcdsaRequest); }; diff --git a/omaha/net/cup_ecdsa_request_impl.h b/omaha/net/cup_ecdsa_request_impl.h index e7eb61b..fc5838b 100644 --- a/omaha/net/cup_ecdsa_request_impl.h +++ b/omaha/net/cup_ecdsa_request_impl.h @@ -17,9 +17,10 @@ #define OMAHA_NET_CUP_ECDSA_REQUEST_IMPL_H__ #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/net/cup_ecdsa_utils.h" namespace omaha { @@ -88,7 +89,7 @@ class CupEcdsaRequestImpl { EcdsaSignature signature; // The decoded ECDSA signature. std::vector observed_hash; // The observed hash of the request body. }; - scoped_ptr cup_; + std::unique_ptr cup_; CString url_; // The original url. const void* request_buffer_; // Contains the request body for POST. @@ -98,7 +99,7 @@ class CupEcdsaRequestImpl { typedef const uint8* PublicKey; EcdsaPublicKey public_key_; // Server public key. - scoped_ptr http_request_; // Inner http request. + std::unique_ptr http_request_; // Inner http request. static const PublicKeyInstance kCupProductionPublicKey; static const PublicKeyInstance kCupTestPublicKey; diff --git a/omaha/net/cup_ecdsa_request_unittest.cc b/omaha/net/cup_ecdsa_request_unittest.cc index 8c7f5ca..1829e6e 100644 --- a/omaha/net/cup_ecdsa_request_unittest.cc +++ b/omaha/net/cup_ecdsa_request_unittest.cc @@ -16,8 +16,9 @@ // This unit test is hardcoded to run against production servers only. #include +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/constants.h" #include "omaha/base/string.h" #include "omaha/base/reg_key.h" @@ -70,8 +71,7 @@ class CupEcdsaRequestTest : public testing::Test { const uint8* request_buffer, size_t request_buffer_length) { // Create a CUP-ECDSA request wrapping the contained request. - scoped_ptr http_request( - new CupEcdsaRequest(contained_request)); + auto http_request = std::make_unique(contained_request); // Set up a a direct (non-proxied) connection. NetworkConfig* network_config = NULL; diff --git a/omaha/net/cup_ecdsa_utils_unittest.cc b/omaha/net/cup_ecdsa_utils_unittest.cc index 5337ecf..25c2e5a 100644 --- a/omaha/net/cup_ecdsa_utils_unittest.cc +++ b/omaha/net/cup_ecdsa_utils_unittest.cc @@ -14,7 +14,7 @@ // ======================================================================== #include -#include "base/scoped_ptr.h" + #include "omaha/base/string.h" #include "omaha/base/security/p256.h" #include "omaha/net/cup_ecdsa_utils.h" @@ -491,7 +491,7 @@ TEST(EcdsaPublicKey, DecodeFromBuffer_ProdKey) { EcdsaPublicKey key; uint8 kProdKey[] = -#include "omaha/net/cup_ecdsa_pubkey.7.h" +#include "omaha/net/cup_ecdsa_pubkey.9.h" ; // NOLINT key.DecodeFromBuffer(kProdKey); diff --git a/omaha/net/detector.cc b/omaha/net/detector.cc index 237863a..c4ed535 100644 --- a/omaha/net/detector.cc +++ b/omaha/net/detector.cc @@ -19,7 +19,7 @@ #include "omaha/net/detector.h" -#include "base/scoped_ptr.h" +#include #include "omaha/base/atl_regexp.h" #include "omaha/base/browser_utils.h" #include "omaha/base/constants.h" @@ -49,7 +49,7 @@ HRESULT IEProxyDetector::Detect(ProxyConfig* config) { return E_FAIL; } - scoped_ptr http_client(CreateHttpClient()); + std::unique_ptr http_client(CreateHttpClient()); // We expect to be able to instantiate either of the http clients. ASSERT1(http_client.get()); @@ -423,7 +423,7 @@ void FirefoxProxyDetector::ParsePrefsLine(const char* ansi_line, HRESULT DefaultProxyDetector::Detect(ProxyConfig* config) { ASSERT1(config); - scoped_ptr http_client(CreateHttpClient()); + std::unique_ptr http_client(CreateHttpClient()); // We expect to be able to instantiate either of the http clients. ASSERT1(http_client.get()); diff --git a/omaha/net/detector.h b/omaha/net/detector.h index 588af34..1d56c43 100644 --- a/omaha/net/detector.h +++ b/omaha/net/detector.h @@ -16,10 +16,11 @@ #ifndef OMAHA_NET_DETECTOR_H__ #define OMAHA_NET_DETECTOR_H__ -#include #include +#include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" namespace omaha { @@ -39,31 +40,31 @@ class RegistryOverrideProxyDetector : public ProxyDetectorInterface { explicit RegistryOverrideProxyDetector(const CString& reg_path) : reg_path_(reg_path) {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("RegistryOverride"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("RegistryOverride"); } private: CString reg_path_; - DISALLOW_EVIL_CONSTRUCTORS(RegistryOverrideProxyDetector); + DISALLOW_COPY_AND_ASSIGN(RegistryOverrideProxyDetector); }; class UpdateDevProxyDetector : public ProxyDetectorInterface { public: UpdateDevProxyDetector(); - virtual HRESULT Detect(ProxyConfig* config) { + HRESULT Detect(ProxyConfig* config) override { return registry_detector_.Detect(config); } - virtual const TCHAR* source() { return _T("UpdateDev"); } + const TCHAR* source() override { return _T("UpdateDev"); } private: RegistryOverrideProxyDetector registry_detector_; - DISALLOW_EVIL_CONSTRUCTORS(UpdateDevProxyDetector); + DISALLOW_COPY_AND_ASSIGN(UpdateDevProxyDetector); }; // A version that picks up proxy override from a group policy. class GroupPolicyProxyDetector : public ProxyDetectorInterface { public: GroupPolicyProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("GroupPolicy"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("GroupPolicy"); } private: DISALLOW_COPY_AND_ASSIGN(GroupPolicyProxyDetector); }; @@ -75,10 +76,10 @@ class GroupPolicyProxyDetector : public ProxyDetectorInterface { class DefaultProxyDetector : public ProxyDetectorInterface { public: DefaultProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("winhttp"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("winhttp"); } private: - DISALLOW_EVIL_CONSTRUCTORS(DefaultProxyDetector); + DISALLOW_COPY_AND_ASSIGN(DefaultProxyDetector); }; // Detects proxy information for Firefox. @@ -95,8 +96,8 @@ class FirefoxProxyDetector : public ProxyDetectorInterface { FirefoxProxyDetector(); - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("Firefox"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("Firefox"); } private: // Parses the prefs.js file. HRESULT ParsePrefsFile(const TCHAR* name, @@ -123,10 +124,10 @@ class FirefoxProxyDetector : public ProxyDetectorInterface { CString cached_prefs_name_; CString cached_prefs_file_path_; int64 cached_prefs_last_modified_; - scoped_ptr cached_config_; + std::unique_ptr cached_config_; friend class FirefoxProxyDetectorTest; - DISALLOW_EVIL_CONSTRUCTORS(FirefoxProxyDetector); + DISALLOW_COPY_AND_ASSIGN(FirefoxProxyDetector); }; namespace internal { @@ -137,10 +138,10 @@ namespace internal { class IEProxyDetector : public ProxyDetectorInterface { public: IEProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("IE"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("IE"); } private: - DISALLOW_EVIL_CONSTRUCTORS(IEProxyDetector); + DISALLOW_COPY_AND_ASSIGN(IEProxyDetector); }; } // namespace internal @@ -150,8 +151,8 @@ class IEProxyDetector : public ProxyDetectorInterface { class IEWPADProxyDetector : public internal::IEProxyDetector { public: IEWPADProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("IEWPAD"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("IEWPAD"); } private: DISALLOW_COPY_AND_ASSIGN(IEWPADProxyDetector); @@ -162,8 +163,8 @@ class IEWPADProxyDetector : public internal::IEProxyDetector { class IEPACProxyDetector : public internal::IEProxyDetector { public: IEPACProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("IEPAC"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("IEPAC"); } private: DISALLOW_COPY_AND_ASSIGN(IEPACProxyDetector); @@ -174,8 +175,8 @@ class IEPACProxyDetector : public internal::IEProxyDetector { class IENamedProxyDetector : public internal::IEProxyDetector { public: IENamedProxyDetector() {} - virtual HRESULT Detect(ProxyConfig* config); - virtual const TCHAR* source() { return _T("IENamed"); } + HRESULT Detect(ProxyConfig* config) override; + const TCHAR* source() override { return _T("IENamed"); } private: DISALLOW_COPY_AND_ASSIGN(IENamedProxyDetector); diff --git a/omaha/net/detector_unittest.cc b/omaha/net/detector_unittest.cc index a9a524c..e891018 100644 --- a/omaha/net/detector_unittest.cc +++ b/omaha/net/detector_unittest.cc @@ -13,15 +13,17 @@ // limitations under the License. // ======================================================================== +#include "omaha/net/detector.h" + #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/browser_utils.h" #include "omaha/base/reg_key.h" #include "omaha/common/const_group_policy.h" -#include "omaha/net/detector.h" #include "omaha/net/network_config.h" #include "omaha/testing/unit_test.h" @@ -31,11 +33,11 @@ class FirefoxProxyDetectorTest : public testing::Test { public: FirefoxProxyDetectorTest() {} - virtual void SetUp() { + void SetUp() override { detector_.reset(new FirefoxProxyDetector); } - virtual void TearDown() { + void TearDown() override { } HRESULT BuildProxyString(const CString& http_host, @@ -82,10 +84,10 @@ class FirefoxProxyDetectorTest : public testing::Test { const CString& ssl_port, CString* file_path); - scoped_ptr detector_; + std::unique_ptr detector_; private: - DISALLOW_EVIL_CONSTRUCTORS(FirefoxProxyDetectorTest); + DISALLOW_COPY_AND_ASSIGN(FirefoxProxyDetectorTest); }; bool FirefoxProxyDetectorTest::BuildPrefsFile(const CString& type, @@ -354,10 +356,10 @@ class GroupPolicyProxyDetectorTest : public testing::TestWithParam { } CString hive_override_key_name_; - scoped_ptr detector_; + std::unique_ptr detector_; private: - DISALLOW_EVIL_CONSTRUCTORS(GroupPolicyProxyDetectorTest); + DISALLOW_COPY_AND_ASSIGN(GroupPolicyProxyDetectorTest); }; const TCHAR kGpoSourceString[] = _T("GroupPolicy"); diff --git a/omaha/net/http_client.h b/omaha/net/http_client.h index 1f1a993..d6a1040 100644 --- a/omaha/net/http_client.h +++ b/omaha/net/http_client.h @@ -351,7 +351,7 @@ class HttpClient { } static Factory* factory_; - DISALLOW_EVIL_CONSTRUCTORS(HttpClient); + DISALLOW_COPY_AND_ASSIGN(HttpClient); }; // Creates an http client, depending on what is available on the platform. diff --git a/omaha/net/http_client_unittest.cc b/omaha/net/http_client_unittest.cc index 7ac6d63..0422cdd 100644 --- a/omaha/net/http_client_unittest.cc +++ b/omaha/net/http_client_unittest.cc @@ -13,11 +13,13 @@ // limitations under the License. // ======================================================================== +#include "omaha/net/http_client.h" + +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/omaha_version.h" -#include "omaha/net/http_client.h" #include "omaha/testing/unit_test.h" namespace omaha { @@ -29,20 +31,20 @@ class HttpClientTest : public testing::Test { static void SetUpTestCase() {} - virtual void SetUp() { + void SetUp() override { http_client_.reset( HttpClient::GetFactory().CreateObject(HttpClient::WINHTTP)); ASSERT_TRUE(http_client_.get()); ASSERT_SUCCEEDED(http_client_->Initialize()); } - virtual void TearDown() { + void TearDown() override { http_client_.reset(); } void GetUrl(const TCHAR* url, bool use_proxy); - scoped_ptr http_client_; + std::unique_ptr http_client_; }; CString BuildUserAgent() { @@ -227,6 +229,45 @@ TEST_F(HttpClientTest, CrackUrl) { ASSERT_STREQ(path, _T("/path")); ASSERT_STREQ(query, _T("?query")); + CString url = _T("http://host/path/oper?P1=11&P2=22%2b33%3d%3d"); + ASSERT_SUCCEEDED(http_client_->CrackUrl(url, + ICU_DECODE, + &scheme, + &server, + &port, + &path, + &query)); + ASSERT_STREQ(scheme, _T("http")); + ASSERT_STREQ(server, _T("host")); + ASSERT_EQ(port, INTERNET_DEFAULT_HTTP_PORT); + ASSERT_STREQ(path, _T("/path/oper")); + ASSERT_STREQ(query, _T("?P1=11&P2=22+33==")); + + ASSERT_SUCCEEDED(http_client_->CrackUrl(url, + 0, + &scheme, + &server, + &port, + &path, + &query)); + ASSERT_STREQ(scheme, _T("http")); + ASSERT_STREQ(server, _T("host")); + ASSERT_EQ(port, INTERNET_DEFAULT_HTTP_PORT); + ASSERT_STREQ(path, _T("/path/oper")); + ASSERT_STREQ(query, _T("?P1=11&P2=22%2b33%3d%3d")); + + ASSERT_SUCCEEDED(http_client_->CrackUrl(url, + 0, + &scheme, + &server, + &port, + &path, + NULL)); + ASSERT_STREQ(scheme, _T("http")); + ASSERT_STREQ(server, _T("host")); + ASSERT_EQ(port, INTERNET_DEFAULT_HTTP_PORT); + ASSERT_STREQ(path, _T("/path/oper?P1=11&P2=22%2b33%3d%3d")); + ASSERT_SUCCEEDED(http_client_->CrackUrl(_T("http://host"), 0, NULL, @@ -239,7 +280,7 @@ TEST_F(HttpClientTest, CrackUrl) { } TEST_F(HttpClientTest, QuerySetOption) { - scoped_ptr http_client(CreateHttpClient()); + std::unique_ptr http_client(CreateHttpClient()); EXPECT_HRESULT_SUCCEEDED(http_client->Initialize()); HINTERNET session_handle = NULL; diff --git a/omaha/net/net_diags.cc b/omaha/net/net_diags.cc deleted file mode 100644 index a17243f..0000000 --- a/omaha/net/net_diags.cc +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2007-2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== -// -// Some simple network diags. - -#include "omaha/net/net_diags.h" -#include -#include -#include -#include "omaha/base/browser_utils.h" -#include "omaha/base/debug.h" -#include "omaha/base/system_info.h" -#include "omaha/base/time.h" -#include "omaha/base/utils.h" -#include "omaha/net/network_config.h" -#include "omaha/net/network_request.h" - -namespace omaha { - -NetDiags::NetDiags() { - Initialize(); -} - -NetDiags::~NetDiags() { - ::CoUninitialize(); -} - -bool PrintToConsole(const TCHAR* format, ...) { - ASSERT1(format); - va_list arg_list; - va_start(arg_list, format); - CString msg; - msg.FormatV(format, arg_list); - ASSERT1(msg.GetLength() > 0); - va_end(arg_list); - - DWORD count = 0; - bool result = !!::WriteConsole(::GetStdHandle(STD_OUTPUT_HANDLE), - msg, - msg.GetLength(), - &count, - NULL); - ASSERT1(result); - ASSERT1(msg.GetLength() == static_cast(count)); - return result; -} - -void NetDiags::Initialize() { - if (!SystemInfo::IsRunningOnXPOrLater()) { - ::MessageBox(NULL, - _T("GoogleUpdate.exe"), - _T("\"GoogleUpdate.exe /NetDiags\" only runs on Windows XP or later."), - MB_OK); - ::ExitProcess(1); - } - - if (!AttachConsoleWrap(ATTACH_PARENT_PROCESS)) { - ::MessageBox(NULL, - _T("GoogleUpdate.exe"), - _T("Please run \"GoogleUpdate.exe /NetDiags\" from a cmd.exe window."), - MB_OK); - ::ExitProcess(1); - } - - PrintToConsole(_T("\n")); - HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); - if (FAILED(hr)) { - PrintToConsole(_T("Failed to ::CoInitialize() [0x%x]\n"), hr); - ::ExitProcess(1); - } - - NetworkConfig* network_config = NULL; - hr = NetworkConfigManager::Instance().GetUserNetworkConfig(&network_config); - if (FAILED(hr)) { - PrintToConsole(_T("Failed to GetUserNetworkConfig() [0x%x]\n"), hr); - ::ExitProcess(1); - } - - // Initialize the detection chain: GoogleProxy, FireFox if it is the - // default browser, and IE. - network_config->Clear(); - BrowserType browser_type(BROWSER_UNKNOWN); - GetDefaultBrowserType(&browser_type); - if (browser_type == BROWSER_FIREFOX) { - PrintToConsole(_T("Default browser is Firefox\n")); - network_config->Add(new FirefoxProxyDetector()); - } - network_config->Add(new IEWPADProxyDetector); - network_config->Add(new IEPACProxyDetector); - network_config->Add(new IENamedProxyDetector); - - std::vector configs = network_config->GetConfigurations(); - if (configs.empty()) { - PrintToConsole(_T("No Network Configurations to display\n")); - } else { - PrintToConsole(_T("[Detected Network Configurations][\n%s]\n"), - NetworkConfig::ToString(configs)); - } -} - -void NetDiags::OnProgress(int bytes, int bytes_total, int, const TCHAR*) { - PrintToConsole(_T("\n[Downloading %d of %d]\n"), bytes, bytes_total); -} - -void NetDiags::OnRequestBegin() { - PrintToConsole(_T("\n[Download begins]\n")); -} - -void NetDiags::OnRequestRetryScheduled(time64 next_retry_time) { - time64 now = GetCurrent100NSTime(); - ASSERT1(next_retry_time > now); - - if (next_retry_time > now) { - PrintToConsole(_T("\n[Download will retry in %d seconds]\n"), - CeilingDivide(next_retry_time - now, kSecsTo100ns)); - } -} - -// http get. -void NetDiags::DoGet(const CString& url) { - PrintToConsole(_T("\nGET request for [%s]\n"), url); - NetworkConfig* network_config = NULL; - NetworkConfigManager& network_manager = NetworkConfigManager::Instance(); - HRESULT hr = network_manager.GetUserNetworkConfig(&network_config); - if (FAILED(hr)) { - PrintToConsole(_T("Failed to GetUserNetworkConfig() [0x%x]\n"), hr); - return; - } - NetworkRequest network_request(network_config->session()); - - network_request.set_callback(this); - network_request.set_num_retries(2); - std::vector response; - hr = network_request.Get(url, &response); - int status = network_request.http_status_code(); - if (FAILED(hr)) { - PrintToConsole(_T("GET request failed. HRESULT=[0x%x], HTTP Status=[%d]\n"), - hr, status); - return; - } - - PrintToConsole(_T("HTTP Status=[%d]\n"), status); - PrintToConsole(_T("HTTP Response=\n[%s]\n"), Utf8BufferToWideChar(response)); -} - -// http download. -void NetDiags::DoDownload(const CString& url) { - PrintToConsole(_T("\nDownload request for [%s]\n"), url); - NetworkConfig* network_config = NULL; - NetworkConfigManager& network_manager = NetworkConfigManager::Instance(); - HRESULT hr = network_manager.GetUserNetworkConfig(&network_config); - if (FAILED(hr)) { - PrintToConsole(_T("Failed to GetUserNetworkConfig() [0x%x]\n"), hr); - return; - } - NetworkRequest network_request(network_config->session()); - - network_request.set_callback(this); - network_request.set_num_retries(2); - - CString temp_file = GetTempFilename(_T("tmp")); - if (temp_file.IsEmpty()) { - PrintToConsole(_T("::GetTempFilename Failed [%d]\n"), ::GetLastError()); - return; - } - - hr = network_request.DownloadFile(url, temp_file); - int status = network_request.http_status_code(); - if (FAILED(hr)) { - PrintToConsole(_T("Download failed. HRESULT=[0x%x], HTTP Status=[%d]\n"), - hr, status); - return; - } - - PrintToConsole(_T("HTTP Status=[%d]\n"), status); - PrintToConsole(_T("Downloaded File=[%s]\n"), temp_file); - if (!::DeleteFile(temp_file)) { - PrintToConsole(_T("::DeleteFile Failed [%s][%d]\n"), - temp_file, ::GetLastError()); - return; - } else { - PrintToConsole(_T("Deleted file [%s]\n"), temp_file); - } -} - -// Run the tests. -int NetDiags::Main() { - DoGet(_T("http://www.google.com/robots.txt")); - DoGet(_T("https://www.google.com/robots.txt")); - DoDownload(_T("http://www.google.com/intl/en_ALL/images/logo.gif")); - return 0; -} - -} // namespace omaha - diff --git a/omaha/net/net_diags.h b/omaha/net/net_diags.h deleted file mode 100644 index c145af8..0000000 --- a/omaha/net/net_diags.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2007-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - - -#ifndef OMAHA_NET_NET_DIAGS_H__ -#define OMAHA_NET_NET_DIAGS_H__ - -#include -#include -#include "base/basictypes.h" -#include "base/time.h" -#include "omaha/net/network_request.h" - -namespace omaha { - -class NetDiags : public NetworkRequestCallback { - public: - NetDiags(); - ~NetDiags(); - - // Run the tests. - int Main(); - - private: - void Initialize(); - virtual void OnProgress(int bytes, int bytes_total, int, const TCHAR*); - virtual void OnRequestBegin(); - virtual void OnRequestRetryScheduled(time64 next_retry_time); - - // http get. - void DoGet(const CString& url); - void DoDownload(const CString& url); -}; - -} // namespace omaha - -#endif // OMAHA_NET_NET_DIAGS_H__ - diff --git a/omaha/net/net_utils.cc b/omaha/net/net_utils.cc index 1823860..cba6e4b 100644 --- a/omaha/net/net_utils.cc +++ b/omaha/net/net_utils.cc @@ -17,11 +17,10 @@ #include #include +#include -#include "base/scoped_ptr.h" #include "omaha/base/const_addresses.h" #include "omaha/base/logging.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/utils.h" namespace omaha { @@ -35,7 +34,7 @@ bool IsMachineConnectedToNetwork() { return true; } - scoped_array buffer(new char[table_size]); + std::unique_ptr buffer(new char[table_size]); MIB_IFTABLE* mib_table = reinterpret_cast(buffer.get()); result = ::GetIfTable(mib_table, &table_size, false); if (result != NO_ERROR) { diff --git a/omaha/net/network_config.cc b/omaha/net/network_config.cc index 78f957b..998ac2f 100644 --- a/omaha/net/network_config.cc +++ b/omaha/net/network_config.cc @@ -18,15 +18,12 @@ #include #include #include -#if _MSC_VER >= 1900 -#include -#else -#include -#endif #include +#include +#include #include + #include "base/error.h" -#include "base/scoped_ptr.h" #include "base/scope_guard.h" #include "omaha/base/browser_utils.h" #include "omaha/base/const_object_names.h" @@ -39,7 +36,6 @@ #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/user_info.h" @@ -453,15 +449,6 @@ CString NetworkConfig::GetMID() { return mid; } -CString NetworkConfig::JoinStrings(const TCHAR* s1, - const TCHAR* s2, - const TCHAR* delim) { - CString result; - const TCHAR* components[] = {s1, s2}; - JoinStringsInArray(components, arraysize(components), delim, &result); - return result; -} - // Using std::hash_set adds about 2K uncompressed code size. Using a CAtlMap // adds about 1.5K. Usually, there are only five detected configurations so // an O(n^2) algorithm would work well. The advantage of the current diff --git a/omaha/net/network_config.h b/omaha/net/network_config.h index 2261c41..aa7f005 100644 --- a/omaha/net/network_config.h +++ b/omaha/net/network_config.h @@ -23,14 +23,14 @@ #include #include #include +#include #include -#include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" + #include "omaha/base/synchronized.h" #include "omaha/net/detector.h" #include "omaha/net/http_client.h" #include "omaha/net/proxy_auth.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace ATL { @@ -200,12 +200,6 @@ class NetworkConfig { static int GetAccessType(const ProxyConfig& config); - // Returns s1 + delim + s2. Consider making it an utility function if - // more usage patterns are found. - static CString JoinStrings(const TCHAR* s1, - const TCHAR* s2, - const TCHAR* delim); - // Uses jsproxy to use a PAC proxy configuration file stored on the local // drive, instead of one sourced from WPAD. static HRESULT GetProxyForUrlLocal(const CString& url, @@ -258,10 +252,10 @@ class NetworkConfig { bool is_initialized_; - scoped_ptr configuration_override_; + std::unique_ptr configuration_override_; Session session_; - scoped_ptr http_client_; + std::unique_ptr http_client_; // Manages the proxy auth credentials. Typically a http client tries to // use autologon via Negotiate/NTLM with a proxy server. If that fails, the @@ -272,7 +266,7 @@ class NetworkConfig { ProxyAuth proxy_auth_; friend class NetworkConfigManager; - DISALLOW_EVIL_CONSTRUCTORS(NetworkConfig); + DISALLOW_COPY_AND_ASSIGN(NetworkConfig); }; class NetworkConfigManager { @@ -307,7 +301,7 @@ class NetworkConfigManager { static LLock instance_lock_; static bool is_machine_; - DISALLOW_EVIL_CONSTRUCTORS(NetworkConfigManager); + DISALLOW_COPY_AND_ASSIGN(NetworkConfigManager); }; } // namespace omaha diff --git a/omaha/net/network_config_unittest.cc b/omaha/net/network_config_unittest.cc index 815e8b4..e68ddb4 100644 --- a/omaha/net/network_config_unittest.cc +++ b/omaha/net/network_config_unittest.cc @@ -68,15 +68,6 @@ TEST_F(NetworkConfigTest, GetAccessType) { WINHTTP_ACCESS_TYPE_NAMED_PROXY); } -TEST_F(NetworkConfigTest, JoinStrings) { - EXPECT_STREQ(NetworkConfig::JoinStrings(NULL, NULL, NULL), _T("")); - - CString result; - EXPECT_STREQ(NetworkConfig::JoinStrings(NULL, NULL, _T("-")), _T("-")); - EXPECT_STREQ(NetworkConfig::JoinStrings(_T("foo"), _T("bar"), _T("-")), - _T("foo-bar")); -} - TEST_F(NetworkConfigTest, GetUserAgentTest) { CString version(GetVersionString()); EXPECT_FALSE(version.IsEmpty()); diff --git a/omaha/net/network_request.h b/omaha/net/network_request.h index a826ef6..b32d380 100644 --- a/omaha/net/network_request.h +++ b/omaha/net/network_request.h @@ -19,9 +19,10 @@ #include #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/string.h" #include "omaha/base/time.h" #include "omaha/common/ping_event_download_metrics.h" @@ -186,8 +187,8 @@ class NetworkRequest { private: // Uses pimpl idiom to minimize dependencies on implementation details. - scoped_ptr impl_; - DISALLOW_EVIL_CONSTRUCTORS(NetworkRequest); + std::unique_ptr impl_; + DISALLOW_COPY_AND_ASSIGN(NetworkRequest); }; } // namespace omaha diff --git a/omaha/net/network_request_impl.cc b/omaha/net/network_request_impl.cc index ac2c9e1..b26de00 100644 --- a/omaha/net/network_request_impl.cc +++ b/omaha/net/network_request_impl.cc @@ -31,13 +31,13 @@ #include "omaha/base/logging.h" #include "omaha/base/omaha_version.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/time.h" #include "omaha/base/user_info.h" #include "omaha/net/http_client.h" #include "omaha/net/net_utils.h" #include "omaha/net/network_config.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -77,32 +77,33 @@ void LogFileBytes(const CString& filename, size_t num_bytes) { NULL); } bytes.resize(bytes_read); - replace_if(bytes.begin(), bytes.end(), std::not1(std::ptr_fun(isprint)), '.'); + replace_if(bytes.begin(), bytes.end(), + [](int ch) {return !isprint(ch); }, '.'); bytes.push_back('\0'); NET_LOG(L3, (_T("[file bytes: %hs]"), &bytes.front())); } NetworkRequestImpl::NetworkRequestImpl( const NetworkConfig::Session& network_session) - : cur_http_request_(NULL), - cur_proxy_config_(NULL), - retry_after_seconds_(-1), - cur_retry_count_(0), - cur_retry_delay_ms_(kDefaultTimeBetweenRetriesMs), - http_attempts_(0), - last_hr_(S_OK), - last_http_status_code_(0), - http_status_code_(0), + : request_buffer_(NULL), + request_buffer_length_(0), proxy_auth_config_(NULL, CString()), num_retries_(0), low_priority_(false), initial_retry_delay_ms_(kDefaultTimeBetweenRetriesMs), retry_delay_jitter_ms_(kDefaultRetryTimeJitterMs), - callback_(NULL), - request_buffer_(NULL), - request_buffer_length_(0), + http_status_code_(0), response_(NULL), network_session_(network_session), + callback_(NULL), + cur_http_request_(NULL), + cur_proxy_config_(NULL), + last_hr_(S_OK), + last_http_status_code_(0), + retry_after_seconds_(-1), + cur_retry_count_(0), + cur_retry_delay_ms_(kDefaultTimeBetweenRetriesMs), + http_attempts_(0), is_canceled_(false) { // NetworkConfig::Initialize must be called before using NetworkRequest. // If Winhttp cannot be loaded, this handle will be NULL. @@ -427,7 +428,7 @@ HRESULT NetworkRequestImpl::DoSendWithConfig( CString msg; SafeCStringFormat(&msg, _T("Trying config: %s"), NetworkConfig::ToString(*cur_proxy_config_)); - NET_LOG(L3, (_T("[%s]"), msg)); + OPT_LOG(L3, (_T("[%s]"), msg)); SafeCStringAppendFormat(&trace_, _T("%s.\r\n"), msg); HRESULT hr = S_OK; @@ -611,14 +612,6 @@ CString NetworkRequestImpl::BuildPerRequestHeaders() const { kHeaderXHTTPAttempts, http_attempts_); - SafeCStringAppendFormat(&headers, _T("%s: %s\r\n"), - kHeaderXInteractive, - low_priority_ ? _T("bg") : _T("fg")); - - SafeCStringAppendFormat(&headers, _T("%s: Omaha-%s\r\n"), - kHeaderXUpdater, - GetVersionString()); - NET_LOG(L4, (_T("[BuildPerRequestHeaders][%s]"), headers)); return headers; } diff --git a/omaha/net/network_request_impl.h b/omaha/net/network_request_impl.h index bffd312..112d68b 100644 --- a/omaha/net/network_request_impl.h +++ b/omaha/net/network_request_impl.h @@ -19,13 +19,13 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/net/network_config.h" #include "omaha/net/network_request.h" #include "omaha/net/http_request.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -162,7 +162,7 @@ class NetworkRequestImpl { // Specifies the proxy configuration override. When set, the proxy // configurations are not auto detected. - scoped_ptr proxy_configuration_; + std::unique_ptr proxy_configuration_; // Input data members. // The request and response buffers are owner by the caller. @@ -227,7 +227,7 @@ class NetworkRequestImpl { static const int kTimeBetweenRetriesMultiplier = 2; static const int kDefaultRetryTimeJitterMs = 3000; // +- 3 seconds. - DISALLOW_EVIL_CONSTRUCTORS(NetworkRequestImpl); + DISALLOW_COPY_AND_ASSIGN(NetworkRequestImpl); }; diff --git a/omaha/net/network_request_unittest.cc b/omaha/net/network_request_unittest.cc index f55d8ca..15fb05e 100644 --- a/omaha/net/network_request_unittest.cc +++ b/omaha/net/network_request_unittest.cc @@ -15,8 +15,9 @@ #include #include +#include #include -#include "base/scoped_ptr.h" + #include "base/basictypes.h" #include "omaha/base/browser_utils.h" #include "omaha/base/constants.h" @@ -24,8 +25,6 @@ #include "omaha/base/logging.h" #include "omaha/base/queue_timer.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/base/vista_utils.h" @@ -35,6 +34,7 @@ #include "omaha/net/network_request.h" #include "omaha/net/simple_request.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -279,7 +279,7 @@ class NetworkRequestTest network_request_->Get(url, &response)); } - scoped_ptr network_request_; + std::unique_ptr network_request_; static HANDLE token_; }; diff --git a/omaha/net/proxy_auth.h b/omaha/net/proxy_auth.h index de38e5f..1b3a068 100644 --- a/omaha/net/proxy_auth.h +++ b/omaha/net/proxy_auth.h @@ -98,16 +98,16 @@ class ProxyAuth { // counts how many times the user has cancelled the authentication prompt. uint32 prompt_cancelled_; + bool proxy_prompt_is_machine_; + // after this many authentication prompt cancellations, stop prompting. uint32 cancel_prompt_threshold_; - bool proxy_prompt_is_machine_; - bool ReadFromIE7(const CString& server); bool ReadFromPreIE7(const CString& server); bool PromptUser(const CString& server, const ProxyAuthConfig& config); - DISALLOW_EVIL_CONSTRUCTORS(ProxyAuth); + DISALLOW_COPY_AND_ASSIGN(ProxyAuth); }; } // namespace omaha diff --git a/omaha/net/simple_request.cc b/omaha/net/simple_request.cc index 2c100b1..07ec60e 100644 --- a/omaha/net/simple_request.cc +++ b/omaha/net/simple_request.cc @@ -38,7 +38,6 @@ #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scope_guard.h" #include "omaha/base/string.h" #include "omaha/common/ping_event_download_metrics.h" @@ -46,14 +45,15 @@ #include "omaha/net/network_request.h" #include "omaha/net/proxy_auth.h" #include "omaha/net/winhttp_adapter.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { SimpleRequest::TransientRequestState::TransientRequestState() : port(0), + is_https(false), http_status_code(0), proxy_authentication_scheme(0), - is_https(false), content_length(0), current_bytes(0), request_begin_ms(0), @@ -64,16 +64,16 @@ SimpleRequest::TransientRequestState::~TransientRequestState() { } SimpleRequest::SimpleRequest() - : request_buffer_(NULL), - request_buffer_length_(0), - proxy_auth_config_(NULL, CString()), - is_canceled_(false), + : is_canceled_(false), is_closed_(false), + pause_happened_(false), session_handle_(NULL), + request_buffer_(NULL), + request_buffer_length_(0), + proxy_auth_config_(NULL, CString()), low_priority_(false), callback_(NULL), - download_completed_(false), - pause_happened_(false) { + download_completed_(false) { SafeCStringFormat(&user_agent_, _T("%s;winhttp"), NetworkConfig::GetUserAgent()); @@ -232,8 +232,7 @@ HRESULT SimpleRequest::Send() { // current_bytes for resume purpose. These two states will be validated // against the previously (partially) downloaded file when reopens the // target file. - scoped_ptr request_state( - new TransientRequestState); + auto request_state = std::make_unique(); request_state->content_length = request_state_->content_length; request_state->current_bytes = request_state_->current_bytes; @@ -300,8 +299,9 @@ HRESULT SimpleRequest::DoSend() { } HRESULT SimpleRequest::Connect() { + // Crack the url without decoding already escaped characters. HRESULT hr = winhttp_adapter_->CrackUrl(url_, - ICU_DECODE, + 0, &request_state_->scheme, &request_state_->server, &request_state_->port, diff --git a/omaha/net/simple_request.h b/omaha/net/simple_request.h index 76241db..2e3e46b 100644 --- a/omaha/net/simple_request.h +++ b/omaha/net/simple_request.h @@ -24,14 +24,15 @@ #define OMAHA_NET_SIMPLE_REQUEST_H_ #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/net/http_request.h" #include "omaha/net/network_config.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -161,7 +162,7 @@ class SimpleRequest : public HttpRequestInterface { int current_bytes; uint64 request_begin_ms; uint64 request_end_ms; - scoped_ptr download_metrics; + std::unique_ptr download_metrics; }; LLock lock_; @@ -180,8 +181,8 @@ class SimpleRequest : public HttpRequestInterface { ProxyConfig proxy_config_; bool low_priority_; NetworkRequestCallback* callback_; - scoped_ptr winhttp_adapter_; - scoped_ptr request_state_; + std::unique_ptr winhttp_adapter_; + std::unique_ptr request_state_; scoped_event event_resume_; bool download_completed_; diff --git a/omaha/net/simple_request_unittest.cc b/omaha/net/simple_request_unittest.cc index c26e494..08cab51 100644 --- a/omaha/net/simple_request_unittest.cc +++ b/omaha/net/simple_request_unittest.cc @@ -278,7 +278,7 @@ void SimpleRequestTest::SimpleGetHostNotFound(const CString& url, // proxy auto detect. // // When a proxy is detected, the proxy server can return some html content - // indicating an error has occured. The status codes will be different, + // indicating an error has occurred. The status codes will be different, // depending on how each proxy is configured. This may be a flaky unit test. if (FAILED(hr)) { if (IsWpadFailureError(hr)) { diff --git a/omaha/net/winhttp.cc b/omaha/net/winhttp.cc index 8a8ceef..bb6de6e 100644 --- a/omaha/net/winhttp.cc +++ b/omaha/net/winhttp.cc @@ -16,9 +16,11 @@ // Internet-access utility functions via winhttp #include "omaha/net/winhttp.h" + +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" @@ -140,7 +142,7 @@ class WinHttp : public HttpClient { static WinHttpVTable winhttp_; static LLock lock_; - DISALLOW_EVIL_CONSTRUCTORS(WinHttp); + DISALLOW_COPY_AND_ASSIGN(WinHttp); }; WinHttpVTable WinHttp::winhttp_; @@ -503,11 +505,11 @@ HRESULT WinHttp::CreateUrl(const TCHAR* scheme, url_comp.dwExtraInfoLength = static_cast(_tcslen(extra_info)); } - DWORD url_length = 0; + DWORD url_length = INTERNET_MAX_URL_LENGTH; bool res = !!winhttp_.WinHttpCreateUrl( &url_comp, flags, - url->GetBuffer(INTERNET_MAX_URL_LENGTH), + url->GetBuffer(url_length), &url_length); if (!res) { return HRESULTFromLastError(); diff --git a/omaha/net/winhttp_adapter.cc b/omaha/net/winhttp_adapter.cc index 0bc6702..d5dcf5b 100644 --- a/omaha/net/winhttp_adapter.cc +++ b/omaha/net/winhttp_adapter.cc @@ -14,7 +14,7 @@ // ======================================================================== #include "omaha/net/winhttp_adapter.h" -#include + #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" diff --git a/omaha/net/winhttp_adapter.h b/omaha/net/winhttp_adapter.h index 47dfc70..2b5c39c 100644 --- a/omaha/net/winhttp_adapter.h +++ b/omaha/net/winhttp_adapter.h @@ -17,11 +17,12 @@ #define OMAHA_NET_WINHTTP_ADAPTER_H_ #include +#include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/net/winhttp.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -130,7 +131,7 @@ class WinHttpAdapter { void* info, DWORD info_len); - scoped_ptr http_client_; + std::unique_ptr http_client_; HINTERNET connection_handle_; HINTERNET request_handle_; diff --git a/omaha/net/winhttp_adapter_unittest.cc b/omaha/net/winhttp_adapter_unittest.cc index 81f206f..3c65801 100644 --- a/omaha/net/winhttp_adapter_unittest.cc +++ b/omaha/net/winhttp_adapter_unittest.cc @@ -13,9 +13,11 @@ // limitations under the License. // ======================================================================== -#include -#include "base/scoped_ptr.h" #include "omaha/net/winhttp_adapter.h" + +#include +#include + #include "omaha/testing/unit_test.h" namespace omaha { @@ -27,7 +29,7 @@ TEST(WinHttpAdapter, NullHandles) { // Opens a session, connects, closes the connection handle, and then // tries to open a request for the null connection. - scoped_ptr http_client(CreateHttpClient()); + std::unique_ptr http_client(CreateHttpClient()); EXPECT_HRESULT_SUCCEEDED(http_client->Initialize()); HINTERNET session_handle = NULL; @@ -65,7 +67,7 @@ TEST(WinHttpAdapter, OpenRequestClose) { EXPECT_HRESULT_SUCCEEDED(winhttp_adapter.Initialize()); // Opens a session, connects, opens the request, then closes the handles. - scoped_ptr http_client(CreateHttpClient()); + std::unique_ptr http_client(CreateHttpClient()); EXPECT_HRESULT_SUCCEEDED(http_client->Initialize()); HINTERNET session_handle = NULL; diff --git a/omaha/net/winhttp_vtable.h b/omaha/net/winhttp_vtable.h index 2249e8c..d90ff7a 100644 --- a/omaha/net/winhttp_vtable.h +++ b/omaha/net/winhttp_vtable.h @@ -140,7 +140,7 @@ class WinHttpVTable { HINSTANCE library_; - DISALLOW_EVIL_CONSTRUCTORS(WinHttpVTable); + DISALLOW_COPY_AND_ASSIGN(WinHttpVTable); }; #define PROTECT_WRAP(function, proto, call, result_type, result_error_value) \ diff --git a/omaha/omaha_version_utils.py b/omaha/omaha_version_utils.py index cf47de7..6b49f23 100644 --- a/omaha/omaha_version_utils.py +++ b/omaha/omaha_version_utils.py @@ -17,10 +17,9 @@ """Constants and utilities related to Omaha and tools versions""" -_ONECLICK_PLUGIN_NAME = 'npGoogleOneClick' -_UPDATE_PLUGIN_NAME = 'npGoogleUpdate' -_BHO_NAME = 'GoopdateBho' -_CRASH_HANDLER_NAME = 'GoogleCrashHandler' +_ONECLICK_PLUGIN_NAME = 'npBraveOneClick' +_UPDATE_PLUGIN_NAME = 'npBraveUpdate' +_CRASH_HANDLER_NAME = 'BraveCrashHandler' # List of languages that are fully supported in the current build. _OMAHA_LANGUAGES = [ @@ -97,6 +96,8 @@ VC110 = 1700 # VC2012/VC11 (not supported by the current build). VC120 = 1800 # VC2013/VC12 VC140 = 1900 # VC2015/VC14 +VC150 = 1910 # VC2017 version 15.0-15.9 / VC14.1-14.16 +VC160 = 1920 # VC2019 version 16.0 / VC14.2 def _IsSupportedOmaha2Version(omaha_version): """Returns true if omaha_version is an Omaha 2 version and is supported.""" @@ -109,12 +110,10 @@ def _IsSupportedOmaha2Version(omaha_version): # languages, so the omaha_version_info parameter is unused. def _GetMetainstallerPayloadFilenames(prefix, update_plugin_filename, - bho_filename, languages, omaha_version): """Returns list of metainstaller payload files for specified Omaha version.""" plugin_dll_name = '%s%s' % (prefix, update_plugin_filename) - bho_dll_name = '%s%s' % (prefix, bho_filename) # The list of files below needs to be kept in sync with the list in # SetupFiles::BuildFileLists(). @@ -124,37 +123,33 @@ def _GetMetainstallerPayloadFilenames(prefix, # files (googleupdate.exe, goopdateres_*.dll, etc.) are hardcoded all over # the place, and require a ton of point fixes to customize. payload_files = [ - 'GoogleUpdate.exe', + 'BraveUpdate.exe', '%s.exe' % _CRASH_HANDLER_NAME, '%sgoopdate.dll' % (prefix), plugin_dll_name, - bho_dll_name, - 'GoogleUpdateHelper.msi', - 'GoogleUpdateBroker.exe', - 'GoogleUpdateOnDemand.exe', - 'GoogleUpdateComRegisterShell64.exe', - 'GoogleUpdateWebPlugin.exe', + 'BraveUpdateHelper.msi', + 'BraveUpdateBroker.exe', + 'BraveUpdateOnDemand.exe', + 'BraveUpdateComRegisterShell64.exe', + 'BraveUpdateWebPlugin.exe', '%spsmachine.dll' % (prefix), '%spsmachine_64.dll' % (prefix), '%spsuser.dll' % (prefix), '%spsuser_64.dll' % (prefix), ] - if (omaha_version[0] >= 1 and - omaha_version[1] >= 3 and - omaha_version[2] >= 13): - # The BHO is not built yet. - payload_files.remove(bho_dll_name) - elif _IsSupportedOmaha2Version(omaha_version): + if _IsSupportedOmaha2Version(omaha_version): payload_files.remove(plugin_dll_name) - payload_files.remove('GoogleUpdateBroker.exe') - payload_files.remove('GoogleUpdateOnDemand.exe') - payload_files.remove('GoogleUpdateComRegisterShell64.exe') + payload_files.remove('BraveUpdateBroker.exe') + payload_files.remove('BraveUpdateOnDemand.exe') + payload_files.remove('BraveUpdateComRegisterShell64.exe') payload_files.remove('psmachine.dll') payload_files.remove('psmachine_64.dll') payload_files.remove('psuser.dll') payload_files.remove('psuser_64.dll') - else: + elif (omaha_version[0] <= 1 and + omaha_version[1] <= 3 and + omaha_version[2] < 13): raise Exception('Unsupported version: ' + ConvertVersionToString(omaha_version)) @@ -169,7 +164,7 @@ def _GetMetainstallerPayloadFilenames(prefix, omaha_version[1] >= 3 and (omaha_version[2] >= 32)): # added with 1.3.32.1 and later - payload_files.append('GoogleUpdateCore.exe') + payload_files.append('BraveUpdateCore.exe') for language in languages: payload_files += ['%sgoopdateres_%s.dll' % (prefix, language)] @@ -192,11 +187,6 @@ def GetUPDATE_PLUGIN_NAME(): # pylint: disable-msg=C6409 return _UPDATE_PLUGIN_NAME -def GetBHO_NAME(): # pylint: disable-msg=C6409 - """Returns the value of the BHO_NAME define for the C++ code.""" - return _BHO_NAME - - def GetCRASH_HANDLER_NAME(): # pylint: disable-msg=C6409 """Returns the value of the CRASH_HANDLER_NAME define for the C++ code.""" return _CRASH_HANDLER_NAME @@ -250,11 +240,8 @@ class OmahaVersionInfo(object): oneclick_plugin_filename: Name of the signed OneClick DLL. update_plugin_version: Version of the Omaha 3 plug-in. update_plugin_filename: Name of the signed Omaha 3 plug-in DLL. - bho_filename: Name of the signed BHO DLL. crash_handler_filename: Name of the Crash Handler EXE. oneclick_signed_file_info: SignedFileInfo object for the OneClick DLL. - bho_signed_file_info: SignedFileInfo object for the BHO DLL. - """ def __init__(self, version_file): @@ -272,13 +259,11 @@ def __init__(self, version_file): _UPDATE_PLUGIN_NAME, 'dll', self.update_plugin_version) - self.bho_signed_file_info = SignedFileInfo(_BHO_NAME, 'dll') # Simple properties for callers that only need the final filename. Not # affected by internal build changes. self.oneclick_plugin_filename = self.oneclick_signed_file_info.filename self.update_plugin_filename = self.plugin_signed_file_info.filename - self.bho_filename = self.bho_signed_file_info.filename self.crash_handler_filename = _CRASH_HANDLER_NAME def _ReadFile(self, version_file): @@ -319,11 +304,14 @@ def _ReadFile(self, version_file): # pylint: enable-msg=E0602 - def MakeTestVersion(self, delta=1): + def MakeTestVersion(self, delta, prefix): """Changes this object to be for a TEST version of Omaha.""" if delta <= 0: - raise Exception('Delta must be greater than 0.') + raise Exception('Invalid version delta.') + + if prefix and prefix != 'TEST_' and prefix != 'TEST2_': + raise Exception('Unrecognized prefix "%s"' % prefix) # If we're doing a patch, increment patch; else, increment build. if self.version_patch > 0: @@ -331,7 +319,7 @@ def MakeTestVersion(self, delta=1): else: self.version_build += delta - self.filename_prefix = 'TEST_' + self.filename_prefix = prefix def GetVersion(self): """Returns the version elements as a list.""" @@ -353,7 +341,6 @@ def GetMetainstallerPayloadFilenames(self): """Returns list of metainstaller payload files for this version of Omaha.""" return _GetMetainstallerPayloadFilenames(self.filename_prefix, self.update_plugin_filename, - self.bho_filename, self.GetSupportedLanguages(), self.GetVersion()) diff --git a/omaha/plugins/base/build.scons b/omaha/plugins/base/build.scons index 9f05e01..2c28bd4 100644 --- a/omaha/plugins/base/build.scons +++ b/omaha/plugins/base/build.scons @@ -17,7 +17,9 @@ Import('env') # Build plugin base. plugin_base_env = env.Clone() -plugin_base_env['CCFLAGS'] +plugin_base_env['CCFLAGS'] = [ + '/wd4100', +], plugin_base_env.ComponentLibrary( lib_name='plugin_base', source=[ diff --git a/omaha/plugins/plugin_version.rc b/omaha/plugins/plugin_version.rc index 4970160..9cd7026 100644 --- a/omaha/plugins/plugin_version.rc +++ b/omaha/plugins/plugin_version.rc @@ -15,7 +15,7 @@ // // This file contains the unlocalized plugin version resources. -#include +#include // The "040904e4" block (for codepage 1252 Ansi Latin) is required for // the Netscape Plugin stuff to see the MIMETYPE value in the resource block. @@ -57,7 +57,6 @@ BEGIN VALUE "FileDescription", OMAHA_APP_NAME_ANSI VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", OMAHA_APP_NAME_ANSI - VALUE "LegalCopyright", OMAHA_COPYRIGHT_STRING_ENGLISH VALUE "OriginalFilename", PLUGIN_FILENAME VALUE "ProductName", OMAHA_APP_NAME_ANSI VALUE "ProductVersion", VERSION_NUMBER_STRING diff --git a/omaha/plugins/update/activex/oneclick_control.cc b/omaha/plugins/update/activex/oneclick_control.cc index d8ccbbf..955cea1 100644 --- a/omaha/plugins/update/activex/oneclick_control.cc +++ b/omaha/plugins/update/activex/oneclick_control.cc @@ -24,8 +24,6 @@ #include "omaha/base/error.h" #include "omaha/base/file.h" -#include "omaha/base/scoped_any.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/vistautil.h" @@ -37,6 +35,7 @@ #include "omaha/common/webplugin_utils.h" #include "omaha/goopdate/app_command.h" #include "omaha/goopdate/app_manager.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "goopdate/omaha3_idl.h" namespace omaha { @@ -75,7 +74,7 @@ STDMETHODIMP OneClickControl::Install(BSTR cmd_line_args, } CORE_LOG(L2, (_T("[OneClickControl::Install][cmd_line \"%s\"]"), - CW2CT(cmd_line_args))); + static_cast(CW2CT(cmd_line_args)))); // We trim cmd_line_args to just the extra args and thunk to Install2(). CString extra_args(cmd_line_args); @@ -109,7 +108,7 @@ STDMETHODIMP OneClickControl::Install2(BSTR extra_args) { } CORE_LOG(L2, (_T("[OneClickControl::Install2][extra_args \"%s\"]"), - CW2CT(extra_args))); + static_cast(CW2CT(extra_args)))); CString browser_url; HRESULT hr = site_lock_.GetCurrentBrowserUrl(this, &browser_url); @@ -193,31 +192,8 @@ STDMETHODIMP OneClickControl::GetOneClickVersion(long* version) { // NOLINT return S_OK; } -STDMETHODIMP OneClickControl::LaunchAppCommand(BSTR app_guid, - VARIANT_BOOL is_machine, - BSTR cmd_id) { - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - CORE_LOG(L2, (_T("[OneClickControl::LaunchAppCommand]"))); - - CComPtr process_launcher; - HRESULT hr = update3_utils::CoCreateWithProxyBlanket( - is_machine ? - __uuidof(OneClickMachineProcessLauncherClass) : - __uuidof(OneClickUserProcessLauncherClass), - &process_launcher); - - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[OneClickControl::LaunchAppCommand]") - _T("[Failed to CoCreate OneClickMachine/User ") - _T("ProcessLauncher implementation: 0x%x"), - hr)); - return hr; - } - - return process_launcher->LaunchAppCommand(app_guid, cmd_id); +STDMETHODIMP OneClickControl::LaunchAppCommand(BSTR, VARIANT_BOOL, BSTR) { + return E_NOTIMPL; } HRESULT OneClickControl::DoGetInstalledVersion(const TCHAR* guid_string, diff --git a/omaha/plugins/update/activex/oneclick_control.h b/omaha/plugins/update/activex/oneclick_control.h index f36ffdd..df70645 100644 --- a/omaha/plugins/update/activex/oneclick_control.h +++ b/omaha/plugins/update/activex/oneclick_control.h @@ -29,7 +29,7 @@ #include #include #include -#include "base/scoped_ptr.h" + #include "omaha/base/ATLRegMapEx.h" #include "omaha/base/const_addresses.h" #include "omaha/base/constants.h" @@ -69,9 +69,6 @@ class ATL_NO_VTABLE OneClickControl DECLARE_REGISTRY_RESOURCEID_EX(IDR_ONECLICK_RGS) -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) BEGIN_REGISTRY_MAP() REGMAP_ENTRY(_T("CLSID"), GetObjectCLSID()) REGMAP_ENTRY(_T("PROGID"), kOneclickControlProgId) @@ -87,7 +84,6 @@ class ATL_NO_VTABLE OneClickControl REGMAP_ENTRY(_T("PLUGINPRODUCT"), kAppName) REGMAP_ENTRY(_T("PLUGINMIMETYPE"), ONECLICK_MIME_TYPE) END_REGISTRY_MAP() -#pragma warning(pop) BEGIN_COM_MAP(OneClickControl) COM_INTERFACE_ENTRY(IDispatch) diff --git a/omaha/plugins/update/activex/update3web_control.cc b/omaha/plugins/update/activex/update3web_control.cc index 20136ce..96abf4c 100644 --- a/omaha/plugins/update/activex/update3web_control.cc +++ b/omaha/plugins/update/activex/update3web_control.cc @@ -338,31 +338,8 @@ HRESULT Update3WebControl::crossInstall(BSTR extra_args) { return S_OK; } -HRESULT Update3WebControl::launchAppCommand(BSTR guid_string, - VARIANT_BOOL is_machine, - BSTR cmd_id) { - if (!site_lock_.InApprovedDomain(this)) { - return GOOPDATE_E_ONECLICK_HOSTCHECK_FAILED; - } - - CORE_LOG(L2, (_T("[Update3WebControl::launchAppCommand]"))); - - CComPtr process_launcher; - HRESULT hr = update3_utils::CoCreateWithProxyBlanket( - is_machine ? - __uuidof(OneClickMachineProcessLauncherClass) : - __uuidof(OneClickUserProcessLauncherClass), - &process_launcher); - - if (FAILED(hr)) { - CORE_LOG(LE, (_T("[Update3WebControl::launchAppCommand]") - _T("[Failed to CoCreate OneClickMachine/User ") - _T("ProcessLauncher implementation: 0x%x"), - hr)); - return hr; - } - - return process_launcher->LaunchAppCommand(guid_string, cmd_id); +HRESULT Update3WebControl::launchAppCommand(BSTR, VARIANT_BOOL, BSTR) { + return E_NOTIMPL; } Update3WebControl::~Update3WebControl() { diff --git a/omaha/plugins/update/activex/update_control_idl.idl b/omaha/plugins/update/activex/update_control_idl.idl index 8db79b0..7074ff9 100644 --- a/omaha/plugins/update/activex/update_control_idl.idl +++ b/omaha/plugins/update/activex/update_control_idl.idl @@ -17,7 +17,7 @@ import "oaidl.idl"; [ object, - uuid(c40a1df0-d2d8-4f01-9b1d-3c0d4f226dd9), + uuid(1655FEDC-1D2A-454C-8CDC-B7C253D3E7B1), dual, helpstring("GoogleUpdate3Web Control"), pointer_default(unique) @@ -42,7 +42,7 @@ interface IGoogleUpdate3WebControl : IDispatch { [ object, - uuid(b8b0a927-6c2a-4de2-b6d7-a98fe4e42465), + uuid(C142C417-EC32-4B1D-AE05-65FCD6F3D1FF), dual, helpstring("Google Update OneClick Control"), pointer_default(unique) @@ -74,7 +74,7 @@ interface IGoogleUpdateOneClick : IDispatch }; [ - uuid(8c1a5505-5837-47e1-963e-dbc5c3f0f52a), + uuid(418F8898-4D9F-4499-9EE6-9255C065F552), version(1.0), helpstring("Omaha Browser Plugins 3.0 Type Library") ] @@ -85,7 +85,7 @@ library GoogleUpdateControlLib { interface IGoogleUpdate3WebControl; [ - uuid(77e6be0b-059d-4ff6-a534-4aa0970a746c), + uuid(15D29936-2A57-4263-AF7E-A1A2BE525A95), helpstring("Google Update OneClick Control Class") ] coclass GoogleUpdateOneClickControlCoClass @@ -94,7 +94,7 @@ library GoogleUpdateControlLib { }; [ - uuid(2f7cf8e2-27d9-4641-845d-3bfedece0326), + uuid(2810C6B4-D693-4E86-A05B-A2F9B6CA37DE), helpstring("GoogleUpdate3Web Control Class") ] coclass GoogleUpdate3WebControlCoClass { diff --git a/omaha/plugins/update/build.scons b/omaha/plugins/update/build.scons index f9b5232..05acb16 100644 --- a/omaha/plugins/update/build.scons +++ b/omaha/plugins/update/build.scons @@ -35,10 +35,6 @@ update_env.Append( '_ATL_FREE_THREADED', ], CPPFLAGS = [ - # TODO(omaha): use PCH so we get /Wall. Need to figure out why half of - # the old plugin builds with PCH, and the other half of it builds - # without... - '/Wall', '/wd4263', # member function does not override any base class virtual # member function '/wd4264', # no override available for virtual member function; @@ -49,6 +45,7 @@ update_env.Append( '/wd4548', # expression before comma has no effect; expected expression # with side-effect '/wd4986', # exception spec does not match previous declaration + '/wd5038', # data member will be initialized after data member ], CPPPATH = [ '$OBJ_ROOT', # Needed for generated files. @@ -58,8 +55,10 @@ update_env.Append( '$LIB_DIR/breakpad.lib', '$LIB_DIR/client.lib', '$LIB_DIR/core.lib', + '$LIB_DIR/crx_file.lib', '$LIB_DIR/google_update_recovery.lib', '$LIB_DIR/goopdate_lib.lib', + '$LIB_DIR/libprotobuf.lib', '$LIB_DIR/logging.lib', '$LIB_DIR/net.lib', '$LIB_DIR/omaha3_idl.lib', @@ -93,7 +92,12 @@ update_env.Append( '/NXCOMPAT', # Enable NX support. ], ) - +if update_env.Bit('has_device_management'): + update_env.Append( + LIBS = [ + '$LIB_DIR/dm_proto.lib', + ], + ) # COM stuff. midl_env = env.Clone() @@ -118,12 +122,9 @@ npapi_testing_midl_env.Tool('midl') npapi_testing_midl_env['MIDLFLAGS'] += [ '/Oicf', ] midl_env.TypeLibrary('activex/update_control_idl.idl') - -# Generate the GUIDs with no precompile option set, otherwise we get an error. -update_control_idl_guids_lib = env.ComponentStaticLibrary( +update_control_idl_guids_lib = env.ComponentLibrary( lib_name='update_control_idl_guids_lib', source='$OBJ_ROOT/plugins/update/activex/update_control_idl_i.c', - use_pch_default=False, ) # Built as library to enable unit testing. @@ -138,24 +139,20 @@ inputs = [ 'config.cc', 'site_lock.cc', ] -update_lib = update_env.ComponentStaticLibrary( +update_lib = update_env.ComponentLibrary( lib_name='update', source=inputs, - use_pch_default=False, ) def BuildNpGoogleUpdateDll(omaha_version_info): - version_string = omaha_version_info.GetVersionString() - prefix = omaha_version_info.filename_prefix - plugin_env = update_env.Clone(COMPONENT_STATIC = False) - if prefix == 'TEST_': - plugin_env['OBJPREFIX'] = plugin_env.subst('test/$OBJPREFIX') - elif prefix: - raise Exception('ERROR: Unrecognized prefix "%s"' % prefix) + prefix = omaha_version_info.filename_prefix + if prefix: + plugin_env['OBJPREFIX'] = plugin_env.subst(prefix + 'obj/$OBJPREFIX') + version_string = omaha_version_info.GetVersionString() plugin_env.Append( LIBS = [ '$LIB_DIR/common.lib', @@ -195,7 +192,6 @@ def BuildNpGoogleUpdateDll(omaha_version_info): unsigned_dll = plugin_env.ComponentLibrary( lib_name=target_name, source=inputs, - use_pch_default=False, ) signed_dll = plugin_env.DualSignedBinary( @@ -218,7 +214,7 @@ for omaha_version_info in env['omaha_versions_info']: # NPAPI unit test helper library npapi_testing_midl_env.TypeLibrary('npapi/testing/dispatch_host_test_idl.idl') -update_env.ComponentStaticLibrary( +update_env.ComponentLibrary( lib_name = 'update_test_helpers', source = [ 'npapi/testing/dispatch_host_test_interface.cc', diff --git a/omaha/plugins/update/npapi/dispatch_host.cc b/omaha/plugins/update/npapi/dispatch_host.cc index e8c22ab..d188031 100644 --- a/omaha/plugins/update/npapi/dispatch_host.cc +++ b/omaha/plugins/update/npapi/dispatch_host.cc @@ -17,9 +17,9 @@ #include "omaha/plugins/update/npapi/dispatch_host.h" +#include #include "base/logging.h" #include "base/scope_guard.h" -#include "base/scoped_ptr.h" #include "omaha/base/safe_format.h" #include "omaha/base/string.h" #include "omaha/plugins/update/npapi/variant_utils.h" @@ -124,7 +124,7 @@ HRESULT DispatchHost::InvokeHelper(DISPID dispatch_id, WORD flags, // Just in case a rogue browser decides to use the return value on failure. VOID_TO_NPVARIANT(*result); - scoped_array dispatch_args(new CComVariant[arg_count]); + std::unique_ptr dispatch_args(new CComVariant[arg_count]); // IDispatch::Invoke expects arguments in "reverse" order for (uint32_t i = 0 ; i < arg_count; ++i) { diff --git a/omaha/plugins/update/npapi/npfunction_host.cc b/omaha/plugins/update/npapi/npfunction_host.cc index 19426cb..fd2c792 100644 --- a/omaha/plugins/update/npapi/npfunction_host.cc +++ b/omaha/plugins/update/npapi/npfunction_host.cc @@ -15,6 +15,7 @@ #include "omaha/plugins/update/npapi/npfunction_host.h" +#include #include "omaha/base/debug.h" #include "omaha/base/utils.h" #include "omaha/plugins/update/npapi/variant_utils.h" @@ -98,7 +99,7 @@ STDMETHODIMP NpFunctionHost::Invoke(DISPID dispIdMember, } uint32_t num_args = 0; - scoped_array arguments; + std::unique_ptr arguments; if (pDispParams) { // Javascript doesn't officially support named args, so the current // implementation ignores any named args that are supplied. However, diff --git a/omaha/plugins/update/npapi/npfunction_host_unittest.cc b/omaha/plugins/update/npapi/npfunction_host_unittest.cc index 63d949c..ca9d8c5 100644 --- a/omaha/plugins/update/npapi/npfunction_host_unittest.cc +++ b/omaha/plugins/update/npapi/npfunction_host_unittest.cc @@ -167,7 +167,7 @@ TEST_F(NpFunctionHostTest, GetTypeInfo_NotImplemented) { } TEST_F(NpFunctionHostTest, GetIDsOfNames_NotImplemented) { - LPOLESTR member_name = L"NonexistentMember"; + LPOLESTR member_name = const_cast(L"NonexistentMember"); DISPID member_dispid = 0; EXPECT_EQ(E_NOTIMPL, host_->GetIDsOfNames(IID_NULL, &member_name, 1, LOCALE_SYSTEM_DEFAULT, diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test.rc b/omaha/plugins/update/npapi/testing/dispatch_host_test.rc index fb0991e..0b44ad0 100644 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test.rc +++ b/omaha/plugins/update/npapi/testing/dispatch_host_test.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include #include "omaha/plugins/update/npapi/testing/resource.h" LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US diff --git a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h b/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h index 3bbef69..589b223 100644 --- a/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h +++ b/omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h @@ -65,7 +65,7 @@ class ATL_NO_VTABLE IDispatchImplResId : public IDispatchImpl { // Override the ITypeInfo in the CComTypeInfoHolder, which will be used in // subsequent calls to the IDispatch methods. - _tih.m_pInfo = type_info.Detach(); + this->_tih.m_pInfo = type_info.Detach(); } virtual ~IDispatchImplResId() {} diff --git a/omaha/plugins/update/npapi/variant_utils_unittest.cc b/omaha/plugins/update/npapi/variant_utils_unittest.cc index bd88f98..b26737a 100644 --- a/omaha/plugins/update/npapi/variant_utils_unittest.cc +++ b/omaha/plugins/update/npapi/variant_utils_unittest.cc @@ -15,8 +15,10 @@ #include "omaha/plugins/update/npapi/variant_utils.h" #include -#include +#include #include +#include +#include #include "omaha/plugins/update/npapi/testing/dispatch_host_test_interface.h" #include "omaha/plugins/update/npapi/testing/stubs.h" #include "omaha/testing/unit_test.h" @@ -108,17 +110,17 @@ TEST_F(VariantUtilsTest, NPVariantToVariant_Bool) { } TEST_F(VariantUtilsTest, NPVariantToVariant_Int32) { - INT32_TO_NPVARIANT(kint32min, np_variant_); + INT32_TO_NPVARIANT(std::numeric_limits::min(), np_variant_); TestNPV2V(); - EXPECT_EQ(kint32min, V_I4(&variant_)); + EXPECT_EQ(std::numeric_limits::min(), V_I4(&variant_)); INT32_TO_NPVARIANT(0, np_variant_); TestNPV2V(); EXPECT_EQ(0, V_I4(&variant_)); - INT32_TO_NPVARIANT(kint32max, np_variant_); + INT32_TO_NPVARIANT(std::numeric_limits::max(), np_variant_); TestNPV2V(); - EXPECT_EQ(kint32max, V_I4(&variant_)); + EXPECT_EQ(std::numeric_limits::max(), V_I4(&variant_)); } TEST_F(VariantUtilsTest, NPVariantToVariant_Double) { @@ -130,10 +132,11 @@ TEST_F(VariantUtilsTest, NPVariantToVariant_Double) { TestNPV2V(); EXPECT_DOUBLE_EQ(0, V_R8(&variant_)); - DOUBLE_TO_NPVARIANT(static_cast(kuint64max), + DOUBLE_TO_NPVARIANT(static_cast(std::numeric_limits::max()), np_variant_); TestNPV2V(); - EXPECT_DOUBLE_EQ(static_cast(kuint64max), V_R8(&variant_)); + EXPECT_DOUBLE_EQ(static_cast(std::numeric_limits::max()), + V_R8(&variant_)); } TEST_F(VariantUtilsTest, NPVariantToVariant_String) { @@ -198,17 +201,17 @@ TEST_F(VariantUtilsTest, VariantToNPVariant_VT_BOOL) { } TEST_F(VariantUtilsTest, VariantToNPVariant_VT_I4) { - variant_ = kint32max; + variant_ = std::numeric_limits::max(); TestV2NPV(); - EXPECT_EQ(kint32max, np_variant_.value.intValue); + EXPECT_EQ(std::numeric_limits::max(), np_variant_.value.intValue); variant_ = 0; TestV2NPV(); EXPECT_EQ(0, np_variant_.value.intValue); - variant_ = kint32min; + variant_ = std::numeric_limits::min(); TestV2NPV(); - EXPECT_EQ(kint32min, np_variant_.value.intValue); + EXPECT_EQ(std::numeric_limits::min(), np_variant_.value.intValue); } TEST_F(VariantUtilsTest, VariantToNPVariant_VT_UI4) { @@ -216,13 +219,13 @@ TEST_F(VariantUtilsTest, VariantToNPVariant_VT_UI4) { TestV2NPV(); EXPECT_EQ(0, np_variant_.value.intValue); - variant_ = static_cast(kint32max); + variant_ = static_cast(std::numeric_limits::max()); TestV2NPV(); - EXPECT_EQ(kint32max, np_variant_.value.intValue); + EXPECT_EQ(std::numeric_limits::max(), np_variant_.value.intValue); // MSIE can natively support VT_UI4. Unfortunately, Firefox cannot. // Check that kuint32max wraps around to -1. - variant_ = kuint32max; + variant_ = std::numeric_limits::max(); TestV2NPV(); EXPECT_EQ(-1, np_variant_.value.intValue); } @@ -236,9 +239,9 @@ TEST_F(VariantUtilsTest, VariantToNPVariant_VT_R8) { TestV2NPV(); EXPECT_DOUBLE_EQ(-1.0, np_variant_.value.doubleValue); - variant_ = static_cast(kuint64max); + variant_ = static_cast(std::numeric_limits::max()); TestV2NPV(); - EXPECT_DOUBLE_EQ(static_cast(kuint64max), + EXPECT_DOUBLE_EQ(static_cast(std::numeric_limits::max()), np_variant_.value.doubleValue); } diff --git a/omaha/plugins/update/site_lock.cc b/omaha/plugins/update/site_lock.cc index b55b3b2..2ec0187 100644 --- a/omaha/plugins/update/site_lock.cc +++ b/omaha/plugins/update/site_lock.cc @@ -18,8 +18,8 @@ #include #include #include +#include -#include "base/scoped_ptr.h" #include "omaha/base/atl_regexp.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" @@ -126,7 +126,7 @@ bool SiteLock::AddPattern(const WCHAR* pattern) { return false; } - scoped_ptr re(new AtlRegExp); + auto re = std::make_unique(); REParseError error = re->Parse(pattern); if (REPARSE_ERROR_OK != error) { ASSERT(false, (L"Failed to parse site lock pattern: %s", diff --git a/omaha/precompile/precompile.cc b/omaha/precompile/precompile.cc deleted file mode 100644 index a108af7..0000000 --- a/omaha/precompile/precompile.cc +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -// 4505: unreferenced local function has been removed -#pragma warning(disable : 4505) - diff --git a/omaha/precompile/precompile.h b/omaha/precompile/precompile.h deleted file mode 100644 index 195c3b6..0000000 --- a/omaha/precompile/precompile.h +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2004-2009 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// ======================================================================== - -#ifndef OMAHA_PRECOMPILE_PRECOMPILE_H__ -#define OMAHA_PRECOMPILE_PRECOMPILE_H__ - -// 'function': name was marked as #pragma deprecated -#pragma warning(disable : 4995) - -#pragma warning(push) -// C4201: nonstandard extension used : nameless struct/union -#pragma warning(disable : 4201) -#include - -// Redefining the macro RegisterEventSource to evaluate to NULL so that -// CAtlServiceModuleT::LogEvent() code does not log to the event log. Doing this -// avoids duplicating the CAtlServiceModuleT code. -#undef RegisterEventSource -#define RegisterEventSource(x, ...) NULL - -#include -#include -#include -#include - -#include "omaha/base/atlassert.h" // Redefines ATLASSERT. - -// C4265: class has virtual functions, but destructor is not virtual -// C4302: 'reinterpret_cast' : truncation from 'type_1' to 'type_2' -// C4350: behavior change: 'member1' called instead of 'member2' -// C4365: conversion from 'type_1' to 'type_2', signed/unsigned mismatch -// C4548: expression before comma has no effect -// C4702: unreachable code -// C4838: conversion requires a narrowing conversion -// C4986: exception specification does not match previous declaration -#pragma warning(disable : 4265 4302 4350 4365 4548 4702 4838 4986) -#include -#include // Needs to be in front of atlapp.h -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if (_MSC_VER < 1800) -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#pragma warning(pop) - -#if (_MSC_VER < 1400) -// TODO(omaha): fix the atlconv for VC8. -#include "omaha/base/atlconvfix.h" -#endif - -#pragma warning(push) -// C4310: cast truncates constant value -#pragma warning(disable : 4310) -#include "base/basictypes.h" -#pragma warning(pop) - -#include "gtest/gtest_prod.h" - -#endif // OMAHA_PRECOMPILE_PRECOMPILE_H__ diff --git a/omaha/recovery/build.scons b/omaha/recovery/build.scons index 42ab260..aa33be6 100644 --- a/omaha/recovery/build.scons +++ b/omaha/recovery/build.scons @@ -66,7 +66,9 @@ test_env.Append( '$LIB_DIR/base.lib', '$LIB_DIR/net.lib', '$LIB_DIR/common.lib', + '$LIB_DIR/crx_file.lib', '$LIB_DIR/google_update_recovery.lib', + '$LIB_DIR/libprotobuf.lib', '$LIB_DIR/security.lib', test_env['atls_libs'][test_env.Bit('debug')], test_env['crt_libs'][test_env.Bit('debug')], @@ -91,8 +93,6 @@ target_name = 'RecoveryTest' test_inputs = [ 'recovery_test.cc', ] -if env.Bit('use_precompiled_headers'): - test_inputs += test_env.EnablePrecompile(target_name) # TODO(omaha): This test asserts when run so we cannot include it in # run_all_tests. Fix it and consider adding to run_all_tests. diff --git a/omaha/recovery/client/google_update_recovery.cc b/omaha/recovery/client/google_update_recovery.cc index 34353e1..fb94a87 100644 --- a/omaha/recovery/client/google_update_recovery.cc +++ b/omaha/recovery/client/google_update_recovery.cc @@ -22,6 +22,7 @@ #include #include #include +#include "components/crx_file/crx_verifier.h" #include "omaha/base/app_util.h" #include "omaha/base/const_addresses.h" #include "omaha/base/error.h" @@ -45,20 +46,32 @@ const TCHAR* const kUserRepairArgs = _T("/recover"); // TODO(omaha): Add a Code Red lib version that is manually updated when // we check in the lib. const TCHAR* const kQueryStringFormat = - _T("?appid=%s&appversion=%s&applang=%s&machine=%u") + _T("&appid=%s&appversion=%s&applang=%s&machine=%u") _T("&version=%s&userid=%s&osversion=%s&servicepack=%s"); // Information about where to obtain Omaha info. // This must never change in Omaha. const TCHAR* const kRegValueProductVersion = _T("pv"); -const TCHAR* const kRelativeGoopdateRegPath = _T("Software\\Google\\Update\\"); +const TCHAR* const kRelativeGoopdateRegPath = _T("Software\\Brave\\Update\\"); const TCHAR* const kRelativeClientsGoopdateRegPath = - _T("Software\\Google\\Update\\Clients\\") - _T("{430FD4D0-B729-4F61-AA34-91526481799D}"); + _T("Software\\Brave\\Update\\Clients\\") + _T("{B131C935-9BE6-41DA-9599-1F776BEB8019}"); // The UpdateDev registry value to override the Code Red url. const TCHAR* const kRegValueNameCodeRedUrl = _T("CodeRedUrl"); +// The hard-coded Recovery subdirectory where the CRX is unpacked and executed. +const TCHAR* const kRecoveryDirectory = _T("Recovery"); + +// The hard-coded SHA256 of the SubjectPublicKeyInfo used to sign the Recovery +// CRX which contains GoogleUpdateRecovery.exe. +std::vector GetRecoveryCRXHash() { + return std::vector{0x5f, 0x94, 0xe0, 0x3c, 0x64, 0x30, 0x9f, 0xbc, + 0xfe, 0x00, 0x9a, 0x27, 0x3e, 0x52, 0xbf, 0xa5, + 0x84, 0xb9, 0xb3, 0x75, 0x07, 0x29, 0xde, 0xfa, + 0x32, 0x76, 0xd9, 0x93, 0xb5, 0xa3, 0xce, 0x02}; +} + // Starts another process via ::CreateProcess. HRESULT StartProcess(const TCHAR* process_name, TCHAR* command_line) { if (!process_name && !command_line) { @@ -166,38 +179,69 @@ HRESULT CreateDir(const CString& dir) { return S_OK; } -HRESULT GetAndCreateTempDir(CString* temp_path) { - if (!temp_path) { - return E_INVALIDARG; +// Create a unique temporary file under the provided parent directory and +// returns the full path. +HRESULT CreateUniqueTempFile(const CPath& parent_dir, + CPath* unique_temp_file_path) { + ASSERT1(parent_dir.IsDirectory()); + ASSERT1(unique_temp_file_path); + + *unique_temp_file_path = CPath(GetTempFilenameAt(parent_dir, _T("GUR"))); + return unique_temp_file_path->FileExists() ? S_OK : HRESULTFromLastError(); +} + +// Create a unique temporary directory under the provided parent directory and +// returns the full path. +HRESULT CreateUniqueTempDir(const CPath& parent_dir, CPath* unique_temp_dir) { + *unique_temp_dir = NULL; + + CPath temp_dir; + HRESULT hr = CreateUniqueTempFile(parent_dir, &temp_dir); + if (FAILED(hr)) { + return hr; } - *temp_path = app_util::GetTempDir(); - if (temp_path->IsEmpty()) { - HRESULT hr = HRESULTFromLastError(); - if (SUCCEEDED(hr)) { - hr = E_FAIL; - } + ::DeleteFile(temp_dir); + hr = CreateDir(temp_dir); + if (FAILED(hr)) { return hr; } - // Create this dir if it doesn't already exist. - return CreateDir(*temp_path); + *unique_temp_dir += temp_dir; + return S_OK; } +// Resets and returns the Recovery directory under the currently executing +// module directory. For machine installs, this directory is under +// %ProgramFiles%. If the directory does not exist, it is created. +HRESULT ResetRecoveryDir(CPath* recovery_dir) { + ASSERT1(recovery_dir); -// Create a unique temporary file and returns the full path. -HRESULT CreateUniqueTempFile(const CString& user_temp_dir, - CString* unique_temp_file_path) { - if (user_temp_dir.IsEmpty() || !unique_temp_file_path) { - return E_INVALIDARG; + CString module_dir = app_util::GetCurrentModuleDirectory(); + if (module_dir.IsEmpty()) { + return HRESULTFromLastError(); } - *unique_temp_file_path = GetTempFilenameAt(user_temp_dir, _T("GUR")); - if (unique_temp_file_path->IsEmpty()) { - return HRESULTFromLastError(); + *recovery_dir = CPath(module_dir); + *recovery_dir += kRecoveryDirectory; + + if (recovery_dir->IsDirectory()) { + VERIFY1(SUCCEEDED(DeleteDirectoryContents(*recovery_dir))); + return S_OK; } - return S_OK; + return CreateDir(*recovery_dir); +} + +// Resets the Recovery directory and creates a temporary directory under the +// Recovery directory. For machine installs, this directory is under +// %ProgramFiles%. +HRESULT ResetRecoveryTempDir(CPath* temp_dir) { + ASSERT1(temp_dir); + + CPath recovery_dir; + HRESULT hr = ResetRecoveryDir(&recovery_dir); + return SUCCEEDED(hr) ? CreateUniqueTempDir(recovery_dir, temp_dir) : hr; } // Obtains the OS version and service pack. @@ -378,36 +422,21 @@ HRESULT BuildUrlQueryPortion(const CString& app_guid, return S_OK; } -// Returns the full path to save the downloaded file to. -// The path is based on a unique temporary filename to avoid a conflict -// between multiple apps downloading to the same location. -// The path to this file is also returned. The caller is responsible for -// deleting the temporary file after using the download target path. -// If it cannot create the unique directory, it attempts to use the user's -// temporary directory and a constant filename. -HRESULT GetDownloadTargetPath(CString* download_target_path, - CString* temp_file_path) { - if (!download_target_path || !temp_file_path) { +// Returns the full path to save the downloaded file to and the corresponding +// parent directory. +HRESULT GetDownloadTargetPath(CPath* download_target_path, + CPath* parent_dir) { + if (!download_target_path || !parent_dir) { return E_INVALIDARG; } - CString user_temp_dir; - HRESULT hr = GetAndCreateTempDir(&user_temp_dir); + HRESULT hr = ResetRecoveryTempDir(parent_dir); if (FAILED(hr)) { return hr; } - hr = CreateUniqueTempFile(user_temp_dir, temp_file_path); - if (SUCCEEDED(hr) && !temp_file_path->IsEmpty()) { - *download_target_path = *temp_file_path; - // Ignore the return value. A .tmp filename is better than none. - download_target_path->Replace(_T(".tmp"), _T(".exe")); - } else { - // Try a static filename in the temp directory as a fallback. - *download_target_path = user_temp_dir + _T("GoogleUpdateSetup.exe"); - *temp_file_path = _T(""); - } - + *download_target_path = *parent_dir; + *download_target_path += _T("GoogleUpdateSetup.crx3"); return S_OK; } @@ -564,6 +593,40 @@ HRESULT VerifyIsValidRepairFile(const CString& filename) { return VerifyRepairFileMarkup(filename); } +// Validates the provided CRX using the |crx_hash|, and if validation succeeds, +// unpacks the CRX under |unpack_under_path|. Returns the unpacked EXE in +// |unpacked_exe|. +HRESULT ValidateAndUnpackCRX(const CPath& from_crx_path, + const crx_file::VerifierFormat& crx_format, + const std::vector& crx_hash, + const CPath& unpack_under_path, + CPath* unpacked_exe) { + ASSERT1(unpacked_exe); + + std::string public_key; + if (crx_file::Verify(std::string(CT2A(from_crx_path)), + crx_format, + {crx_hash}, + {}, + &public_key, + NULL) != crx_file::VerifierResult::OK_FULL) { + return CRYPT_E_NO_MATCH; + } + + if (!crx_file::Crx3Unzip(from_crx_path, unpack_under_path)) { + return E_UNEXPECTED; + } + + CPath exe = unpack_under_path; + exe += _T("GoogleUpdateSetup.exe"); + if (!exe.FileExists()) { + return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); + } + + *unpacked_exe = exe; + return S_OK; +} + } // namespace omaha // If a repair file is run, the file will not be deleted until reboot. Delete @@ -593,19 +656,14 @@ HRESULT FixGoogleUpdate(const TCHAR* app_guid, } } - CString download_target_path; - CString temp_file_path; + CPath download_target_path; + CPath parent_dir; HRESULT hr = omaha::GetDownloadTargetPath(&download_target_path, - &temp_file_path); + &parent_dir); if (FAILED(hr)) { return hr; } - if (download_target_path.IsEmpty()) { - return E_FAIL; - } - // After calling DownloadRepairFile, don't return until the repair file and - // temp file have been deleted. hr = omaha::DownloadRepairFile(download_target_path, app_guid, app_version, @@ -614,19 +672,20 @@ HRESULT FixGoogleUpdate(const TCHAR* app_guid, download_callback, context); - if (SUCCEEDED(hr)) { - hr = omaha::VerifyIsValidRepairFile(download_target_path); + if (FAILED(hr)) { + return hr; } + CPath unpacked_exe; + hr = omaha::ValidateAndUnpackCRX( + CPath(download_target_path), + crx_file::VerifierFormat::CRX3_WITH_PUBLISHER_PROOF, + omaha::GetRecoveryCRXHash(), + parent_dir, + &unpacked_exe); if (FAILED(hr)) { - ::DeleteFile(download_target_path); - ::DeleteFile(temp_file_path); return hr; } - hr = omaha::RunRepairFile(download_target_path, is_machine_app); - ::MoveFileEx(download_target_path, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); - ::DeleteFile(temp_file_path); - - return hr; + return omaha::RunRepairFile(unpacked_exe, is_machine_app); } diff --git a/omaha/recovery/client/google_update_recovery_unittest.cc b/omaha/recovery/client/google_update_recovery_unittest.cc index 478d605..a349864 100644 --- a/omaha/recovery/client/google_update_recovery_unittest.cc +++ b/omaha/recovery/client/google_update_recovery_unittest.cc @@ -81,6 +81,8 @@ const HRESULT kDummyNoFileError = 0x80041234; const TCHAR kArgumentSavingExecutableRelativePath[] = _T("unittest_support\\SaveArguments.exe"); +const TCHAR kArgumentSavingExecutableCrx3RelativePath[] = + _T("unittest_support\\CodeRed.crx3"); const TCHAR kSavedArgumentsFileName[] = _T("saved_arguments.txt"); const TCHAR* const kInvalidFileUrl = _T("http://www.google.com/robots.txt"); @@ -93,7 +95,7 @@ const TCHAR* const kInvalidFileUrl = _T("http://www.google.com/robots.txt"); const TCHAR kRegistryHiveOverrideRoot[] = _T("HKCU\\Software\\Google\\Update\\UnitTest\\"); -const TCHAR kExpectedUrlForDummyAppAndNoOmahaValues[] = _T("https://clients2.google.com/service/check2?appid=%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%7D&appversion=3.4.5.6&applang=en-us&machine=1&version=0.0.0.0&userid=&osversion="); // NOLINT +const TCHAR kExpectedUrlForDummyAppAndNoOmahaValues[] = _T("https://clients2.google.com/service/check2?crx3=true&appid=%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%7D&appversion=3.4.5.6&applang=en-us&machine=1&version=0.0.0.0&userid=&osversion="); // NOLINT const int kExpectedUrlForDummyAppAndNoOmahaValuesLength = arraysize(kExpectedUrlForDummyAppAndNoOmahaValues) - 1; @@ -224,27 +226,14 @@ class GoogleUpdateRecoveryTest : public testing::Test { EXPECT_STREQ(expected_string, buffer); } - void VerifyExpectedSavedFilePath(const CString& expected_temp_directory) { - const int kMaxUniqueChars = 4; - const CString expected_path_part_a = expected_temp_directory + _T("\\GUR"); - const CString expected_path_part_b = _T(".exe"); - EXPECT_STREQ(expected_path_part_a, - saved_file_path_.Left(expected_path_part_a.GetLength())); - EXPECT_STREQ(expected_path_part_b, - saved_file_path_.Right(expected_path_part_b.GetLength())); - const int constant_chars = expected_path_part_a.GetLength() + - expected_path_part_b.GetLength(); - EXPECT_GT(saved_file_path_.GetLength(), constant_chars); - EXPECT_LE(saved_file_path_.GetLength(), constant_chars + kMaxUniqueChars); - } - static CString saved_url_; static CString saved_file_path_; static void* saved_context_; protected: - // Copies SaveArguments.exe to the specified location. - static HRESULT DownloadArgumentSavingFile(const TCHAR* url, + // Copies the Crx3 containing the argument saving executable to the specified + // location. + static HRESULT DownloadArgumentSavingCrx3(const TCHAR* url, const TCHAR* file_path, void* context) { ASSERT1(url); @@ -254,11 +243,11 @@ class GoogleUpdateRecoveryTest : public testing::Test { GoogleUpdateRecoveryTest::set_saved_file_path(file_path); GoogleUpdateRecoveryTest::set_saved_context(context); - CString executable_full_path(app_util::GetCurrentModuleDirectory()); - VERIFY1(::PathAppend(CStrBuf(executable_full_path, MAX_PATH), - kArgumentSavingExecutableRelativePath)); + CString crx_full_path(app_util::GetCurrentModuleDirectory()); + VERIFY1(::PathAppend(CStrBuf(crx_full_path, MAX_PATH), + kArgumentSavingExecutableCrx3RelativePath)); - if (!::CopyFile(executable_full_path, file_path, false)) { + if (!::CopyFile(crx_full_path, file_path, false)) { HRESULT hr = HRESULTFromLastError(); return hr; } @@ -409,7 +398,7 @@ class GoogleUpdateRecoveryRegistryProtectedTest // TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_UseRealHttpClient) { - EXPECT_EQ(TRUST_E_SUBJECT_FORM_UNKNOWN, + EXPECT_EQ(CRYPT_E_NO_MATCH, FixGoogleUpdate(kDummyAppGuid, kDummyAppVersion, kDummyAppLang, @@ -419,55 +408,35 @@ TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_UseRealHttpClient) { } TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_FileReturned_Machine) { - CString saved_arguments_path = ConcatenatePath(app_util::GetTempDir(), - kSavedArgumentsFileName); - - ::DeleteFile(saved_arguments_path); - EXPECT_FALSE(File::Exists(saved_arguments_path)); - CString context_string(_T("some context")); EXPECT_HRESULT_SUCCEEDED(FixGoogleUpdate(kDummyAppGuid, kDummyAppVersion, kDummyAppLang, true, - DownloadArgumentSavingFile, + DownloadArgumentSavingCrx3, &context_string)); EXPECT_EQ(&context_string, saved_context_); EXPECT_STREQ(_T("some context"), *static_cast(saved_context_)); ::Sleep(200); - EXPECT_TRUE(File::Exists(saved_file_path_)); VerifySavedArgumentsFile(_T("/recover /machine")); - - EXPECT_TRUE(::DeleteFile(saved_file_path_)); - EXPECT_TRUE(::DeleteFile(saved_arguments_path)); } TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_FileReturned_User) { - CString saved_arguments_path = ConcatenatePath(app_util::GetTempDir(), - kSavedArgumentsFileName); - - ::DeleteFile(saved_arguments_path); - EXPECT_FALSE(File::Exists(saved_arguments_path)); - CString context_string(_T("more context")); EXPECT_HRESULT_SUCCEEDED(FixGoogleUpdate(kDummyAppGuid, kDummyAppVersion, kDummyAppLang, false, - DownloadArgumentSavingFile, + DownloadArgumentSavingCrx3, &context_string)); EXPECT_EQ(&context_string, saved_context_); EXPECT_STREQ(_T("more context"), *static_cast(saved_context_)); ::Sleep(200); - EXPECT_TRUE(File::Exists(saved_file_path_)); VerifySavedArgumentsFile(_T("/recover")); - - EXPECT_TRUE(::DeleteFile(saved_file_path_)); - EXPECT_TRUE(::DeleteFile(saved_arguments_path)); } TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_NoFile_Machine) { @@ -480,11 +449,6 @@ TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_NoFile_Machine) { EXPECT_EQ(static_cast(NULL), saved_context_); EXPECT_FALSE(File::Exists(saved_file_path_)); - - TCHAR temp_dir[MAX_PATH] = {0}; - EXPECT_TRUE(::GetEnvironmentVariable(_T("TMP"), temp_dir, MAX_PATH)); - EXPECT_TRUE(File::Exists(temp_dir)) - << _T("The temp directory was deleted or not created."); } TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_NoFile_User) { @@ -497,11 +461,6 @@ TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_NoFile_User) { EXPECT_EQ(static_cast(NULL), saved_context_); EXPECT_FALSE(File::Exists(saved_file_path_)); - - TCHAR temp_dir[MAX_PATH] = {0}; - EXPECT_TRUE(::GetEnvironmentVariable(_T("TMP"), temp_dir, MAX_PATH)); - EXPECT_TRUE(File::Exists(temp_dir)) - << _T("The temp directory was deleted or not created."); } INSTANTIATE_TEST_CASE_P(IsDomain, @@ -510,10 +469,7 @@ INSTANTIATE_TEST_CASE_P(IsDomain, TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, FixGoogleUpdate_AllValues_MachineApp) { - const TCHAR kExpectedUrlFormat[] = _T("https://clients2.google.com/service/check2?appid=%%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%%7D&appversion=3.4.5.6&applang=en-us&machine=1&version=5.6.78.1&userid=%s&osversion="); // NOLINT - - const CString prev_tmp = GetTmp(); - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), kTempDirectory)); + const TCHAR kExpectedUrlFormat[] = _T("https://clients2.google.com/service/check2?crx3=true&appid=%%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%%7D&appversion=3.4.5.6&applang=en-us&machine=1&version=5.6.78.1&userid=%s&osversion="); // NOLINT EnableUsageStats(true); EXPECT_HRESULT_SUCCEEDED(RegKey::SetValue(kFullMachineOmahaClientKeyPath, @@ -531,17 +487,11 @@ TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, expected_url.Format(kExpectedUrlFormat, GetEscapedUserId(true)); EXPECT_STREQ(expected_url, saved_url_.Left(expected_url.GetLength())); CheckSavedUrlOSFragment(); - VerifyExpectedSavedFilePath(kTempDirectory); - - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), prev_tmp)); } TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, FixGoogleUpdate_AllValues_UserApp) { - const TCHAR kExpectedUrlFormat[] = _T("https://clients2.google.com/service/check2?appid=%%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%%7D&appversion=3.4.5.6&applang=en-us&machine=0&version=5.6.78.1&userid=%s&osversion="); // NOLINT - - const CString prev_tmp = GetTmp(); - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), kTempDirectory)); + const TCHAR kExpectedUrlFormat[] = _T("https://clients2.google.com/service/check2?crx3=true&appid=%%7B8E472B0D-3E8B-43b1-B89A-E8506AAF1F16%%7D&appversion=3.4.5.6&applang=en-us&machine=0&version=5.6.78.1&userid=%s&osversion="); // NOLINT EnableUsageStats(true); EXPECT_HRESULT_SUCCEEDED(RegKey::SetValue(kFullUserOmahaClientKeyPath, @@ -559,9 +509,6 @@ TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, expected_url.Format(kExpectedUrlFormat, GetEscapedUserId(false)); EXPECT_STREQ(expected_url, saved_url_.Left(expected_url.GetLength())); CheckSavedUrlOSFragment(); - VerifyExpectedSavedFilePath(kTempDirectory); - - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), prev_tmp)); } TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, @@ -579,7 +526,7 @@ TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, FixGoogleUpdate_EmptyAppInfo) { - const TCHAR kExpectedUrl[] = _T("https://clients2.google.com/service/check2?appid=&appversion=&applang=&machine=1&version=0.0.0.0&userid=&osversion="); // NOLINT + const TCHAR kExpectedUrl[] = _T("https://clients2.google.com/service/check2?crx3=true&appid=&appversion=&applang=&machine=1&version=0.0.0.0&userid=&osversion="); // NOLINT EXPECT_EQ(kDummyNoFileError, FixGoogleUpdate(_T(""), _T(""), @@ -765,45 +712,15 @@ TEST_P(GoogleUpdateRecoveryRegistryProtectedTest, CheckSavedUrlOSFragment(); } -// Verifies that the file is saved even if the temp directory doesn't exist. -TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_SaveToNonExistantDirectory) { - const TCHAR kNonExistantDirectory[] = _T("c:\\directory_does_not_exist"); - DeleteDirectory(kNonExistantDirectory); - EXPECT_FALSE(File::Exists(kNonExistantDirectory)); - - const CString prev_tmp = GetTmp(); - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), kNonExistantDirectory)); - - EXPECT_EQ(TRUST_E_SUBJECT_FORM_UNKNOWN, - FixGoogleUpdate(kDummyAppGuid, - kDummyAppVersion, - kDummyAppLang, - true, - DownloadFileInvalidFile, - NULL)); - - VerifyExpectedSavedFilePath(kNonExistantDirectory); - - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), prev_tmp)); - EXPECT_HRESULT_SUCCEEDED(DeleteDirectory(kNonExistantDirectory)); -} - TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_FileCollision) { - const CString prev_tmp = GetTmp(); - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), kTempDirectory)); - - CString saved_arguments_path = ConcatenatePath(app_util::GetTempDir(), - kSavedArgumentsFileName); - EXPECT_HRESULT_SUCCEEDED(FixGoogleUpdate(kDummyAppGuid, kDummyAppVersion, kDummyAppLang, false, - DownloadArgumentSavingFile, + DownloadArgumentSavingCrx3, NULL)); EXPECT_TRUE(File::Exists(saved_file_path_)); - VerifyExpectedSavedFilePath(kTempDirectory); CString first_saved_file_path = saved_file_path_; @@ -815,10 +732,9 @@ TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_FileCollision) { kDummyAppVersion, kDummyAppLang, false, - DownloadArgumentSavingFile, + DownloadArgumentSavingCrx3, NULL)); EXPECT_TRUE(File::Exists(saved_file_path_)); - VerifyExpectedSavedFilePath(kTempDirectory); EXPECT_STRNE(first_saved_file_path, saved_file_path_); @@ -832,9 +748,6 @@ TEST_F(GoogleUpdateRecoveryTest, FixGoogleUpdate_FileCollision) { EXPECT_TRUE(is_deleted); EXPECT_TRUE(::DeleteFile(first_saved_file_path)); - EXPECT_TRUE(::DeleteFile(saved_arguments_path)); - - EXPECT_TRUE(::SetEnvironmentVariable(_T("TMP"), prev_tmp)); } // diff --git a/omaha/recovery/recovery_markup.rc b/omaha/recovery/recovery_markup.rc index e707c72..28af8a4 100644 --- a/omaha/recovery/recovery_markup.rc +++ b/omaha/recovery/recovery_markup.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 diff --git a/omaha/recovery/repair_exe/build.scons b/omaha/recovery/repair_exe/build.scons index 57b5848..75f0658 100644 --- a/omaha/recovery/repair_exe/build.scons +++ b/omaha/recovery/repair_exe/build.scons @@ -26,8 +26,7 @@ inputs = [ 'repair_goopdate.cc', ] -repair_goopdate_lib = local_env.ComponentStaticLibrary('repair_goopdate', - inputs) +repair_goopdate_lib = local_env.ComponentLibrary('repair_goopdate', inputs) subdirs = [ 'custom_action', 'msp', diff --git a/omaha/recovery/repair_exe/custom_action/build.scons b/omaha/recovery/repair_exe/custom_action/build.scons index efded4f..60738e8 100644 --- a/omaha/recovery/repair_exe/custom_action/build.scons +++ b/omaha/recovery/repair_exe/custom_action/build.scons @@ -30,8 +30,6 @@ lib_env = env.Clone() lib_inputs = [ 'execute_repair_file.cc', ] -if env.Bit('use_precompiled_headers'): - lib_inputs += lib_env.EnablePrecompile(lib_target_name) lib_output = lib_env.ComponentLibrary( lib_name=lib_target_name, @@ -51,11 +49,14 @@ dll_env.Append( dll_env['crt_libs'][dll_env.Bit('debug')], '$LIB_DIR/base.lib', '$LIB_DIR/common.lib', + '$LIB_DIR/crx_file.lib', '$LIB_DIR/google_update_recovery.lib', + '$LIB_DIR/libprotobuf.lib', '$LIB_DIR/repair_goopdate.lib', '$LIB_DIR/security.lib', 'crypt32.lib', 'msi.lib', + '$LIB_DIR/net.lib', 'wintrust.lib', # These are required by base.lib @@ -77,8 +78,6 @@ dll_inputs = [ 'executecustomaction.cc', 'executecustomaction.def', ] -if env.Bit('use_precompiled_headers'): - dll_inputs += dll_env.EnablePrecompile(dll_target_name) dll_env.ComponentLibrary( lib_name=dll_target_name, @@ -117,8 +116,6 @@ target_name = 'testelevateusingmsp' test_inputs = [ 'testelevateusingmsp.cc', ] -if env.Bit('use_precompiled_headers'): - test_inputs += test_env.EnablePrecompile(target_name) # This test requires arguments, so do not create a run alias. test_env.ComponentTestProgram( diff --git a/omaha/recovery/repair_exe/custom_action/executecustomaction.h b/omaha/recovery/repair_exe/custom_action/executecustomaction.h index 033f6f7..d2377d3 100644 --- a/omaha/recovery/repair_exe/custom_action/executecustomaction.h +++ b/omaha/recovery/repair_exe/custom_action/executecustomaction.h @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== -// -// Header files to precompile for the installer. #ifndef OMAHA_RECOVERY_REPAIR_EXE_CUSTOM_ACTION_EXECUTECUSTOMACTION_H__ #define OMAHA_RECOVERY_REPAIR_EXE_CUSTOM_ACTION_EXECUTECUSTOMACTION_H__ diff --git a/omaha/recovery/repair_exe/msp/build.scons b/omaha/recovery/repair_exe/msp/build.scons index d9ddaf9..89d0ae3 100644 --- a/omaha/recovery/repair_exe/msp/build.scons +++ b/omaha/recovery/repair_exe/msp/build.scons @@ -58,7 +58,7 @@ def CreateMsiInstallerFiles(env, wxs_file, suffix=''): ) old_unsigned_output = old_unsigned_env.WiX( - 'GoogleUpdateHelper%s_unsigned.msi' % suffix, + 'BraveUpdateHelper%s_unsigned.msi' % suffix, wxs_file) env.Depends(old_unsigned_output, [_custom_actions_path, _required_file]) @@ -170,7 +170,7 @@ msp_output_for_legacy = CreateMsiPatchFile( # Sign the old MSI and MSP files # signed_msi = env.SignedBinary( - target='GoogleUpdateHelper.msi', + target='BraveUpdateHelper.msi', source=old_msi, ) diff --git a/omaha/recovery/repair_exe/msp/legacy/patch.wxs b/omaha/recovery/repair_exe/msp/legacy/patch.wxs index c46dcef..601b381 100644 --- a/omaha/recovery/repair_exe/msp/legacy/patch.wxs +++ b/omaha/recovery/repair_exe/msp/legacy/patch.wxs @@ -8,9 +8,9 @@ diff --git a/omaha/recovery/repair_exe/msp/legacy/patchableinstaller.wxs b/omaha/recovery/repair_exe/msp/legacy/patchableinstaller.wxs index 71f38d1..026b8ef 100644 --- a/omaha/recovery/repair_exe/msp/legacy/patchableinstaller.wxs +++ b/omaha/recovery/repair_exe/msp/legacy/patchableinstaller.wxs @@ -6,12 +6,12 @@ Codepage="1252" UpgradeCode="9515FFBD-40AB-4690-B983-4FA8E14EE7F5" Version="$(var.GoogleUpdateVersion)" - Manufacturer="Google Inc."> + Manufacturer="Google LLC"> diff --git a/omaha/recovery/repair_exe/msp/patchableinstaller.wxs b/omaha/recovery/repair_exe/msp/patchableinstaller.wxs index b3bb1a2..fe38dcd 100644 --- a/omaha/recovery/repair_exe/msp/patchableinstaller.wxs +++ b/omaha/recovery/repair_exe/msp/patchableinstaller.wxs @@ -6,12 +6,12 @@ Codepage="1252" UpgradeCode="9515FFBD-40AB-4690-B983-4FA8E14EE7F5" Version="$(var.GoogleUpdateVersion)" - Manufacturer="Google Inc."> + Manufacturer="Google LLC"> - + @@ -32,7 +32,7 @@ - + diff --git a/omaha/recovery/repair_exe/mspexecutableelevator_unittest.cc b/omaha/recovery/repair_exe/mspexecutableelevator_unittest.cc index 77a6c5d..2d0a59c 100644 --- a/omaha/recovery/repair_exe/mspexecutableelevator_unittest.cc +++ b/omaha/recovery/repair_exe/mspexecutableelevator_unittest.cc @@ -37,7 +37,7 @@ namespace omaha { // Note: For some reason, the product ID GUIDs are swizzled in the registry. extern const TCHAR kMsiProductPatchesKey[] = - _T("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\") + _T("HKEY_LOCAL_MACHINE[64]\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\") _T("Installer\\UserData\\S-1-5-18\\Products\\") _T("93BAD29AC2E44034A96BCB446EB8552E\\Patches"); @@ -172,10 +172,9 @@ TEST_F(RepairGoopdateWithMsiInstalledTest, } // Verify that no patch is installed. - EXPECT_TRUE(RegKey::HasNativeKey(kMsiProductPatchesKey)); + EXPECT_TRUE(RegKey::HasKey(kMsiProductPatchesKey)); RegKey product_patches_key; - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); HANDLE process = NULL; @@ -186,8 +185,7 @@ TEST_F(RepairGoopdateWithMsiInstalledTest, // Verify that patch was uninstalled. // GetSubkeyCount fails if we don't re-open the key. - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); bool is_found = false; diff --git a/omaha/recovery/repair_exe/repair_goopdate_unittest.cc b/omaha/recovery/repair_exe/repair_goopdate_unittest.cc index f403cae..cd7d3a8 100644 --- a/omaha/recovery/repair_exe/repair_goopdate_unittest.cc +++ b/omaha/recovery/repair_exe/repair_goopdate_unittest.cc @@ -87,10 +87,9 @@ TEST_F(RepairGoopdateTest, InstallMsi(); // Verify that no patch is installed. - EXPECT_TRUE(RegKey::HasNativeKey(kMsiProductPatchesKey)); + EXPECT_TRUE(RegKey::HasKey(kMsiProductPatchesKey)); RegKey product_patches_key; - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); HRESULT hr = E_FAIL; @@ -99,8 +98,7 @@ TEST_F(RepairGoopdateTest, // Verify that patch was uninstalled. // GetSubkeyCount fails if we don't re-open the key. - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); bool is_found = false; @@ -172,10 +170,9 @@ TEST_F(RepairGoopdateTest, InstallMsi(); // Verify that no patch is installed. - EXPECT_TRUE(RegKey::HasNativeKey(kMsiProductPatchesKey)); + EXPECT_TRUE(RegKey::HasKey(kMsiProductPatchesKey)); RegKey product_patches_key; - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); HRESULT hr = E_FAIL; @@ -187,8 +184,7 @@ TEST_F(RepairGoopdateTest, // Verify that patch was uninstalled. // GetSubkeyCount fails if we don't re-open the key. - EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, - KEY_READ | KEY_WOW64_64KEY)); + EXPECT_SUCCEEDED(product_patches_key.Open(kMsiProductPatchesKey, KEY_READ)); EXPECT_EQ(0, product_patches_key.GetSubkeyCount()); RemoveMsi(); diff --git a/omaha/service/build.scons b/omaha/service/build.scons index 8d04159..7ba41a6 100644 --- a/omaha/service/build.scons +++ b/omaha/service/build.scons @@ -30,4 +30,4 @@ inputs = [ ] # Build these into a library. -local_env.ComponentStaticLibrary('service', inputs) +local_env.ComponentLibrary('service', inputs) diff --git a/omaha/service/service_main.h b/omaha/service/service_main.h index f0ce42d..c8aa5b9 100644 --- a/omaha/service/service_main.h +++ b/omaha/service/service_main.h @@ -40,10 +40,18 @@ #ifndef OMAHA_SERVICE_SERVICE_MAIN_H_ #define OMAHA_SERVICE_SERVICE_MAIN_H_ +#include + +// Redefining the macro RegisterEventSource to evaluate to NULL so that +// CAtlServiceModuleT::LogEvent() code does not log to the event log. Doing this +// avoids duplicating the CAtlServiceModuleT code. +#undef RegisterEventSource +#define RegisterEventSource(x, ...) NULL + #include #include #include "base/basictypes.h" -#include "base/scoped_ptr.h" + #include "omaha/base/atlregmapex.h" #include "omaha/base/debug.h" // Use client/resource.h because it does not use StringFormatter and some of the @@ -92,16 +100,15 @@ class UpdateMediumServiceMode { static HRESULT PreMessageLoop(); }; -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) - template class ServiceModule : public CAtlServiceModuleT, IDS_SERVICE_NAME> { public: typedef CAtlServiceModuleT Base; + using Base::OnStop; + using Base::SetServiceStatus; + DECLARE_REGISTRY_APPID_RESOURCEID_EX(IDR_GOOGLE_UPDATE3_SERVICE_APPID, T::app_id_string()) @@ -114,7 +121,7 @@ class ServiceModule : service_thread_(NULL), is_service_com_server_(false) { SERVICE_LOG(L1, (_T("[ServiceModule]"))); - _tcscpy(m_szServiceName, T::GetCurrentServiceName()); + _tcscpy(this->m_szServiceName, T::GetCurrentServiceName()); } ~ServiceModule() { @@ -247,7 +254,7 @@ class ServiceModule } // m_szServiceName is set in the constructor. - hr = key.SetValue(_T("LocalService"), m_szServiceName); + hr = key.SetValue(_T("LocalService"), this->m_szServiceName); if (FAILED(hr)) { SERVICE_LOG(LE, (_T("[Could not set LocalService value][0x%x]"), hr)); return hr; @@ -279,8 +286,8 @@ class ServiceModule SERVICE_LOG(L1, (_T("[PreMessageLoop]"))); - m_dwThreadID = ::GetCurrentThreadId(); - service_thread_ = ::OpenThread(SYNCHRONIZE, false, m_dwThreadID); + this->m_dwThreadID = ::GetCurrentThreadId(); + service_thread_ = ::OpenThread(SYNCHRONIZE, false, this->m_dwThreadID); if (is_service_com_server_) { return InitializeCOMServer(); @@ -324,7 +331,7 @@ class ServiceModule // further information. virtual LONG Lock() throw() { ::CoAddRefServerProcess(); - LONG retval = CComGlobalsThreadModel::Increment(&m_nLockCnt); + LONG retval = CComGlobalsThreadModel::Increment(&this->m_nLockCnt); return retval; } @@ -343,10 +350,10 @@ class ServiceModule // OnStop() correctly sets the service status to SERVICE_STOP_PENDING, and // posts a WM_QUIT to the service thread. virtual LONG Unlock() throw() { - ASSERT1(!m_bDelayShutdown); + ASSERT1(!this->m_bDelayShutdown); ::CoReleaseServerProcess(); - LONG retval = CComGlobalsThreadModel::Decrement(&m_nLockCnt); + LONG retval = CComGlobalsThreadModel::Decrement(&this->m_nLockCnt); if (retval == 0) { OnStop(); @@ -362,41 +369,41 @@ class ServiceModule SERVICE_LOG(L3, (_T("[MonitorShutdown]"))); while (true) { - ::WaitForSingleObject(m_hEventShutdown, INFINITE); - SERVICE_LOG(L4, (_T("[Infinite Wait][%d][%d]"), m_bActivity, m_nLockCnt)); + ::WaitForSingleObject(this->m_hEventShutdown, INFINITE); + SERVICE_LOG(L4, (_T("[Infinite Wait][%d][%d]"), this->m_bActivity, this->m_nLockCnt)); DWORD wait = 0; do { - m_bActivity = false; - wait = ::WaitForSingleObject(m_hEventShutdown, m_dwTimeOut); + this->m_bActivity = false; + wait = ::WaitForSingleObject(this->m_hEventShutdown, this->m_dwTimeOut); } while (wait == WAIT_OBJECT_0); SERVICE_LOG(L4, (_T("[MonitorShutdown][%d][%d]"), - m_bActivity, m_nLockCnt)); - if (!m_bActivity && m_nLockCnt == 0) { + this->m_bActivity, this->m_nLockCnt)); + if (!this->m_bActivity && this->m_nLockCnt == 0) { ::CoSuspendClassObjects(); - if (m_nLockCnt == 0) { + if (this->m_nLockCnt == 0) { break; } } } - ::CloseHandle(m_hEventShutdown); + ::CloseHandle(this->m_hEventShutdown); OnStop(); } // This is cloned from CAtlExeModuleT.StartMonitor(). HANDLE StartMonitor() throw() { SERVICE_LOG(L3, (_T("[StartMonitor]"))); - m_hEventShutdown = ::CreateEvent(NULL, false, false, NULL); - if (m_hEventShutdown == NULL) { + this->m_hEventShutdown = ::CreateEvent(NULL, false, false, NULL); + if (this->m_hEventShutdown == NULL) { return NULL; } DWORD thread_id(0); HANDLE monitor = ::CreateThread(NULL, 0, MonitorProc, this, 0, &thread_id); if (monitor == NULL) { - ::CloseHandle(m_hEventShutdown); + ::CloseHandle(this->m_hEventShutdown); } return monitor; @@ -430,7 +437,7 @@ class ServiceModule // Initialize COM security right at the beginning, because Worker // initialization can cause interface marshaling. The first few lines below // are adapted from the beginning of CAtlServiceModuleT::PreMessageLoop(). - ASSERT1(m_bService); + ASSERT1(this->m_bService); HRESULT hr = InitializeSecurity(); if (FAILED(hr)) { return hr; @@ -467,13 +474,13 @@ class ServiceModule UNREFERENCED_PARAMETER(show_cmd); SERVICE_TABLE_ENTRY st[] = { - { m_szServiceName, Base::_ServiceMain }, + { this->m_szServiceName, Base::_ServiceMain }, { NULL, NULL } }; - m_status.dwWin32ExitCode = 0; + this->m_status.dwWin32ExitCode = 0; if (!::StartServiceCtrlDispatcher(st)) { - m_status.dwWin32ExitCode = ::GetLastError(); + this->m_status.dwWin32ExitCode = ::GetLastError(); } if (service_thread_) { @@ -483,7 +490,7 @@ class ServiceModule service_thread_ = NULL; } - return m_status.dwWin32ExitCode; + return this->m_status.dwWin32ExitCode; } HANDLE service_thread_; // The service thread provided by the SCM. @@ -505,11 +512,9 @@ class ServiceModule // Time to wait before performing the specified action. static const DWORD kActionDelayMs = 1000L * 60 * 15; // 15 minutes. - DISALLOW_EVIL_CONSTRUCTORS(ServiceModule); + DISALLOW_COPY_AND_ASSIGN(ServiceModule); }; -#pragma warning(pop) - typedef ServiceModule Update3ServiceModule; typedef ServiceModule UpdateMediumServiceModule; diff --git a/omaha/setup/build.scons b/omaha/setup/build.scons index 6af16a6..72b286b 100644 --- a/omaha/setup/build.scons +++ b/omaha/setup/build.scons @@ -30,6 +30,5 @@ inputs = [ # TODO(omaha): It would be nice to eliminate references to COM files from setup. local_env['CPPPATH'] += ['$OBJ_ROOT'] - # Build these into a static library. -local_env.ComponentStaticLibrary('setup', inputs) +local_env.ComponentLibrary('setup', inputs) diff --git a/omaha/setup/setup.cc b/omaha/setup/setup.cc index d890b6d..3f2f416 100644 --- a/omaha/setup/setup.cc +++ b/omaha/setup/setup.cc @@ -21,7 +21,6 @@ #include #include #include -#include #include #include "omaha/base/const_object_names.h" #include "omaha/base/constants.h" @@ -33,7 +32,6 @@ #include "omaha/base/process.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scope_guard.h" #include "omaha/base/synchronized.h" #include "omaha/base/system.h" @@ -122,7 +120,6 @@ void IncrementProcessWaitFailCount(CommandLineMode mode) { case COMMANDLINE_MODE_REGSERVER: case COMMANDLINE_MODE_UNREGSERVER: - case COMMANDLINE_MODE_NETDIAGS: case COMMANDLINE_MODE_CRASH: case COMMANDLINE_MODE_INSTALL: case COMMANDLINE_MODE_RECOVER: @@ -949,9 +946,9 @@ HRESULT Setup::GetPidsToWaitForUsingCommandLine(Pids* pids) const { // * "/registerproduct" - same as for /install. std::vector command_lines; CString switch_to_exclude; - SafeCStringFormat(&switch_to_exclude, _T("/%s"), kCmdLineInstall); + SafeCStringFormat(&switch_to_exclude, _T(" /%s "), kCmdLineInstall); command_lines.push_back(switch_to_exclude); - SafeCStringFormat(&switch_to_exclude, _T("/%s"), kCmdLineRegisterProduct); + SafeCStringFormat(&switch_to_exclude, _T(" /%s "), kCmdLineRegisterProduct); command_lines.push_back(switch_to_exclude); CString user_sid; @@ -1138,7 +1135,7 @@ HRESULT Setup::FindCoreProcesses(Pids* found_core_pids) const { const Pids::iterator new_end = std::remove_if( found_core_pids->begin(), found_core_pids->end(), - std::not1(std::ptr_fun(IsCoreProcess))); + [](Pids::value_type pid) { return !IsCoreProcess(pid); }); if (new_end != found_core_pids->end()) { found_core_pids->erase(new_end, found_core_pids->end()); } diff --git a/omaha/setup/setup.h b/omaha/setup/setup.h index aa286b1..708eac3 100644 --- a/omaha/setup/setup.h +++ b/omaha/setup/setup.h @@ -27,10 +27,11 @@ #include #include +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -186,7 +187,7 @@ class Setup { scoped_event shutdown_event_; int extra_code1_; - scoped_ptr metrics_timer_; + std::unique_ptr metrics_timer_; // Whether this process uninstalled Google Update for any reason. // Access must be protected by the Setup Lock. @@ -194,7 +195,7 @@ class Setup { friend class SetupTest; friend class SetupOfflineInstallerTest; - DISALLOW_EVIL_CONSTRUCTORS(Setup); + DISALLOW_COPY_AND_ASSIGN(Setup); }; } // namespace omaha diff --git a/omaha/setup/setup_files.cc b/omaha/setup/setup_files.cc index a067cc3..43e0e74 100644 --- a/omaha/setup/setup_files.cc +++ b/omaha/setup/setup_files.cc @@ -27,7 +27,6 @@ #include "omaha/base/omaha_version.h" #include "omaha/base/path.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scoped_current_directory.h" #include "omaha/base/signatures.h" #include "omaha/base/signaturevalidator.h" @@ -38,6 +37,7 @@ #include "omaha/common/goopdate_utils.h" #include "omaha/goopdate/resource_manager.h" #include "omaha/setup/setup_metrics.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -328,10 +328,6 @@ HRESULT SetupFiles::BuildFileLists() { // Machine-specific files are always installed, to support cross installs from // user to machine and machine to user. - // TODO(omaha3): Enable once it is being built. -#if 0 - optional_files_.push_back(BHO_FILENAME); -#endif return S_OK; } diff --git a/omaha/setup/setup_files.h b/omaha/setup/setup_files.h index 0b8e216..2d8406a 100644 --- a/omaha/setup/setup_files.h +++ b/omaha/setup/setup_files.h @@ -88,7 +88,7 @@ class SetupFiles { friend class SetupFilesTest; - DISALLOW_EVIL_CONSTRUCTORS(SetupFiles); + DISALLOW_COPY_AND_ASSIGN(SetupFiles); }; } // namespace omaha diff --git a/omaha/setup/setup_files_unittest.cc b/omaha/setup/setup_files_unittest.cc index 7309e35..100839a 100644 --- a/omaha/setup/setup_files_unittest.cc +++ b/omaha/setup/setup_files_unittest.cc @@ -13,8 +13,9 @@ // limitations under the License. // ======================================================================== +#include #include -#include "base/scoped_ptr.h" + #include "omaha/base/app_util.h" #include "omaha/base/error.h" #include "omaha/base/file.h" @@ -73,10 +74,6 @@ void CopyGoopdateFiles(const CString& omaha_path, const CString& version) { kOmahaBrokerFileName, kOmahaOnDemandFileName, kOmahaWebPluginFileName, -// TODO(omaha3): Enable once this is being built. -#if 0 - _T("GoopdateBho.dll"), -#endif UPDATE_PLUGIN_FILENAME, kPSFileNameMachine, kPSFileNameMachine64, @@ -191,10 +188,6 @@ class SetupFilesTest : public testing::Test { EXPECT_STREQ(kOmahaMetainstallerFileName, files[file_index++]); EXPECT_STREQ(kOmahaWebPluginFileName, files[file_index++]); EXPECT_STREQ(kOmahaDllName, files[file_index++]); -// TODO(omaha3): Enable as this is built. -#if 0 - EXPECT_STREQ(_T("GoopdateBho.dll"), files[file_index++]); -#endif EXPECT_STREQ(_T("goopdateres_am.dll"), files[file_index++]); EXPECT_STREQ(_T("goopdateres_ar.dll"), files[file_index++]); EXPECT_STREQ(_T("goopdateres_bg.dll"), files[file_index++]); @@ -270,7 +263,7 @@ class SetupFilesTest : public testing::Test { const bool is_machine_; const CString omaha_path_; const CString hive_override_key_name_; - scoped_ptr setup_files_; + std::unique_ptr setup_files_; static CString exe_parent_dir_; static CString this_version_; diff --git a/omaha/setup/setup_google_update.cc b/omaha/setup/setup_google_update.cc index 4df7f3d..37d20d5 100644 --- a/omaha/setup/setup_google_update.cc +++ b/omaha/setup/setup_google_update.cc @@ -33,7 +33,6 @@ #include "omaha/base/path.h" #include "omaha/base/reg_key.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/service_utils.h" #include "omaha/base/utils.h" #include "omaha/base/user_info.h" @@ -47,6 +46,7 @@ #include "omaha/common/scheduled_task_utils.h" #include "omaha/setup/setup_metrics.h" #include "omaha/setup/setup_service.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -116,11 +116,13 @@ HRESULT VerifyCOMLocalServerRegistration(bool is_machine) { } #endif -HRESULT RegisterOrUnregisterService(bool reg, CString service_path) { +HRESULT RegisterOrUnregisterService(bool register_server, + CString service_path) { EnclosePath(&service_path); - CommandLineBuilder builder(reg ? COMMANDLINE_MODE_SERVICE_REGISTER : - COMMANDLINE_MODE_SERVICE_UNREGISTER); + CommandLineBuilder builder( + register_server ? COMMANDLINE_MODE_SERVICE_REGISTER : + COMMANDLINE_MODE_SERVICE_UNREGISTER); CString cmd_line = builder.GetCommandLineArgs(); return RegisterOrUnregisterExe(service_path, cmd_line); } @@ -621,19 +623,6 @@ HRESULT SetupGoogleUpdate::InstallBrowserPlugins() { SETUP_LOG(L1, (_T("[Register plugin DLL failed][0x%08x]"), hr)); } -// TODO(omaha): Enable when we ship the BHO. -#if 0 - // Only install the BHO for machine installs. There is no corresponding HKCU - // registration for BHOs. - if (is_machine_) { - CString goopdate_bho_proxy_path = BuildSupportFileInstallPath(BHO_FILENAME); - hr = RegisterDll(goopdate_bho_proxy_path); - if (FAILED(hr)) { - SETUP_LOG(L1, (_T("[Register bho_proxy DLL failed][0x%08x]"), hr)); - } - } -#endif - return hr; } @@ -649,17 +638,6 @@ HRESULT SetupGoogleUpdate::UninstallBrowserPlugins() { SETUP_LOG(L1, (_T("[Unregister plugin DLL failed][0x%08x]"), hr)); } -// TODO(omaha): Enable when we ship the BHO. -#if 0 - if (is_machine_) { - CString goopdate_bho_proxy_path = BuildSupportFileInstallPath(BHO_FILENAME); - hr = UnregisterDll(goopdate_bho_proxy_path); - if (FAILED(hr)) { - SETUP_LOG(L1, (_T("[Unregister bho_proxy DLL failed][0x%08x]"), hr)); - } - } -#endif - return hr; } @@ -764,21 +742,6 @@ HRESULT SetupGoogleUpdate::UninstallPreviousVersions() { VERIFY1(SUCCEEDED(UnregisterDll(old_plugin_file))); } - - if (is_machine_) { - // TODO(omaha): Enable when we ship the BHO. - /* - // BHO is only installed for the machine case. - // Unregister the previous version BHO if it exists. Ignore failures. - CPath old_bho_dll(file_or_directory); - VERIFY1(old_bho_dll.Append(BHO_FILENAME)); - if (File::Exists(old_bho_dll)) { - if (FAILED(UnregisterDll(old_bho_dll))) { - SETUP_LOG(LW, (L"[UnregisterDll() failed][%s]", old_bho_dll)); - } - } - */ - } // Delete entire sub-directory. DeleteBeforeOrAfterReboot(file_or_directory); } diff --git a/omaha/setup/setup_google_update.h b/omaha/setup/setup_google_update.h index 54e47ab..2daaa05 100644 --- a/omaha/setup/setup_google_update.h +++ b/omaha/setup/setup_google_update.h @@ -78,7 +78,7 @@ class SetupGoogleUpdate { HRESULT SetInstallationId(); // Register COM classes and interfaces. - HRESULT RegisterOrUnregisterCOMLocalServer(bool register); + HRESULT RegisterOrUnregisterCOMLocalServer(bool register_server); // Uninstalls the helper (MSI). HRESULT UninstallMsiHelper(); @@ -96,7 +96,6 @@ class SetupGoogleUpdate { // the following: // * Delete all sub-directories under Google\\Update, except the running // version's directory and the cache directory. - // * Uninstall the BHO, so IE does not load it in the future. HRESULT UninstallPreviousVersions(); const bool is_machine_; @@ -111,7 +110,7 @@ class SetupGoogleUpdate { friend class SetupGoogleUpdateTest; friend class AppManagerTestBase; - DISALLOW_EVIL_CONSTRUCTORS(SetupGoogleUpdate); + DISALLOW_COPY_AND_ASSIGN(SetupGoogleUpdate); }; } // namespace omaha diff --git a/omaha/setup/setup_google_update_unittest.cc b/omaha/setup/setup_google_update_unittest.cc index ba3edb1..8d370c2 100644 --- a/omaha/setup/setup_google_update_unittest.cc +++ b/omaha/setup/setup_google_update_unittest.cc @@ -16,7 +16,6 @@ #include #include #include -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/atlregmapex.h" #include "omaha/base/constants.h" @@ -24,9 +23,7 @@ #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/scoped_impersonation.h" -#include "omaha/base/scoped_ptr_address.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/base/vista_utils.h" @@ -39,6 +36,7 @@ #include "omaha/setup/msi_test_utils.h" #include "omaha/setup/setup_google_update.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -210,7 +208,7 @@ void VerifyHklmKeyHasIntegrity( TRUSTEE administrators = {0}; administrators.TrusteeForm = TRUSTEE_IS_NAME; administrators.TrusteeType = TRUSTEE_IS_GROUP; - administrators.ptstrName = _T("Administrators"); + administrators.ptstrName = const_cast(_T("Administrators")); VerifyAccessRightsForTrustee(key_name, KEY_ALL_ACCESS, &dacl, @@ -219,13 +217,13 @@ void VerifyHklmKeyHasIntegrity( TRUSTEE users = {0}; users.TrusteeForm = TRUSTEE_IS_NAME; users.TrusteeType = TRUSTEE_IS_GROUP; - users.ptstrName = _T("Users"); + users.ptstrName = const_cast(_T("Users")); VerifyAccessRightsForTrustee(key_name, KEY_READ, &dacl, &users); TRUSTEE power_users = {0}; power_users.TrusteeForm = TRUSTEE_IS_NAME; power_users.TrusteeType = TRUSTEE_IS_GROUP; - power_users.ptstrName = _T("Power Users"); + power_users.ptstrName = const_cast(_T("Power Users")); VerifyAccessRightsForTrustee(key_name, kExpectedPowerUsersAccess, &dacl, @@ -234,7 +232,7 @@ void VerifyHklmKeyHasIntegrity( TRUSTEE interactive = {0}; interactive.TrusteeForm = TRUSTEE_IS_NAME; interactive.TrusteeType = TRUSTEE_IS_GROUP; - interactive.ptstrName = _T("INTERACTIVE"); + interactive.ptstrName = const_cast(_T("INTERACTIVE")); VerifyAccessRightsForTrustee(key_name, expected_non_admin_interactive_access, &dacl, @@ -243,13 +241,13 @@ void VerifyHklmKeyHasIntegrity( TRUSTEE everyone = {0}; everyone.TrusteeForm = TRUSTEE_IS_NAME; everyone.TrusteeType = TRUSTEE_IS_GROUP; - everyone.ptstrName = _T("Everyone"); + everyone.ptstrName = const_cast(_T("Everyone")); VerifyAccessRightsForTrustee(key_name, 0, &dacl, &everyone); TRUSTEE guest = {0}; guest.TrusteeForm = TRUSTEE_IS_NAME; guest.TrusteeType = TRUSTEE_IS_USER; - guest.ptstrName = _T("Guest"); + guest.ptstrName = const_cast(_T("Guest")); VerifyAccessRightsForTrustee(key_name, 0, &dacl, &guest); } @@ -270,7 +268,7 @@ class SetupGoogleUpdateTest : public testing::Test { explicit SetupGoogleUpdateTest(bool is_machine) : is_machine_(is_machine) {} virtual ~SetupGoogleUpdateTest() {} - virtual void SetUp() { + void SetUp() override { setup_google_update_.reset(new SetupGoogleUpdate(is_machine_, false)); } @@ -299,7 +297,7 @@ class SetupGoogleUpdateTest : public testing::Test { } bool is_machine_; - scoped_ptr setup_google_update_; + std::unique_ptr setup_google_update_; }; class SetupGoogleUpdateUserTest : public SetupGoogleUpdateTest { @@ -311,12 +309,12 @@ class SetupGoogleUpdateUserTest : public SetupGoogleUpdateTest { kOmahaCoreFileName); } - virtual void SetUp() { + void SetUp() override { SetupGoogleUpdateTest::SetUp(); RegKey::DeleteKey(USER_REG_UPDATE); } - virtual void TearDown() { + void TearDown() override { RegKey::DeleteKey(USER_REG_UPDATE); SetupGoogleUpdateTest::TearDown(); } @@ -328,12 +326,12 @@ class SetupGoogleUpdateMachineTest : public SetupGoogleUpdateTest { protected: SetupGoogleUpdateMachineTest() : SetupGoogleUpdateTest(true) {} - virtual void SetUp() { + void SetUp() override { RegKey::DeleteKey(MACHINE_REG_UPDATE); SetupGoogleUpdateTest::SetUp(); } - virtual void TearDown() { + void TearDown() override { RegKey::DeleteKey(MACHINE_REG_UPDATE); SetupGoogleUpdateTest::TearDown(); } @@ -557,12 +555,12 @@ TEST_F(SetupGoogleUpdateMachineTest, TRUSTEE users = {0}; users.TrusteeForm = TRUSTEE_IS_NAME; users.TrusteeType = TRUSTEE_IS_GROUP; - users.ptstrName = _T("Users"); + users.ptstrName = const_cast(_T("Users")); TRUSTEE interactive = {0}; interactive.TrusteeForm = TRUSTEE_IS_NAME; interactive.TrusteeType = TRUSTEE_IS_GROUP; - interactive.ptstrName = _T("INTERACTIVE"); + interactive.ptstrName = const_cast(_T("INTERACTIVE")); EXPECT_SUCCEEDED(RegKey::CreateKey(MACHINE_REG_UPDATE)); diff --git a/omaha/setup/setup_service.h b/omaha/setup/setup_service.h index 730fe03..11866d0 100644 --- a/omaha/setup/setup_service.h +++ b/omaha/setup/setup_service.h @@ -29,7 +29,6 @@ #include "omaha/base/logging.h" #include "omaha/base/path.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/service_utils.h" #include "omaha/base/system_info.h" #include "omaha/client/resource.h" @@ -37,6 +36,7 @@ #include "omaha/common/const_cmd_line.h" #include "omaha/common/const_goopdate.h" #include "omaha/service/service_main.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/setup/setup_unittest.cc b/omaha/setup/setup_unittest.cc index e5e5486..7326b1b 100644 --- a/omaha/setup/setup_unittest.cc +++ b/omaha/setup/setup_unittest.cc @@ -13,10 +13,12 @@ // limitations under the License. // ======================================================================== +#include "omaha/setup/setup.h" +#include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" #include "omaha/base/app_util.h" #include "omaha/base/const_object_names.h" #include "omaha/base/error.h" @@ -25,7 +27,6 @@ #include "omaha/base/omaha_version.h" #include "omaha/base/process.h" #include "omaha/base/scope_guard.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/synchronized.h" #include "omaha/base/system.h" #include "omaha/base/thread.h" @@ -35,9 +36,9 @@ #include "omaha/common/command_line.h" #include "omaha/common/config_manager.h" #include "omaha/common/const_goopdate.h" -#include "omaha/setup/setup.h" #include "omaha/setup/setup_files.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -238,7 +239,7 @@ class SetupTest : public testing::Test { // /install is always ignored. LaunchProcess(not_listening_exe_path_, - _T("/install"), + _T("/install foobar"), is_machine_, address(install_process)); ASSERT_TRUE(install_process); @@ -661,7 +662,7 @@ class SetupTest : public testing::Test { CString omaha_exe_path_; CString not_listening_exe_path_; CString not_listening_exe_opposite_path_; - scoped_ptr setup_; + std::unique_ptr setup_; static CString not_listening_user_exe_path_; static CString not_listening_machine_exe_path_; diff --git a/omaha/site_scons/site_tools/atlmfc_vc15_0.py b/omaha/site_scons/site_tools/atlmfc_vc15_0.py new file mode 100644 index 0000000..e583088 --- /dev/null +++ b/omaha/site_scons/site_tools/atlmfc_vc15_0.py @@ -0,0 +1,42 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +# Windows ATL MFC for VC15 (Visual Studio 2017) tool for SCons. + +import os + + +def _FindLocalInstall(): + """Returns the directory containing the local install of the tool. + + Returns: + Path to tool (as a string), or None if not found. + """ + default_dir = os.environ['VCToolsInstallDir'] + 'atlmfc' + if os.path.exists(default_dir): + return default_dir + else: + return None + + +def generate(env): + # NOTE: SCons requires the use of this name, which fails gpylint. + """SCons entry point for this tool.""" + + if not env.get('ATLMFC_VC15_0_DIR'): + env['ATLMFC_VC15_0_DIR'] = _FindLocalInstall() + + env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC15_0_DIR/include').abspath) + env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC15_0_DIR/lib/x86').abspath) diff --git a/omaha/site_scons/site_tools/atlmfc_vc15_amd64.py b/omaha/site_scons/site_tools/atlmfc_vc15_amd64.py new file mode 100644 index 0000000..2156461 --- /dev/null +++ b/omaha/site_scons/site_tools/atlmfc_vc15_amd64.py @@ -0,0 +1,42 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +# Windows ATL MFC for VC15 (Visual Studio 2017) tool for SCons. + +import os + + +def _FindLocalInstall(): + """Returns the directory containing the local install of the tool. + + Returns: + Path to tool (as a string), or None if not found. + """ + default_dir = os.environ['VCToolsInstallDir'] + 'atlmfc' + if os.path.exists(default_dir): + return default_dir + else: + return None + + +def generate(env): + # NOTE: SCons requires the use of this name, which fails gpylint. + """SCons entry point for this tool.""" + + if not env.get('ATLMFC_VC15_0_DIR'): + env['ATLMFC_VC15_0_DIR'] = _FindLocalInstall() + + env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC15_0_DIR/include').abspath) + env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC15_0_DIR/lib/x64').abspath) diff --git a/omaha/site_scons/site_tools/atlmfc_vc16_0.py b/omaha/site_scons/site_tools/atlmfc_vc16_0.py new file mode 100644 index 0000000..3dbd7ef --- /dev/null +++ b/omaha/site_scons/site_tools/atlmfc_vc16_0.py @@ -0,0 +1,42 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +# Windows ATL MFC for VC16 (Visual Studio 2019) tool for SCons. + +import os + + +def _FindLocalInstall(): + """Returns the directory containing the local install of the tool. + + Returns: + Path to tool (as a string), or None if not found. + """ + default_dir = os.environ['VCToolsInstallDir'] + 'atlmfc' + if os.path.exists(default_dir): + return default_dir + else: + return None + + +def generate(env): + # NOTE: SCons requires the use of this name, which fails gpylint. + """SCons entry point for this tool.""" + + if not env.get('ATLMFC_VC16_0_DIR'): + env['ATLMFC_VC16_0_DIR'] = _FindLocalInstall() + + env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC16_0_DIR/include').abspath) + env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC16_0_DIR/lib/x86').abspath) diff --git a/omaha/site_scons/site_tools/atlmfc_vc16_amd64.py b/omaha/site_scons/site_tools/atlmfc_vc16_amd64.py new file mode 100644 index 0000000..56e5b4e --- /dev/null +++ b/omaha/site_scons/site_tools/atlmfc_vc16_amd64.py @@ -0,0 +1,42 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +# Windows ATL MFC for VC15 (Visual Studio 2017) tool for SCons. + +import os + + +def _FindLocalInstall(): + """Returns the directory containing the local install of the tool. + + Returns: + Path to tool (as a string), or None if not found. + """ + default_dir = os.environ['VCToolsInstallDir'] + 'atlmfc' + if os.path.exists(default_dir): + return default_dir + else: + return None + + +def generate(env): + # NOTE: SCons requires the use of this name, which fails gpylint. + """SCons entry point for this tool.""" + + if not env.get('ATLMFC_VC16_0_DIR'): + env['ATLMFC_VC16_0_DIR'] = _FindLocalInstall() + + env.AppendENVPath('INCLUDE', env.Dir('$ATLMFC_VC16_0_DIR/include').abspath) + env.AppendENVPath('LIB', env.Dir('$ATLMFC_VC16_0_DIR/lib/x64').abspath) diff --git a/omaha/site_scons/site_tools/omaha_builders.py b/omaha/site_scons/site_tools/omaha_builders.py index f8ad8ad..3168156 100644 --- a/omaha/site_scons/site_tools/omaha_builders.py +++ b/omaha/site_scons/site_tools/omaha_builders.py @@ -17,6 +17,7 @@ """Omaha builders tool for SCons.""" +from copy import copy from copy import deepcopy import os.path import SCons.Action @@ -26,53 +27,6 @@ import omaha_version_utils -def EnablePrecompile(env, target_name): - """Enable use of precompiled headers for target_name. - - Args: - env: The environment. - target_name: Name of component. - - Returns: - The pch .obj file. - """ - if env.Bit('use_precompiled_headers'): - # We enable all warnings on all levels. The goal is to fix the code that - # we have written and to programmatically disable the warnings for the - # code we do not control. This list of warnings should shrink as the code - # gets fixed. - env.FilterOut(CCFLAGS=['/W3']) - env.Append( - CCFLAGS=[ - '/W4', - '/Wall', - ], - INCLUDES=[ - '$MAIN_DIR/precompile/precompile.h' - ], - ) - - env['PCHSTOP'] = '$MAIN_DIR/precompile/precompile.h' - - pch_env = env.Clone() - # Must manually force-include the header, as the precompilation step does - # not evaluate $INCLUDES - pch_env.Append(CCFLAGS=['/FI$MAIN_DIR/precompile/precompile.h']) - # Append '_pch' to the target base name to prevent target name collisions. - # One case where this might have occurred is when a .cc file has the same - # base name as the target program/library. - pch_output = pch_env.PCH( - target=target_name.replace('.', '_') + '_pch' + '.pch', - source='$MAIN_DIR/precompile/precompile.cc', - ) - - env['PCH'] = pch_output[0] - - # Return the pch .obj file that is created, so it can be - # included with the inputs of a module - return [pch_output[1]] - - def SignDotNetManifest(env, target, unsigned_manifest): """Signs a .NET manifest. @@ -94,8 +48,7 @@ def SignDotNetManifest(env, target, unsigned_manifest): # If signing fails with the following error, the hash may not match any # certificates: "Internal error, please try again. Object reference not set # to an instance of an object." - sign_manifest_cmd += ('-CertHash ' + - env['build_server_certificate_hash']) + sign_manifest_cmd += ('-CertHash ' + env['CERTIFICATE_HASH']) else: sign_manifest_cmd += '-CertFile %s -Password %s' % ( env.GetOption('authenticode_file'), @@ -163,52 +116,10 @@ def OmahaTagExe(env, target, source, tag): # # Custom Library and Program builders. # -# These builders have additional cababilities, including enabling precompiled -# headers when appropriate and signing DLLs and EXEs. -# - -# TODO(omaha): Make all build files use these builders instead of Hammer's. -# This will eliminate many lines in build.scons files related to enabling -# precompiled header and signing binaries. - - -def _ConditionallyEnablePrecompile(env, target_name, *args, **kwargs): - """Enables precompiled headers for target_name when appropriate. - - Enables precompiled headers if they are enabled for the build unless - use_pch_default = False. This requires that the source files are specified in - sources or in a list as the first argument after target_name. - - Args: - env: Environment in which we were called. - target_name: Name of the build target. - args: Positional arguments. - kwargs: Keyword arguments. - """ - use_pch_default = kwargs.get('use_pch_default', True) - - if use_pch_default and env.Bit('use_precompiled_headers'): - pch_output = env.EnablePrecompile(target_name) - - # Search the keyworded list first. - for key in ['source', 'sources', 'input', 'inputs']: - if key in kwargs: - kwargs[key] += pch_output - return - - # If the keyword was not found, assume the sources are the first argument in - # the non-keyworded list. - if args: - args[0].append(pch_output[0]) - def ComponentStaticLibrary(env, lib_name, *args, **kwargs): """Pseudo-builder for static library. - Enables precompiled headers if they are enabled for the build unless - use_pch_default = False. This requires that the source files are specified in - sources or in a list as the first argument after lib_name. - Args: env: Environment in which we were called. lib_name: Static library name. @@ -218,79 +129,8 @@ def ComponentStaticLibrary(env, lib_name, *args, **kwargs): Returns: Output node list from env.ComponentLibrary(). """ - _ConditionallyEnablePrecompile(env, lib_name, *args, **kwargs) - - return env.ComponentLibrary(lib_name, *args, **kwargs) - - -# TODO(omaha): Add signing. -def ComponentDll(env, lib_name, *args, **kwargs): - """Pseudo-builder for DLL. - - Enables precompiled headers if they are enabled for the build unless - use_pch_default = False. This requires that the source files are specified in - sources or in a list as the first argument after lib_name. - - Args: - env: Environment in which we were called. - lib_name: DLL name. - args: Positional arguments. - kwargs: Keyword arguments. - - Returns: - Output node list from env.ComponentLibrary(). - """ - env.Append(COMPONENT_STATIC=False) - - _ConditionallyEnablePrecompile(env, lib_name, *args, **kwargs) - return env.ComponentLibrary(lib_name, *args, **kwargs) - -# TODO(omaha): Add signing. -def ComponentSignedProgram(env, prog_name, *args, **kwargs): - """Pseudo-builder for signed EXEs. - - Enables precompiled headers if they are enabled for the build unless - use_pch_default = False. This requires that the source files are specified in - sources or in a list as the first argument after prog_name. - - Args: - env: Environment in which we were called. - prog_name: Executable name. - args: Positional arguments. - kwargs: Keyword arguments. - - Returns: - Output node list from env.ComponentProgram(). - """ - _ConditionallyEnablePrecompile(env, prog_name, *args, **kwargs) - - return env.ComponentProgram(prog_name, *args, **kwargs) - - -# TODO(omaha): Put these in a tools/ directory instead of staging. -def ComponentTool(env, prog_name, *args, **kwargs): - """Pseudo-builder for utility programs that do not need to be signed. - - Enables precompiled headers if they are enabled for the build unless - use_pch_default = False. This requires that the source files are specified in - sources or in a list as the first argument after prog_name. - - Args: - env: Environment in which we were called. - prog_name: Executable name. - args: Positional arguments. - kwargs: Keyword arguments. - - Returns: - Output node list from env.ComponentProgram(). - """ - _ConditionallyEnablePrecompile(env, prog_name, *args, **kwargs) - - return env.ComponentProgram(prog_name, *args, **kwargs) - - # # Unit Test Builders # @@ -389,7 +229,6 @@ def ConfigureEnvFor64Bit(env): LIBFLAGS=['/MACHINE:x64'], LINKFLAGS=['/MACHINE:x64']) - platform_sdk_version = env['WINDOWS_SDK_10_0_VERSION'] platform_sdk_lib_dir = ('$WINDOWS_SDK_10_0_DIR/lib/' + '$WINDOWS_SDK_10_0_VERSION') @@ -407,6 +246,14 @@ def ConfigureEnvFor64Bit(env): '$ATLMFC_VC14_0_DIR/lib/amd64', platform_sdk_lib_dir + '/um/x64', platform_sdk_lib_dir + '/ucrt/x64',], + omaha_version_utils.VC150: [ '$VC15_0_DIR/lib/x64', + '$ATLMFC_VC15_0_DIR/lib/x64', + '$WINDOWS_SDK_10_0_LIB_DIR/um/x64', + '$WINDOWS_SDK_10_0_LIB_DIR/ucrt/x64',], + omaha_version_utils.VC160: [ '$VC16_0_DIR/lib/x64', + '$ATLMFC_VC16_0_DIR/lib/x64', + '$WINDOWS_SDK_10_0_LIB_DIR/um/x64', + '$WINDOWS_SDK_10_0_LIB_DIR/ucrt/x64',], }[env['msc_ver']] env.Prepend(LIBPATH=lib_paths) @@ -416,7 +263,9 @@ def ConfigureEnvFor64Bit(env): {omaha_version_utils.VC80 : '$VC80_DIR/vc/bin/x86_amd64', omaha_version_utils.VC100 : '$VC10_0_DIR/vc/bin/x86_amd64', omaha_version_utils.VC120 : '$VC12_0_DIR/vc/bin/x86_amd64', - omaha_version_utils.VC140 : '$VC14_0_DIR/vc/bin/x86_amd64'} + omaha_version_utils.VC140 : '$VC14_0_DIR/vc/bin/x86_amd64', + omaha_version_utils.VC150 : '$VC15_0_DIR/bin/HostX64/x64', + omaha_version_utils.VC160 : '$VC16_0_DIR/bin/HostX64/x64'} [env['msc_ver']])) # Filter x86 options that are not supported or conflict with x86-x64 options. @@ -446,7 +295,6 @@ def ConfigureEnvFor64Bit(env): if env.IsCoverageBuild(): env['INSTALL'] = env['PRECOVERAGE_INSTALL'] - def CloneAndMake64Bit(env): """Clones the supplied environment and calls ConfigureEnvFor64Bit() on the clone. @@ -492,8 +340,10 @@ def ComponentStaticLibraryMultiarch(env, lib_name, *args, **kwargs): """ # ComponentStaticLibrary() will actually modify the input arg lists, so - # make a deep copy of both. - args64 = deepcopy(args) + # make a copy of both. It's only necessary to make a shallow copy of each arg + # in |args|, as the modification by ComponentStaticLibrary only adds to one + # of the argument lists. + args64 = [copy(arg) for arg in args] kwargs64 = deepcopy(kwargs) nodes32 = ComponentStaticLibrary(env.Clone(), lib_name, *args, **kwargs) @@ -503,44 +353,79 @@ def ComponentStaticLibraryMultiarch(env, lib_name, *args, **kwargs): return nodes32 + nodes64 -def CompileProtoBuf(env, target, input_proto_file): +# os.path.relpath is not available in Python 2.4, so make our own. +def RelativePath(path, start): + """Returns a relative path. + + Args: + path: Some path. + start: A parent of |path|. + + Returns: + A relative path from |start| to |path|. + """ + path_list = [x for x in os.path.normpath(path).split(os.path.sep) if x] + start_list = [x for x in os.path.normpath(start).split(os.path.sep) if x] + i = 0 + for start_item, path_item in zip(start_list, path_list): + if start_item.lower() != path_item.lower(): + break + i += 1 + rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:] + if not rel_list: + return os.path.curdir + return os.path.join(*rel_list) + + +def CompileProtoBuf(env, input_proto_files): """Invokes the protocol buffer compiler. Args: - env: The environment. - target: The generated .pb.cc and .pb.h files. - input_proto_file: The protocol buffer .proto file. + env: The environment, which must specify the following construction + variables + $PROTO_PATH: The "proto path" passed to protoc. This is the base path in + which all .proto files reside. + $CPP_OUT: The "output path" passed to protoc. This is the path into + which the generated files are placed, preserving their paths + relative to $PROTO_PATH. + input_proto_files: The protocol buffer .proto file(s). Returns: - Output node list from env.Command(). + Output node list of generated .cc files. """ - proto_compiler_path = '%s/protoc.exe' % os.getenv('OMAHA_PROTOBUF_BIN_DIR') + proto_compiler_path = '%s/protoc.exe' % os.getenv('OMAHA_PROTOBUF_BIN_DIR', + '$OBJ_ROOT/base/Default') + proto_path = env['PROTO_PATH'] + cpp_out = env['CPP_OUT'] + # Generate the list of .pb.cc and .pb.h targets in the cpp_out dir. + targets = [os.path.join(cpp_out, os.path.splitext(base)[0] + ext) + for base in [RelativePath(in_file, proto_path) + for in_file in input_proto_files] + for ext in ('.pb.cc', '.pb.h')] proto_arguments = (' --proto_path=%s --cpp_out=%s %s ' % - (os.path.dirname(input_proto_file[0]), - os.path.dirname(target[0]), - input_proto_file[0])) + (proto_path, + cpp_out, + ' '.join(input_proto_files))) proto_cmd_line = proto_compiler_path + proto_arguments - compile_proto_buf = env.Command( - target=target, - source=input_proto_file, + target=targets, + source=input_proto_files, action=proto_cmd_line, ) - return compile_proto_buf + if 'OMAHA_PROTOBUF_BIN_DIR' not in os.environ: + env.Depends(compile_proto_buf, proto_compiler_path) + + # Return only the generated .pb.cc files for convenience. + return [node for node in compile_proto_buf if node.name.endswith('.cc')] # NOTE: SCons requires the use of this name, which fails gpylint. def generate(env): # pylint: disable-msg=C6409 """SCons entry point for this tool.""" - env.AddMethod(EnablePrecompile) env.AddMethod(SignDotNetManifest) env.AddMethod(OmahaCertificateTagExe) env.AddMethod(OmahaTagExe) - env.AddMethod(ComponentStaticLibrary) - env.AddMethod(ComponentDll) - env.AddMethod(ComponentSignedProgram) - env.AddMethod(ComponentTool) env.AddMethod(IsBuildingModule) env.AddMethod(GetAllInOneUnittestSources) env.AddMethod(GetAllInOneUnittestLibs) diff --git a/omaha/site_scons/site_tools/windows_vc.py b/omaha/site_scons/site_tools/windows_vc.py new file mode 100644 index 0000000..bb0402f --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc.py @@ -0,0 +1,182 @@ +#!/usr/bin/python2.4 +# +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2013. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. +""" + +import os +import SCons + + +def SetMsvcCompilerVersion( + env, version_num, vc_flavor='x86'): + """When run on a non-Windows system, this function does nothing. + + When run on a Windows system, this function wipes the binary, include + and lib paths so that any non-hermetic tools won't be used. + These paths will be set up by target_platform_windows and other tools. + By wiping the paths here, we make the adding the other tools + order-independent. + Args: + env: The SCons environment in question. + version_num: Either 15.0 or 16.0 to select the Visual Studion 2017 or 2019 + toolchain. Any other value will raise an exception. + + vc_flavor: Defaults to x64_x86. It can be 'x86_x86', 'x86_x64', 'x64_x64, + or 'x64_x86'. The latter is using 64-bit compiler host to + generate x86 binaries. + Returns: + Nothing. + Raises: + ValueError: An error if vc_flavor is not valid. + """ + if version_num in (15.0, 16.0): + if not vc_flavor: + vc_flavor = 'x64_x86' + if vc_flavor not in ['x86_x86', 'x86_x64', 'x64_x86', 'x64_x64']: + raise ValueError('Invalid vc_flavor %s.' % str(vc_flavor)) + + if version_num == 16.0: + env.Replace(VC16_0_DIR=os.environ.get('VCToolsInstallDir')) + _SetMsvcCompilerVersion(env, + vc_version='16.0', + vc_flavor=vc_flavor) + elif version_num == 15.0: + env.Replace(VC15_0_DIR=os.environ.get('VCToolsInstallDir')), + _SetMsvcCompilerVersion(env, + vc_version='15.0', + vc_flavor=vc_flavor) + else: + raise ValueError('Unknown MSVC compiler version: "%s".' % version_num) + + +def _SetMsvcCompilerVersion(env, vc_version, vc_flavor='x64_x86'): + if (vc_flavor == 'x86_x64' or vc_flavor == 'x64_x64'): + flavor = 'amd64' + else: + flavor = 'x86' + + vc_install_dir = os.environ.get('VCToolsInstallDir') + vc_redist_dir = os.environ.get('VCToolsRedistDir') + + platform_sdk_dir = os.environ.get('OMAHA_PLATFORM_SDK_DIR') + platform_sdk_version = os.environ.get('OMAHA_WINDOWS_SDK_10_0_VERSION') + platform_sdk_include_dir = (platform_sdk_dir + 'include/' + + platform_sdk_version) + platform_sdk_lib_dir = platform_sdk_dir + 'lib/' + platform_sdk_version + + env['GOOGLECLIENT'] = '$MAIN_DIR/..' + env['THIRD_PARTY'] = '$GOOGLECLIENT/third_party/' + + env.Replace( + PLATFORM_SDK_DIR=platform_sdk_dir, + WINDOWS_SDK_10_0_VERSION=platform_sdk_version, + WINDOWS_SDK_10_0_LIB_DIR=platform_sdk_lib_dir, + + # The msvc tool has a nasty habit of searching the registry for + # installed versions of MSVC and prepending them to the path. Flag + # that it shouldn't be allowed to do that. + MSVC_BLOCK_ENVIRONMENT_CHANGES=True, + MSVC_FLAVOR=('amd64', 'x86')[vc_flavor == 'x86'], + ) + + # Clear any existing paths. + env['ENV']['PATH'] = '' + env['ENV']['INCLUDE'] = '' + env['ENV']['LIB'] = '' + + tools_paths = [] + include_paths = [] + lib_paths = [] + + vc_bin_dir = vc_install_dir + '/bin' + vc_first_bin_dir = '' + vc_second_bin_dir = '' + if vc_flavor == 'x86_x86': + vc_first_bin_dir = vc_bin_dir + '/Hostx86/x86' + elif vc_flavor == 'x64_x64': + vc_first_bin_dir = vc_bin_dir + '/Hostx64/x64' + elif vc_flavor == 'x86_x64': + vc_first_bin_dir = vc_bin_dir + '/Hostx86/x64' + vc_second_bin_dir = vc_bin_dir + '/Hostx86/x86' + elif vc_flavor == 'x64_x86': + vc_first_bin_dir = vc_bin_dir + '/Hostx64/x86' + vc_second_bin_dir = vc_bin_dir + '/HostX64/x64' + + tools_paths += [vc_first_bin_dir, + vc_second_bin_dir, # can be empty + vc_install_dir + '/team_tools/performance_tools', + vc_install_dir + '/Shared/Common/VSPerfCollectionTools'] + include_paths.append(vc_install_dir + '/include') + if (vc_flavor == 'x64_x86' or vc_flavor == 'x86_x86'): + tools_paths += [ + vc_redist_dir + '/x86/Microsoft.VC141.CRT', + ] + lib_paths.append(vc_install_dir + '/lib/x86') + tools_paths.append(platform_sdk_dir + '/bin/x86') + elif (vc_flavor == 'x64_x64' or vc_flavor == 'x86_x64'): + tools_paths += [ + vc_redist_dir + '/x64/Microsoft.VC141.CRT', + ] + lib_paths.append(vc_install_dir + '/lib/x64') + tools_paths.append(platform_sdk_dir + '/bin/x64') + + include_paths += [ + platform_sdk_include_dir + '/um', + platform_sdk_include_dir + '/shared', + platform_sdk_include_dir + '/ucrt', + ] + + if vc_flavor == 'x86_x86': + lib_paths += [ + platform_sdk_lib_dir + '/um/x86', + platform_sdk_lib_dir + '/ucrt/x86', + ] + tools_paths.append(platform_sdk_dir + '/bin/x86') + elif vc_flavor == 'x64_x64': + lib_paths += [ + platform_sdk_lib_dir + '/um/x64', + platform_sdk_lib_dir + '/ucrt/x64', + ] + tools_paths.append(platform_sdk_dir + '/bin/x64') + elif vc_flavor == 'x64_x86': + lib_paths += [ + platform_sdk_lib_dir + '/um/x86', + platform_sdk_lib_dir + '/ucrt/x86', + ] + tools_paths.append(platform_sdk_dir + '/bin/x64') + elif vc_flavor == 'x86_x64': + lib_paths += [ + platform_sdk_lib_dir + '/um/x64', + platform_sdk_lib_dir + '/ucrt/x64', + ] + tools_paths.append(platform_sdk_dir + '/bin/x86') + + for p in tools_paths: + env.AppendENVPath('PATH', env.Dir(p).abspath) + for p in include_paths: + env.AppendENVPath('INCLUDE', env.Dir(p).abspath) + for p in lib_paths: + env.AppendENVPath('LIB', env.Dir(p).abspath) diff --git a/omaha/site_scons/site_tools/windows_vc15_0_host64_x64.py b/omaha/site_scons/site_tools/windows_vc15_0_host64_x64.py new file mode 100644 index 0000000..bf3f598 --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc15_0_host64_x64.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=15.0, + vc_flavor='x64_x64') diff --git a/omaha/site_scons/site_tools/windows_vc15_0_host64_x86.py b/omaha/site_scons/site_tools/windows_vc15_0_host64_x86.py new file mode 100644 index 0000000..17ca81f --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc15_0_host64_x86.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=15.0, + vc_flavor='x64_x86') diff --git a/omaha/site_scons/site_tools/windows_vc15_0_host86_x64.py b/omaha/site_scons/site_tools/windows_vc15_0_host86_x64.py new file mode 100644 index 0000000..fdcce8b --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc15_0_host86_x64.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=15.0, + vc_flavor='x86_x64') diff --git a/omaha/site_scons/site_tools/windows_vc15_0_host86_x86.py b/omaha/site_scons/site_tools/windows_vc15_0_host86_x86.py new file mode 100644 index 0000000..59161b1 --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc15_0_host86_x86.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=15.0, + vc_flavor='x86_x86') diff --git a/omaha/site_scons/site_tools/windows_vc16_0_host64_x64.py b/omaha/site_scons/site_tools/windows_vc16_0_host64_x64.py new file mode 100644 index 0000000..adf0c0d --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc16_0_host64_x64.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=16.0, + vc_flavor='x64_x64') diff --git a/omaha/site_scons/site_tools/windows_vc16_0_host64_x86.py b/omaha/site_scons/site_tools/windows_vc16_0_host64_x86.py new file mode 100644 index 0000000..17861ed --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc16_0_host64_x86.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=16.0, + vc_flavor='x64_x86') diff --git a/omaha/site_scons/site_tools/windows_vc16_0_host86_x64.py b/omaha/site_scons/site_tools/windows_vc16_0_host86_x64.py new file mode 100644 index 0000000..8cc3ba0 --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc16_0_host86_x64.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=16.0, + vc_flavor='x86_x64') diff --git a/omaha/site_scons/site_tools/windows_vc16_0_host86_x86.py b/omaha/site_scons/site_tools/windows_vc16_0_host86_x86.py new file mode 100644 index 0000000..c16655d --- /dev/null +++ b/omaha/site_scons/site_tools/windows_vc16_0_host86_x86.py @@ -0,0 +1,34 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http:#www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ======================================================================== + +"""Tool-specific initialization for Visual Studio 2017. + +NOTE: This tool is order-dependent, and must be run before +any other tools that modify the binary, include, or lib paths because it will +wipe out any existing values for those variables. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +import windows_vc + + +def generate(env): + windows_vc.SetMsvcCompilerVersion(env=env, + version_num=16.0, + vc_flavor='x86_x86') diff --git a/omaha/standalone/utils.py b/omaha/standalone/utils.py index 624c5a0..47bf0ba 100644 --- a/omaha/standalone/utils.py +++ b/omaha/standalone/utils.py @@ -6,13 +6,7 @@ import array import base64 -try: - # Import _hashlib instead of hashlib, otherwise, when used in an Omaha build, - # it collides with the incompatible Scons hashlib hack in: - # googleclient/third_party/scons/hammer_version/scons-local/SCons/compat/_scons_hashlib.py - import _hashlib -except ImportError: - from third_party.hashlib import _hashlib +import hashlib import os @@ -49,7 +43,7 @@ def GenerateUpdateResponseFile(target, sources, version_list, has_x64_binaries): installer_file = open(os.path.abspath(binary_path), mode='rb') data.fromfile(installer_file, size) installer_file.close() - sha256 = _hashlib.openssl_sha256() + sha256 = hashlib.sha256() sha256.update(data) hash_value = sha256.hexdigest() diff --git a/omaha/statsreport/aggregator-win32.cc b/omaha/statsreport/aggregator-win32.cc index 4bf56f3..bbdce91 100644 --- a/omaha/statsreport/aggregator-win32.cc +++ b/omaha/statsreport/aggregator-win32.cc @@ -16,6 +16,8 @@ // Implementation of Win32 metrics aggregator. #include "omaha/statsreport/aggregator-win32.h" +#include + #include "omaha/base/safe_format.h" #include "omaha/statsreport/const-win32.h" #include "omaha/statsreport/util-win32.h" diff --git a/omaha/statsreport/aggregator-win32.h b/omaha/statsreport/aggregator-win32.h index f9ad30b..a8a0df2 100644 --- a/omaha/statsreport/aggregator-win32.h +++ b/omaha/statsreport/aggregator-win32.h @@ -78,7 +78,7 @@ class MetricsAggregatorWin32: public MetricsAggregator { /// Specifies HKLM or HKCU, respectively. bool is_machine_; - DISALLOW_EVIL_CONSTRUCTORS(MetricsAggregatorWin32); + DISALLOW_COPY_AND_ASSIGN(MetricsAggregatorWin32); }; } // namespace stats_report diff --git a/omaha/statsreport/aggregator.h b/omaha/statsreport/aggregator.h index 02cec72..f288d28 100644 --- a/omaha/statsreport/aggregator.h +++ b/omaha/statsreport/aggregator.h @@ -50,7 +50,7 @@ class MetricsAggregator { virtual void Aggregate(BoolMetric &metric) = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(MetricsAggregator); + DISALLOW_COPY_AND_ASSIGN(MetricsAggregator); const MetricCollection &coll_; }; diff --git a/omaha/statsreport/build.scons b/omaha/statsreport/build.scons index 688e107..62d1fd9 100644 --- a/omaha/statsreport/build.scons +++ b/omaha/statsreport/build.scons @@ -24,8 +24,10 @@ local_env.Append( '/we4018', '/we4365', - # enumerator in switch is not explicitly handled by a case label - '/wd4061', + + '/wd4061', # enumerator in switch is not explicitly handled by a + # case label + '/wd4365', #conversion from '' to '', signed/unsigned mismatch ], ) diff --git a/omaha/statsreport/const-win32.cc b/omaha/statsreport/const-win32.cc index 79106ff..ce25d91 100644 --- a/omaha/statsreport/const-win32.cc +++ b/omaha/statsreport/const-win32.cc @@ -16,6 +16,8 @@ // Constants for Win32 stats aggregation and uploading #include "const-win32.h" +#include + namespace stats_report { const wchar_t kTimingsKeyName[] = L"Timings"; diff --git a/omaha/statsreport/formatter.h b/omaha/statsreport/formatter.h index d219d89..5b0e7aa 100644 --- a/omaha/statsreport/formatter.h +++ b/omaha/statsreport/formatter.h @@ -50,7 +50,7 @@ class Formatter { const char *output() { output_ << std::ends; return output_.str(); } private: - DISALLOW_EVIL_CONSTRUCTORS(Formatter); + DISALLOW_COPY_AND_ASSIGN(Formatter); mutable std::strstream output_; }; diff --git a/omaha/statsreport/metrics.cc b/omaha/statsreport/metrics.cc index 6cf6a97..1e5b6de 100644 --- a/omaha/statsreport/metrics.cc +++ b/omaha/statsreport/metrics.cc @@ -15,6 +15,8 @@ // // Implements metrics and metrics collections #include "omaha/statsreport/metrics.h" +#include +#include #include "omaha/base/synchronized.h" namespace stats_report { @@ -25,9 +27,8 @@ MetricCollection &g_global_metrics = *static_cast(&g_global_metric_storage); #pragma warning(push) -// C4640: construction of local static object is not thread-safe. // C4073: initializers put in library initialization area. -#pragma warning(disable : 4640 4073) +#pragma warning(disable : 4073) // Serialize all metric manipulation and access under this lock. // @@ -50,7 +51,7 @@ class MetricBase::ObjectLock { private: MetricBase const *const metric_; - DISALLOW_EVIL_CONSTRUCTORS(MetricBase::ObjectLock); + DISALLOW_COPY_AND_ASSIGN(MetricBase::ObjectLock); }; void MetricBase::Lock() const { @@ -202,8 +203,7 @@ void TimingMetric::AddSamples(int64 count, int64 total_time_ms) { data_.maximum = time_ms; } - // TODO(omaha): truncation from 64 to 32 may occur here. - DCHECK_LE(count, kuint32max); + DCHECK_LE(count, std::numeric_limits::max()); data_.count += static_cast(count); data_.sum += total_time_ms; } diff --git a/omaha/statsreport/metrics.h b/omaha/statsreport/metrics.h index d809076..cc33a5c 100644 --- a/omaha/statsreport/metrics.h +++ b/omaha/statsreport/metrics.h @@ -14,10 +14,12 @@ // ======================================================================== // // Declares the interface to in-memory metrics capture + #ifndef OMAHA_STATSREPORT_METRICS_H__ #define OMAHA_STATSREPORT_METRICS_H__ #include + #include "base/basictypes.h" #include "omaha/base/highres_timer-win32.h" #include "omaha/base/logging/logging.h" @@ -166,7 +168,7 @@ class MetricBase { MetricCollectionBase *const coll_; private: - DISALLOW_EVIL_CONSTRUCTORS(MetricBase); + DISALLOW_COPY_AND_ASSIGN(MetricBase); }; /// Must be a POD @@ -212,7 +214,7 @@ class MetricCollection: public MetricCollectionBase { using MetricCollectionBase::initialized_; using MetricCollectionBase::first_; - DISALLOW_EVIL_CONSTRUCTORS(MetricCollection); + DISALLOW_COPY_AND_ASSIGN(MetricCollection); /// MetricBase is intimate with us friend class MetricBase; @@ -230,10 +232,16 @@ class MetricIterator: public std::iterator() { return curr_; } - MetricBase *operator->() const { + const MetricBase *operator->() const { return curr_; } MetricIterator operator++() { // preincrement @@ -296,7 +304,7 @@ class IntegerMetricBase: public MetricBase { int64 value_; private: - DISALLOW_EVIL_CONSTRUCTORS(IntegerMetricBase); + DISALLOW_COPY_AND_ASSIGN(IntegerMetricBase); }; /// A count metric is a cumulative counter of events. @@ -314,7 +322,7 @@ class CountMetric: public IntegerMetricBase { int64 Reset(); private: - DISALLOW_EVIL_CONSTRUCTORS(CountMetric); + DISALLOW_COPY_AND_ASSIGN(CountMetric); }; class TimingMetric: public MetricBase { @@ -362,7 +370,7 @@ class TimingMetric: public MetricBase { TimingData Reset(); private: - DISALLOW_EVIL_CONSTRUCTORS(TimingMetric); + DISALLOW_COPY_AND_ASSIGN(TimingMetric); void Clear(); @@ -414,7 +422,7 @@ class TimingSample { /// The item count we divide the captured time by uint32 count_; - DISALLOW_EVIL_CONSTRUCTORS(TimingSample); + DISALLOW_COPY_AND_ASSIGN(TimingSample); }; /// An integer metric is used to sample values that vary over time. @@ -436,7 +444,7 @@ class IntegerMetric: public IntegerMetricBase { void operator -= (int64 sub) { Subtract(sub); } private: - DISALLOW_EVIL_CONSTRUCTORS(IntegerMetric); + DISALLOW_COPY_AND_ASSIGN(IntegerMetric); }; /// A bool metric is tri-state, and can be: @@ -486,7 +494,7 @@ class BoolMetric: public MetricBase { TristateBoolValue value() const { return value_; }; private: - DISALLOW_EVIL_CONSTRUCTORS(BoolMetric); + DISALLOW_COPY_AND_ASSIGN(BoolMetric); TristateBoolValue value_; }; @@ -539,6 +547,6 @@ inline const BoolMetric &MetricBase::AsBool() const { return static_cast(*this); } -} // namespace stats_report +} // namespace stats_report #endif // OMAHA_STATSREPORT_METRICS_H__ diff --git a/omaha/statsreport/metrics_unittest.cc b/omaha/statsreport/metrics_unittest.cc index 380280a..13a63db 100644 --- a/omaha/statsreport/metrics_unittest.cc +++ b/omaha/statsreport/metrics_unittest.cc @@ -15,6 +15,7 @@ #include #include +#include #include "gtest/gtest.h" #include "omaha/statsreport/metrics.h" @@ -31,7 +32,12 @@ DEFINE_METRIC_integer(integer); DECLARE_METRIC_bool(bool); DEFINE_METRIC_bool(bool); -using namespace stats_report; +namespace stats_report { + +std::ostream& operator <<(std::ostream& str, const MetricIterator&it) { + str << std::hex << (void*)*it; + return str; +} namespace { @@ -83,13 +89,6 @@ TEST_F(MetricsTest, Globals) { EXPECT_STREQ("bool", metric_bool.name()); } - -// make GTest happy -inline std::ostream &operator << (std::ostream &str, const MetricIterator &it) { - str << std::hex << (void*)*it; - return str; -} - TEST_F(MetricsTest, CollectionInitialization) { // The global MetricCollection is aliased to zero memory so as to ensure // no initialization order snafus. If an initialized MetricCollection @@ -359,3 +358,4 @@ TEST_F(MetricsTest, SimpleConstruction) { EXPECT_TRUE(NULL == bool_false.next()); } +} // namespace stats_reports diff --git a/omaha/statsreport/persistent_iterator-win32.h b/omaha/statsreport/persistent_iterator-win32.h index 1a6efb6..8611a05 100644 --- a/omaha/statsreport/persistent_iterator-win32.h +++ b/omaha/statsreport/persistent_iterator-win32.h @@ -21,7 +21,6 @@ #include #include -#include "base/scoped_ptr.h" #include "omaha/base/safe_format.h" #include "omaha/statsreport/metrics.h" #include "omaha/statsreport/const-win32.h" @@ -116,7 +115,7 @@ class PersistentMetricsIteratorWin32 CStringA current_value_name_; /// The metric under the iterator - scoped_ptr current_value_; + std::unique_ptr current_value_; /// Specifies HKLM or HKCU, respectively. bool is_machine_; diff --git a/omaha/test/build.scons b/omaha/test/build.scons index c4646ae..3575eb7 100644 --- a/omaha/test/build.scons +++ b/omaha/test/build.scons @@ -105,7 +105,7 @@ def BuildMSI(version, namespace, exe_name, wxs_template, msi_base_name, # The metainstaller change does not get passed through even though the # .wixobj file is rebuilt because the hash of the .wixobj does not change. - metainstaller_path = '$STAGING_DIR/%sGoogleUpdateSetup.exe' % (prefix) + metainstaller_path = '$STAGING_DIR/%sBraveUpdateSetup.exe' % (prefix) google_update_wixobj = build_enterprise_installer.BuildGoogleUpdateFragment( env, metainstaller_path, diff --git a/omaha/test/test_foo.rc b/omaha/test/test_foo.rc index a9d997b..c0c454f 100644 --- a/omaha/test/test_foo.rc +++ b/omaha/test/test_foo.rc @@ -22,7 +22,7 @@ // // Generated from the TEXTINCLUDE 2 resource. // -#include "afxres.h" +#include ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS @@ -49,7 +49,7 @@ END 2 TEXTINCLUDE BEGIN - "#include ""afxres.h""\r\n" + "#include ""winres.h""\r\n" "\0" END @@ -83,10 +83,10 @@ BEGIN BEGIN BLOCK "040904e4" BEGIN - VALUE "CompanyName", "Google Inc." + VALUE "CompanyName", "Google LLC" VALUE "FileDescription", "test_foo.exe" VALUE "FileVersion", VERSION_STRING - VALUE "LegalCopyright", "Copyright 2007-2010 Google Inc." + VALUE "LegalCopyright", "Copyright 2018 Google LLC" VALUE "InternalName", "test_foo.exe" VALUE "OriginalFilename", "test_foo.exe" VALUE "ProductName", "test_foo.exe" diff --git a/omaha/test/test_foo.wxs.xml b/omaha/test/test_foo.wxs.xml index e505cd8..b733f9b 100644 --- a/omaha/test/test_foo.wxs.xml +++ b/omaha/test/test_foo.wxs.xml @@ -86,11 +86,11 @@ @@ -98,11 +98,11 @@ NOT NOTIFY_FAILURE AND NOT DO_NOT_NOTIFY_SUCCESS @@ -111,7 +111,7 @@ REGISTER_LAUNCH_COMMAND AND NOT DO_NOT_NOTIFY_SUCCESS @@ -128,15 +128,15 @@ NOTIFY_FAILURE @@ -144,7 +144,7 @@ PROPBAR=7 diff --git a/omaha/testing/build.scons b/omaha/testing/build.scons index 83699d8..7c7fa1c 100644 --- a/omaha/testing/build.scons +++ b/omaha/testing/build.scons @@ -51,6 +51,7 @@ unittest_support = env.Replicate('$STAGING_DIR/unittest_support/', [ 'unittest_support/chrome_certificate_09E28B26DB593EC4E73286B66499C370.dll', # Chrome certificate: sha1 (01/28/2014 to 01/29/2016) 'unittest_support/chrome_certificate_2912C70C9A2B8A3EF6F6074662D68B8D.dll', + 'unittest_support/CodeRed.crx3', 'unittest_support/GoogleUpdate_corrupted.exe', 'unittest_support/GoogleUpdate_now_expired_cert.exe', 'unittest_support/GoogleUpdate_old_signature.exe', @@ -81,6 +82,14 @@ unittest_support = env.Replicate('$STAGING_DIR/unittest_support/', [ # serial=2a9c21acaaa63a3c58a7b9322bee948d 'unittest_support/sha2_2a9c21acaaa63a3c58a7b9322bee948d.exe', + # Omaha and Chrome certificate: sha256 (11/06/2018 to 11/17/2021). + # serial=0c15be4a15bb0903c901b1d6c265302f + 'unittest_support/sha2_0c15be4a15bb0903c901b1d6c265302f.msi', + + # The actual Chrome setup signed with sha256 (11/06/2018 to 11/17/2021). + # serial=0c15be4a15bb0903c901b1d6c265302f + 'unittest_support/chrome_setup.exe', + # Minidump file for the crash unit test. 'unittest_support/minidump.dmp', 'unittest_support/minidump.txt', @@ -224,6 +233,17 @@ omaha_unittest_libs = [ 'ws2_32.lib', 'wtsapi32.lib', ] +if omaha_unittest_env.Bit('has_device_management'): + protobuf_src_dir = os.getenv('OMAHA_PROTOBUF_SRC_DIR', + '$GOOGLE3/third_party/protobuf/src') + omaha_unittest_libs.append('$LIB_DIR/dm_proto.lib') + omaha_unittest_env.Append( + CPPPATH = [ + '$GOOGLE3', + protobuf_src_dir, + '$TARGET_ROOT/proto_files', + ], + ) # Add conditional lib dependencies. if omaha_unittest_env.IsBuildingModule('mi_exe_stub'): @@ -250,13 +270,18 @@ omaha_unittest_libs += omaha_unittest_env.GetAllInOneUnittestLibs() omaha_unittest_env.Append( CPPPATH = [ '$OBJ_ROOT', # Needed for the generated files - '$THIRD_PARTY/gmock/include', - '$THIRD_PARTY/gtest/include', + '$THIRD_PARTY/googletest/googlemock/include', + '$THIRD_PARTY/googletest/googletest/include', ], CCFLAGS = [ + '/wd4100', # unreferenced formal parameter + '/wd4244', # possible loss of data '/wd4388', # signed/unsigned mismatch '/wd4389', # signed/unsigned mismatch + '/wd4647', # behavior change: __is_pod(type) has different value + '/wd4800', # forcing value to bool 'true' or 'false' '/wd4826', # Conversion from 'type_1' to 'type_2' is sign-extended. + '/wd4946', # reinterpret_cast used between related classes # Disable static analysis warnings. '/wd6326', # Potential comparison of a constant with another constant. @@ -297,12 +322,12 @@ unittest_base_env.Append( ], ) -unittest_base_env.ComponentStaticLibrary( +unittest_base_env.ComponentLibrary( 'unittest_base', [ 'omaha_unittest.cc', 'unit_test.cc', ] ) -unittest_base_env.ComponentStaticLibrary( +unittest_base_env.ComponentLibrary( 'unittest_base_large_with_network', [ 'unittest_base.lib', 'omaha_unittest_main.cc', @@ -310,12 +335,12 @@ unittest_base_env.ComponentStaticLibrary( ] ) -unittest_base_env.ComponentStaticLibrary( +unittest_base_env.ComponentLibrary( 'unittest_base_small', [ 'unittest_base.lib', 'omaha_unittest_main_small_tests.cc', ] ) -unittest_base_env.ComponentStaticLibrary( +unittest_base_env.ComponentLibrary( 'unittest_base_small_with_resources', [ 'unittest_base.lib', 'omaha_unittest_main_small_tests_with_resources.cc', @@ -347,33 +372,25 @@ omaha_unittest_inputs = [ '../base/event_trace_provider_unittest.cc', '../base/extractor_unittest.cc', '../base/file_reader_unittest.cc', - '../base/file_store_unittest.cc', '../base/file_unittest.cc', '../base/firewall_product_detection_unittest.cc', '../base/highres_timer_unittest.cc', - '../base/localization_unittest.cc', - '../base/lock_ptr_unittest.cc', '../base/logging_unittest.cc', - '../base/md5_unittest.cc', '../base/omaha_version_unittest.cc', '../base/path_unittest.cc', - '../base/pe_utils_unittest.cc', '../base/proc_utils_unittest.cc', '../base/process_unittest.cc', '../base/queue_timer_unittest.cc', '../base/reactor_unittest.cc', '../base/reg_key_unittest.cc', '../base/registry_monitor_manager_unittest.cc', - '../base/registry_store_unittest.cc', '../base/safe_format_unittest.cc', '../base/scoped_impersonation_unittest.cc', '../base/scoped_ptr_cotask_unittest.cc', - '../base/serializable_object_unittest.cc', '../base/service_utils_unittest.cc', '../base/shell_unittest.cc', '../base/signatures_unittest.cc', '../base/signaturevalidator_unittest.cc', - '../base/sta_unittest.cc', '../base/string_unittest.cc', '../base/synchronized_unittest.cc', '../base/system_unittest.cc', @@ -429,6 +446,7 @@ omaha_unittest_inputs = [ '../common/scheduled_task_utils_unittest.cc', '../common/stats_uploader_unittest.cc', '../common/update_request_unittest.cc', + '../common/url_utils_unittest.cc', '../common/webplugin_utils_unittest.cc', '../common/web_services_client_unittest.cc', '../common/xml_parser_unittest.cc', @@ -438,6 +456,7 @@ omaha_unittest_inputs = [ # Core unit tests '../core/core_unittest.cc', + '../core/scheduler_unittest.cc', '../core/system_monitor_unittest.cc', '../core/google_update_core_unittest.cc', @@ -528,8 +547,17 @@ omaha_unittest_inputs = [ '../third_party/chrome/files/src/base/cpu_unittest.cc', '../third_party/chrome/files/src/base/rand_util_unittest.cc', '../third_party/chrome/files/src/crypto/rsa_private_key_unittest.cc', + '../third_party/chrome/files/src/crypto/signature_creator_unittest.cc', + '../third_party/chrome/files/src/crypto/signature_verifier_win_unittest.cc', ] +if omaha_unittest_env.Bit('has_device_management'): + omaha_unittest_inputs += [ + '../goopdate/dm_client_unittest.cc', + '../goopdate/dm_storage_test_utils.cc', + '../goopdate/dm_storage_unittest.cc', + ] + # Conditionally built unit tests. if omaha_unittest_env.IsBuildingModule('mi_exe_stub'): omaha_unittest_inputs += [ @@ -580,9 +608,6 @@ omaha_unittest_env['OBJPREFIX'] = omaha_unittest_env['OBJPREFIX'] + 'testing/' target_name = 'omaha_unittest' -if env.Bit('use_precompiled_headers'): - omaha_unittest_inputs += omaha_unittest_env.EnablePrecompile(target_name) - # omaha_unittest can be built as a test program in 'tests\' or a normal program # in 'staging\'. # TODO(omaha3): Switch entirely to the former. @@ -625,7 +650,7 @@ omaha_unittest_env.Depends(test, unittest_support) # extractor_unittest.cc uses GoogleUpdateSetup_repair.exe as a zero-length tag # cert-tagged exe. -omaha_unittest_env.Depends(test, '$STAGING_DIR/GoogleUpdateSetup_repair.exe') +omaha_unittest_env.Depends(test, '$STAGING_DIR/BraveUpdateSetup_repair.exe') # Customization/UI tests depend on goopdate.dll (for TypeLib/resources) omaha_unittest_env.Depends(test, '$TESTS_DIR/goopdate.dll') @@ -682,9 +707,6 @@ if env.Bit('all'): '$MAIN_DIR/VERSION' ) - if env.Bit('use_precompiled_headers'): - unsigned_inputs += save_args_env.EnablePrecompile(target_name) - # Build the *unsigned* executeable unsigned_output = save_args_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/testing/omaha_unittest.cc b/omaha/testing/omaha_unittest.cc index f2021b7..8dd66b8 100644 --- a/omaha/testing/omaha_unittest.cc +++ b/omaha/testing/omaha_unittest.cc @@ -23,9 +23,9 @@ #include "omaha/base/logging.h" #include "omaha/base/omaha_version.h" #include "omaha/base/safe_format.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/vistautil.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/testing/omaha_unittest.rc b/omaha/testing/omaha_unittest.rc index 9d8d04b..37e2472 100644 Binary files a/omaha/testing/omaha_unittest.rc and b/omaha/testing/omaha_unittest.rc differ diff --git a/omaha/testing/omaha_unittest_version.rc b/omaha/testing/omaha_unittest_version.rc index 4e3b5cc..5e20689 100644 --- a/omaha/testing/omaha_unittest_version.rc +++ b/omaha/testing/omaha_unittest_version.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US diff --git a/omaha/testing/save_arguments.cc b/omaha/testing/save_arguments.cc index b11ebf2..7765c24 100644 --- a/omaha/testing/save_arguments.cc +++ b/omaha/testing/save_arguments.cc @@ -21,7 +21,7 @@ #include #include #include "omaha/base/app_util.h" -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace { diff --git a/omaha/testing/save_arguments_version.rc b/omaha/testing/save_arguments_version.rc index 08e779d..7320982 100644 --- a/omaha/testing/save_arguments_version.rc +++ b/omaha/testing/save_arguments_version.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US diff --git a/omaha/testing/ui/build.scons b/omaha/testing/ui/build.scons index 146ae9a..039411f 100644 --- a/omaha/testing/ui/build.scons +++ b/omaha/testing/ui/build.scons @@ -99,8 +99,6 @@ inputs = [ '../../worker/progresswnd_unittest.cc', unittest_res, ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/testing/ui/ui_unittest.rc b/omaha/testing/ui/ui_unittest.rc index 4b1cdfa..80dcaad 100644 --- a/omaha/testing/ui/ui_unittest.rc +++ b/omaha/testing/ui/ui_unittest.rc @@ -15,7 +15,7 @@ #include "omaha/goopdate/resource.h" -#include +#include #include "omaha/goopdate/resources/goopdateres/generated_resources_en.rc" diff --git a/omaha/testing/unit_test.cc b/omaha/testing/unit_test.cc index 622b15d..9799ce4 100644 --- a/omaha/testing/unit_test.cc +++ b/omaha/testing/unit_test.cc @@ -20,7 +20,6 @@ #include "omaha/base/path.h" #include "omaha/base/process.h" #include "omaha/base/reg_key.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/string.h" #include "omaha/base/system.h" #include "omaha/base/utils.h" @@ -29,6 +28,7 @@ #include "omaha/common/command_line.h" #include "omaha/common/command_line_builder.h" #include "omaha/common/const_goopdate.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { @@ -267,7 +267,9 @@ void LaunchProcess(const CString& exe_path, CString launch_cmd = exe_path; EnclosePath(&launch_cmd); - launch_cmd += args.IsEmpty() ? _T("") : _T(" ") + args; + if (!args.IsEmpty()) { + launch_cmd += CString(_T(" ")) + args; + } if (as_system) { // Retry the process launch if the process handle is invalid. Hopefully this @@ -367,3 +369,8 @@ void CreateFiles(const TCHAR* parent_dir, } } // namespace omaha + +std::ostream& operator<<(std::ostream& os, const CString& str) { + ::testing::internal::UniversalPrint(str.GetString(), &os); + return os; +} diff --git a/omaha/testing/unit_test.h b/omaha/testing/unit_test.h index 87a8f1d..fc85e84 100644 --- a/omaha/testing/unit_test.h +++ b/omaha/testing/unit_test.h @@ -20,15 +20,9 @@ #include #include -#include "base/scoped_ptr.h" -#pragma warning(push) -// C4628: digraphs not supported with -Ze. -#pragma warning(disable : 4628) #include "gmock/gmock.h" #include "gtest/gtest.h" -#pragma warning(pop) - #include "omaha/testing/unittest_debug_helper.h" namespace omaha { @@ -243,4 +237,7 @@ void CreateFiles(const TCHAR* parent_dir, UNREFERENCED_PARAMETER(arg8); \ UNREFERENCED_PARAMETER(arg9) +// Teach Google Test how to print a CString. +std::ostream& operator<<(std::ostream& os, const CString& str); + #endif // OMAHA_TESTING_UNIT_TEST_H_ diff --git a/omaha/testing/unittest_debug_helper.h b/omaha/testing/unittest_debug_helper.h index 1f3d73d..b315823 100644 --- a/omaha/testing/unittest_debug_helper.h +++ b/omaha/testing/unittest_debug_helper.h @@ -52,7 +52,7 @@ class UseAssertFunction { private: DebugAssertFunctionType *old_function_; - DISALLOW_EVIL_CONSTRUCTORS(UseAssertFunction); + DISALLOW_COPY_AND_ASSIGN(UseAssertFunction); }; @@ -78,7 +78,7 @@ class FailOnAssert { private: UseAssertFunction inner_; - DISALLOW_EVIL_CONSTRUCTORS(FailOnAssert); + DISALLOW_COPY_AND_ASSIGN(FailOnAssert); }; // A class with no methods which will cause asserts to be ignored; @@ -102,7 +102,7 @@ class IgnoreAsserts { private: UseAssertFunction inner_; - DISALLOW_EVIL_CONSTRUCTORS(IgnoreAsserts); + DISALLOW_COPY_AND_ASSIGN(IgnoreAsserts); }; // A class with no methods which will cause asserts to be counted but otherwise @@ -138,9 +138,9 @@ class ExpectAsserts { } } - int old_assert_count_; UseAssertFunction inner_; - DISALLOW_EVIL_CONSTRUCTORS(ExpectAsserts); + int old_assert_count_; + DISALLOW_COPY_AND_ASSIGN(ExpectAsserts); }; } // namespace omaha diff --git a/omaha/testing/unittest_support/CodeRed.crx3 b/omaha/testing/unittest_support/CodeRed.crx3 new file mode 100644 index 0000000..b3853d8 Binary files /dev/null and b/omaha/testing/unittest_support/CodeRed.crx3 differ diff --git a/omaha/testing/unittest_support/SaveArguments.exe b/omaha/testing/unittest_support/SaveArguments.exe index 044aa5a..228ff4b 100644 Binary files a/omaha/testing/unittest_support/SaveArguments.exe and b/omaha/testing/unittest_support/SaveArguments.exe differ diff --git a/omaha/testing/unittest_support/chrome_setup.exe b/omaha/testing/unittest_support/chrome_setup.exe new file mode 100644 index 0000000..44c763c Binary files /dev/null and b/omaha/testing/unittest_support/chrome_setup.exe differ diff --git a/omaha/testing/unittest_support/sha2_0c15be4a15bb0903c901b1d6c265302f.msi b/omaha/testing/unittest_support/sha2_0c15be4a15bb0903c901b1d6c265302f.msi new file mode 100644 index 0000000..d2d2dcb Binary files /dev/null and b/omaha/testing/unittest_support/sha2_0c15be4a15bb0903c901b1d6c265302f.msi differ diff --git a/omaha/third_party/bar/shared_ptr.h b/omaha/third_party/bar/shared_ptr.h deleted file mode 100644 index 5f70388..0000000 --- a/omaha/third_party/bar/shared_ptr.h +++ /dev/null @@ -1,438 +0,0 @@ -// Copyright 2006 and onwards Google Inc. -// Author: Michael Ellman (with suggestions from jrvb, m3b, toddw, jwray) -// -// A simple reference counted pointer implementation. It is a subset -// of the boost/tr1 shared_ptr class, which is expected to be part of -// the next C++ standard. See section 20.8.10 [util.smartptr] of the -// draft standard for a full description of the standard interface. -// -// Standard features that have been omitted from this implementation include: -// - no custom deallocators - uses delete -// - shared_ptr's constructor isn't templated: its argument is just T*. -// - no support for smart pointer casts -// - no support for unowned pointers -// - no support for variadic templates or rvalue references -// - no integration with auto_ptr or unique_ptr -// - not exception-safe -// - no overloaded comparison operators (e.g. operator<). They're -// convenient, but they can be explicitly defined outside the class. -// -// It's usually the case that when you want to share an object, there -// is a clear owner that outlives the other users. If that's the case, -// the owner can use scoped_ptr and the rest can use a raw pointer. -// -// A somewhat common design pattern that doesn't have a clear object -// owner is when there is a shared container in which older versions -// of an object are replaced with newer versions. The objects should be -// deleted only when (a) they are replaced with a new version and (b) -// there are no outside users of the old version. Replacing raw pointers -// in the implementation with shared_ptr's ensures that the accounting -// and object lifetimes are handled appropriately. -// -// The typical usage is as follows. -// -// 1. Functions using shared_ptr's should declare shared_ptr parameters to -// be of type const reference since the caller will still have its own -// shared_ptr for the entire call. -// -// void foo(const shared_ptr& param) -// -// 2. Functions setting shared_ptr's should declare shared_ptr parameters -// to be of pointer type. -// -// typedef map > MyMap; -// void GetAndSharedObject(const Key& key, shared_ptr* value) { -// ReaderMutexLock l(&lock_); -// MyMap::iterator iter = shared_container.find(key); -// *value = iter->second; -// } -// -// Thread Safety: -// Once constructed, a shared_ptr has the same thread-safety as built-in -// types. In particular, it is safe to read a shared object simultaneously -// from multiple threads. -// -// Weak ptrs -// The weak_ptr auxiliary class (see clause 20.8.10.3 of the draft standard) -// is used to break ownership cycles. A weak_ptr points to an object that's -// owned by a shared_ptr, but the weak_ptr is an observer, not an owner. When -// the last shared_ptr that points to the object disappears, the weak_ptr -// expires, at which point the expired() member function will return true. -// -// You can't directly get a raw pointer from weak_ptr, i.e. it has no get() -// or operator*() member function. (These features were intentionally left out -// to avoid the risk of dangling pointers.) To access a weak_ptr's pointed-to -// object, use lock() to obtain a temporary shared_ptr. -// -// enable_shared_from_this -// A user-defined class T can inherit from enable_shared_from_this (see -// clause 20.8.10.5 of the draft standard) to inherit T::shared_from_this(), -// which returns a shared_ptr pointing to *this. It is similar to weak_ptr in -// that there must already be at least one shared_ptr instance that owns -// *this. - -#ifndef BAR_COMMON_SHARED_PTR_H_ -#define BAR_COMMON_SHARED_PTR_H_ - -#include -#include // for swap - -template class shared_ptr; -template class weak_ptr; - -// This class is an internal implementation detail for shared_ptr. If two -// shared_ptrs point to the same object, they also share a control block. -// An "empty" shared_pointer refers to NULL and also has a NULL control block. -// It contains all of the state that's needed for reference counting or any -// other kind of resource management. In this implementation the control block -// happens to consist of two atomic words, the reference count (the number -// of shared_ptrs that share ownership of the object) and the weak count -// (the number of weak_ptrs that observe the object, plus 1 if the -// refcount is nonzero). -// -// The "plus 1" is to prevent a race condition in the shared_ptr and -// weak_ptr destructors. We need to make sure the control block is -// only deleted once, so we need to make sure that at most one -// object sees the weak count decremented from 1 to 0. -class SharedPtrControlBlock { - template friend class shared_ptr; - template friend class weak_ptr; - private: - SharedPtrControlBlock() : refcount_(1), weak_count_(1) { } - LONG refcount_; - LONG weak_count_; -}; - -// Forward declaration. The class is defined below. -template class enable_shared_from_this; - -template -class shared_ptr { - template friend class weak_ptr; - public: - typedef T element_type; - - explicit shared_ptr(T* ptr = NULL) - : ptr_(ptr), - control_block_(ptr != NULL ? new SharedPtrControlBlock : NULL) { - // If p is non-null and T inherits from enable_shared_from_this, we - // set up the data that shared_from_this needs. - MaybeSetupWeakThis(ptr); - } - - // Copy constructor: makes this object a copy of ptr, and increments - // the reference count. - template - shared_ptr(const shared_ptr& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - // Need non-templated version to prevent the compiler-generated default - shared_ptr(const shared_ptr& ptr) - : ptr_(NULL), - control_block_(NULL) { - Initialize(ptr); - } - - // Assignment operator. Replaces the existing shared_ptr with ptr. - // Increment ptr's reference count and decrement the one being replaced. - template - shared_ptr& operator=(const shared_ptr& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // Need non-templated version to prevent the compiler-generated default - shared_ptr& operator=(const shared_ptr& ptr) { - if (ptr_ != ptr.ptr_) { - shared_ptr me(ptr); // will hold our previous state to be destroyed. - swap(me); - } - return *this; - } - - // TODO(austern): Consider providing this constructor. The draft C++ standard - // (20.8.10.2.1) includes it. However, it says that this constructor throws - // a bad_weak_ptr exception when ptr is expired. Is it better to provide this - // constructor and make it do something else, like fail with a CHECK, or to - // leave this constructor out entirely? - // - // template - // shared_ptr(const weak_ptr& ptr); - - ~shared_ptr() { - if (ptr_ != NULL) { - if (::InterlockedDecrement(&control_block_->refcount_) == 0) { - delete ptr_; - - // weak_count_ is defined as the number of weak_ptrs that observe - // ptr_, plus 1 if refcount_ is nonzero. - if (::InterlockedDecrement(&control_block_->weak_count_) == 0) { - delete control_block_; - } - } - } - } - - // Replaces underlying raw pointer with the one passed in. The reference - // count is set to one (or zero if the pointer is NULL) for the pointer - // being passed in and decremented for the one being replaced. - void reset(T* p = NULL) { - if (p != ptr_) { - shared_ptr tmp(p); - tmp.swap(*this); - } - } - - // Exchanges the contents of this with the contents of r. This function - // supports more efficient swapping since it eliminates the need for a - // temporary shared_ptr object. - void swap(shared_ptr& r) { - std::swap(ptr_, r.ptr_); - std::swap(control_block_, r.control_block_); - } - - // The following function is useful for gaining access to the underlying - // pointer when a shared_ptr remains in scope so the reference-count is - // known to be > 0 (e.g. for parameter passing). - T* get() const { - return ptr_; - } - - T& operator*() const { - return *ptr_; - } - - T* operator->() const { - return ptr_; - } - - LONG use_count() const { - return control_block_ ? control_block_->refcount_ : 1; - } - - bool unique() const { - return use_count() == 1; - } - - private: - // If r is non-empty, initialize *this to share ownership with r, - // increasing the underlying reference count. - // If r is empty, *this remains empty. - // Requires: this is empty, namely this->ptr_ == NULL. - template - void Initialize(const shared_ptr& r) { - if (r.control_block_ != NULL) { - ::InterlockedIncrement(&r.control_block_->refcount_); - - ptr_ = r.ptr_; - control_block_ = r.control_block_; - } - } - - // Helper function for the constructor that takes a raw pointer. If T - // doesn't inherit from enable_shared_from_this then we have nothing to - // do, so this function is trivial and inline. The other version is declared - // out of line, after the class definition of enable_shared_from_this. - void MaybeSetupWeakThis(enable_shared_from_this* ptr); - void MaybeSetupWeakThis(...) { } - - T* ptr_; - SharedPtrControlBlock* control_block_; - - template - friend class shared_ptr; -}; - -// Matches the interface of std::swap as an aid to generic programming. -template void swap(shared_ptr& r, shared_ptr& s) { - r.swap(s); -} - -// See comments at the top of the file for a description of why this -// class exists, and the draft C++ standard (as of July 2009 the -// latest draft is N2914) for the detailed specification. -template -class weak_ptr { - template friend class weak_ptr; - public: - typedef T element_type; - - // Create an empty (i.e. already expired) weak_ptr. - weak_ptr() : ptr_(NULL), control_block_(NULL) { } - - // Create a weak_ptr that observes the same object that ptr points - // to. Note that there is no race condition here: we know that the - // control block can't disappear while we're looking at it because - // it is owned by at least one shared_ptr, ptr. - template weak_ptr(const shared_ptr& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Copy a weak_ptr. The object it points to might disappear, but we - // don't care: we're only working with the control block, and it can't - // disappear while we're looking at because it's owned by at least one - // weak_ptr, ptr. - template weak_ptr(const weak_ptr& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Need non-templated version to prevent default copy constructor - weak_ptr(const weak_ptr& ptr) { - CopyFrom(ptr.ptr_, ptr.control_block_); - } - - // Destroy the weak_ptr. If no shared_ptr owns the control block, and if - // we are the last weak_ptr to own it, then it can be deleted. Note that - // weak_count_ is defined as the number of weak_ptrs sharing this control - // block, plus 1 if there are any shared_ptrs. We therefore know that it's - // safe to delete the control block when weak_count_ reaches 0, without - // having to perform any additional tests. - ~weak_ptr() { - if (control_block_ != NULL && - ::InterlockedDecrement(&control_block_->weak_count_) == 0) { - delete control_block_; - } - } - - weak_ptr& operator=(const weak_ptr& ptr) { - if (&ptr != this) { - weak_ptr tmp(ptr); - tmp.swap(*this); - } - return *this; - } - template weak_ptr& operator=(const weak_ptr& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - template weak_ptr& operator=(const shared_ptr& ptr) { - weak_ptr tmp(ptr); - tmp.swap(*this); - return *this; - } - - void swap(weak_ptr& ptr) { - std::swap(ptr_, ptr.ptr_); - std::swap(control_block_, ptr.control_block_); - } - - void reset() { - weak_ptr tmp; - tmp.swap(*this); - } - - // Return the number of shared_ptrs that own the object we are observing. - // Note that this number can be 0 (if this pointer has expired). - LONG use_count() const { - return control_block_ != NULL ? control_block_->refcount_ : 0; - } - - bool expired() const { return use_count() == 0; } - - // Return a shared_ptr that owns the object we are observing. If we - // have expired, the shared_ptr will be empty. We have to be careful - // about concurrency, though, since some other thread might be - // destroying the last owning shared_ptr while we're in this - // function. We want to increment the refcount only if it's nonzero - // and get the new value, and we want that whole operation to be - // atomic. - shared_ptr lock() const { - shared_ptr result; - if (control_block_ != NULL) { - LONG old_refcount; - do { - old_refcount = control_block_->refcount_; - if (old_refcount == 0) - break; - } while (old_refcount != - ::InterlockedCompareExchange( - &control_block_->refcount_, old_refcount + 1, - old_refcount)); - if (old_refcount > 0) { - result.ptr_ = ptr_; - result.control_block_ = control_block_; - } - } - - return result; - } - - private: - void CopyFrom(T* ptr, SharedPtrControlBlock* control_block) { - ptr_ = ptr; - control_block_ = control_block; - if (control_block_ != NULL) - ::InterlockedIncrement(&control_block_->weak_count_); - } - - private: - element_type* ptr_; - SharedPtrControlBlock* control_block_; -}; - -template void swap(weak_ptr& r, weak_ptr& s) { - r.swap(s); -} - -// See comments at the top of the file for a description of why this class -// exists, and section 20.8.10.5 of the draft C++ standard (as of July 2009 -// the latest draft is N2914) for the detailed specification. -template -class enable_shared_from_this { - friend class shared_ptr; - public: - // Precondition: there must be a shared_ptr that owns *this and that was - // created, directly or indirectly, from a raw pointer of type T*. (The - // latter part of the condition is technical but not quite redundant; it - // rules out some complicated uses involving inheritance hierarchies.) - shared_ptr shared_from_this() { - // Behavior is undefined if the precondition isn't satisfied; we choose - // to die with an access violation exception. -#if DEBUG - if (weak_this_.expired()) { - // No shared_ptr owns this object. - *static_cast(NULL) = 0; - } -#endif - return weak_this_.lock(); - } - shared_ptr shared_from_this() const { -#if DEBUG - if (weak_this_.expired()) { - // No shared_ptr owns this object. - *static_cast(NULL) = 0; - } -#endif - return weak_this_.lock(); - } - - protected: - enable_shared_from_this() { } - enable_shared_from_this(const enable_shared_from_this& other) { } - enable_shared_from_this& operator=(const enable_shared_from_this& other) { - return *this; - } - ~enable_shared_from_this() { } - - private: - weak_ptr weak_this_; -}; - -// This is a helper function called by shared_ptr's constructor from a raw -// pointer. If T inherits from enable_shared_from_this, it sets up -// weak_this_ so that shared_from_this works correctly. If T does not inherit -// from weak_this we get a different overload, defined inline, which does -// nothing. -template -void shared_ptr::MaybeSetupWeakThis(enable_shared_from_this* ptr) { - if (ptr) - ptr->weak_this_ = *this; -} - -#endif // BAR_COMMON_SHARED_PTR_H_ diff --git a/omaha/third_party/build.scons b/omaha/third_party/build.scons index 4ab9ef1..beaa2d2 100644 --- a/omaha/third_party/build.scons +++ b/omaha/third_party/build.scons @@ -54,13 +54,8 @@ breakpad_env.ComponentStaticLibraryMultiarch(target_name, breakpad_inputs) # gtest_env = env.Clone() -if gtest_env.Bit('is_google_update_build'): - _gtest_repository = '$THIRD_PARTY/gtest' -else: - _gtest_repository ='$THIRD_PARTY/googletest/googletest' - +_gtest_repository ='$THIRD_PARTY/googletest/googletest' gtest_env.Dir('gtest').addRepository(env.Dir(_gtest_repository)) - gtest_env.Append( CCFLAGS = [ '/wd4061', # enumerator in switch is not handled by a case label @@ -80,9 +75,6 @@ gtest_env.Append( target_name = 'gtest' gtest_inputs = [ 'gtest/src/gtest-all.cc' ] -if env.Bit('use_precompiled_headers'): - gtest_inputs += gtest_env.EnablePrecompile(target_name) - gtest_env.ComponentLibrary( lib_name=target_name, source=gtest_inputs, @@ -93,13 +85,9 @@ gtest_env.ComponentLibrary( # gmock_env = env.Clone() -if gmock_env.Bit('is_google_update_build'): - _gmock_repository = '$THIRD_PARTY/gmock' -else: - _gmock_repository ='$THIRD_PARTY/googletest/googlemock' +_gmock_repository ='$THIRD_PARTY/googletest/googlemock' gmock_env.Dir('gmock').addRepository(env.Dir(_gmock_repository)) - gmock_env.Append( CCFLAGS = [ '/wd4061', # enumerator is not explicitly handled by a case label @@ -116,10 +104,6 @@ gmock_env.Append( target_name = 'gmock' gmock_inputs = [ 'gmock/src/gmock-all.cc' ] - -if env.Bit('use_precompiled_headers'): - gmock_inputs += gmock_env.EnablePrecompile(target_name) - gmock_env.ComponentLibrary( lib_name=target_name, source=gmock_inputs, @@ -131,6 +115,12 @@ gmock_env.ComponentLibrary( lzma_env = env.Clone() lzma_env.Dir('lzma').addRepository(env.Dir('$THIRD_PARTY/lzma')) lzma_env.FilterOut(CCFLAGS=['/RTC1']) +lzma_env.Append( + CCFLAGS = [ + '/wd4456', # declaration of '...' hides previous local declaration + '/wd4457', # declaration of '...' hides function parameter + ], +) lzma_env.ComponentLibrary( lib_name='lzma', source=[ @@ -139,4 +129,3 @@ lzma_env.ComponentLibrary( 'lzma/files/C/LzmaDec.c', ], ) - diff --git a/omaha/third_party/chrome/files/src/base/basictypes.h b/omaha/third_party/chrome/files/src/base/basictypes.h index ae7e2f1..4ec75ea 100644 --- a/omaha/third_party/chrome/files/src/base/basictypes.h +++ b/omaha/third_party/chrome/files/src/base/basictypes.h @@ -5,9 +5,9 @@ #ifndef BASE_BASICTYPES_H_ #define BASE_BASICTYPES_H_ -#include // So we can set the bounds of our types -#include // For size_t -#include // for memcpy +#include // So we can set the bounds of our types +#include // For size_t +#include // for memcpy #include "base/port.h" // Types that only need exist on certain systems @@ -65,32 +65,12 @@ typedef unsigned long long uint64; // and it should always be the signed version of whatever int32 is.) typedef signed int char32; -const uint8 kuint8max = (( uint8) 0xFF); -const uint16 kuint16max = ((uint16) 0xFFFF); -const uint32 kuint32max = ((uint32) 0xFFFFFFFF); -const uint64 kuint64max = ((uint64) GG_LONGLONG(0xFFFFFFFFFFFFFFFF)); -const int8 kint8min = (( int8) 0x80); -const int8 kint8max = (( int8) 0x7F); -const int16 kint16min = (( int16) 0x8000); -const int16 kint16max = (( int16) 0x7FFF); -const int32 kint32min = (( int32) 0x80000000); -const int32 kint32max = (( int32) 0x7FFFFFFF); -const int64 kint64min = (( int64) GG_LONGLONG(0x8000000000000000)); -const int64 kint64max = (( int64) GG_LONGLONG(0x7FFFFFFFFFFFFFFF)); - // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) -// An older, deprecated, politically incorrect name for the above. -// NOTE: The usage of this macro was baned from our code base, but some -// third_party libraries are yet using it. -// TODO(tfarina): Figure out how to fix the usage of this macro in the -// third_party libraries and get rid of it. -#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName) - // A macro to disallow all the implicit constructors, namely the // default constructor, copy constructor and operator= functions. // @@ -326,7 +306,7 @@ inline Dest bit_cast(const Source& source) { // really sure you don't want to do anything with the return value of a function // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example: // -// scoped_ptr my_var = ...; +// std::unique_ptr my_var = ...; // if (TakeOwnership(my_var.get()) == SUCCESS) // ignore_result(my_var.release()); // diff --git a/omaha/third_party/chrome/files/src/base/rand_util.cc b/omaha/third_party/chrome/files/src/base/rand_util.cc index 3a69333..4327a1c 100644 --- a/omaha/third_party/chrome/files/src/base/rand_util.cc +++ b/omaha/third_party/chrome/files/src/base/rand_util.cc @@ -40,7 +40,7 @@ bool RandBytes(void* output, size_t output_length) { return true; } -bool RandUint32(uint32* number) { +bool RandUint32(uint32_t* number) { ASSERT1(number); return RandBytes(number, sizeof(*number)); diff --git a/omaha/third_party/chrome/files/src/base/rand_util.h b/omaha/third_party/chrome/files/src/base/rand_util.h index 1b05089..a6f35da 100644 --- a/omaha/third_party/chrome/files/src/base/rand_util.h +++ b/omaha/third_party/chrome/files/src/base/rand_util.h @@ -5,13 +5,16 @@ #ifndef BASE_RAND_UTIL_H_ #define BASE_RAND_UTIL_H_ +#include +#include + namespace omaha { // Fills |output_length| bytes of |output| with random data. bool RandBytes(void* output, size_t output_length); // Returns a random number in range [0, kuint32max]. Thread-safe. -bool RandUint32(uint32* number); +bool RandUint32(uint32_t* number); } // namespace omaha diff --git a/omaha/third_party/chrome/files/src/base/scoped_ptr.h b/omaha/third_party/chrome/files/src/base/scoped_ptr.h deleted file mode 100644 index 4489f2d..0000000 --- a/omaha/third_party/chrome/files/src/base/scoped_ptr.h +++ /dev/null @@ -1,380 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Scopers help you manage ownership of a pointer, helping you easily manage the -// a pointer within a scope, and automatically destroying the pointer at the -// end of a scope. There are two main classes you will use, which coorespond -// to the operators new/delete and new[]/delete[]. -// -// Example usage (scoped_ptr): -// { -// scoped_ptr foo(new Foo("wee")); -// } // foo goes out of scope, releasing the pointer with it. -// -// { -// scoped_ptr foo; // No pointer managed. -// foo.reset(new Foo("wee")); // Now a pointer is managed. -// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed. -// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed. -// foo->Method(); // Foo::Method() called. -// foo.get()->Method(); // Foo::Method() called. -// SomeFunc(foo.Release()); // SomeFunc takes owernship, foo no longer -// // manages a pointer. -// foo.reset(new Foo("wee4")); // foo manages a pointer again. -// foo.reset(); // Foo("wee4") destroyed, foo no longer -// // manages a pointer. -// } // foo wasn't managing a pointer, so nothing was destroyed. -// -// Example usage (scoped_array): -// { -// scoped_array foo(new Foo[100]); -// foo.get()->Method(); // Foo::Method on the 0th element. -// foo[10].Method(); // Foo::Method on the 10th element. -// } - -#ifndef BASE_SCOPED_PTR_H_ -#define BASE_SCOPED_PTR_H_ - -// This is an implementation designed to match the anticipated future TR2 -// implementation of the scoped_ptr class, and its closely-related brethren, -// scoped_array, scoped_ptr_malloc. - -#include -#include -#include - -// A scoped_ptr is like a T*, except that the destructor of scoped_ptr -// automatically deletes the pointer it holds (if any). -// That is, scoped_ptr owns the T object that it points to. -// Like a T*, a scoped_ptr may hold either NULL or a pointer to a T object. -// Also like T*, scoped_ptr is thread-compatible, and once you -// dereference it, you get the threadsafety guarantees of T. -// -// The size of a scoped_ptr is small: -// sizeof(scoped_ptr) == sizeof(C*) -template -class scoped_ptr { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to intializing with NULL. - // There is no way to create an uninitialized scoped_ptr. - // The input parameter must be allocated with new. - explicit scoped_ptr(C* p = NULL) : ptr_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_ptr() { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != ptr_) { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - ptr_ = p; - } - } - - // Accessors to get the owned object. - // operator* and operator-> will assert() if there is no current object. - C& operator*() const { - assert(ptr_ != NULL); - return *ptr_; - } - C* operator->() const { - assert(ptr_ != NULL); - return ptr_; - } - C* get() const { return ptr_; } - - // Comparison operators. - // These return whether two scoped_ptr refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return ptr_ == p; } - bool operator!=(C* p) const { return ptr_ != p; } - - // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - C* tmp = ptr_; - ptr_ = p2.ptr_; - p2.ptr_ = tmp; - } - - // Release a pointer. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = ptr_; - ptr_ = NULL; - return retVal; - } - - private: - C* ptr_; - - // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't - // make sense, and if C2 == C, it still doesn't make sense because you should - // never have the same object owned by two different scoped_ptrs. - template bool operator==(scoped_ptr const& p2) const; - template bool operator!=(scoped_ptr const& p2) const; - - // Disallow evil constructors - scoped_ptr(const scoped_ptr&); - void operator=(const scoped_ptr&); -}; - -// Free functions -template -void swap(scoped_ptr& p1, scoped_ptr& p2) { - p1.swap(p2); -} - -template -bool operator==(C* p1, const scoped_ptr& p2) { - return p1 == p2.get(); -} - -template -bool operator!=(C* p1, const scoped_ptr& p2) { - return p1 != p2.get(); -} - -// scoped_array is like scoped_ptr, except that the caller must allocate -// with new [] and the destructor deletes objects with delete []. -// -// As with scoped_ptr, a scoped_array either points to an object -// or is NULL. A scoped_array owns the object that it points to. -// scoped_array is thread-compatible, and once you index into it, -// the returned objects have only the threadsafety guarantees of T. -// -// Size: sizeof(scoped_array) == sizeof(C*) -template -class scoped_array { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to intializing with NULL. - // There is no way to create an uninitialized scoped_array. - // The input parameter must be allocated with new []. - explicit scoped_array(C* p = NULL) : array_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_array() { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != array_) { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - array_ = p; - } - } - - // Get one element of the current object. - // Will assert() if there is no current object, or index i is negative. - C& operator[](std::ptrdiff_t i) const { - assert(i >= 0); - assert(array_ != NULL); - return array_[i]; - } - - // Get a pointer to the zeroth element of the current object. - // If there is no current object, return NULL. - C* get() const { - return array_; - } - - // Comparison operators. - // These return whether two scoped_array refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return array_ == p; } - bool operator!=(C* p) const { return array_ != p; } - - // Swap two scoped arrays. - void swap(scoped_array& p2) { - C* tmp = array_; - array_ = p2.array_; - p2.array_ = tmp; - } - - // Release an array. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = array_; - array_ = NULL; - return retVal; - } - - private: - C* array_; - - // Forbid comparison of different scoped_array types. - template bool operator==(scoped_array const& p2) const; - template bool operator!=(scoped_array const& p2) const; - - // Disallow evil constructors - scoped_array(const scoped_array&); - void operator=(const scoped_array&); -}; - -// Free functions -template -void swap(scoped_array& p1, scoped_array& p2) { - p1.swap(p2); -} - -template -bool operator==(C* p1, const scoped_array& p2) { - return p1 == p2.get(); -} - -template -bool operator!=(C* p1, const scoped_array& p2) { - return p1 != p2.get(); -} - -// This class wraps the c library function free() in a class that can be -// passed as a template argument to scoped_ptr_malloc below. -class ScopedPtrMallocFree { - public: - inline void operator()(void* x) const { - free(x); - } -}; - -// scoped_ptr_malloc<> is similar to scoped_ptr<>, but it accepts a -// second template argument, the functor used to free the object. - -template -class scoped_ptr_malloc { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to intializing with NULL. - // There is no way to create an uninitialized scoped_ptr. - // The input parameter must be allocated with an allocator that matches the - // Free functor. For the default Free functor, this is malloc, calloc, or - // realloc. - explicit scoped_ptr_malloc(C* p = NULL): ptr_(p) {} - - // Destructor. If there is a C object, call the Free functor. - ~scoped_ptr_malloc() { - free_(ptr_); - } - - // Reset. Calls the Free functor on the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (ptr_ != p) { - free_(ptr_); - ptr_ = p; - } - } - - // Get the current object. - // operator* and operator-> will cause an assert() failure if there is - // no current object. - C& operator*() const { - assert(ptr_ != NULL); - return *ptr_; - } - - C* operator->() const { - assert(ptr_ != NULL); - return ptr_; - } - - C* get() const { - return ptr_; - } - - // Comparison operators. - // These return whether a scoped_ptr_malloc and a plain pointer refer - // to the same object, not just to two different but equal objects. - // For compatibility wwith the boost-derived implementation, these - // take non-const arguments. - bool operator==(C* p) const { - return ptr_ == p; - } - - bool operator!=(C* p) const { - return ptr_ != p; - } - - // Swap two scoped pointers. - void swap(scoped_ptr_malloc & b) { - C* tmp = b.ptr_; - b.ptr_ = ptr_; - ptr_ = tmp; - } - - // Release a pointer. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* tmp = ptr_; - ptr_ = NULL; - return tmp; - } - - private: - C* ptr_; - - // no reason to use these: each scoped_ptr_malloc should have its own object - template - bool operator==(scoped_ptr_malloc const& p) const; - template - bool operator!=(scoped_ptr_malloc const& p) const; - - static FreeProc const free_; - - // Disallow evil constructors - scoped_ptr_malloc(const scoped_ptr_malloc&); - void operator=(const scoped_ptr_malloc&); -}; - -template -FP const scoped_ptr_malloc::free_ = FP(); - -template inline -void swap(scoped_ptr_malloc& a, scoped_ptr_malloc& b) { - a.swap(b); -} - -template inline -bool operator==(C* p, const scoped_ptr_malloc& b) { - return p == b.get(); -} - -template inline -bool operator!=(C* p, const scoped_ptr_malloc& b) { - return p != b.get(); -} - -#endif // BASE_SCOPED_PTR_H_ diff --git a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc index 9599d2b..dcb445a 100644 --- a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc +++ b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.cc @@ -35,11 +35,13 @@ #include "crypto/signature_verifier.h" #include "omaha/base/debug.h" #include "omaha/base/file.h" +#include "omaha/base/scope_guard.h" #include "omaha/base/security/sha256.h" #include "omaha/base/signatures.h" +#include "omaha/base/utils.h" #include "omaha/net/cup_ecdsa_utils.h" -#include "third_party/bar/shared_ptr.h" #include "third_party/chrome/files/src/components/crx_file/crx3.pb.h" +#include "third_party/libzip/lib/zip.h" namespace crx_file { @@ -57,7 +59,7 @@ const uint8_t kPublisherKeyHash[] = { 0x24, 0x97, 0xcc, 0x9b, 0x04, 0x25, 0x4c, 0x65, 0x8f, 0x79, 0xf2, 0x14, 0x53, 0x92, 0x86, 0x7e, 0xa8, 0x36, 0x63, 0x67, 0xcf}; -typedef std::vector> Verifiers; +typedef std::vector> Verifiers; typedef google::protobuf::RepeatedPtrField RepeatedProof; // Returns the number of bytes read, or -1 in the case of an unexpected EOF or @@ -103,10 +105,6 @@ bool ReadHashAndVerifyArchive(omaha::File* file, } } - if (len < 0) { - return false; - } - for (Verifiers::const_iterator verifier = verifiers.begin(); verifier != verifiers.end(); ++verifier) { @@ -197,7 +195,7 @@ VerifierResult VerifyCrx3( proof_type != proof_types.end(); ++proof_type) { const RepeatedProof& repeated_proof = (header.*proof_type->first)(); - for (RepeatedProof::const_iterator& proof = repeated_proof.begin(); + for (RepeatedProof::const_iterator proof = repeated_proof.begin(); proof != repeated_proof.end(); ++proof) { const std::string& key = proof->public_key(); @@ -217,7 +215,8 @@ VerifierResult VerifyCrx3( continue; } - shared_ptr v(new crypto::SignatureVerifier); + std::shared_ptr v( + new crypto::SignatureVerifier); ASSERT1(sizeof(unsigned char) == sizeof(uint8_t)); if (!v->VerifyInit( @@ -253,6 +252,165 @@ VerifierResult VerifyCrx3( return VerifierResult::OK_FULL; } +int ReadBuffer(uint8_t* buffer, int length, omaha::File* file) { + ASSERT1(sizeof(byte) == sizeof(uint8_t)); + uint32 bytes_read = 0; + HRESULT hr = file->Read(length, reinterpret_cast(buffer), &bytes_read); + if (FAILED(hr)) { + return -1; + } + + return bytes_read; +} + +uint32_t ReadLittleEndianUInt32(omaha::File* file) { + uint8_t buffer[4] = {}; + if (ReadBuffer(buffer, 4, file) != 4) { + return UINT32_MAX; + } + return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; +} + +HRESULT ReadArchiveAndWrite(omaha::File* file, const CPath& write_to) { + omaha::File write_to_file; + HRESULT hr = write_to_file.Open(write_to, true, false); + if (FAILED(hr)) { + return hr; + } + + uint8_t buffer[1 << 12] = {}; + size_t len = 0; + while ((len = ReadBuffer(buffer, arraysize(buffer), file)) > 0) { + uint32 bytes_written(0); + hr = write_to_file.Write(buffer, len, &bytes_written); + if (FAILED(hr) || bytes_written != len) { + return hr; + } + } + + return S_OK; +} + +// Reduces a Crx3 file into a corresponding Zip file sans the Crx3 headers. +bool Crx3ToZip(const CPath& crx_path, const CPath& zip_path) { + if (!omaha::File::Exists(crx_path)) { + return false; + } + + omaha::File file; + HRESULT hr = file.Open(crx_path, false, false); + if (FAILED(hr)) { + return false; + } + + char buffer[kCrx2FileHeaderMagicSize] = {}; + uint32 bytes_read = 0; + if (FAILED(file.Read(kCrx2FileHeaderMagicSize, + reinterpret_cast(buffer), + &bytes_read)) || + bytes_read != kCrx2FileHeaderMagicSize) { + return false; + } + + if (strncmp(buffer, kCrxDiffFileHeaderMagic, kCrx2FileHeaderMagicSize) && + strncmp(buffer, kCrx2FileHeaderMagic, kCrx2FileHeaderMagicSize)) { + return false; + } + + const uint32_t version = ReadLittleEndianUInt32(&file); + if (version != 3) { + return false; + } + + const uint32_t header_size = ReadLittleEndianUInt32(&file); + if (header_size > kMaxHeaderSize) { + return false; + } + + // Skip the crx header which contains the following: + // [crx-magic] + [version] + [header-size] + [header]. + hr = file.SeekFromBegin(12 + header_size); + if (FAILED(hr)) { + return false; + } + + if (FAILED(ReadArchiveAndWrite(&file, zip_path))) { + return false; + } + + return true; +} + +// Unzips the given zip file |zip_file_path| into the directory |to_dir|. +bool Unzip(const CPath& zip_file_path, const CPath& to_dir) { + HRESULT hr = omaha::CreateDir(to_dir, NULL); + if (FAILED(hr)) { + return false; + } + + struct zip* zip_archive = zip_open(CT2A(zip_file_path), 0, NULL); + if (!zip_archive) { + return false; + } + omaha::ScopeGuard zip_close_guard = omaha::MakeGuard(zip_close, zip_archive); + + const zip_int64_t num_entries = zip_get_num_entries(zip_archive, 0); + for (zip_int64_t i = 0; i < num_entries; ++i) { + struct zip_stat zip_entry_information = {}; + if (zip_stat_index(zip_archive, i, 0, &zip_entry_information)) { + continue; + } + + size_t len = strlen(zip_entry_information.name); + if (!len) { + return false; + } + + if (zip_entry_information.name[len - 1] == '/' || + zip_entry_information.name[len - 1] == '\\') { + CPathA sub_directory = static_cast(CT2A(to_dir)); + sub_directory += zip_entry_information.name; + omaha::CreateDir(CA2T(sub_directory), NULL); + + continue; + } + + struct zip_file* zip_entry_file = zip_fopen_index(zip_archive, i, 0); + if (!zip_entry_file) { + return false; + } + omaha::ScopeGuard zip_fclose_guard = + omaha::MakeGuard(zip_fclose, zip_entry_file); + + CPathA output_file = static_cast(CT2A(to_dir)); + output_file += zip_entry_information.name; + + omaha::File file; + hr = file.Open(CString(output_file), true, false); + if (FAILED(hr)) { + return false; + } + + for (zip_uint64_t sum = 0; sum != zip_entry_information.size;) { + byte buf[100] = {}; + zip_int64_t read_len = zip_fread(zip_entry_file, buf, arraysize(buf)); + if (read_len < 0) { + return false; + } + + uint32 bytes_written = 0; + if (FAILED(file.Write(buf, read_len, &bytes_written)) || + bytes_written != read_len) { + return false; + } + + sum += read_len; + } + } + + return true; +} + } // namespace VerifierResult Verify( @@ -274,7 +432,7 @@ VerifierResult Verify( return VerifierResult::ERROR_FILE_NOT_READABLE; } - shared_ptr file_hash( + std::shared_ptr file_hash( omaha::CryptDetails::CreateHasher(true)); // Magic number. @@ -332,5 +490,20 @@ VerifierResult Verify( return diff ? VerifierResult::OK_DELTA : VerifierResult::OK_FULL; } +bool Crx3Unzip(const CPath& crx_path, const CPath& to_dir) { + HRESULT hr = omaha::CreateDir(to_dir, NULL); + if (FAILED(hr)) { + return false; + } + + const CString zip = omaha::GetTempFilenameAt(to_dir, _T("C3U")); + if (zip.IsEmpty()) { + return false; + } + + const CPath zip_path(zip); + return Crx3ToZip(crx_path, zip_path) ? Unzip(zip_path, to_dir) : false; +} + } // namespace crx_file diff --git a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.h b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.h index 72ee9f0..574cfcf 100644 --- a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.h +++ b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier.h @@ -20,6 +20,7 @@ #ifndef OMAHA_THIRD_PARTY_CHROME_FILES_SRC_COMPONENTS_CRX_FILE_CRX_VERIFIER_H_ #define OMAHA_THIRD_PARTY_CHROME_FILES_SRC_COMPONENTS_CRX_FILE_CRX_VERIFIER_H_ +#include #include #include #include @@ -68,6 +69,9 @@ VerifierResult Verify( std::string* public_key, std::string* crx_id); +// Unzips the given crx file |crx_path| into the directory |to_dir|. +bool Crx3Unzip(const CPath& crx_path, const CPath& to_dir); + } // namespace crx_file #endif // OMAHA_THIRD_PARTY_CHROME_FILES_SRC_COMPONENTS_CRX_FILE_CRX_VERIFIER_H_ diff --git a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier_unittest.cc b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier_unittest.cc index 37a45d5..bcd7a99 100644 --- a/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier_unittest.cc +++ b/omaha/third_party/chrome/files/src/components/crx_file/crx_verifier_unittest.cc @@ -20,21 +20,28 @@ #include "components/crx_file/crx_verifier.h" #include +#include #include "omaha/base/app_util.h" +#include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/string.h" +#include "omaha/base/utils.h" #include "omaha/testing/unit_test.h" namespace { using omaha::ConcatenatePath; +CPath TestFileCPath(const CString& file) { + return CPath(ConcatenatePath(ConcatenatePath( + omaha::app_util::GetCurrentModuleDirectory(), + _T("unittest_support")), + file)); +} + std::string TestFile(const std::string& file) { - const CString base_path = ConcatenatePath( - omaha::app_util::GetCurrentModuleDirectory(), - _T("unittest_support")); - return std::string(CT2A(ConcatenatePath(base_path, CString(file.c_str())))); + return std::string(CT2A(TestFileCPath(CString(file.c_str())))); } const char kOjjHash[] = "ojjgnpkioondelmggbekfhllhdaimnho"; @@ -199,4 +206,19 @@ TEST_F(CrxVerifierTest, RequiresDeveloperKey) { EXPECT_EQ("UNSET", public_key); } +TEST(CrxVerifierTest, Crx3Unzip) { + const CPath to_dir(omaha::GetUniqueTempDirectoryName()); + EXPECT_TRUE(Crx3Unzip(TestFileCPath(_T("valid_publisher.crx3")), to_dir)); + + EXPECT_TRUE(omaha::File::Exists( + ConcatenatePath(to_dir, _T("manifest.json")))); + EXPECT_TRUE(omaha::File::Exists( + ConcatenatePath(to_dir, _T("_metadata\\verified_contents.json")))); + EXPECT_TRUE(omaha::File::Exists( + ConcatenatePath(to_dir, _T("_platform_specific\\all\\sths\\0301") + _T("9df3fd85a69a8ebd1facc6da9ba73e469774fe77f579fc5a08b8328c1d6b.sth")))); + + EXPECT_SUCCEEDED(omaha::DeleteDirectory(to_dir)); +} + } // namespace crx_file diff --git a/omaha/third_party/chrome/files/src/components/crx_file/id_util.cc b/omaha/third_party/chrome/files/src/components/crx_file/id_util.cc index d74a7a0..fb6dd57 100644 --- a/omaha/third_party/chrome/files/src/components/crx_file/id_util.cc +++ b/omaha/third_party/chrome/files/src/components/crx_file/id_util.cc @@ -45,6 +45,12 @@ static void ConvertHexadecimalToIDAlphabet(std::string* id) { } } +// ASCII-specific tolower. The standard library's tolower is locale sensitive, +// so we don't want to use it here. +char ToLowerChar(char c) { + return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; +} + } // namespace namespace crx_file { @@ -69,7 +75,7 @@ std::string HexEncode(const void* bytes, size_t size) { std::string ToLowerASCII(const std::string& s) { std::string ret(s.size(), '\0'); - std::transform(s.begin(), s.end(), ret.begin(), std::tolower); + std::transform(s.begin(), s.end(), ret.begin(), ToLowerChar); return ret; } diff --git a/omaha/third_party/chrome/files/src/crypto/rsa_private_key.cc b/omaha/third_party/chrome/files/src/crypto/rsa_private_key.cc index 008bf0f..cf95136 100644 --- a/omaha/third_party/chrome/files/src/crypto/rsa_private_key.cc +++ b/omaha/third_party/chrome/files/src/crypto/rsa_private_key.cc @@ -5,17 +5,49 @@ #include "crypto/rsa_private_key.h" #include +#include -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" +#include "omaha/base/logging.h" namespace crypto { +HRESULT CryptAcquireContextWithFallback(DWORD provider_type, + HCRYPTPROV* provider) { + ASSERT1(provider); + + const TCHAR* kHashCryptoProviders[] = { + NULL, // The default provider. + MS_ENH_RSA_AES_PROV, // The named provider for Vista and up. + MS_ENH_RSA_AES_PROV_XP // The named provider for XP SP3 and up. + }; + + // Try different providers until one of them succeeds. + HRESULT hr = S_OK; + ScopedHCRYPTPROV scoped_provider; + for (auto hash_crypto_provider : kHashCryptoProviders) { + if (::CryptAcquireContext(scoped_provider.receive(), + NULL, + hash_crypto_provider, + provider_type, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + REPORT_LOG(L6, (_T("[CryptAcquireContext succeeded]"))); + *provider = scoped_provider.release(); + return S_OK; + } + + hr = HRESULT_FROM_WIN32(::GetLastError()); + REPORT_LOG(LE, (_T("[CryptAcquireContext failed][%#x]"), hr)); + } + + return hr; +} + // static RSAPrivateKey* RSAPrivateKey::Create(uint16 num_bits) { - scoped_ptr result(new RSAPrivateKey); + std::unique_ptr result(new RSAPrivateKey()); if (!result->InitProvider()) - return NULL; + return nullptr; DWORD flags = CRYPT_EXPORTABLE; @@ -23,7 +55,7 @@ RSAPrivateKey* RSAPrivateKey::Create(uint16 num_bits) { flags |= (num_bits << 16); if (!CryptGenKey(result->provider_, CALG_RSA_SIGN, flags, result->key_.receive())) - return NULL; + return nullptr; return result.release(); } @@ -32,15 +64,15 @@ RSAPrivateKey* RSAPrivateKey::Create(uint16 num_bits) { RSAPrivateKey* RSAPrivateKey::CreateSensitive(uint16 num_bits) { UNREFERENCED_PARAMETER(num_bits); ASSERT1(false); - return NULL; + return nullptr; } // static RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfo( const std::vector& input) { - scoped_ptr result(new RSAPrivateKey); + std::unique_ptr result(new RSAPrivateKey()); if (!result->InitProvider()) - return NULL; + return nullptr; PrivateKeyInfoCodec pki(false); // Little-Endian pki.Import(input); @@ -54,7 +86,7 @@ RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfo( pki.exponent2()->size() + pki.coefficient()->size() + pki.private_exponent()->size(); - scoped_array blob(new BYTE[blob_size]); + std::unique_ptr blob(new BYTE[blob_size]); uint8* dest = blob.get(); PUBLICKEYSTRUC* public_key_struc = reinterpret_cast(dest); @@ -96,7 +128,7 @@ RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfo( reinterpret_cast(public_key_struc), static_cast(blob_size), 0, CRYPT_EXPORTABLE, result->key_.receive())) - return NULL; + return nullptr; return result.release(); } @@ -106,7 +138,7 @@ RSAPrivateKey* RSAPrivateKey::CreateSensitiveFromPrivateKeyInfo( const std::vector& input) { UNREFERENCED_PARAMETER(input); ASSERT1(false); - return NULL; + return nullptr; } // static @@ -114,7 +146,7 @@ RSAPrivateKey* RSAPrivateKey::FindFromPublicKeyInfo( const std::vector& input) { UNREFERENCED_PARAMETER(input); ASSERT1(false); - return NULL; + return nullptr; } RSAPrivateKey::RSAPrivateKey() : provider_(NULL), key_(NULL) {} @@ -122,8 +154,8 @@ RSAPrivateKey::RSAPrivateKey() : provider_(NULL), key_(NULL) {} RSAPrivateKey::~RSAPrivateKey() {} bool RSAPrivateKey::InitProvider() { - return FALSE != CryptAcquireContext(provider_.receive(), NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); + return SUCCEEDED(CryptAcquireContextWithFallback(PROV_RSA_AES, + provider_.receive())); } bool RSAPrivateKey::ExportPrivateKey(std::vector* output) { @@ -134,7 +166,7 @@ bool RSAPrivateKey::ExportPrivateKey(std::vector* output) { return false; } - scoped_array blob(new uint8[blob_length]); + std::unique_ptr blob(new uint8[blob_length]); if (!CryptExportKey(key_, 0, PRIVATEKEYBLOB, 0, blob.get(), &blob_length)) { ASSERT1(false); return false; @@ -188,7 +220,7 @@ bool RSAPrivateKey::ExportPublicKey(std::vector* output) { return false; } - scoped_array key_info(new uint8[key_info_len]); + std::unique_ptr key_info(new uint8[key_info_len]); if (!CryptExportPublicKeyInfo( provider_, AT_SIGNATURE, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, reinterpret_cast(key_info.get()), &key_info_len)) { @@ -205,7 +237,7 @@ bool RSAPrivateKey::ExportPublicKey(std::vector* output) { return false; } - scoped_array encoded(new BYTE[encoded_length]); + std::unique_ptr encoded(new BYTE[encoded_length]); if (!CryptEncodeObject( X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, reinterpret_cast(key_info.get()), encoded.get(), diff --git a/omaha/third_party/chrome/files/src/crypto/rsa_private_key.h b/omaha/third_party/chrome/files/src/crypto/rsa_private_key.h index 7a58d95..00eb6f4 100644 --- a/omaha/third_party/chrome/files/src/crypto/rsa_private_key.h +++ b/omaha/third_party/chrome/files/src/crypto/rsa_private_key.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CRYPTO_RSA_PRIVATE_KEY_H_ -#define CRYPTO_RSA_PRIVATE_KEY_H_ +#ifndef OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_RSA_PRIVATE_KEY_H_ +#define OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_RSA_PRIVATE_KEY_H_ #pragma once #include "build/build_config.h" @@ -33,11 +33,18 @@ struct SECKEYPublicKeyStr; namespace crypto { +// Providers implementing SHA256 can be instantiated using different names. +// On Vista and up, both the default provider and the enhanced RSA/AES +// provider support SHA256. On Windows XP, the named provider has a different +// name, therefore, the code falls back to a specific named provider in case +// of errors. +HRESULT CryptAcquireContextWithFallback(DWORD provider_type, + HCRYPTPROV* provider); + // Used internally by RSAPrivateKey for serializing and deserializing // PKCS #8 PrivateKeyInfo and PublicKeyInfo. class PrivateKeyInfoCodec { public: - // ASN.1 encoding of the AlgorithmIdentifier from PKCS #8. static const uint8 kRsaAlgorithmIdentifier[]; @@ -76,14 +83,14 @@ class PrivateKeyInfoCodec { // Accessors to the contents of the integer components of the PrivateKeyInfo // structure. - std::vector* modulus() { return &modulus_; }; - std::vector* public_exponent() { return &public_exponent_; }; - std::vector* private_exponent() { return &private_exponent_; }; - std::vector* prime1() { return &prime1_; }; - std::vector* prime2() { return &prime2_; }; - std::vector* exponent1() { return &exponent1_; }; - std::vector* exponent2() { return &exponent2_; }; - std::vector* coefficient() { return &coefficient_; }; + std::vector* modulus() { return &modulus_; } + std::vector* public_exponent() { return &public_exponent_; } + std::vector* private_exponent() { return &private_exponent_; } + std::vector* prime1() { return &prime1_; } + std::vector* prime2() { return &prime2_; } + std::vector* exponent1() { return &exponent1_; } + std::vector* exponent2() { return &exponent2_; } + std::vector* coefficient() { return &coefficient_; } private: // Utility wrappers for PrependIntegerImpl that use the class's |big_endian_| @@ -270,5 +277,5 @@ class RSAPrivateKey { } // namespace crypto -#endif // CRYPTO_RSA_PRIVATE_KEY_H_ +#endif // OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_RSA_PRIVATE_KEY_H_ diff --git a/omaha/third_party/chrome/files/src/crypto/rsa_private_key_unittest.cc b/omaha/third_party/chrome/files/src/crypto/rsa_private_key_unittest.cc index 2532e3f..4192d97 100644 --- a/omaha/third_party/chrome/files/src/crypto/rsa_private_key_unittest.cc +++ b/omaha/third_party/chrome/files/src/crypto/rsa_private_key_unittest.cc @@ -4,15 +4,16 @@ #include "crypto/rsa_private_key.h" -#include "base/scoped_ptr.h" +#include + #include "omaha/testing/unit_test.h" // Generate random private keys with two different sizes. Reimport, then // export them again. We should get back the same exact bytes. TEST(RSAPrivateKeyUnitTest, InitRandomTest) { - scoped_ptr keypair1( + std::unique_ptr keypair1( crypto::RSAPrivateKey::Create(1024)); - scoped_ptr keypair2( + std::unique_ptr keypair2( crypto::RSAPrivateKey::Create(2048)); ASSERT_TRUE(keypair1.get()); ASSERT_TRUE(keypair2.get()); @@ -27,9 +28,9 @@ TEST(RSAPrivateKeyUnitTest, InitRandomTest) { ASSERT_TRUE(keypair1->ExportPublicKey(&pubkey1)); ASSERT_TRUE(keypair2->ExportPublicKey(&pubkey2)); - scoped_ptr keypair3( + std::unique_ptr keypair3( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(privkey1)); - scoped_ptr keypair4( + std::unique_ptr keypair4( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(privkey2)); ASSERT_TRUE(keypair3.get()); ASSERT_TRUE(keypair4.get()); @@ -162,7 +163,7 @@ TEST(RSAPrivateKeyUnitTest, PublicKeyTest) { input.resize(sizeof(private_key_info)); memcpy(&input.front(), private_key_info, sizeof(private_key_info)); - scoped_ptr key( + std::unique_ptr key( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(input)); ASSERT_TRUE(key.get()); @@ -365,9 +366,9 @@ TEST(RSAPrivateKeyUnitTest, ShortIntegers) { memcpy(&input2.front(), short_integer_without_high_bit, sizeof(short_integer_without_high_bit)); - scoped_ptr keypair1( + std::unique_ptr keypair1( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(input1)); - scoped_ptr keypair2( + std::unique_ptr keypair2( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(input2)); ASSERT_TRUE(keypair1.get()); ASSERT_TRUE(keypair2.get()); diff --git a/omaha/third_party/chrome/files/src/crypto/rsa_private_key_win.cc b/omaha/third_party/chrome/files/src/crypto/rsa_private_key_win.cc index d63f5f3..38d972b 100644 --- a/omaha/third_party/chrome/files/src/crypto/rsa_private_key_win.cc +++ b/omaha/third_party/chrome/files/src/crypto/rsa_private_key_win.cc @@ -7,7 +7,6 @@ #include #include -#include "base/scoped_ptr.h" #include "omaha/base/debug.h" // This file manually encodes and decodes RSA private keys using PrivateKeyInfo diff --git a/omaha/third_party/chrome/files/src/crypto/signature_creator.h b/omaha/third_party/chrome/files/src/crypto/signature_creator.h index ee210fb..55d1b42 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_creator.h +++ b/omaha/third_party/chrome/files/src/crypto/signature_creator.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CRYPTO_SIGNATURE_CREATOR_H_ -#define CRYPTO_SIGNATURE_CREATOR_H_ +#ifndef OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_CREATOR_H_ +#define OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_CREATOR_H_ #include @@ -21,7 +21,7 @@ class SignatureCreator { // Create an instance. The caller must ensure that the provided PrivateKey // instance outlives the created SignatureCreator. - static SignatureCreator* Create(RSAPrivateKey* key); + static SignatureCreator* Create(RSAPrivateKey* key, ALG_ID algorithm_id); // Update the signature with more data. bool Update(const uint8* data_part, int data_part_len); @@ -42,5 +42,5 @@ class SignatureCreator { } // namespace crypto -#endif // CRYPTO_SIGNATURE_CREATOR_H_ +#endif // OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_CREATOR_H_ diff --git a/omaha/third_party/chrome/files/src/crypto/signature_creator_unittest.cc b/omaha/third_party/chrome/files/src/crypto/signature_creator_unittest.cc index f61d3a1..247f4c4 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_creator_unittest.cc +++ b/omaha/third_party/chrome/files/src/crypto/signature_creator_unittest.cc @@ -2,52 +2,47 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "crypto/signature_creator.h" + +#include #include -#include "base/scoped_ptr.h" -#include "crypto/signature_creator.h" -#include "crypto/signature_verifier.h" +#include "crypto/signature_verifier_win.h" #include "omaha/testing/unit_test.h" TEST(SignatureCreatorTest, BasicTest) { // Do a verify round trip. - scoped_ptr key_original( + std::unique_ptr key_original( crypto::RSAPrivateKey::Create(1024)); ASSERT_TRUE(key_original.get()); - std::vector key_info; + std::vector key_info; key_original->ExportPrivateKey(&key_info); - scoped_ptr key( + std::unique_ptr key( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_info)); ASSERT_TRUE(key.get()); - scoped_ptr signer( - crypto::SignatureCreator::Create(key.get())); + std::unique_ptr signer( + crypto::SignatureCreator::Create(key.get(), CALG_SHA1)); ASSERT_TRUE(signer.get()); std::string data("Hello, World!"); - ASSERT_TRUE(signer->Update(reinterpret_cast(data.c_str()), + ASSERT_TRUE(signer->Update(reinterpret_cast(data.c_str()), static_cast(data.size()))); - std::vector signature; + std::vector signature; ASSERT_TRUE(signer->Final(&signature)); - std::vector public_key_info; + std::vector public_key_info; ASSERT_TRUE(key_original->ExportPublicKey(&public_key_info)); - // This is the algorithm ID for SHA-1 with RSA encryption. - // TODO(aa): Factor this out into some shared location. - const uint8 kSHA1WithRSAAlgorithmID[] = { - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, - 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00 - }; - crypto::SignatureVerifier verifier; + crypto::SignatureVerifierWin verifier; ASSERT_TRUE(verifier.VerifyInit( - kSHA1WithRSAAlgorithmID, sizeof(kSHA1WithRSAAlgorithmID), + CALG_SHA1, &signature.front(), static_cast(signature.size()), &public_key_info.front(), static_cast(public_key_info.size()))); - verifier.VerifyUpdate(reinterpret_cast(data.c_str()), + verifier.VerifyUpdate(reinterpret_cast(data.c_str()), static_cast(data.size())); ASSERT_TRUE(verifier.VerifyFinal()); } diff --git a/omaha/third_party/chrome/files/src/crypto/signature_creator_win.cc b/omaha/third_party/chrome/files/src/crypto/signature_creator_win.cc index 238e1bd..3ef6be9 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_creator_win.cc +++ b/omaha/third_party/chrome/files/src/crypto/signature_creator_win.cc @@ -4,17 +4,19 @@ #include "crypto/signature_creator.h" -#include "base/scoped_ptr.h" +#include + #include "omaha/base/debug.h" namespace crypto { // static -SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key) { - scoped_ptr result(new SignatureCreator); +SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key, + ALG_ID algorithm_id) { + std::unique_ptr result(new SignatureCreator); result->key_ = key; - if (!CryptCreateHash(key->provider(), CALG_SHA1, 0, 0, + if (!CryptCreateHash(key->provider(), algorithm_id, 0, 0, result->hash_object_.receive())) { ASSERT1(false); return NULL; diff --git a/omaha/third_party/chrome/files/src/crypto/signature_verifier.h b/omaha/third_party/chrome/files/src/crypto/signature_verifier.h index 9891b2a..aba4303 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_verifier.h +++ b/omaha/third_party/chrome/files/src/crypto/signature_verifier.h @@ -20,10 +20,10 @@ #ifndef OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_VERIFIER_H_ #define OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_VERIFIER_H_ -#include +#include #include #include -#include "base/scoped_ptr.h" + #include "crypto/crypto_export.h" #include "omaha/base/signatures.h" #include "omaha/net/cup_ecdsa_utils.h" @@ -83,7 +83,7 @@ class CRYPTO_EXPORT SignatureVerifier { omaha::internal::EcdsaSignature sig_; omaha::internal::EcdsaPublicKey key_; - scoped_ptr hasher_; + std::unique_ptr hasher_; }; } // namespace crypto diff --git a/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.cc b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.cc index 71cfe6c..c2fd4d1 100644 --- a/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.cc +++ b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.cc @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "crypto/signature_verifier.h" +#include "crypto/signature_verifier_win.h" +#include "crypto/rsa_private_key.h" #include "omaha/base/debug.h" +#include "omaha/base/logging.h" namespace { @@ -22,21 +24,27 @@ void WINAPI MyCryptFree(void* p) { namespace crypto { -SignatureVerifier::SignatureVerifier() : hash_object_(0), public_key_(0) { - if (!CryptAcquireContext(provider_.receive(), NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) +SignatureVerifierWin::SignatureVerifierWin() : hash_object_(0), public_key_(0) { + if (FAILED(CryptAcquireContextWithFallback(PROV_RSA_AES, + provider_.receive()))) { provider_.reset(); + } } -SignatureVerifier::~SignatureVerifier() { +SignatureVerifierWin::~SignatureVerifierWin() { } -bool SignatureVerifier::VerifyInit(const uint8* signature_algorithm, - int signature_algorithm_len, - const uint8* signature, - int signature_len, - const uint8* public_key_info, - int public_key_info_len) { +bool SignatureVerifierWin::VerifyInit(ALG_ID algorithm_id, + const uint8_t* signature, + size_t signature_len, + const uint8_t* public_key_info, + size_t public_key_info_len) { + if (algorithm_id != CALG_SHA_256 && algorithm_id != CALG_SHA1) { + REPORT_LOG(LE, (_T("[VerifyInit][Invalid signature algorithm][%d]"), + algorithm_id)); + return false; + } + signature_.reserve(signature_len); // CryptoAPI uses big integers in the little-endian byte order, so we need // to first swap the order of signature bytes. @@ -68,61 +76,30 @@ bool SignatureVerifier::VerifyInit(const uint8* signature_algorithm, if (!ok) return false; - CRYPT_ALGORITHM_IDENTIFIER* signature_algorithm_id; - struct_len = 0; - ok = CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, - X509_ALGORITHM_IDENTIFIER, - signature_algorithm, - signature_algorithm_len, - CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, - &decode_para, - &signature_algorithm_id, - &struct_len); - ASSERT1(ok || GetLastError() == ERROR_FILE_NOT_FOUND); - ALG_ID hash_alg_id; - if (ok) { - hash_alg_id = CALG_MD4; // Initialize to a weak hash algorithm that we - // don't support. - if (!strcmp(signature_algorithm_id->pszObjId, szOID_RSA_SHA1RSA)) - hash_alg_id = CALG_SHA1; - else if (!strcmp(signature_algorithm_id->pszObjId, szOID_RSA_MD5RSA)) - hash_alg_id = CALG_MD5; - free(signature_algorithm_id); - ASSERT1(static_cast(CALG_MD4) != hash_alg_id); - if (hash_alg_id == CALG_MD4) - return false; // Unsupported hash algorithm. - } else if (GetLastError() == ERROR_FILE_NOT_FOUND) { - // TODO(wtc): X509_ALGORITHM_IDENTIFIER isn't supported on XP SP2. We - // may be able to encapsulate signature_algorithm in a dummy SignedContent - // and decode it with X509_CERT into a CERT_SIGNED_CONTENT_INFO. For now, - // just hardcode the hash algorithm to be SHA-1. - hash_alg_id = CALG_SHA1; - } else { - return false; - } - - ok = CryptCreateHash(provider_, hash_alg_id, 0, 0, hash_object_.receive()); + ok = CryptCreateHash(provider_, algorithm_id, 0, 0, hash_object_.receive()); if (!ok) return false; + return true; } -void SignatureVerifier::VerifyUpdate(const uint8* data_part, - int data_part_len) { +void SignatureVerifierWin::VerifyUpdate(const uint8_t* data_part, + size_t data_part_len) { CryptHashData(hash_object_, data_part, data_part_len, 0); } -bool SignatureVerifier::VerifyFinal() { +bool SignatureVerifierWin::VerifyFinal() { BOOL ok = CryptVerifySignature(hash_object_, &signature_[0], static_cast(signature_.size()), public_key_, NULL, 0); Reset(); if (!ok) return false; + return true; } -void SignatureVerifier::Reset() { +void SignatureVerifierWin::Reset() { hash_object_.reset(); public_key_.reset(); signature_.clear(); diff --git a/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.h b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.h new file mode 100644 index 0000000..b0eecdd --- /dev/null +++ b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win.h @@ -0,0 +1,70 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_VERIFIER_WIN_H_ +#define OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_VERIFIER_WIN_H_ + +#include +#include +#include + +#include "base/basictypes.h" +#include "crypto/scoped_capi_types.h" + +// defines from wincrypt.h. These are copied here because we currently compile +// with support for XP, and these defines are valid for XP SP2 and above. +#define ALG_SID_SHA_256 12 +#define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256) + +namespace crypto { + +// The SignatureVerifierWin class verifies a signature using a bare public key +// (as opposed to a certificate). +class SignatureVerifierWin { + public: + SignatureVerifierWin(); + ~SignatureVerifierWin(); + + // Streaming interface: + + // Initiates a signature verification operation. This should be followed + // by one or more VerifyUpdate calls and a VerifyFinal call. + // + // The |signature| is encoded according to the |algorithm_id|, but it must not + // be further encoded in an ASN.1 BIT STRING. + // Note: An RSA signatures is actually a big integer. It must be in the + // big-endian byte order. + // + // The public key is specified as a DER encoded ASN.1 SubjectPublicKeyInfo + // structure, which contains not only the public key but also its type + // (algorithm): + // SubjectPublicKeyInfo ::= SEQUENCE { + // algorithm AlgorithmIdentifier, + // subjectPublicKey BIT STRING } + bool VerifyInit(ALG_ID algorithm_id, + const uint8_t* signature, + size_t signature_len, + const uint8_t* public_key_info, + size_t public_key_info_len); + + // Feeds a piece of the data to the signature verifier. + void VerifyUpdate(const uint8_t* data_part, size_t data_part_len); + + // Concludes a signature verification operation. Returns true if the + // signature is valid. Returns false if the signature is invalid or an + // error occurred. + bool VerifyFinal(); + + private: + void Reset(); + + std::vector signature_; + ScopedHCRYPTPROV provider_; + ScopedHCRYPTHASH hash_object_; + ScopedHCRYPTKEY public_key_; +}; + +} // namespace crypto + +#endif // OMAHA_THIRD_PARTY_CHROME_FILES_SRC_CRYPTO_SIGNATURE_VERIFIER_WIN_H_ diff --git a/omaha/third_party/chrome/files/src/crypto/signature_verifier_win_unittest.cc b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win_unittest.cc new file mode 100644 index 0000000..87aec00 --- /dev/null +++ b/omaha/third_party/chrome/files/src/crypto/signature_verifier_win_unittest.cc @@ -0,0 +1,243 @@ +// Copyright (c) 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "crypto/signature_verifier_win.h" +#include "omaha/testing/unit_test.h" + +TEST(SignatureVerifierWinTest, BasicTest) { + // The input data in this test comes from real certificates. + // + // tbs_certificate ("to-be-signed certificate", the part of a certificate + // that is signed), signature_algorithm, and algorithm come from the + // certificate of bugs.webkit.org. + // + // public_key_info comes from the certificate of the issuer, Go Daddy Secure + // Certification Authority. + // + // The bytes in the array initializers are formatted to expose the DER + // encoding of the ASN.1 structures. + + // The data that is signed is the following ASN.1 structure: + // TBSCertificate ::= SEQUENCE { + // ... -- omitted, not important + // } + const uint8 tbs_certificate[1017] = { + 0x30, 0x82, 0x03, 0xf5, // a SEQUENCE of length 1013 (0x3f5) + 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x43, 0xdd, 0x63, 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, + 0x00, 0x30, 0x81, 0xca, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, + 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, + 0x04, 0x08, 0x13, 0x07, 0x41, 0x72, 0x69, 0x7a, 0x6f, 0x6e, 0x61, 0x31, + 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0a, 0x53, 0x63, + 0x6f, 0x74, 0x74, 0x73, 0x64, 0x61, 0x6c, 0x65, 0x31, 0x1a, 0x30, 0x18, + 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x47, 0x6f, 0x44, 0x61, 0x64, + 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, + 0x31, 0x33, 0x30, 0x31, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x2a, 0x68, + 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, + 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, + 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, + 0x69, 0x74, 0x6f, 0x72, 0x79, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, + 0x04, 0x03, 0x13, 0x27, 0x47, 0x6f, 0x20, 0x44, 0x61, 0x64, 0x64, 0x79, + 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x43, 0x65, 0x72, 0x74, + 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, + 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31, 0x11, 0x30, 0x0f, 0x06, + 0x03, 0x55, 0x04, 0x05, 0x13, 0x08, 0x30, 0x37, 0x39, 0x36, 0x39, 0x32, + 0x38, 0x37, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x38, 0x30, 0x33, 0x31, 0x38, + 0x32, 0x33, 0x33, 0x35, 0x31, 0x39, 0x5a, 0x17, 0x0d, 0x31, 0x31, 0x30, + 0x33, 0x31, 0x38, 0x32, 0x33, 0x33, 0x35, 0x31, 0x39, 0x5a, 0x30, 0x79, + 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, + 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, + 0x43, 0x61, 0x6c, 0x69, 0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x12, + 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x43, 0x75, 0x70, + 0x65, 0x72, 0x74, 0x69, 0x6e, 0x6f, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, + 0x55, 0x04, 0x0a, 0x13, 0x0a, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x49, + 0x6e, 0x63, 0x2e, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x0b, + 0x13, 0x0c, 0x4d, 0x61, 0x63, 0x20, 0x4f, 0x53, 0x20, 0x46, 0x6f, 0x72, + 0x67, 0x65, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, + 0x0c, 0x2a, 0x2e, 0x77, 0x65, 0x62, 0x6b, 0x69, 0x74, 0x2e, 0x6f, 0x72, + 0x67, 0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, + 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xa7, 0x62, 0x79, 0x41, 0xda, 0x28, + 0xf2, 0xc0, 0x4f, 0xe0, 0x25, 0xaa, 0xa1, 0x2e, 0x3b, 0x30, 0x94, 0xb5, + 0xc9, 0x26, 0x3a, 0x1b, 0xe2, 0xd0, 0xcc, 0xa2, 0x95, 0xe2, 0x91, 0xc0, + 0xf0, 0x40, 0x9e, 0x27, 0x6e, 0xbd, 0x6e, 0xde, 0x7c, 0xb6, 0x30, 0x5c, + 0xb8, 0x9b, 0x01, 0x2f, 0x92, 0x04, 0xa1, 0xef, 0x4a, 0xb1, 0x6c, 0xb1, + 0x7e, 0x8e, 0xcd, 0xa6, 0xf4, 0x40, 0x73, 0x1f, 0x2c, 0x96, 0xad, 0xff, + 0x2a, 0x6d, 0x0e, 0xba, 0x52, 0x84, 0x83, 0xb0, 0x39, 0xee, 0xc9, 0x39, + 0xdc, 0x1e, 0x34, 0xd0, 0xd8, 0x5d, 0x7a, 0x09, 0xac, 0xa9, 0xee, 0xca, + 0x65, 0xf6, 0x85, 0x3a, 0x6b, 0xee, 0xe4, 0x5c, 0x5e, 0xf8, 0xda, 0xd1, + 0xce, 0x88, 0x47, 0xcd, 0x06, 0x21, 0xe0, 0xb9, 0x4b, 0xe4, 0x07, 0xcb, + 0x57, 0xdc, 0xca, 0x99, 0x54, 0xf7, 0x0e, 0xd5, 0x17, 0x95, 0x05, 0x2e, + 0xe9, 0xb1, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x82, 0x01, 0xce, 0x30, + 0x82, 0x01, 0xca, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, + 0x30, 0x00, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, + 0x02, 0x05, 0xa0, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x16, + 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, + 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x57, + 0x06, 0x03, 0x55, 0x1d, 0x1f, 0x04, 0x50, 0x30, 0x4e, 0x30, 0x4c, 0xa0, + 0x4a, 0xa0, 0x48, 0x86, 0x46, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, + 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, + 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x2f, + 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x65, 0x78, 0x74, 0x65, 0x6e, + 0x64, 0x65, 0x64, 0x69, 0x73, 0x73, 0x75, 0x69, 0x6e, 0x67, 0x33, 0x2e, + 0x63, 0x72, 0x6c, 0x30, 0x52, 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04, 0x4b, + 0x30, 0x49, 0x30, 0x47, 0x06, 0x0b, 0x60, 0x86, 0x48, 0x01, 0x86, 0xfd, + 0x6d, 0x01, 0x07, 0x17, 0x02, 0x30, 0x38, 0x30, 0x36, 0x06, 0x08, 0x2b, + 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x01, 0x16, 0x2a, 0x68, 0x74, 0x74, + 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, + 0x61, 0x74, 0x65, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, + 0x6f, 0x72, 0x79, 0x30, 0x7f, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, + 0x07, 0x01, 0x01, 0x04, 0x73, 0x30, 0x71, 0x30, 0x23, 0x06, 0x08, 0x2b, + 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x17, 0x68, 0x74, 0x74, + 0x70, 0x3a, 0x2f, 0x2f, 0x6f, 0x63, 0x73, 0x70, 0x2e, 0x67, 0x6f, 0x64, + 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x4a, 0x06, 0x08, + 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x3e, 0x68, 0x74, + 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, + 0x63, 0x61, 0x74, 0x65, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, + 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, + 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x67, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x74, 0x65, 0x2e, 0x63, 0x72, 0x74, + 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x48, + 0xdf, 0x60, 0x32, 0xcc, 0x89, 0x01, 0xb6, 0xdc, 0x2f, 0xe3, 0x73, 0xb5, + 0x9c, 0x16, 0x58, 0x32, 0x68, 0xa9, 0xc3, 0x30, 0x1f, 0x06, 0x03, 0x55, + 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xfd, 0xac, 0x61, 0x32, + 0x93, 0x6c, 0x45, 0xd6, 0xe2, 0xee, 0x85, 0x5f, 0x9a, 0xba, 0xe7, 0x76, + 0x99, 0x68, 0xcc, 0xe7, 0x30, 0x23, 0x06, 0x03, 0x55, 0x1d, 0x11, 0x04, + 0x1c, 0x30, 0x1a, 0x82, 0x0c, 0x2a, 0x2e, 0x77, 0x65, 0x62, 0x6b, 0x69, + 0x74, 0x2e, 0x6f, 0x72, 0x67, 0x82, 0x0a, 0x77, 0x65, 0x62, 0x6b, 0x69, + 0x74, 0x2e, 0x6f, 0x72, 0x67 + }; + + // RSA signature, a big integer in the big-endian byte order. + const uint8 signature[256] = { + 0x1e, 0x6a, 0xe7, 0xe0, 0x4f, 0xe7, 0x4d, 0xd0, 0x69, 0x7c, 0xf8, 0x8f, + 0x99, 0xb4, 0x18, 0x95, 0x36, 0x24, 0x0f, 0x0e, 0xa3, 0xea, 0x34, 0x37, + 0xf4, 0x7d, 0xd5, 0x92, 0x35, 0x53, 0x72, 0x76, 0x3f, 0x69, 0xf0, 0x82, + 0x56, 0xe3, 0x94, 0x7a, 0x1d, 0x1a, 0x81, 0xaf, 0x9f, 0xc7, 0x43, 0x01, + 0x64, 0xd3, 0x7c, 0x0d, 0xc8, 0x11, 0x4e, 0x4a, 0xe6, 0x1a, 0xc3, 0x01, + 0x74, 0xe8, 0x35, 0x87, 0x5c, 0x61, 0xaa, 0x8a, 0x46, 0x06, 0xbe, 0x98, + 0x95, 0x24, 0x9e, 0x01, 0xe3, 0xe6, 0xa0, 0x98, 0xee, 0x36, 0x44, 0x56, + 0x8d, 0x23, 0x9c, 0x65, 0xea, 0x55, 0x6a, 0xdf, 0x66, 0xee, 0x45, 0xe8, + 0xa0, 0xe9, 0x7d, 0x9a, 0xba, 0x94, 0xc5, 0xc8, 0xc4, 0x4b, 0x98, 0xff, + 0x9a, 0x01, 0x31, 0x6d, 0xf9, 0x2b, 0x58, 0xe7, 0xe7, 0x2a, 0xc5, 0x4d, + 0xbb, 0xbb, 0xcd, 0x0d, 0x70, 0xe1, 0xad, 0x03, 0xf5, 0xfe, 0xf4, 0x84, + 0x71, 0x08, 0xd2, 0xbc, 0x04, 0x7b, 0x26, 0x1c, 0xa8, 0x0f, 0x9c, 0xd8, + 0x12, 0x6a, 0x6f, 0x2b, 0x67, 0xa1, 0x03, 0x80, 0x9a, 0x11, 0x0b, 0xe9, + 0xe0, 0xb5, 0xb3, 0xb8, 0x19, 0x4e, 0x0c, 0xa4, 0xd9, 0x2b, 0x3b, 0xc2, + 0xca, 0x20, 0xd3, 0x0c, 0xa4, 0xff, 0x93, 0x13, 0x1f, 0xfc, 0xba, 0x94, + 0x93, 0x8c, 0x64, 0x15, 0x2e, 0x28, 0xa9, 0x55, 0x8c, 0x2c, 0x48, 0xd3, + 0xd3, 0xc1, 0x50, 0x69, 0x19, 0xe8, 0x34, 0xd3, 0xf1, 0x04, 0x9f, 0x0a, + 0x7a, 0x21, 0x87, 0xbf, 0xb9, 0x59, 0x37, 0x2e, 0xf4, 0x71, 0xa5, 0x3e, + 0xbe, 0xcd, 0x70, 0x83, 0x18, 0xf8, 0x8a, 0x72, 0x85, 0x45, 0x1f, 0x08, + 0x01, 0x6f, 0x37, 0xf5, 0x2b, 0x7b, 0xea, 0xb9, 0x8b, 0xa3, 0xcc, 0xfd, + 0x35, 0x52, 0xdd, 0x66, 0xde, 0x4f, 0x30, 0xc5, 0x73, 0x81, 0xb6, 0xe8, + 0x3c, 0xd8, 0x48, 0x8a + }; + + // The public key is specified as the following ASN.1 structure: + // SubjectPublicKeyInfo ::= SEQUENCE { + // algorithm AlgorithmIdentifier, + // subjectPublicKey BIT STRING } + const uint8 public_key_info[294] = { + 0x30, 0x82, 0x01, 0x22, // a SEQUENCE of length 290 (0x122) + // algorithm + 0x30, 0x0d, // a SEQUENCE of length 13 + 0x06, 0x09, // an OBJECT IDENTIFIER of length 9 + 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, + 0x05, 0x00, // a NULL of length 0 + // subjectPublicKey + 0x03, 0x82, 0x01, 0x0f, // a BIT STRING of length 271 (0x10f) + 0x00, // number of unused bits + 0x30, 0x82, 0x01, 0x0a, // a SEQUENCE of length 266 (0x10a) + // modulus + 0x02, 0x82, 0x01, 0x01, // an INTEGER of length 257 (0x101) + 0x00, 0xc4, 0x2d, 0xd5, 0x15, 0x8c, 0x9c, 0x26, 0x4c, 0xec, + 0x32, 0x35, 0xeb, 0x5f, 0xb8, 0x59, 0x01, 0x5a, 0xa6, 0x61, + 0x81, 0x59, 0x3b, 0x70, 0x63, 0xab, 0xe3, 0xdc, 0x3d, 0xc7, + 0x2a, 0xb8, 0xc9, 0x33, 0xd3, 0x79, 0xe4, 0x3a, 0xed, 0x3c, + 0x30, 0x23, 0x84, 0x8e, 0xb3, 0x30, 0x14, 0xb6, 0xb2, 0x87, + 0xc3, 0x3d, 0x95, 0x54, 0x04, 0x9e, 0xdf, 0x99, 0xdd, 0x0b, + 0x25, 0x1e, 0x21, 0xde, 0x65, 0x29, 0x7e, 0x35, 0xa8, 0xa9, + 0x54, 0xeb, 0xf6, 0xf7, 0x32, 0x39, 0xd4, 0x26, 0x55, 0x95, + 0xad, 0xef, 0xfb, 0xfe, 0x58, 0x86, 0xd7, 0x9e, 0xf4, 0x00, + 0x8d, 0x8c, 0x2a, 0x0c, 0xbd, 0x42, 0x04, 0xce, 0xa7, 0x3f, + 0x04, 0xf6, 0xee, 0x80, 0xf2, 0xaa, 0xef, 0x52, 0xa1, 0x69, + 0x66, 0xda, 0xbe, 0x1a, 0xad, 0x5d, 0xda, 0x2c, 0x66, 0xea, + 0x1a, 0x6b, 0xbb, 0xe5, 0x1a, 0x51, 0x4a, 0x00, 0x2f, 0x48, + 0xc7, 0x98, 0x75, 0xd8, 0xb9, 0x29, 0xc8, 0xee, 0xf8, 0x66, + 0x6d, 0x0a, 0x9c, 0xb3, 0xf3, 0xfc, 0x78, 0x7c, 0xa2, 0xf8, + 0xa3, 0xf2, 0xb5, 0xc3, 0xf3, 0xb9, 0x7a, 0x91, 0xc1, 0xa7, + 0xe6, 0x25, 0x2e, 0x9c, 0xa8, 0xed, 0x12, 0x65, 0x6e, 0x6a, + 0xf6, 0x12, 0x44, 0x53, 0x70, 0x30, 0x95, 0xc3, 0x9c, 0x2b, + 0x58, 0x2b, 0x3d, 0x08, 0x74, 0x4a, 0xf2, 0xbe, 0x51, 0xb0, + 0xbf, 0x87, 0xd0, 0x4c, 0x27, 0x58, 0x6b, 0xb5, 0x35, 0xc5, + 0x9d, 0xaf, 0x17, 0x31, 0xf8, 0x0b, 0x8f, 0xee, 0xad, 0x81, + 0x36, 0x05, 0x89, 0x08, 0x98, 0xcf, 0x3a, 0xaf, 0x25, 0x87, + 0xc0, 0x49, 0xea, 0xa7, 0xfd, 0x67, 0xf7, 0x45, 0x8e, 0x97, + 0xcc, 0x14, 0x39, 0xe2, 0x36, 0x85, 0xb5, 0x7e, 0x1a, 0x37, + 0xfd, 0x16, 0xf6, 0x71, 0x11, 0x9a, 0x74, 0x30, 0x16, 0xfe, + 0x13, 0x94, 0xa3, 0x3f, 0x84, 0x0d, 0x4f, + // public exponent + 0x02, 0x03, // an INTEGER of length 3 + 0x01, 0x00, 0x01 + }; + + // We use the signature verifier to perform four signature verification + // tests. + crypto::SignatureVerifierWin verifier; + bool ok; + + // Test 1: feed all of the data to the verifier at once (a single + // VerifyUpdate call). + ok = verifier.VerifyInit(CALG_SHA1, + signature, sizeof(signature), + public_key_info, sizeof(public_key_info)); + EXPECT_TRUE(ok); + verifier.VerifyUpdate(tbs_certificate, sizeof(tbs_certificate)); + ok = verifier.VerifyFinal(); + EXPECT_TRUE(ok); + + // Test 2: feed the data to the verifier in three parts (three VerifyUpdate + // calls). + ok = verifier.VerifyInit(CALG_SHA1, + signature, sizeof(signature), + public_key_info, sizeof(public_key_info)); + EXPECT_TRUE(ok); + verifier.VerifyUpdate(tbs_certificate, 256); + verifier.VerifyUpdate(tbs_certificate + 256, 256); + verifier.VerifyUpdate(tbs_certificate + 512, sizeof(tbs_certificate) - 512); + ok = verifier.VerifyFinal(); + EXPECT_TRUE(ok); + + // Test 3: verify the signature with incorrect data. + uint8 bad_tbs_certificate[sizeof(tbs_certificate)]; + memcpy(bad_tbs_certificate, tbs_certificate, sizeof(tbs_certificate)); + bad_tbs_certificate[10] += 1; // Corrupt one byte of the data. + ok = verifier.VerifyInit(CALG_SHA1, + signature, sizeof(signature), + public_key_info, sizeof(public_key_info)); + EXPECT_TRUE(ok); + verifier.VerifyUpdate(bad_tbs_certificate, sizeof(bad_tbs_certificate)); + ok = verifier.VerifyFinal(); + EXPECT_FALSE(ok); + + // Test 4: verify a bad signature. + uint8 bad_signature[sizeof(signature)]; + memcpy(bad_signature, signature, sizeof(signature)); + bad_signature[10] += 1; // Corrupt one byte of the signature. + ok = verifier.VerifyInit(CALG_SHA1, + bad_signature, sizeof(bad_signature), + public_key_info, sizeof(public_key_info)); + + // A crypto library (e.g., NSS) may detect that the signature is corrupted + // and cause VerifyInit to return false, so it is fine for 'ok' to be false. + if (ok) { + verifier.VerifyUpdate(tbs_certificate, sizeof(tbs_certificate)); + ok = verifier.VerifyFinal(); + EXPECT_FALSE(ok); + } +} + diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions_private.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions_private.h deleted file mode 100644 index 3b0a458..0000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_extensions_private.h +++ /dev/null @@ -1,27 +0,0 @@ -/* Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - -#ifndef _NP_EXTENSIONS_PRIVATE_H_ -#define _NP_EXTENSIONS_PRIVATE_H_ - -#include "third_party/npapi/bindings/npapi.h" - -// Some reserved GetStateContext/SetStateContext selectors. -typedef enum { - NPExtensionsReservedStateSharedMemory = 66536, - // Used by the Device2D and Audio devices to return a pointer to the - // structure used to implement the shared memory buffer for the device. - NPExtensionsReservedStateSharedMemorySize = 66537, - // Used by the Audio device to return a pointer to the - // structure used to implement the shared memory buffer for the device. - NPExtensionsReservedStateSyncChannel = 66538, - // Used by the Audio device to return a pointer to the - // structure used to implement the synchronization channel for the device. - NPExtensionsReservedStateSharedMemoryChecksum = 66539 - // Used by the Device2D to return the CRC32 checksum of the content - // stored in the shared memory buffer for the device. -} NPExtensionsReservedStates; - -#endif /* _NP_EXTENSIONS_PRIVATE_H_ */ diff --git a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_x11.h b/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_x11.h deleted file mode 100644 index c586419..0000000 --- a/omaha/third_party/chrome/files/src/third_party/npapi/bindings/npapi_x11.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#ifndef THIRD_PARTY_NPAPI_BINDINGS_NPAPI_X11_H_ -#define THIRD_PARTY_NPAPI_BINDINGS_NPAPI_X11_H_ - -// This file was split off the original npapi.h, to avoid including intrusive X -// headers unless necessary. - -#include "third_party/npapi/bindings/npapi.h" - -#ifdef XP_UNIX -#include -#include - -typedef struct _NPSetWindowCallbackStruct -{ - int32 type; -#ifdef MOZ_X11 - Display* display; - Visual* visual; - Colormap colormap; - unsigned int depth; -#endif -} NPSetWindowCallbackStruct; -#endif - -#endif // THIRD_PARTY_NPAPI_BINDINGS_NPAPI_X11_H_ diff --git a/omaha/third_party/hashlib/__init__.py b/omaha/third_party/hashlib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/omaha/third_party/hashlib/_hashlib.pyd b/omaha/third_party/hashlib/_hashlib.pyd deleted file mode 100644 index 9ecb5c1..0000000 Binary files a/omaha/third_party/hashlib/_hashlib.pyd and /dev/null differ diff --git a/omaha/third_party/smartany/scoped_any.h b/omaha/third_party/smartany/scoped_any.h index 2eb3063..ab89fee 100644 --- a/omaha/third_party/smartany/scoped_any.h +++ b/omaha/third_party/smartany/scoped_any.h @@ -194,7 +194,7 @@ inline T get( scoped_any const & t ) template inline bool valid( scoped_any const & t ) { - return t; + return static_cast(t); } // return wrapped resource and give up ownership diff --git a/omaha/third_party/smartany/shared_any.cc b/omaha/third_party/smartany/shared_any.cc deleted file mode 100644 index 064001d..0000000 --- a/omaha/third_party/smartany/shared_any.cc +++ /dev/null @@ -1,246 +0,0 @@ -//+--------------------------------------------------------------------------- -// -// Copyright ( C ) Microsoft, 2002. -// -// File: shared_any.cpp -// -// Contents: pool allocator for reference counts -// -// Classes: ref_count_allocator and helpers -// -// Functions: -// -// Author: Eric Niebler ( ericne@microsoft.com ) -// -//---------------------------------------------------------------------------- - -#ifdef _MT -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0403 -# endif -# include -# include -#endif - -#include -#include // for std::less -#include // for std::swap - -#pragma warning(push) -// C4640: construction of local static object is not thread-safe -#pragma warning(disable : 4640) -#include "shared_any.h" -#include "scoped_any.h" -#pragma warning(pop) - -namespace detail -{ - struct critsec - { -#ifdef _MT - CRITICAL_SECTION m_cs; - - critsec() - { - InitializeCriticalSectionAndSpinCount( &m_cs, 4000 ); - } - ~critsec() - { - DeleteCriticalSection( &m_cs ); - } - void enter() - { - EnterCriticalSection( &m_cs ); - } - void leave() - { - LeaveCriticalSection( &m_cs ); - } -#endif - }; - - namespace - { - critsec g_critsec; - } - - struct lock - { -#ifdef _MT - critsec & m_cs; - - explicit lock( critsec & cs ) - : m_cs(cs) - { - m_cs.enter(); - } - ~lock() - { - m_cs.leave(); - } -#else - explicit lock( critsec & ) - { - } -#endif - private: - lock( lock const & ); - lock & operator=( lock const & ); - }; - - struct ref_count_block - { - static long const s_sizeBlock = 256; - - short m_free_list; // offset to start of freelist - short m_available; // count of refcounts in this block that are available - long m_refcounts[ s_sizeBlock ]; - - ref_count_block() - : m_free_list(0), m_available(s_sizeBlock) - { - for( long l=0; l( *refcount ); - --m_available; - return refcount; - } - - void free( long volatile *refcount, lock & ) // throw() - { - assert( owns( refcount ) ); - *refcount = m_free_list; - m_free_list = static_cast( refcount - m_refcounts ); - ++m_available; - } - - bool owns( long volatile *refcount ) const // throw() - { - return ! std::less()( const_cast( refcount ), const_cast( m_refcounts ) ) && - std::less()( const_cast( refcount ), const_cast( m_refcounts ) + s_sizeBlock ); - } - }; - - - struct ref_count_allocator::node - { - node *m_next; - node *m_prev; - ref_count_block m_block; - explicit node( node *next=0, node *prev=0 ) - : m_next(next), m_prev(prev), m_block() - { - if( m_next ) - m_next->m_prev = this; - if( m_prev ) - m_prev->m_next = this; - } - }; - - - ref_count_allocator::ref_count_allocator() - : m_list_blocks(0), m_last_alloc(0), m_last_free(0) - { - } - - ref_count_allocator::~ref_count_allocator() - { - // Just leak the blocks. It's ok, really. - // If you need to clean up the blocks and - // you are certain that no refcounts are - // outstanding, you can use the finalize() - // method to force deallocation - } - - void ref_count_allocator::finalize() - { - lock l( g_critsec ); - for( node *next; m_list_blocks; m_list_blocks=next ) - { - next = m_list_blocks->m_next; - delete m_list_blocks; - } - m_last_alloc = 0; - m_last_free = 0; - } - - long volatile *ref_count_allocator::alloc() - { - lock l( g_critsec ); - if( ! m_last_alloc || m_last_alloc->m_block.full() ) - { - for( m_last_alloc = m_list_blocks; - m_last_alloc && m_last_alloc->m_block.full(); - m_last_alloc = m_last_alloc->m_next ); - if( ! m_last_alloc ) - { - m_last_alloc = new( std::nothrow ) node( m_list_blocks ); - if( ! m_last_alloc ) - return 0; - m_list_blocks = m_last_alloc; - } - } - return m_last_alloc->m_block.alloc( l ); - } - - long volatile *ref_count_allocator::alloc( long val ) - { - long volatile *refcount = alloc(); - *refcount = val; - return refcount; - } - - void ref_count_allocator::free( long volatile *refcount ) // throw() - { - // don't rearrange the order of these locals! - scoped_any scoped_last_free; - lock l( g_critsec ); - - if( ! m_last_free || ! m_last_free->m_block.owns( refcount ) ) - { - for( m_last_free = m_list_blocks; - m_last_free && ! m_last_free->m_block.owns( refcount ); - m_last_free = m_last_free->m_next ); - } - - assert( m_last_free && m_last_free->m_block.owns( refcount ) ); - m_last_free->m_block.free( refcount, l ); - - if( m_last_free != m_list_blocks && m_last_free->m_block.empty() ) - { - if( 0 != ( m_last_free->m_prev->m_next = m_last_free->m_next ) ) - m_last_free->m_next->m_prev = m_last_free->m_prev; - - if( ! m_list_blocks->m_block.empty() ) - { - m_last_free->m_next = m_list_blocks; - m_last_free->m_prev = 0; - m_list_blocks->m_prev = m_last_free; - m_list_blocks = m_last_free; - } - else - reset( scoped_last_free, m_last_free ); // deleted after critsec is released - - m_last_free = 0; - } - } - - // Here is the global reference count allocator. - ref_count_allocator ref_count_allocator::instance; -} diff --git a/omaha/third_party/smartany/shared_any.h b/omaha/third_party/smartany/shared_any.h deleted file mode 100644 index 6fcc0af..0000000 --- a/omaha/third_party/smartany/shared_any.h +++ /dev/null @@ -1,412 +0,0 @@ -//+--------------------------------------------------------------------------- -// -// Copyright ( C ) Microsoft, 2002. -// -// File: shared_any.h -// -// Contents: automatic resource management -// -// Classes: shared_any<> and various typedefs -// -// Functions: get -// reset -// valid -// -// Author: Eric Niebler ( ericne@microsoft.com ) -// -//---------------------------------------------------------------------------- - - -#ifndef SHARED_ANY -#define SHARED_ANY - -#include -#include // for std::less -#include // for std::swap -#include "smart_any_fwd.h" - -namespace detail -{ - class ref_count_allocator - { - struct node; - node *m_list_blocks; - node *m_last_alloc; - node *m_last_free; - - ref_count_allocator(); - ~ref_count_allocator(); - public: - void finalize(); - long volatile *alloc(); - long volatile *alloc( long val ); - void free( long volatile *refcount ); - - static ref_count_allocator instance; - }; - - template - struct shared_any_helper; - - template - struct shared_holder : Super - { - explicit shared_holder( typename Super::type t ) - : Super( t ) - { - } - - shared_holder( shared_holder const & that ) - : Super( that ) - { - if( Super::valid() ) - { - Super::inc_ref(); - } - } - - ~shared_holder() - { - if( Super::valid() ) - { - Super::dec_ref(); - } - } - }; - - template - struct intrusive - { - typedef T type; - - explicit intrusive( T t ) - : m_t( t ) - { - } - - bool valid() const - { - return m_t != static_cast( invalid_value_type() ); - } - - void inc_ref() - { - m_t->AddRef(); - } - - void dec_ref() - { - if( 0 == m_t->Release() ) - { - m_t = static_cast( invalid_value_type() ); - } - } - - T m_t; - }; - - template - struct nonintrusive - { - typedef T type; - - explicit nonintrusive( T t ) - : m_t( t ), - m_ref( 0 ) - { - if( valid() ) - { - m_ref = ref_count_allocator::instance.alloc(1L); - if( ! m_ref ) - { - m_t = static_cast( invalid_value_type() ); - throw std::bad_alloc(); - } - } - } - - bool valid() const - { - return m_t != static_cast( invalid_value_type() ); - } - - void inc_ref() - { - ::InterlockedIncrement( m_ref ); - } - - void dec_ref() - { - if( 0L == ::InterlockedDecrement( m_ref ) ) - { - ref_count_allocator::instance.free( m_ref ); - m_ref = 0; - close_policy::close( m_t ); - m_t = static_cast( invalid_value_type() ); - } - } - - typename holder::type m_t; - long volatile *m_ref; - }; - - template - struct is_close_release_com - { - static bool const value = false; - }; - template<> - struct is_close_release_com - { - static bool const value = true; - }; - - // credit Rani Sharoni for showing me how to implement - // is_com_ptr on VC7. This is deeply magical code. - template - struct is_com_ptr - { - private: - struct maybe - { - operator IUnknown*() const; - operator T(); - }; - - template - static yes check(T, U); - static no check(IUnknown*, int); - static maybe get(); - public: - static bool const value = sizeof(check(get(),0)) == sizeof(yes); - }; - - template<> - struct is_com_ptr - { - static bool const value = true; - }; -} - -template -class shared_any -{ - typedef detail::safe_types safe_types; - - // disallow comparison of shared_any's - bool operator==( detail::safe_bool ) const; - bool operator!=( detail::safe_bool ) const; - -public: - typedef typename detail::holder::type element_type; - typedef close_policy close_policy_type; - typedef typename safe_types::pointer_type pointer_type; - typedef typename safe_types::reference_type reference_type; - - // Fix-up the invalid_value type on older compilers - typedef typename detail::fixup_invalid_value:: - template rebind::type invalid_value_type; - - friend struct detail::shared_any_helper; - - // default construct - shared_any() - : m_held( static_cast( invalid_value_type() ) ) - { - } - - // construct from object. If we fail to allocate a reference count, - // then the T object is closed, and a bad_alloc exception is thrown. - explicit shared_any( T t ) - try : m_held( t ) - { - } - catch( std::bad_alloc & ) - { - close_policy::close( t ); - throw; - } - - // construct from another shared_any, incrementing ref count. - // Only throws if T's copy-c'tor throws, in which case, ref-count - // is unchanged. - shared_any( shared_any const & right ) - : m_held( right.m_held ) - { - } - - // construct from an auto_any, taking ownership. If allocation - // fails, auto_any retains ownership. - shared_any( auto_any & right ) - : m_held( get( right ) ) - { - release( right ); - } - - // assign from another shared_any - shared_any & operator=( - shared_any const & right ) - { - shared_any( right ).swap( *this ); - return *this; - } - - // assign from an auto_any - shared_any & operator=( - auto_any & right ) - { - shared_any( right ).swap( *this ); - return *this; - } - - operator detail::safe_bool() const - { - return m_held.valid() ? detail::safe_true : detail::safe_false; - } - - bool operator!() const - { - return ! m_held.valid(); - } - - // return pointer to class object (assume pointer) - pointer_type operator->() const - { - #ifdef SMART_ANY_PTS - // You better not be applying operator-> to a handle! - static detail::smartany_static_assert::value> const cannot_dereference_a_handle; - #endif - assert( m_held.valid() ); - return safe_types::to_pointer( m_held.m_t ); - } - - #ifdef SMART_ANY_PTS - // if this shared_any is managing an array, we can use operator[] to index it - typename detail::deref::type operator[]( int i ) const - { - static detail::smartany_static_assert::value> const cannot_dereference_a_handle; - static detail::smartany_static_assert::value> const accessed_like_an_array_but_not_deleted_like_an_array; - assert( m_held.valid() ); - return m_held.m_t[ i ]; - } - - // unary operator* lets you write code like: - // shared_any pfoo( new foo ); - // foo & f = *pfoo; - reference_type operator*() const - { - static detail::smartany_static_assert::value> const cannot_dereference_a_handle; - assert( m_held.valid() ); - return safe_types::to_reference( m_held.m_t ); - } - #endif - -private: - - void swap( shared_any & right ) - { - using std::swap; - swap( m_held, right.m_held ); - } - - // if we are wrapping a COM object, then use COM's reference counting. - // otherwise, use our own reference counting. - typedef typename detail::select< - detail::is_com_ptr::value && detail::is_close_release_com::value, - detail::intrusive, - detail::nonintrusive >::type holder_policy; - - detail::shared_holder m_held; -}; - -namespace detail -{ - template - struct shared_any_helper - { - static T get( shared_any const & t ) - { - return t.m_held.m_t; - } - - static void reset( shared_any & t, T newT ) - { - shared_any( newT ).swap( t ); - } - - static void swap( shared_any & left, - shared_any & right ) - { - left.swap( right ); - } - }; -} - -// return wrapped resource -template -inline T get( shared_any const & t ) -{ - return detail::shared_any_helper::get( t ); -} - -// return true if the shared_any contains a currently valid resource -template -inline bool valid( shared_any const & t ) -{ - return t; -} - -// destroy designated object -template -inline void reset( shared_any & t ) -{ - typedef typename detail::fixup_invalid_value:: - template rebind::type invalid_value_type; - detail::shared_any_helper::reset( t, invalid_value_type() ); -} - -// destroy designated object and store new resource -template -inline void reset( shared_any & t, U newT ) -{ - detail::shared_any_helper::reset( t, newT ); -} - -// swap the contents of two shared_any objects -template -inline void swap( shared_any & left, - shared_any & right ) -{ - detail::shared_any_helper::swap( left, right ); -} - -// Define some relational operators on shared_* types so they -// can be used in hashes and maps -template -inline bool operator==( - shared_any const & left, - shared_any const & right ) -{ - return get( left ) == get( right ); -} - -template -inline bool operator!=( - shared_any const & left, - shared_any const & right ) -{ - return get( left ) != get( right ); -} - -template -inline bool operator<( - shared_any const & left, - shared_any const & right ) -{ - return std::less( get( left ), get( right ) ); -} - -#endif // SHARED_ANY - -// This causes the shared_* typedefs to be defined -DECLARE_SMART_ANY_TYPEDEFS(shared) diff --git a/omaha/tools/ApplyTag/build.scons b/omaha/tools/ApplyTag/build.scons index 6a8ff44..63f7fdc 100644 --- a/omaha/tools/ApplyTag/build.scons +++ b/omaha/tools/ApplyTag/build.scons @@ -49,8 +49,6 @@ target_name = 'ApplyTag' inputs = [ 'apply_tag_tool.cc', ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/CrashHandlerClient/build.scons b/omaha/tools/CrashHandlerClient/build.scons index 920d0d0..c5e7e05 100644 --- a/omaha/tools/CrashHandlerClient/build.scons +++ b/omaha/tools/CrashHandlerClient/build.scons @@ -50,8 +50,6 @@ target_name = 'CrashHandlerClient' inputs = [ 'crash_handler_client_tool.cc', ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/CrashProcess/build.scons b/omaha/tools/CrashProcess/build.scons index 515df2c..c6bff2f 100644 --- a/omaha/tools/CrashProcess/build.scons +++ b/omaha/tools/CrashProcess/build.scons @@ -45,8 +45,6 @@ target_name = 'CrashProcess' inputs = [ 'crash_process.cc', ] -if local_env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/MsiTagger.exe b/omaha/tools/MsiTagger.exe new file mode 100644 index 0000000..bc9cb0d Binary files /dev/null and b/omaha/tools/MsiTagger.exe differ diff --git a/omaha/tools/MsiTagger/build.scons b/omaha/tools/MsiTagger/build.scons index f0125c7..d23e6b0 100644 --- a/omaha/tools/MsiTagger/build.scons +++ b/omaha/tools/MsiTagger/build.scons @@ -49,8 +49,6 @@ target_name = 'MsiTagger' inputs = [ 'msi_tag_tool.cc', ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/MsiTagger/msi_tag_tool.cc b/omaha/tools/MsiTagger/msi_tag_tool.cc index dbcce85..f771237 100644 --- a/omaha/tools/MsiTagger/msi_tag_tool.cc +++ b/omaha/tools/MsiTagger/msi_tag_tool.cc @@ -32,6 +32,7 @@ #include // NOLINT(readability/streams) #include +#include #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/utils.h" @@ -81,7 +82,24 @@ int WriteMsiTag( write_uint16(&out, static_cast(tag_length)); // Actual tag. - std::string tag_ansi(tag, tag + tag_length); + // Formerly: std::string tag_ansi(tag, tag + tag_length); + + // That code converted UTF-16 to iso-8859-1 (Latin1) via blindly + // chopping all but the lowest eight bits. This is not utf-8; it's + // Latin1, with garbage for anything outside that repertoire. Newer + // compilers rightly complain about data loss. Apparently that is + // fine though, so we do exactly as above, but more explicitly, and + // raising an assertion if we actually hit anything outside + // US-ASCII. + std::string tag_ansi; + tag_ansi.reserve(static_cast(tag_length)); + for (auto it=tag, itend=static_cast(tag + tag_length); + it != itend; + ++it) { + ASSERT1(*it < 128); + tag_ansi += static_cast(*it); + } + out.write(tag_ansi.data(), tag_length); in.close(); diff --git a/omaha/tools/ReadTag/build.scons b/omaha/tools/ReadTag/build.scons index a7e9b3c..0014bfb 100644 --- a/omaha/tools/ReadTag/build.scons +++ b/omaha/tools/ReadTag/build.scons @@ -46,8 +46,6 @@ target_name = 'ReadTag' inputs = [ 'read_tag.cc', ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/ReadTag/read_tag.cc b/omaha/tools/ReadTag/read_tag.cc index 9ec3ed7..e2cc478 100644 --- a/omaha/tools/ReadTag/read_tag.cc +++ b/omaha/tools/ReadTag/read_tag.cc @@ -15,9 +15,10 @@ // // Simple tool to read the stamped tag inside a binary. -#include -#include -#include "base/scoped_ptr.h" +#include +#include +#include + #include "omaha/base/file.h" #include "omaha/base/extractor.h" @@ -46,7 +47,7 @@ int _tmain(int argc, TCHAR* argv[]) { return -1; } - scoped_array buffer(new char[len]); + std::unique_ptr buffer(new char[len]); if (!ext.ExtractTag(buffer.get(), &len)) { _tprintf(_T("Extract tag failed.")); return -1; diff --git a/omaha/tools/SetShutDownEvent/build.scons b/omaha/tools/SetShutDownEvent/build.scons index 0f29f50..b1309e7 100644 --- a/omaha/tools/SetShutDownEvent/build.scons +++ b/omaha/tools/SetShutDownEvent/build.scons @@ -51,9 +51,6 @@ target_name = 'SetShutDownEvent' inputs = [ 'signal_shutdown.cc', ] -if env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) - local_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/SetShutDownEvent/signal_shutdown.cc b/omaha/tools/SetShutDownEvent/signal_shutdown.cc index de24c52..bc1b0f7 100644 --- a/omaha/tools/SetShutDownEvent/signal_shutdown.cc +++ b/omaha/tools/SetShutDownEvent/signal_shutdown.cc @@ -19,8 +19,9 @@ #include #include "omaha/base/const_object_names.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/utils.h" +#include "omaha/third_party/smartany/scoped_any.h" + int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { diff --git a/omaha/tools/eckeytool/README.md b/omaha/tools/eckeytool/README.md index ab98d1c..8ed3e48 100644 --- a/omaha/tools/eckeytool/README.md +++ b/omaha/tools/eckeytool/README.md @@ -1,7 +1,13 @@ -This tool converts an ECDSA public key in a PEM format to a CUP-ECDSA public key in a text format, which can be included as source code in the Omaha project tree. +This tool converts an ECDSA public key in a PEM format to a CUP-ECDSA public key +in a text format, which can be included as source code in the Omaha project +tree. -This directory is not built as part of the Omaha tree. Instead, build this code on Linux, using the provide makefile. The code provided has a dependency on openssl. To generate a key, use the following steps: -* generate an EC private key using openssl: `openssl ecparam -out priv.pem -name prime256v1 -genkey` -* extract the corresponding EC public key: `openssl ec -in priv.pem -pubout -out public.pem` +This directory is not built as part of the Omaha tree. Instead, build this code +on Linux, using the provide makefile. The code provided has a dependency on +openssl. To generate a key, use the following steps: +* generate an EC private key using openssl: + `openssl ecparam -out priv.pem -name prime256v1 -genkey` +* extract the corresponding EC public key: + `openssl ec -in priv.pem -pubout -out public.pem` * convert the EC public to a CUP ECDSA key: `./eckeytool public.pem 1` * take the output of the eckeytool and add it to your project tree. diff --git a/omaha/tools/eckeytool/eckeytool.c b/omaha/tools/eckeytool/eckeytool.c index fabe423..309c7ef 100644 --- a/omaha/tools/eckeytool/eckeytool.c +++ b/omaha/tools/eckeytool/eckeytool.c @@ -203,7 +203,7 @@ int load_and_print_pubkey(FILE* pemFile, int version) { return 1; } - if (EVP_PKEY_type(pubkey->type) != EVP_PKEY_EC) { + if (EVP_PKEY_base_id(pubkey) != EVP_PKEY_EC) { fprintf(stderr, "error: PEM does not contain an EC key.\n"); EVP_PKEY_free(pubkey); return 1; diff --git a/omaha/tools/generate_omaha3_idl.py b/omaha/tools/generate_omaha3_idl.py index 7e0445d..9a4bb8e 100644 --- a/omaha/tools/generate_omaha3_idl.py +++ b/omaha/tools/generate_omaha3_idl.py @@ -17,7 +17,7 @@ """Generates IDL file Omaha3 internfaces.""" -import commands +import subprocess import getopt import os import sys @@ -33,7 +33,7 @@ def _GetStatusOutput(cmd): if text[-1:] == "\n": text = text[:-1] return sts, text else: - return commands.getstatusoutput(cmd) + return subprocess.getstatusoutput(cmd) def _GenerateGuid(): @@ -67,7 +67,7 @@ def _GenerateIDLFile(idl_template_filename, idl_output_filename): def _Usage(): """Prints out script usage information.""" - print """ + print(""" generate_omaha3_idl.py: Write out the given IDL file. Usage: @@ -79,7 +79,7 @@ def _Usage(): --help Show this information. --idl_output_file filename Path/name of output IDL filename. --idl_template_file filename Path/name of input IDL template. -""" +""") def _Main(): diff --git a/omaha/tools/goopdump/build.scons b/omaha/tools/goopdump/build.scons index 3f24ea6..4ebcb38 100644 --- a/omaha/tools/goopdump/build.scons +++ b/omaha/tools/goopdump/build.scons @@ -41,8 +41,6 @@ lib_inputs = [ 'process_commandline.cc', 'process_monitor.cc', ] -if env.Bit('use_precompiled_headers'): - lib_inputs += lib_env.EnablePrecompile(target_name) lib_env.ComponentLibrary( lib_name=target_name, @@ -126,8 +124,6 @@ exe_inputs = [ 'goopdump_main.cc', exe_env.RES('resource.rc'), ] -if env.Bit('use_precompiled_headers'): - exe_inputs += exe_env.EnablePrecompile(target_name) exe_env.ComponentTestProgram( prog_name=target_name, diff --git a/omaha/tools/goopdump/data_dumper.h b/omaha/tools/goopdump/data_dumper.h index 886ed93..c90929c 100644 --- a/omaha/tools/goopdump/data_dumper.h +++ b/omaha/tools/goopdump/data_dumper.h @@ -53,7 +53,7 @@ class DataDumper { RegKey* key, const int indent); - DISALLOW_EVIL_CONSTRUCTORS(DataDumper); + DISALLOW_COPY_AND_ASSIGN(DataDumper); }; class DumpHeader { @@ -63,7 +63,7 @@ class DumpHeader { private: const DumpLog& dump_log_; - DISALLOW_EVIL_CONSTRUCTORS(DumpHeader); + DISALLOW_COPY_AND_ASSIGN(DumpHeader); }; } // namespace omaha diff --git a/omaha/tools/goopdump/data_dumper_app_manager.cc b/omaha/tools/goopdump/data_dumper_app_manager.cc index a07c818..752c58f 100644 --- a/omaha/tools/goopdump/data_dumper_app_manager.cc +++ b/omaha/tools/goopdump/data_dumper_app_manager.cc @@ -64,7 +64,7 @@ CString GuidToFriendlyAppName(const GUID& guid) { // to customers. MapGuidToName guid_to_name[] = { {_T("{283EAF47-8817-4c2b-A801-AD1FADFB7BAA}"), _T("Gears")}, - {_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), _T("Google Update")}, + {_T("{B131C935-9BE6-41DA-9599-1F776BEB8019}"), _T("Brave Update")}, {_T("{8A69D345-D564-463C-AFF1-A69D9E530F96}"), _T("Chrome")}, }; diff --git a/omaha/tools/goopdump/data_dumper_app_manager.h b/omaha/tools/goopdump/data_dumper_app_manager.h index 1f7f842..cd48684 100644 --- a/omaha/tools/goopdump/data_dumper_app_manager.h +++ b/omaha/tools/goopdump/data_dumper_app_manager.h @@ -39,7 +39,7 @@ class DataDumperAppManager : public DataDumper { const AppManager& app_manager); void DumpRawRegistryData(const DumpLog& dump_log, bool is_machine); - DISALLOW_EVIL_CONSTRUCTORS(DataDumperAppManager); + DISALLOW_COPY_AND_ASSIGN(DataDumperAppManager); }; } // namespace omaha diff --git a/omaha/tools/goopdump/data_dumper_goopdate.cc b/omaha/tools/goopdump/data_dumper_goopdate.cc index 30fde1c..2a91a4e 100644 --- a/omaha/tools/goopdump/data_dumper_goopdate.cc +++ b/omaha/tools/goopdump/data_dumper_goopdate.cc @@ -23,6 +23,7 @@ #include #include +#include #include "omaha/common/constants.h" #include "omaha/common/error.h" @@ -203,8 +204,8 @@ HRESULT DataDumperGoopdate::GetDllDir(bool is_machine, CString* dll_path) { } void DataDumperGoopdate::DumpGoogleUpdateIniFile(const DumpLog& dump_log) { - DumpHeader header(dump_log, _T("GoogleUpdate.ini File Contents")); - DumpFileContents(dump_log, _T("c:\\googleupdate.ini"), 0); + DumpHeader header(dump_log, _T("BraveUpdate.ini File Contents")); + DumpFileContents(dump_log, _T("c:\\braveupdate.ini"), 0); } void DataDumperGoopdate::DumpHostsFile(const DumpLog& dump_log) { @@ -275,7 +276,7 @@ void DataDumperGoopdate::DumpEventLog(const DumpLog& dump_log) { const int kInitialBufferSize = 8192; int buffer_size = kInitialBufferSize; - scoped_array buffer(new TCHAR[buffer_size]); + std::unique_ptr buffer(new TCHAR[buffer_size]); while (1) { EVENTLOGRECORD* record = reinterpret_cast(buffer.get()); @@ -339,7 +340,7 @@ void DataDumperGoopdate::DumpEventLog(const DumpLog& dump_log) { } void DataDumperGoopdate::DumpGoogleUpdateProcessInfo(const DumpLog& dump_log) { - DumpHeader header(dump_log, _T("GoogleUpdate.exe Process Info")); + DumpHeader header(dump_log, _T("BraveUpdate.exe Process Info")); EnableDebugPrivilege(); @@ -363,7 +364,7 @@ void DataDumperGoopdate::DumpGoogleUpdateProcessInfo(const DumpLog& dump_log) { CString exe_file_name = process_entry32.szExeFile; exe_file_name.MakeLower(); - if (exe_file_name.Find(_T("googleupdate.exe")) >= 0) { + if (exe_file_name.Find(_T("braveupdate.exe")) >= 0) { if (first) { first = false; } else { diff --git a/omaha/tools/goopdump/data_dumper_goopdate.h b/omaha/tools/goopdump/data_dumper_goopdate.h index 55f5ad5..296c9ac 100644 --- a/omaha/tools/goopdump/data_dumper_goopdate.h +++ b/omaha/tools/goopdump/data_dumper_goopdate.h @@ -52,7 +52,7 @@ class DataDumperGoopdate : public DataDumper { int num_tail_lines); - DISALLOW_EVIL_CONSTRUCTORS(DataDumperGoopdate); + DISALLOW_COPY_AND_ASSIGN(DataDumperGoopdate); }; } // namespace omaha diff --git a/omaha/tools/goopdump/data_dumper_network.h b/omaha/tools/goopdump/data_dumper_network.h index 8477598..1c77f2a 100644 --- a/omaha/tools/goopdump/data_dumper_network.h +++ b/omaha/tools/goopdump/data_dumper_network.h @@ -35,7 +35,7 @@ class DataDumperNetwork : public DataDumper { private: void DumpNetworkConfig(const DumpLog& dump_log); - DISALLOW_EVIL_CONSTRUCTORS(DataDumperNetwork); + DISALLOW_COPY_AND_ASSIGN(DataDumperNetwork); }; } // namespace omaha diff --git a/omaha/tools/goopdump/data_dumper_oneclick.h b/omaha/tools/goopdump/data_dumper_oneclick.h index 66aceb0..ba76144 100644 --- a/omaha/tools/goopdump/data_dumper_oneclick.h +++ b/omaha/tools/goopdump/data_dumper_oneclick.h @@ -36,7 +36,7 @@ class DataDumperOneClick : public DataDumper { private: void DumpOneClickDataForVersion(const DumpLog& dump_log, int plugin_version); - DISALLOW_EVIL_CONSTRUCTORS(DataDumperOneClick); + DISALLOW_COPY_AND_ASSIGN(DataDumperOneClick); }; } // namespace omaha diff --git a/omaha/tools/goopdump/data_dumper_osdata.h b/omaha/tools/goopdump/data_dumper_osdata.h index 03bee91..f90d7fc 100644 --- a/omaha/tools/goopdump/data_dumper_osdata.h +++ b/omaha/tools/goopdump/data_dumper_osdata.h @@ -34,7 +34,7 @@ class DataDumperOSData : public DataDumper { private: HRESULT GetSystemUptime(CString* uptime); - DISALLOW_EVIL_CONSTRUCTORS(DataDumperOSData); + DISALLOW_COPY_AND_ASSIGN(DataDumperOSData); }; } // namespace omaha diff --git a/omaha/tools/goopdump/dump_log.h b/omaha/tools/goopdump/dump_log.h index 1e1ce7c..b9c31a8 100644 --- a/omaha/tools/goopdump/dump_log.h +++ b/omaha/tools/goopdump/dump_log.h @@ -33,7 +33,7 @@ class DumpLogHandler { virtual void WriteLine(const TCHAR* line) = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(DumpLogHandler); + DISALLOW_COPY_AND_ASSIGN(DumpLogHandler); }; class ConsoleDumpLogHandler : public DumpLogHandler { @@ -44,7 +44,7 @@ class ConsoleDumpLogHandler : public DumpLogHandler { virtual void WriteLine(const TCHAR* line); private: - DISALLOW_EVIL_CONSTRUCTORS(ConsoleDumpLogHandler); + DISALLOW_COPY_AND_ASSIGN(ConsoleDumpLogHandler); }; class DebugDumpLogHandler : public DumpLogHandler { @@ -55,7 +55,7 @@ class DebugDumpLogHandler : public DumpLogHandler { virtual void WriteLine(const TCHAR* line); private: - DISALLOW_EVIL_CONSTRUCTORS(DebugDumpLogHandler); + DISALLOW_COPY_AND_ASSIGN(DebugDumpLogHandler); }; class FileDumpLogHandler : public DumpLogHandler { @@ -70,7 +70,7 @@ class FileDumpLogHandler : public DumpLogHandler { void WriteBufToFile(const void* buf, DWORD num_bytes_to_write); CString filename_; - DISALLOW_EVIL_CONSTRUCTORS(FileDumpLogHandler); + DISALLOW_COPY_AND_ASSIGN(FileDumpLogHandler); }; @@ -103,7 +103,7 @@ class DumpLog { ConsoleDumpLogHandler console_handler_; DebugDumpLogHandler debug_handler_; - DISALLOW_EVIL_CONSTRUCTORS(DumpLog); + DISALLOW_COPY_AND_ASSIGN(DumpLog); }; } // namespace omaha diff --git a/omaha/tools/goopdump/goopdump.cc b/omaha/tools/goopdump/goopdump.cc index 5b4ac18..6dd50d6 100644 --- a/omaha/tools/goopdump/goopdump.cc +++ b/omaha/tools/goopdump/goopdump.cc @@ -55,7 +55,7 @@ class GoopdateProcessMonitorCallback : public ProcessMonitorCallbackInterface { private: const DumpLog& dump_log_; - DISALLOW_EVIL_CONSTRUCTORS(GoopdateProcessMonitorCallback); + DISALLOW_COPY_AND_ASSIGN(GoopdateProcessMonitorCallback); }; @@ -122,7 +122,7 @@ HRESULT Goopdump::Main(const TCHAR* cmd_line, int argc, TCHAR** argv) { ProcessMonitor process_monitor; GoopdateProcessMonitorCallback callback(dump_log_); std::vector patterns; - patterns.push_back(CString(_T("googleupdate.exe"))); + patterns.push_back(CString(_T("braveupdate.exe"))); patterns.push_back(CString(_T("notepad.exe"))); process_monitor.StartWithPatterns(&callback, patterns); getchar(); diff --git a/omaha/tools/goopdump/goopdump.h b/omaha/tools/goopdump/goopdump.h index 8a34351..d968b2e 100644 --- a/omaha/tools/goopdump/goopdump.h +++ b/omaha/tools/goopdump/goopdump.h @@ -56,7 +56,7 @@ class Goopdump { GoopdumpCmdLineArgs args_; DumpLog dump_log_; - DISALLOW_EVIL_CONSTRUCTORS(Goopdump); + DISALLOW_COPY_AND_ASSIGN(Goopdump); }; } // namespace omaha diff --git a/omaha/tools/goopdump/process_monitor.h b/omaha/tools/goopdump/process_monitor.h index 154a4e7..c5d461c 100644 --- a/omaha/tools/goopdump/process_monitor.h +++ b/omaha/tools/goopdump/process_monitor.h @@ -46,7 +46,7 @@ class ProcessMonitorCallbackInterface { virtual void OnProcessRemoved(DWORD process_id) = 0; private: - DISALLOW_EVIL_CONSTRUCTORS(ProcessMonitorCallbackInterface); + DISALLOW_COPY_AND_ASSIGN(ProcessMonitorCallbackInterface); }; // This class creates a thread to monitor running processes for particular @@ -101,7 +101,7 @@ class ProcessMonitor { scoped_handle event_thread_exit_; // Signal to exit monitor_thread_. scoped_handle monitor_thread_; // Handle to the monitoring thread. - DISALLOW_EVIL_CONSTRUCTORS(ProcessMonitor); + DISALLOW_COPY_AND_ASSIGN(ProcessMonitor); }; } // namespace omaha diff --git a/omaha/tools/goopdump/process_monitor_unittest.cc b/omaha/tools/goopdump/process_monitor_unittest.cc index 6f99bc4..ed982a9 100644 --- a/omaha/tools/goopdump/process_monitor_unittest.cc +++ b/omaha/tools/goopdump/process_monitor_unittest.cc @@ -57,7 +57,7 @@ class MockProcessMonitorCallback : public ProcessMonitorCallbackInterface { std::vector process_ids_added_; std::vector process_ids_removed_; - DISALLOW_EVIL_CONSTRUCTORS(MockProcessMonitorCallback); + DISALLOW_COPY_AND_ASSIGN(MockProcessMonitorCallback); }; TEST(GoopdumpProcessMonitorTest, TestStartStopNoop) { diff --git a/omaha/tools/goopdump/resource.rc b/omaha/tools/goopdump/resource.rc index c7ce0a2..97aebbd 100644 --- a/omaha/tools/goopdump/resource.rc +++ b/omaha/tools/goopdump/resource.rc @@ -13,7 +13,7 @@ // limitations under the License. // ======================================================================== -#include +#include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US @@ -30,11 +30,11 @@ BEGIN BEGIN BLOCK "040904e4" BEGIN - VALUE "CompanyName", "Google Inc." + VALUE "CompanyName", "Google LLC" VALUE "FileDescription", "Goopdump" VALUE "FileVersion", VERSION_NUMBER_STRING VALUE "InternalName", "Goopdump" - VALUE "LegalCopyright", "Copyright 2008-2010 Google Inc." + VALUE "LegalCopyright", "Copyright 2018 Google LLC" VALUE "OriginalFilename", "Goopdump" VALUE "ProductName", "Goopdump" VALUE "ProductVersion", VERSION_NUMBER_STRING diff --git a/omaha/tools/performondemand/build.scons b/omaha/tools/performondemand/build.scons index d19673d..fcc50fa 100644 --- a/omaha/tools/performondemand/build.scons +++ b/omaha/tools/performondemand/build.scons @@ -64,9 +64,6 @@ def BuildPerformOnDemand(local_env): else: inputs.append('$OBJ_ROOT/goopdate/omaha3_idl_i.obj') - if local_env.Bit('use_precompiled_headers'): - inputs += local_env.EnablePrecompile(target_name) - local_env.ComponentTestProgram( prog_name=target_name, source=inputs, diff --git a/omaha/tools/proxy_clsid_utils.py b/omaha/tools/proxy_clsid_utils.py index 827a914..d4244a9 100644 --- a/omaha/tools/proxy_clsid_utils.py +++ b/omaha/tools/proxy_clsid_utils.py @@ -17,7 +17,7 @@ """Generates Omaha build file and Omaha customization unit test file.""" -import commands +import subprocess import os @@ -37,7 +37,7 @@ def _GetStatusOutput(cmd): if text[-1:] == "\n": text = text[:-1] return sts, text else: - return commands.getstatusoutput(cmd) + return subprocess.getstatusoutput(cmd) def _GenerateGuid(): diff --git a/omaha/tools/retry.py b/omaha/tools/retry.py index 6c6756c..3c63efb 100644 --- a/omaha/tools/retry.py +++ b/omaha/tools/retry.py @@ -11,11 +11,11 @@ cmd = sys.argv[3:] # Open stdout with no buffering. -sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) +sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0) for i in range(times): if i: - print 'Retrying %d...' % i + print('Retrying %d...' % i) retcode = subprocess.call(cmd, stderr=subprocess.STDOUT) if retcode == 0: sys.exit(0) diff --git a/omaha/ui/build.scons b/omaha/ui/build.scons index 416a57b..b19d8c7 100644 --- a/omaha/ui/build.scons +++ b/omaha/ui/build.scons @@ -35,7 +35,7 @@ local_env['CPPPATH'] += ['$OBJ_ROOT'] # Build these into a static library. -local_env.ComponentStaticLibrary('ui', inputs) +local_env.ComponentLibrary('ui', inputs) ui_test_env = env.Clone() ui_test_env.Append( diff --git a/omaha/ui/complete_wnd.h b/omaha/ui/complete_wnd.h index de3453e..1b2a60e 100644 --- a/omaha/ui/complete_wnd.h +++ b/omaha/ui/complete_wnd.h @@ -16,7 +16,6 @@ #ifndef OMAHA_UI_COMPLETE_WND_H_ #define OMAHA_UI_COMPLETE_WND_H_ -#include "base/scoped_ptr.h" #include "omaha/ui/ui.h" namespace omaha { @@ -80,7 +79,7 @@ class CompleteWnd : public OmahaWnd { CompleteWndEvents* events_sink_; const DWORD control_classes_; - DISALLOW_EVIL_CONSTRUCTORS(CompleteWnd); + DISALLOW_COPY_AND_ASSIGN(CompleteWnd); }; } // namespace omaha diff --git a/omaha/ui/owner_draw_title_bar.cc b/omaha/ui/owner_draw_title_bar.cc index 87e195c..b6ec750 100644 --- a/omaha/ui/owner_draw_title_bar.cc +++ b/omaha/ui/owner_draw_title_bar.cc @@ -1,4 +1,4 @@ -// Copyright 2013 Google Inc. + // Copyright 2013 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ // Classes that help creating a owner-drawn Titlebar. #include "omaha/ui/owner_draw_title_bar.h" + +#include + #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/client/resource.h" @@ -24,10 +27,10 @@ namespace omaha { CaptionButton::CaptionButton() : bk_color_(RGB(0, 0, 0)), - is_tracking_mouse_events_(false), - is_mouse_hovering_(false), foreground_brush_(::CreateSolidBrush(kCaptionForegroundColor)), - frame_brush_(::CreateSolidBrush(kCaptionFrameColor)) { + frame_brush_(::CreateSolidBrush(kCaptionFrameColor)), + is_tracking_mouse_events_(false), + is_mouse_hovering_(false) { } CaptionButton::~CaptionButton() { @@ -211,7 +214,9 @@ MinimizeButton::MinimizeButton() { HRGN MinimizeButton::GetButtonRgn(int rgn_width, int rgn_height) { // The Minimize button is a single rectangle. - const RECT minimize_button_rect = {0, rgn_height - 2, rgn_width, rgn_height}; + CRect minimize_button_rect(0, 0, rgn_width, 2); + int center_point = rgn_height / 2; + minimize_button_rect.OffsetRect(0, center_point - 1); return ::CreateRectRgnIndirect(&minimize_button_rect); } @@ -573,7 +578,8 @@ CustomProgressBarCtrl::CustomProgressBarCtrl() : kMinPosition(0), kMaxPosition(100), kMarqueeWidth(20), - kMarqueeTimerId(1), + kMarqueeTimerId(111), + is_marquee_mode_(false), current_position_(kMinPosition), bar_color_light_(kProgressBarLightColor), bar_color_dark_(kProgressBarDarkColor), @@ -700,9 +706,8 @@ LRESULT CustomProgressBarCtrl::OnPaint(UINT, left_highlight_rect.right = left_highlight_rect.left + 1; dc.FillSolidRect(left_highlight_rect, kProgressLeftHighlightColor); - // Adjust progress bar rectangle to accomodate the highlight and shadow. - // Then draw the outer and inner frames. - // Then fill in the bar. + // Adjust progress bar rectangle to accommodate the highlight and shadow. + // Then draw the outer and inner frames. Then fill in the bar. progress_bar_rect.DeflateRect(1, 0, 0, 2); GradientFill(dc, progress_bar_rect, @@ -727,7 +732,12 @@ LRESULT CustomProgressBarCtrl::OnTimer(UINT, BOOL& handled) { // NOLINT handled = TRUE; - VERIFY1(event_id == kMarqueeTimerId); + // We only handle the timer with ID kMarqueeTimerId. + if (event_id != kMarqueeTimerId) { + handled = FALSE; + return 0; + } + ::SendMessage(m_hWnd, PBM_SETPOS, 0, 0L); return 0; } @@ -736,7 +746,9 @@ LRESULT CustomProgressBarCtrl::OnSetPos(UINT, WPARAM new_position, LPARAM, BOOL& handled) { // NOLINT - handled = TRUE; + // To allow accessibility to show the correct progress values, we pass + // PBM_SETPOS to the underlying Win32 control. + handled = FALSE; int old_position = current_position_; @@ -792,13 +804,17 @@ LRESULT CustomProgressBarCtrl::OnSetMarquee(UINT, WPARAM is_set_marquee, LPARAM update_msec, BOOL& handled) { // NOLINT - handled = TRUE; + // To allow accessibility to show the correct progress values, we pass + // PBM_SETMARQUEE to the underlying Win32 control. + handled = FALSE; - if (is_set_marquee) { + if (is_set_marquee && !is_marquee_mode_) { current_position_ = kMinPosition; VERIFY1(SetTimer(kMarqueeTimerId, static_cast(update_msec))); - } else { + is_marquee_mode_ = true; + } else if (!is_set_marquee && is_marquee_mode_) { VERIFY1(KillTimer(kMarqueeTimerId)); + is_marquee_mode_ = false; } VERIFY1(RedrawWindow()); diff --git a/omaha/ui/owner_draw_title_bar.h b/omaha/ui/owner_draw_title_bar.h index 6f42b95..ecbf990 100644 --- a/omaha/ui/owner_draw_title_bar.h +++ b/omaha/ui/owner_draw_title_bar.h @@ -33,26 +33,25 @@ // wtl_atlapp_wrapper.h as a project-specific header and is unhappy with the // header order. Hence all the NOLINT for the atl/wtl headers. #include "omaha/base/wtl_atlapp_wrapper.h" -#include // NOLINT +#include // NOLINT #include // NOLINT #include // NOLINT -#include // NOLINT -#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT + +#include "base\basictypes.h" namespace omaha { class CaptionButton : public CWindowImpl, public COwnerDraw { public: - #pragma warning(push) - // C4640: construction of local static object is not thread-safe - #pragma warning(disable : 4640) // This class uses DECLARE_WND_CLASS_EX because DECLARE_WND_CLASS includes the // CS_DBLCLKS style which we want to avoid. DECLARE_WND_CLASS_EX(_T("CaptionButton"), CS_HREDRAW | CS_VREDRAW, COLOR_WINDOW) - #pragma warning(pop) BEGIN_MSG_MAP(CaptionButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) @@ -148,15 +147,11 @@ class MaximizeButton : public CaptionButton { class OwnerDrawTitleBarWindow : public CWindowImpl { public: - #pragma warning(push) - // C4640: construction of local static object is not thread-safe - #pragma warning(disable : 4640) // This class uses DECLARE_WND_CLASS_EX because DECLARE_WND_CLASS includes the // CS_DBLCLKS style which we want to avoid. DECLARE_WND_CLASS_EX(_T("OwnerDrawTitleBarWindow"), CS_HREDRAW | CS_VREDRAW, COLOR_WINDOW) - #pragma warning(pop) BEGIN_MSG_MAP(OwnerDrawTitleBarWindow) MESSAGE_HANDLER(WM_CREATE, OnCreate) @@ -353,6 +348,7 @@ class CustomProgressBarCtrl : public CWindowImpl { const int kMarqueeWidth; const UINT_PTR kMarqueeTimerId; + bool is_marquee_mode_; int current_position_; COLORREF bar_color_light_; diff --git a/omaha/ui/progress_wnd.cc b/omaha/ui/progress_wnd.cc index a563c6b..2f2ca51 100644 --- a/omaha/ui/progress_wnd.cc +++ b/omaha/ui/progress_wnd.cc @@ -190,6 +190,8 @@ LRESULT ProgressWnd::OnInitDialog(UINT message, InitializeDialog(); + VERIFY1(SUCCEEDED(SetMarqueeMode(true))); + CString state_text; VERIFY1(state_text.LoadString(IDS_INITIALIZING)); VERIFY1(::SetWindowText(GetDlgItem(IDC_INSTALLER_STATE_TEXT), state_text)); @@ -498,7 +500,9 @@ void ProgressWnd::OnDownloading(const CString& app_id, // the user has no indication something is still going on. // TODO(omaha): when resuming an incomplete download this will not work. VERIFY1(SUCCEEDED(SetMarqueeMode(pos == 0))); - SendDlgItemMessage(IDC_PROGRESS, PBM_SETPOS, pos, 0); + if (pos > 0) { + SendDlgItemMessage(IDC_PROGRESS, PBM_SETPOS, pos, 0); + } } void ProgressWnd::OnWaitingRetryDownload(const CString& app_id, @@ -838,13 +842,15 @@ HRESULT ProgressWnd::ChangeControlState() { } HRESULT ProgressWnd::SetMarqueeMode(bool is_marquee) { + CWindow progress_bar = GetDlgItem(IDC_PROGRESS); + LONG_PTR style = progress_bar.GetWindowLongPtr(GWL_STYLE); if (is_marquee) { - GetDlgItem(IDC_MARQUEE).ShowWindow(SW_SHOW); - GetDlgItem(IDC_PROGRESS).ShowWindow(SW_HIDE); + style |= PBS_MARQUEE; } else { - GetDlgItem(IDC_MARQUEE).ShowWindow(SW_HIDE); - GetDlgItem(IDC_PROGRESS).ShowWindow(SW_SHOW); + style &= ~PBS_MARQUEE; } + progress_bar.SetWindowLongPtr(GWL_STYLE, style); + progress_bar.SendMessage(PBM_SETMARQUEE, !!is_marquee, 0); return S_OK; } diff --git a/omaha/ui/progress_wnd.h b/omaha/ui/progress_wnd.h index 8677fb9..dcc82fc 100644 --- a/omaha/ui/progress_wnd.h +++ b/omaha/ui/progress_wnd.h @@ -17,12 +17,13 @@ #define OMAHA_UI_PROGRESS_WND_H_ #include +#include #include -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" + #include "omaha/base/time.h" #include "omaha/base/wtl_atlapp_wrapper.h" #include "omaha/client/install_progress_observer.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/complete_wnd.h" #include "omaha/ui/owner_draw_title_bar.h" @@ -103,7 +104,7 @@ class InstallStoppedWnd CFont default_font_; - DISALLOW_EVIL_CONSTRUCTORS(InstallStoppedWnd); + DISALLOW_COPY_AND_ASSIGN(InstallStoppedWnd); }; @@ -113,7 +114,7 @@ class ProgressWnd public InstallProgressObserver { public: ProgressWnd(CMessageLoop* message_loop, HWND parent); - virtual ~ProgressWnd(); + ~ProgressWnd() override; void SetEventSink(ProgressWndEvents* ev); @@ -209,11 +210,11 @@ class ProgressWnd STATE_END, }; - scoped_ptr metrics_timer_; + std::unique_ptr metrics_timer_; States cur_state_; - scoped_ptr install_stopped_wnd_; + std::unique_ptr install_stopped_wnd_; ProgressWndEvents* events_sink_; std::vector post_install_urls_; @@ -231,7 +232,7 @@ class ProgressWnd static const int kMarqueeModeUpdatesMs = 75; friend class UITest; - DISALLOW_EVIL_CONSTRUCTORS(ProgressWnd); + DISALLOW_COPY_AND_ASSIGN(ProgressWnd); }; } // namespace omaha diff --git a/omaha/ui/progress_wnd_unittest.cc b/omaha/ui/progress_wnd_unittest.cc index ed3f1d2..9d0d5e2 100644 --- a/omaha/ui/progress_wnd_unittest.cc +++ b/omaha/ui/progress_wnd_unittest.cc @@ -233,7 +233,7 @@ TEST_F(UITest, OnCompleteError) { FormatWindowTitle(_T("Complete error")); progress_wnd_.OnComplete( COMPLETION_CODE_ERROR, - _T("An error occured while installing Gears: an existing copy of ") + _T("An error occurred while installing Gears: an existing copy of ") _T("Gears is currently running. Please exit the software and ") _T("retry installation. For more information visit the ") _T("Gears web site."), @@ -294,7 +294,7 @@ TEST_F(UITest, OnMultipleCompletes) { FormatWindowTitle(_T("Complete error")); progress_wnd_.OnComplete( COMPLETION_CODE_ERROR, - _T("An error occured while installing Gears: an existing copy of ") + _T("An error occurred while installing Gears: an existing copy of ") _T("Gears is currently running. Please exit the software and ") _T("retry installation. For more information visit the ") _T("Gears web site."), diff --git a/omaha/ui/scoped_gdi.h b/omaha/ui/scoped_gdi.h index bdceeed..7d8ee82 100644 --- a/omaha/ui/scoped_gdi.h +++ b/omaha/ui/scoped_gdi.h @@ -40,7 +40,7 @@ #define OMAHA_UI_SCOPED_GDI_H_ #include -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/ui/splash_screen.cc b/omaha/ui/splash_screen.cc index 158f1d3..8f102da 100644 --- a/omaha/ui/splash_screen.cc +++ b/omaha/ui/splash_screen.cc @@ -28,7 +28,6 @@ #include "omaha/common/lang.h" #include "omaha/google_update/resource.h" // For the IDI_APP #include "omaha/goopdate/non_localized_resource.h" -#include "omaha/ui/scoped_gdi.h" #include "omaha/ui/ui.h" namespace { @@ -52,8 +51,8 @@ namespace omaha { SplashScreen::SplashScreen(const CString& bundle_name) : IDD(IDD_PROGRESS), - alpha_index_(0), - timer_created_(false) { + timer_created_(false), + alpha_index_(0) { CORE_LOG(L3, (_T("[SplashScreen::SplashScreen]"))); caption_ = client_utils::GetInstallerDisplayName(bundle_name); text_.LoadString(IDS_SPLASH_SCREEN_MESSAGE); @@ -160,20 +159,6 @@ HRESULT SplashScreen::Initialize() { (EnableFlatButtons(m_hWnd)); - // ::GetModuleHandle(kOmahaDllName) is needed to allow the Splash Screen unit - // test to work, since it runs under omaha_unittest.exe. In production, since - // this code runs from goopdate.dll, the ::GetModuleHandle(kOmahaDllName) is - // unnecessary, and even if ::GetModuleHandle(kOmahaDllName) returns NULL, the - // code will work as expected since Animate_OpenEx will get the resource from - // the current module. - const HMODULE module_omaha_dll(::GetModuleHandle(kOmahaDllName)); - VERIFY1(Animate_OpenEx(GetDlgItem(IDC_MARQUEE), - module_omaha_dll, - MAKEINTRESOURCE(IDR_MARQUEE))); - VERIFY1(Animate_Play(GetDlgItem(IDC_MARQUEE), 0, -1, -1)); - - GetDlgItem(IDC_MARQUEE).ShowWindow(SW_SHOW); - SwitchToState(STATE_INITIALIZED); return S_OK; } @@ -198,11 +183,10 @@ void SplashScreen::EnableSystemButtons(bool enable) { void SplashScreen::InitProgressBar() { progress_bar_.SubclassWindow(GetDlgItem(IDC_PROGRESS)); - const LONG kStyle = WS_CHILD | WS_VISIBLE | PBS_SMOOTH; - - CWindow progress_bar = GetDlgItem(IDC_PROGRESS); - LONG style = progress_bar.GetWindowLong(GWL_STYLE) | kStyle; - progress_bar.SetWindowLong(GWL_STYLE, style); + LONG_PTR style = progress_bar_.GetWindowLongPtr(GWL_STYLE); + style |= PBS_MARQUEE | WS_CHILD | WS_VISIBLE; + progress_bar_.SetWindowLongPtr(GWL_STYLE, style); + progress_bar_.SendMessage(PBM_SETMARQUEE, true, 0); } LRESULT SplashScreen::OnTimer(UINT message, @@ -237,10 +221,6 @@ LRESULT SplashScreen::OnClose(UINT message, UNREFERENCED_PARAMETER(wparam); UNREFERENCED_PARAMETER(lparam); - GetDlgItem(IDC_MARQUEE).ShowWindow(SW_HIDE); - - VERIFY1(Animate_Stop(GetDlgItem(IDC_MARQUEE))); - DestroyWindow(); handled = TRUE; return 0; diff --git a/omaha/ui/splash_screen.h b/omaha/ui/splash_screen.h index cbc19ff..a21dc30 100644 --- a/omaha/ui/splash_screen.h +++ b/omaha/ui/splash_screen.h @@ -16,12 +16,13 @@ #ifndef OMAHA_UI_SPLASH_SCREEN_H_ #define OMAHA_UI_SPLASH_SCREEN_H_ -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" +#include + #include "omaha/base/smart_handle.h" #include "omaha/base/synchronized.h" #include "omaha/base/thread.h" #include "omaha/base/wtl_atlapp_wrapper.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/owner_draw_title_bar.h" namespace omaha { diff --git a/omaha/ui/splash_screen_test.cc b/omaha/ui/splash_screen_test.cc index 6e71350..397e392 100644 --- a/omaha/ui/splash_screen_test.cc +++ b/omaha/ui/splash_screen_test.cc @@ -22,13 +22,13 @@ #include #include "omaha/base/app_util.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/smart_handle.h" #include "omaha/base/string.h" #include "omaha/base/utils.h" #include "omaha/goopdate/resource_manager.h" #include "omaha/testing/resource.h" #include "omaha/testing/unit_test.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/splash_screen.h" namespace omaha { diff --git a/omaha/ui/ui.cc b/omaha/ui/ui.cc index 2b1c127..7a12632 100644 --- a/omaha/ui/ui.cc +++ b/omaha/ui/ui.cc @@ -111,11 +111,6 @@ void OmahaWnd::InitializeDialog() { // NOLINT VERIFY1(error_font_.CreatePointFont(110, _T("Segoe UI"))); GetDlgItem(IDC_ERROR_TEXT).SetFont(error_font_); - VERIFY1(Animate_OpenEx(GetDlgItem(IDC_MARQUEE), - app_util::GetCurrentModuleHandle(), - MAKEINTRESOURCE(IDR_MARQUEE))); - VERIFY1(Animate_Play(GetDlgItem(IDC_MARQUEE), 0, -1, -1)); - CreateOwnerDrawTitleBar(m_hWnd, GetDlgItem(IDC_TITLE_BAR_SPACER), kBkColor); SetCustomDlgColors(kTextColor, kBkColor); @@ -136,8 +131,6 @@ LRESULT OmahaWnd::OnClose(UINT, } HRESULT OmahaWnd::CloseWindow() { - VERIFY1(Animate_Stop(GetDlgItem(IDC_MARQUEE))); - HRESULT hr = DestroyWindow() ? S_OK : HRESULTFromLastError(); if (events_sink_) { events_sink_->DoClose(); diff --git a/omaha/ui/ui.h b/omaha/ui/ui.h index 00c5a06..c867d28 100644 --- a/omaha/ui/ui.h +++ b/omaha/ui/ui.h @@ -19,15 +19,15 @@ #include #include #include + #include "base/basictypes.h" -#include "base/scoped_ptr.h" -#include "omaha/base/scoped_any.h" #include "omaha/base/wtl_atlapp_wrapper.h" // TODO(omaha3): Depending on how separate the UI is, we may want to separate // the UI-specific resources, especially the dialogs. Can we handle bidi // independent of languages? This would allow simple replacement of Omaha's // UI without impacting the core or error messages. #include "omaha/client/resource.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/owner_draw_title_bar.h" namespace omaha { @@ -174,7 +174,7 @@ class OmahaWnd CustomProgressBarCtrl progress_bar_; - DISALLOW_EVIL_CONSTRUCTORS(OmahaWnd); + DISALLOW_COPY_AND_ASSIGN(OmahaWnd); }; // Registers the specified common control classes from the common control DLL. diff --git a/omaha/ui/ui_ctls.h b/omaha/ui/ui_ctls.h index 4c831b9..1b8f1f9 100644 --- a/omaha/ui/ui_ctls.h +++ b/omaha/ui/ui_ctls.h @@ -28,28 +28,12 @@ const ProgressWnd::ControlState ProgressWnd::ctls_[] = { // The struct values are: // is_ignore_entry, is_visible, is_enabled, is_button, is_default { IDC_PROGRESS, - { { false, false, false, false, false }, // STATE_INIT - { false, false, false, false, false }, // STATE_CHECKING_FOR_UPDATE - { false, false, false, false, false }, // STATE_WAITING_TO_DOWNLOAD - { true, false, false, false, false }, // STATE_DOWNLOADING - { false, false, false, false, false }, // STATE_WAITING_TO_INSTALL - { false, false, false, false, false }, // STATE_INSTALLING - { false, false, false, false, false }, // STATE_PAUSED - { false, false, false, false, false }, // STATE_COMPLETE_SUCCESS - { false, false, false, false, false }, // STATE_COMPLETE_ERROR - { false, false, false, false, false }, // STATE_COMPLETE_RESTART_BROWSER - { false, false, false, false, false }, // COMPLETE_RESTART_ALL_BROWSERS - { false, false, false, false, false }, // STATE_COMPLETE_REBOOT - { false, false, false, false, false }, // STATE_END - }, - }, - { IDC_MARQUEE, - { { false, true, false, false, false }, // STATE_INIT - { false, true, false, false, false }, // STATE_CHECKING_FOR_UPDATE - { false, true, false, false, false }, // STATE_WAITING_TO_DOWNLOAD - { true, false, false, false, false }, // STATE_DOWNLOADING - { false, true, false, false, false }, // STATE_WAITING_TO_INSTALL - { true, false, false, false, false }, // STATE_INSTALLING + { { false, true, false, false, false }, // STATE_INIT + { false, true, false, false, false }, // STATE_CHECKING_FOR_UPDATE + { false, true, false, false, false }, // STATE_WAITING_TO_DOWNLOAD + { false, true, false, false, false }, // STATE_DOWNLOADING + { false, true, false, false, false }, // STATE_WAITING_TO_INSTALL + { false, true, false, false, false }, // STATE_INSTALLING { false, false, false, false, false }, // STATE_PAUSED { false, false, false, false, false }, // STATE_COMPLETE_SUCCESS { false, false, false, false, false }, // STATE_COMPLETE_ERROR diff --git a/omaha/ui/ui_displayed_event.h b/omaha/ui/ui_displayed_event.h index 50fe728..bb8caf0 100644 --- a/omaha/ui/ui_displayed_event.h +++ b/omaha/ui/ui_displayed_event.h @@ -22,7 +22,7 @@ #define OMAHA_UI_UI_DISPLAYED_EVENT_H_ #include -#include "omaha/base/scoped_any.h" +#include "omaha/third_party/smartany/scoped_any.h" namespace omaha { diff --git a/omaha/ui/yes_no_dialog.h b/omaha/ui/yes_no_dialog.h index 45127e9..349cab2 100644 --- a/omaha/ui/yes_no_dialog.h +++ b/omaha/ui/yes_no_dialog.h @@ -16,9 +16,11 @@ #ifndef OMAHA_UI_YES_NO_DIALOG_H_ #define OMAHA_UI_YES_NO_DIALOG_H_ -#include "omaha/base/scoped_any.h" +#include + #include "omaha/base/wtl_atlapp_wrapper.h" #include "omaha/client/resource.h" +#include "omaha/third_party/smartany/scoped_any.h" #include "omaha/ui/owner_draw_title_bar.h" namespace omaha { diff --git a/third_party/breakpad b/third_party/breakpad index 33c2477..4a6d7c7 160000 --- a/third_party/breakpad +++ b/third_party/breakpad @@ -1 +1 @@ -Subproject commit 33c24776f30e58420b73d7a8bef9639faf30e1c6 +Subproject commit 4a6d7c70cc5a007bbd8de2f5a2e226b212e3256f diff --git a/third_party/googletest b/third_party/googletest index a2b8a8e..947aeab 160000 --- a/third_party/googletest +++ b/third_party/googletest @@ -1 +1 @@ -Subproject commit a2b8a8e07628e5fd60644b6dd99c1b5e7d7f1f47 +Subproject commit 947aeab281f1b160d2db5045064be73c984f1ae6 diff --git a/third_party/libzip/API-CHANGES.md b/third_party/libzip/API-CHANGES.md new file mode 100644 index 0000000..24e3d8e --- /dev/null +++ b/third_party/libzip/API-CHANGES.md @@ -0,0 +1,162 @@ +# libzip API changes + +This file describes changes in the libzip API and how to adapt your +code for them. + +You can define `ZIP_DISABLE_DEPRECATED` before including `` to hide +prototypes for deprecated functions, to find out about functions that +might be removed at some point. + +## Changed in libzip-1.0 + +### new type `zip_error_t` + +Error information is stored in the newly public type `zip_error_t`. Use +this to access information about an error, instead of the deprecated +functions that operated on two ints. + +deprecated functions: +- `zip_error_get_sys_type()` +- `zip_error_get()` +- `zip_error_to_str()` +- `zip_file_error_get()` + +See their man pages for instructions on how to replace them. + +The most common affected use is `zip_open`. The new recommended usage +is: + +```c +int err; +if ((za = zip_open(archive, flags, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "can't open zip archive '%s': %s\n", archive, zip_error_strerror(&error)); + zip_error_fini(&error); +} +``` + +### more typedefs + +The following typedefs have been added for better readability: + +```c +typedef struct zip zip_t; +typedef struct zip_file zip_file_t; +typedef struct zip_source zip_source_t; +typedef struct zip_stat zip_stat_t; +``` + +This means you can use "`zip_t`" instead of "`struct zip`", etc. + + +### torrentzip support removed + +torrentzip depends on a particular zlib version which is by now quite +old. + +## Changed in libzip-0.11 + +### new type `zip_flags_t` + +The functions which have flags now use the `zip_flags_t` type for this. +All old flags fit; you need only to adapt code if you were saving flags in a +local variable. Use `zip_flags_t` for such a variable. +This affects: +- `zip_fopen()` +- `zip_fopen_encrypted()` +- `zip_fopen_index()` +- `zip_fopen_index_encrypted()` +- `zip_get_archive_comment()` +- `zip_get_archive_flag()` +- `zip_get_num_entries()` +- `zip_get_name()` +- `zip_name_locate()` +- `zip_set_archive_flag()` +- `zip_source_zip()` +- `zip_stat()` +- `zip_stat_index()` + +#### `ZIP_FL_*`, `ZIP_AFL_*`, `ZIP_STAT_*` are now unsigned constants + +To match the new `zip_flags_t` type. + +#### `zip_add()`, `zip_add_dir()` + +These functions were replaced with `zip_file_add()` and `zip_dir_add()`, respectively, +to add a flags argument. + +#### `zip_rename()`, `zip_replace()` + +These functions were replaced with `zip_file_rename()` and `zip_file_replace()`, +respectively, to add a flags argument. + +#### `zip_get_file_comment()` + +This function was replaced with `zip_file_get_comment()`; one argument was promoted from +`int` to `zip_uint32_t`, the other is now a `zip_flags_t`. + +#### `zip_set_file_comment()` + +This function was replaced with `zip_file_set_comment()`; an argument was promoted from +`int` to `zip_uint16_t`, and a `zip_flags_t` argument was added. + +### integer type size changes + +Some argument and return values were not the right size or sign. + +#### `zip_name_locate()` + +The return value was `int`, which can be too small. The function now returns `zip_int64_t`. + + +#### `zip_get_num_entries()` + +The return type is now signed, to allow signaling errors. + +#### `zip_set_archive_comment()` + +The last argument changed from `int` to `zip_uint16_t`. + +### extra field handling rewritten + +The `zip_get_file_extra()` and `zip_set_file_extra()` functions were removed. +They only worked on the whole extra field set. + +Instead, you can now set, get, count, and delete each extra field separately, +using the functions: +- `zip_file_extra_field_delete()` +- `zip_file_extra_field_delete_by_id()` +- `zip_file_extra_field_get()` +- `zip_file_extra_field_get_by_id()` +- `zip_file_extra_fields_count()` +- `zip_file_extra_fields_count_by_id()` +- `zip_file_extra_field_set()` + +Please read the corresponding man pages for details. + +### new functions + +#### `zip_discard()` + +The new `zip_discard()` function closes an archive without committing the +scheduled changes. + +#### `zip_set_file_compression()` + +The new `zip_set_file_compression()` function allows setting compression +levels for files. + +### argument changes + +#### file names + +File names arguments are now allowed to be `NULL` to have an empty file name. +This mostly affects `zip_file_add()`, `zip_dir_add()`, and `zip_file_rename()`. + +For `zip_get_name()`, `zip_file_get_comment()`, and `zip_get_archive_comment()`, if +the file name or comment is empty, a string of length 0 is returned. +`NULL` is returned for errors only. + +Previously, `NULL` was returned for empty/unset file names and comments and +errors, leaving no way to differentiate between the two. diff --git a/third_party/libzip/AUTHORS b/third_party/libzip/AUTHORS new file mode 100644 index 0000000..a33707b --- /dev/null +++ b/third_party/libzip/AUTHORS @@ -0,0 +1,2 @@ +Dieter Baron +Thomas Klausner diff --git a/third_party/libzip/CMakeLists.txt b/third_party/libzip/CMakeLists.txt new file mode 100644 index 0000000..8008995 --- /dev/null +++ b/third_party/libzip/CMakeLists.txt @@ -0,0 +1,420 @@ +# TODO: +# create usable libtool .la file + +CMAKE_MINIMUM_REQUIRED(VERSION 3.0.2) + +LIST(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +PROJECT(libzip C) + +OPTION(ENABLE_COMMONCRYPTO "Enable use of CommonCrypto" ON) +OPTION(ENABLE_GNUTLS "Enable use of GnuTLS" ON) +OPTION(ENABLE_MBEDTLS "Enable use of mbed TLS" ON) +OPTION(ENABLE_OPENSSL "Enable use of OpenSSL" ON) +OPTION(ENABLE_WINDOWS_CRYPTO "Enable use of Windows cryptography libraries" ON) + +OPTION(ENABLE_BZIP2 "Enable use of BZip2" ON) + +OPTION(BUILD_TOOLS "Build tools in the src directory (zipcmp, zipmerge, ziptool)" ON) +OPTION(BUILD_REGRESS "Build regression tests" ON) +OPTION(BUILD_EXAMPLES "Build examples" ON) +OPTION(BUILD_DOC "Build documentation" ON) + +INCLUDE(CheckFunctionExists) +INCLUDE(CheckIncludeFiles) +INCLUDE(CheckSymbolExists) +INCLUDE(CheckTypeSize) +INCLUDE(CheckCSourceRuns) +INCLUDE(CheckCSourceCompiles) +INCLUDE(CheckStructHasMember) +INCLUDE(TestBigEndian) +INCLUDE(GNUInstallDirs) +IF(ENABLE_COMMONCRYPTO) + CHECK_INCLUDE_FILES(CommonCrypto/CommonCrypto.h COMMONCRYPTO_FOUND) +ELSE() + SET(COMMONCRYPTO_FOUND FALSE) +ENDIF() +IF(ENABLE_GNUTLS) + INCLUDE(FindNettle) + INCLUDE(FindGnuTLS) +ELSE() + SET(GNUTLS_FOUND FALSE) +ENDIF() +IF(ENABLE_MBEDTLS) + FIND_PATH(MBEDTLS_INCLUDE_DIR mbedtls/aes.h) + FIND_LIBRARY(MBEDTLS_LIBRARIES NAMES mbedtls) +ELSE() + SET(MBEDTLS_LIBRARIES FALSE) +ENDIF() +IF(ENABLE_OPENSSL) + INCLUDE(FindOpenSSL) +ELSE() + SET(OPENSSL_FOUND FALSE) +ENDIF() +IF(WIN32) + IF(ENABLE_WINDOWS_CRYPTO) + SET(WINDOWS_CRYPTO_FOUND TRUE) + ENDIF() +ELSE() + SET(WINDOWS_CRYPTO_FOUND FALSE) +ENDIF() + +OPTION(BUILD_SHARED_LIBS "Build shared libraries" ON) + + +OPTION(SHARED_LIB_VERSIONNING "Add SO version in .so build" ON) + +FIND_PROGRAM(MDOCTOOL NAMES mandoc groff) +IF (MDOCTOOL) + SET(DOCUMENTATION_FORMAT "mdoc" CACHE STRING "Documentation format") +ELSE() + FIND_PROGRAM(MANTOOL NAMES nroff) + IF (MANTOOL) + SET(DOCUMENTATION_FORMAT "man" CACHE STRING "Documentation format") + ELSE() + SET(DOCUMENTATION_FORMAT "html" CACHE STRING "Documentation format") + ENDIF() +ENDIF() + +SET(PACKAGE "libzip") +SET(PACKAGE_NAME ${PACKAGE}) +SET(PACKAGE_VERSION_MAJOR "1") +SET(PACKAGE_VERSION_MINOR "5") +SET(PACKAGE_VERSION_MICRO "2") +#SET(VERSION "${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}") +SET(VERSION "${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}.${PACKAGE_VERSION_MICRO}") +SET(PACKAGE_VERSION ${VERSION}) +SET(LIBZIP_VERSION ${PACKAGE_VERSION}) +SET(LIBZIP_VERSION_MAJOR ${PACKAGE_VERSION_MAJOR}) +SET(LIBZIP_VERSION_MINOR ${PACKAGE_VERSION_MINOR}) +SET(LIBZIP_VERSION_MICRO ${PACKAGE_VERSION_MICRO}) +SET(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") + +SET(ARCHIVE_NAME ${PACKAGE_NAME}-${PACKAGE_VERSION}) +ADD_CUSTOM_TARGET(dist + COMMAND git config tar.tar.xz.command "xz -c" + COMMAND git archive --prefix=${ARCHIVE_NAME}/ -o ${ARCHIVE_NAME}.tar.gz HEAD + COMMAND git archive --prefix=${ARCHIVE_NAME}/ -o ${ARCHIVE_NAME}.tar.xz HEAD + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + ) +ADD_CUSTOM_TARGET(distcheck + COMMAND chmod -R u+w ${ARCHIVE_NAME} ${ARCHIVE_NAME}-build ${ARCHIVE_NAME}-dest 2>/dev/null || true + COMMAND rm -rf ${ARCHIVE_NAME} ${ARCHIVE_NAME}-build ${ARCHIVE_NAME}-dest + COMMAND cmake -E tar xf ${ARCHIVE_NAME}.tar.gz + COMMAND chmod -R u-w ${ARCHIVE_NAME} + COMMAND mkdir ${ARCHIVE_NAME}-build + COMMAND mkdir ${ARCHIVE_NAME}-dest + COMMAND cd ${ARCHIVE_NAME}-build && cmake -DCMAKE_INSTALL_PREFIX=../${ARCHIVE_NAME}-dest ../${ARCHIVE_NAME} + COMMAND cd ${ARCHIVE_NAME}-build && make -j4 + COMMAND cd ${ARCHIVE_NAME}-build && make test + COMMAND cd ${ARCHIVE_NAME}-build && make install +# COMMAND cd ${ARCHIVE_NAME}-build && make uninstall +# COMMAND if [ `find ${ARCHIVE_NAME}-dest ! -type d | wc -l` -ne 0 ]; then echo leftover files in ${ARCHIVE_NAME}-dest; false; fi + COMMAND cd ${ARCHIVE_NAME}-build && make clean + COMMAND chmod -R u+w ${ARCHIVE_NAME} ${ARCHIVE_NAME}-build ${ARCHIVE_NAME}-dest + COMMAND rm -rf ${ARCHIVE_NAME} ${ARCHIVE_NAME}-build ${ARCHIVE_NAME}-dest + COMMAND echo "${ARCHIVE_NAME}.tar.gz is ready for distribution." + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + ) +ADD_DEPENDENCIES(distcheck dist) + +IF(BUILD_SHARED_LIBS) + SET(HAVE_SHARED TRUE) +ELSE() + SET(ZIP_STATIC TRUE) +ENDIF() + +# Checks + +CHECK_FUNCTION_EXISTS(_chmod HAVE__CHMOD) +CHECK_FUNCTION_EXISTS(_close HAVE__CLOSE) +CHECK_FUNCTION_EXISTS(_dup HAVE__DUP) +CHECK_FUNCTION_EXISTS(_fdopen HAVE__FDOPEN) +CHECK_FUNCTION_EXISTS(_fileno HAVE__FILENO) +CHECK_FUNCTION_EXISTS(_open HAVE__OPEN) +CHECK_FUNCTION_EXISTS(_setmode HAVE__SETMODE) +CHECK_FUNCTION_EXISTS(_snprintf HAVE__SNPRINTF) +CHECK_FUNCTION_EXISTS(_strdup HAVE__STRDUP) +CHECK_FUNCTION_EXISTS(_stricmp HAVE__STRICMP) +CHECK_FUNCTION_EXISTS(_strtoi64 HAVE__STRTOI64) +CHECK_FUNCTION_EXISTS(_strtoui64 HAVE__STRTOUI64) +CHECK_FUNCTION_EXISTS(_umask HAVE__UMASK) +CHECK_FUNCTION_EXISTS(_unlink HAVE__UNLINK) +CHECK_FUNCTION_EXISTS(clonefile HAVE_CLONEFILE) +CHECK_FUNCTION_EXISTS(explicit_bzero HAVE_EXPLICIT_BZERO) +CHECK_FUNCTION_EXISTS(explicit_memset HAVE_EXPLICIT_MEMSET) +CHECK_FUNCTION_EXISTS(fileno HAVE_FILENO) +CHECK_FUNCTION_EXISTS(fseeko HAVE_FSEEKO) +CHECK_FUNCTION_EXISTS(ftello HAVE_FTELLO) +CHECK_FUNCTION_EXISTS(getprogname HAVE_GETPROGNAME) +CHECK_FUNCTION_EXISTS(open HAVE_OPEN) +CHECK_FUNCTION_EXISTS(mkstemp HAVE_MKSTEMP) +CHECK_FUNCTION_EXISTS(setmode HAVE_SETMODE) +CHECK_FUNCTION_EXISTS(snprintf HAVE_SNPRINTF) +CHECK_FUNCTION_EXISTS(strcasecmp HAVE_STRCASECMP) +CHECK_FUNCTION_EXISTS(strdup HAVE_STRDUP) +CHECK_FUNCTION_EXISTS(stricmp HAVE_STRICMP) +CHECK_FUNCTION_EXISTS(strtoll HAVE_STRTOLL) +CHECK_FUNCTION_EXISTS(strtoull HAVE_STRTOULL) + +CHECK_INCLUDE_FILES("sys/types.h;sys/stat.h;fts.h" HAVE_FTS_H) +CHECK_INCLUDE_FILES(stdbool.h HAVE_STDBOOL_H) +CHECK_INCLUDE_FILES(strings.h HAVE_STRINGS_H) +CHECK_INCLUDE_FILES(unistd.h HAVE_UNISTD_H) + +CHECK_INCLUDE_FILES(inttypes.h HAVE_INTTYPES_H_LIBZIP) +CHECK_INCLUDE_FILES(stdint.h HAVE_STDINT_H_LIBZIP) +CHECK_INCLUDE_FILES(sys/types.h HAVE_SYS_TYPES_H_LIBZIP) + +# TODO: fix test +# this test does not find __progname even when it exists +#CHECK_SYMBOL_EXISTS(__progname stdlib.h HAVE___PROGNAME) + +CHECK_TYPE_SIZE(__int8 __INT8_LIBZIP) +CHECK_TYPE_SIZE(int8_t INT8_T_LIBZIP) +CHECK_TYPE_SIZE(uint8_t UINT8_T_LIBZIP) +CHECK_TYPE_SIZE(__int16 __INT16_LIBZIP) +CHECK_TYPE_SIZE(int16_t INT16_T_LIBZIP) +CHECK_TYPE_SIZE(uint16_t UINT16_T_LIBZIP) +CHECK_TYPE_SIZE(__int32 __INT32_LIBZIP) +CHECK_TYPE_SIZE(int32_t INT32_T_LIBZIP) +CHECK_TYPE_SIZE(uint32_t UINT32_T_LIBZIP) +CHECK_TYPE_SIZE(__int64 __INT64_LIBZIP) +CHECK_TYPE_SIZE(int64_t INT64_T_LIBZIP) +CHECK_TYPE_SIZE(uint64_t UINT64_T_LIBZIP) +CHECK_TYPE_SIZE("short" SHORT_LIBZIP) +CHECK_TYPE_SIZE("int" INT_LIBZIP) +CHECK_TYPE_SIZE("long" LONG_LIBZIP) +CHECK_TYPE_SIZE("long long" LONG_LONG_LIBZIP) +CHECK_TYPE_SIZE("off_t" SIZEOF_OFF_T) +CHECK_TYPE_SIZE("size_t" SIZE_T_LIBZIP) +CHECK_TYPE_SIZE("ssize_t" SSIZE_T_LIBZIP) + +CHECK_C_SOURCE_COMPILES("#include +#include +int main(int argc, char *argv[]) { unsigned long x = FICLONERANGE; }" HAVE_FICLONERANGE) + +CHECK_C_SOURCE_COMPILES(" +int foo(char * _Nullable bar); +int main(int argc, char *argv[]) { }" HAVE_NULLABLE) + +TEST_BIG_ENDIAN(WORDS_BIGENDIAN) + +FIND_PACKAGE(ZLIB REQUIRED) +INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR}) +SET(CMAKE_REQUIRED_INCLUDES ${ZLIB_INCLUDE_DIR}) +IF(ZLIB_VERSION_STRING VERSION_LESS "1.1.2") + MESSAGE(FATAL_ERROR "-- ZLIB version too old, please install at least v1.1.2") +ENDIF(ZLIB_VERSION_STRING VERSION_LESS "1.1.2") + +IF(ENABLE_BZIP2) + FIND_PACKAGE(BZip2) + IF(BZIP2_FOUND) + SET (HAVE_LIBBZ2 1) + + INCLUDE_DIRECTORIES(${BZIP2_INCLUDE_DIR}) + SET (OPTIONAL_LIBRARY ${BZIP2_LIBRARY}) + ELSE() + MESSAGE(WARNING "-- bzip2 library not found; bzip2 support disabled") + ENDIF(BZIP2_FOUND) +ENDIF(ENABLE_BZIP2) + +IF (COMMONCRYPTO_FOUND) + SET (HAVE_CRYPTO 1) + SET (HAVE_COMMONCRYPTO 1) +ELSEIF (WINDOWS_CRYPTO_FOUND) + SET (HAVE_CRYPTO 1) + SET (HAVE_WINDOWS_CRYPTO 1) +ELSEIF (GNUTLS_FOUND AND NETTLE_FOUND) + SET (HAVE_CRYPTO 1) + SET (HAVE_GNUTLS 1) + INCLUDE_DIRECTORIES(${GNUTLS_INCLUDE_DIR} ${NETTLE_INCLUDE_DIR}) + SET (OPTIONAL_LIBRARY ${OPTIONAL_LIBRARY} ${GNUTLS_LIBRARY} ${NETTLE_LIBRARY}) +ELSEIF (OPENSSL_FOUND) + SET (HAVE_CRYPTO 1) + SET (HAVE_OPENSSL 1) + INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR}) + SET (OPTIONAL_LIBRARY ${OPTIONAL_LIBRARY} ${OPENSSL_LIBRARIES}) +ELSEIF (MBEDTLS_LIBRARIES) + SET (HAVE_CRYPTO 1) + SET (HAVE_MBEDTLS 1) + INCLUDE_DIRECTORIES(${MBEDTLS_INCLUDE_DIR}) + SET (OPTIONAL_LIBRARY ${OPTIONAL_LIBRARY} ${MBEDTLS_LIBRARIES}) +ENDIF() + +IF (NOT HAVE_CRYPTO) + MESSAGE(WARNING "-- neither Common Crypto, GnuTLS, mbed TLS, OpenSSL, nor Windows Cryptography found; AES support disabled") +ENDIF() + +IF(MSVC) +ADD_DEFINITIONS("-D_CRT_SECURE_NO_WARNINGS") +ADD_DEFINITIONS("-D_CRT_NONSTDC_NO_DEPRECATE") +ENDIF(MSVC) + +if(WIN32) + if(HAVE_WINDOWS_CRYPTO) + SET (OPTIONAL_LIBRARY "${OPTIONAL_LIBRARY}" bcrypt) + endif() + if(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore) + ADD_DEFINITIONS(-DMS_UWP) + else(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore) + SET (OPTIONAL_LIBRARY "${OPTIONAL_LIBRARY}" advapi32) + endif(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore) +endif(WIN32) + +ADD_DEFINITIONS("-DHAVE_CONFIG_H") + +# rpath handling: use rpath in installed binaries +IF(NOT CMAKE_SYSTEM_NAME MATCHES Linux) + SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}") + SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) +ENDIF() + +# Testing +ENABLE_TESTING() + +# Targets +ADD_SUBDIRECTORY(lib) + +IF(BUILD_DOC) +ADD_SUBDIRECTORY(man) +ENDIF() + +IF(BUILD_TOOLS) +ADD_SUBDIRECTORY(src) +ENDIF() + +IF(BUILD_REGRESS) +ADD_SUBDIRECTORY(regress) +ENDIF() + +IF(BUILD_EXAMPLES) +ADD_SUBDIRECTORY(examples) +ENDIF() + + +# pkgconfig file +SET(prefix ${CMAKE_INSTALL_PREFIX}) +SET(exec_prefix \${prefix}) +SET(bindir \${exec_prefix}/${CMAKE_INSTALL_BINDIR}) +SET(libdir \${exec_prefix}/${CMAKE_INSTALL_LIBDIR}) +SET(includedir \${prefix}/${CMAKE_INSTALL_INCLUDEDIR}) +IF(BZIP2_FOUND) + SET(LIBS "${LIBS} -lbz2") +ENDIF() +SET(LIBS "${LIBS} -lz") +IF(CMAKE_SYSTEM_NAME MATCHES BSD) + SET(PKG_CONFIG_RPATH "-Wl,-R\${libdir}") +ENDIF(CMAKE_SYSTEM_NAME MATCHES BSD) +CONFIGURE_FILE(libzip.pc.in libzip.pc @ONLY) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/libzip.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) + +# fixed size integral types + +IF(HAVE_STDINT_H_LIBZIP) + SET(LIBZIP_TYPES_INCLUDE "#include ") +ELSEIF(HAVE_INTTYPES_H_LIBZIP) + SET(LIBZIP_TYPES_INCLUDE "#include ") +ELSEIF(HAVE_SYS_TYPES_H_LIBZIP) + SET(LIBZIP_TYPES_INCLUDE "#include ") +ENDIF() + +IF(HAVE_INT8_T_LIBZIP) + SET(ZIP_INT8_T int8_t) +ELSEIF(HAVE___INT8_LIBZIP) + SET(ZIP_INT8_T __int8) +ELSE() + SET(ZIP_INT8_T "signed char") +ENDIF() + +IF(HAVE_UINT8_T_LIBZIP) + SET(ZIP_UINT8_T uint8_t) +ELSEIF(HAVE___INT8_LIBZIP) + SET(ZIP_UINT8_T "unsigned __int8") +ELSE() + SET(ZIP_UINT8_T "unsigned char") +ENDIF() + +IF(HAVE_INT16_T_LIBZIP) + SET(ZIP_INT16_T int16_t) +ELSEIF(HAVE___INT16_LIBZIP) + SET(INT16_T_LIBZIP __int16) +ELSEIF(SHORT_LIBZIP EQUAL 2) + SET(INT16_T_LIBZIP short) +ENDIF() + +IF(HAVE_UINT16_T_LIBZIP) + SET(ZIP_UINT16_T uint16_t) +ELSEIF(HAVE___INT16_LIBZIP) + SET(UINT16_T_LIBZIP "unsigned __int16") +ELSEIF(SHORT_LIBZIP EQUAL 2) + SET(UINT16_T_LIBZIP "unsigned short") +ENDIF() + +IF(HAVE_INT32_T_LIBZIP) + SET(ZIP_INT32_T int32_t) +ELSEIF(HAVE___INT32_LIBZIP) + SET(ZIP_INT32_T __int32) +ELSEIF(INT_LIBZIP EQUAL 4) + SET(ZIP_INT32_T int) +ELSEIF(LONG_LIBZIP EQUAL 4) + SET(ZIP_INT32_T long) +ENDIF() + +IF(HAVE_UINT32_T_LIBZIP) +SET(ZIP_UINT32_T uint32_t) +ELSEIF(HAVE___INT32_LIBZIP) +SET(ZIP_UINT32_T "unsigned __int32") +ELSEIF(INT_LIBZIP EQUAL 4) +SET(ZIP_UINT32_T "unsigned int") +ELSEIF(LONG_LIBZIP EQUAL 4) +SET(ZIP_UINT32_T "unsigned long") +ENDIF() + +IF(HAVE_INT64_T_LIBZIP) + SET(ZIP_INT64_T int64_t) +ELSEIF(HAVE___INT64_LIBZIP) + SET(ZIP_INT64_T __int64) +ELSEIF(LONG_LIBZIP EQUAL 8) + SET(ZIP_INT64_T long) +ELSEIF(LONG_LONG_LIBZIP EQUAL 8) + SET(ZIP_INT64_T "long long") +ENDIF() + +IF(HAVE_UINT64_T_LIBZIP) + SET(ZIP_UINT64_T uint64_t) +ELSEIF(HAVE___INT64_LIBZIP) + SET(ZIP_UINT64_T "unsigned __int64") +ELSEIF(LONG_LIBZIP EQUAL 8) + SET(ZIP_UINT64_T "unsigned long") +ELSEIF(LONG_LONG_LIBZIP EQUAL 8) + SET(ZIP_UINT64_T "unsigned long long") +ENDIF() + +IF(HAVE_NULLABLE) + SET(ZIP_NULLABLE_DEFINES) +ELSE() + SET(ZIP_NULLABLE_DEFINES "#define _Nullable +#define _Nonnull") +ENDIF() + +# write out config file +CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake-config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) +CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake-zipconf.h.in ${CMAKE_CURRENT_BINARY_DIR}/zipconf.h) + +# for tests + +SET(srcdir ${CMAKE_CURRENT_SOURCE_DIR}/regress) +SET(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR}/regress) +SET(top_builddir ${CMAKE_BINARY_DIR}) + +CONFIGURE_FILE(regress/runtest.in ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/runtest @ONLY) +FILE(COPY ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/runtest + DESTINATION ${CMAKE_BINARY_DIR}/regress + FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + + +# installation + +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/zipconf.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) diff --git a/third_party/libzip/FindNettle.cmake b/third_party/libzip/FindNettle.cmake new file mode 100644 index 0000000..1f66610 --- /dev/null +++ b/third_party/libzip/FindNettle.cmake @@ -0,0 +1,23 @@ +# - Find Nettle +# Find the Nettle include directory and library +# +# NETTLE_INCLUDE_DIR - where to find , etc. +# NETTLE_LIBRARIES - List of libraries when using libnettle. +# NETTLE_FOUND - True if libnettle found. + +IF (NETTLE_INCLUDE_DIR) + # Already in cache, be silent + SET(NETTLE_FIND_QUIETLY TRUE) +ENDIF (NETTLE_INCLUDE_DIR) + +FIND_PATH(NETTLE_INCLUDE_DIR nettle/md5.h nettle/ripemd160.h nettle/sha.h) +FIND_LIBRARY(NETTLE_LIBRARY NAMES nettle libnettle) + +# handle the QUIETLY and REQUIRED arguments and set NETTLE_FOUND to TRUE if +# all listed variables are TRUE +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(NETTLE DEFAULT_MSG NETTLE_LIBRARY NETTLE_INCLUDE_DIR) + +IF(NETTLE_FOUND) + SET(NETTLE_LIBRARIES ${NETTLE_LIBRARY}) +ENDIF(NETTLE_FOUND) diff --git a/third_party/libzip/INSTALL.md b/third_party/libzip/INSTALL.md new file mode 100644 index 0000000..eef900e --- /dev/null +++ b/third_party/libzip/INSTALL.md @@ -0,0 +1,55 @@ +libzip uses [cmake](https://cmake.org) to build. + +For running the tests, you need to have [perl](https://www.perl.org). + +You'll need [zlib](http://www.zlib.net/) (at least version 1.1.2). It +comes with most operating systems. + +For supporting bzip2-compressed zip archives, you need +[bzip2](http://bzip.org/). + +For AES (encryption) support, you need one of these cryptographic libraries, +listed in order of preference: + +- Apple's CommonCrypto (available on macOS and iOS) +- [GnuTLS](https://www.gnutls.org/) +- [mbed TLS](https://tls.mbed.org/) +- [OpenSSL](https://www.openssl.org/) >= 1.0. +- Microsoft Windows Cryptography Framework + +If you don't want a library even if it is installed, you can +pass `-DENABLE_=OFF` to cmake, where `` is one of +`COMMONCRYPTO`, `GNUTLS`, `MBEDTLS`, or `OPENSSL`. + +The basic usage is +```sh +mkdir build +cd build +cmake .. +make +make test +make install +``` + +Some useful parameters you can pass to `cmake` with `-Dparameter=value`: + +- `BUILD_SHARED_LIBS`: set to `ON` or `OFF` to enable/disable building + of shared libraries, defaults to `ON` +- `CMAKE_INSTALL_PREFIX`: for setting the installation path +- `DOCUMENTATION_FORMAT`: choose one of 'man', 'mdoc', and 'html' for + the installed documentation (default: decided by cmake depending on + available tools) + +If you want to compile with custom `CFLAGS`, set them in the environment +before running `cmake`: +```sh +CFLAGS=-DMY_CUSTOM_FLAG cmake .. +``` + +If you are compiling on a system with a small stack size, add +`-DZIP_ALLOCATE_BUFFER` to `CFLAGS`. + +You can get verbose build output with by passing `VERBOSE=1` to +`make`. + +You can also check the [cmake FAQ](https://cmake.org/Wiki/CMake_FAQ). diff --git a/third_party/libzip/LICENSE b/third_party/libzip/LICENSE new file mode 100644 index 0000000..e93454e --- /dev/null +++ b/third_party/libzip/LICENSE @@ -0,0 +1,31 @@ +Copyright (C) 1999-2017 Dieter Baron and Thomas Klausner + +The authors can be contacted at + +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. + +3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. diff --git a/third_party/libzip/NEWS.md b/third_party/libzip/NEWS.md new file mode 100644 index 0000000..9d8d2a3 --- /dev/null +++ b/third_party/libzip/NEWS.md @@ -0,0 +1,227 @@ +1.5.2 [2019-03-12] +================== +* Fix bug in AES encryption affecting certain file sizes +* Keep file permissions when modifying zip archives +* Support systems with small stack size. +* Support mbed TLS as crypto backend. +* Add nullability annotations. + +1.5.1 [2018-04-11] +================== + +* Choose format of installed documentation based on available tools. +* Fix visibility of symbols. +* Fix zipcmp directory support. +* Don't set RPATH on Linux. +* Use Libs.private for link dependencies in pkg-config file. +* Fix build with LibreSSL. +* Various bugfixes. + +1.5.0 [2018-03-11] +================== + +* Use standard cryptographic library instead of custom AES implementation. + This also simplifies the license. +* Use `clang-format` to format the source code. +* More Windows improvements. + +1.4.0 [2017-12-29] +================== + +* Improve build with cmake +* Retire autoconf/automake build system +* Add `zip_source_buffer_fragment()`. +* Add support to clone unchanged beginning of archive (instead of rewriting it). + Supported for buffer sources and on Apple File System. +* Add support for Microsoft Universal Windows Platform. + +1.3.2 [2017-11-20] +================== +* Fix bug introduced in last: zip_t was erroneously freed if zip_close() failed. + +1.3.1 [2017-11-19] +================== + +* Install zipconf.h into ${PREFIX}/include +* Add zip_libzip_version() +* Fix AES tests on Linux + +1.3.0 [2017-09-02] +================== + +* Support bzip2 compressed zip archives +* Improve file progress callback code +* Fix zip_fdopen() +* CVE-2017-12858: Fix double free() +* CVE-2017-14107: Improve EOCD64 parsing + +1.2.0 [2017-02-19] +================== + +* Support for AES encryption (Winzip version), both encryption + and decryption +* Support legacy zip files with >64k entries +* Fix seeking in zip_source_file if start > 0 +* Add zip_fseek() for seeking in uncompressed data +* Add zip_ftell() for telling position in uncompressed data +* Add zip_register_progress_callback() for UI updates during zip_close() + +1.1.3 [2016-05-28] +================== + +* Fix build on Windows when using autoconf + +1.1.2 [2016-02-19] +================== + +* Improve support for 3MF files + +1.1.1 [2016-02-07] +================== + +* Build fixes for Linux +* Fix some warnings reported by PVS-Studio + +1.1 [2016-01-26] +================ + +* ziptool(1): command line tool to modify zip archives +* Speedups for archives with many entries +* Coverity fixes +* Better APK support +* Support for running tests on Windows +* More build fixes for Windows +* Portability fixes +* Documentation improvements + +1.0.1 [2015-05-04] +================== + +* Build fixes for Windows + +1.0 [2015-05-03] +================ + +* Implemented an I/O abstraction layer +* Added support for native Windows API for files +* Added support for setting the last modification time for a file +* Added a new type zip_error_t for errors +* Added more typedefs for structs +* Torrentzip support was removed +* CVE-2015-2331 was fixed +* Addressed all Coverity CIDs + +0.11.2 [2013-12-19] +=================== + +* Support querying/setting operating system and external attributes +* For newly added files, set operating system to UNIX, permissions + to 0666 (0777 for directories) +* Fix bug when writing zip archives containing files bigger than 4GB + +0.11.1 [2013-04-27] +=================== + +* Fix bugs in zip_set_file_compression() +* Include Xcode build infrastructure + +0.11 [2013-03-23] +================= + +* Added Zip64 support (large file support) +* Added UTF-8 support for file names, file comments, and archive comments +* Changed API for name and comment related functions for UTF-8 support +* Added zip_discard() +* Added ZIP_TRUNCATE for zip_open() +* Added zip_set_file_compression() +* Added API for accessing and modifying extra fields +* Improved API type consistency +* Use gcc4's visibility __attribute__ +* More changes for Windows support +* Additional test cases + +0.10.1 [2012-03-20] +=================== + +* Fixed CVE-2012-1162 +* Fixed CVE-2012-1163 + +0.10 [2010-03-18] +================= + +* Added zip_get_num_entries(), deprecated zip_get_num_files() +* Better windows support +* Support for traditional PKWARE encryption added +* Fix opening archives with more than 65535 entries +* Fix some memory leaks +* Fix cmake build and installation +* Fix memory leak in error case in zip_open() +* Fixed CVE-2011-0421 (no security implications though) +* More documentation + +0.9.3 [2010-02-01] +================== + +* Include m4/ directory in distribution; some packagers need it + +0.9.2 [2010-01-31] +================== + +* Avoid passing uninitialized data to deflate() +* Fix memory leak when closing zip archives + +0.9.1 [2010-01-24] +================== + +* Fix infinite loop on reading some broken files +* Optimization in time conversion (don't call localtime()) +* Clear data descriptor flag in central directory, fixing Open Office files +* Allow more than 64k entries + +0.9 [2008-07-25] +================== + +* on Windows, explictly set dllimport/dllexport +* remove erroneous references to GPL +* add support for torrentzip +* new functions: zip_get_archive_flag, zip_set_archive_flag +* zip_source_zip: add flag to force recompression +* zip_sorce_file: only keep file open while reading from it + +0.8 [2007-06-06] +================== + +* fix for zip archives larger than 2GiB +* fix zip_error_strerror to include libzip error string +* add support for reading streamed zip files +* new functions: zip_add_dir, zip_error_clear, zip_file_error_clear +* add basic support for building with CMake (incomplete) + +0.7.1 [2006-05-18] +================== + +* bugfix for zip_close + +0.7 [2006-05-06] +================ + +* struct zip_stat increased for future encryption support +* zip_add return value changed (now returns new index of added file) +* shared library major bump because of previous two +* added functions for reading and writing file and archive comments + New functions: zip_get_archive_comment, zip_get_file_comment, + zip_set_archive_comment, zip_set_file_comment, zip_unchange_archive + +0.6.1 [2005-07-14] +================== + +* various bug fixes + +0.6 [2005-06-09] +================ + +* first standalone release +* changed license to three-clause BSD +* overhauled API +* added man pages +* install zipcmp and zipmerge diff --git a/third_party/libzip/README.md b/third_party/libzip/README.md new file mode 100644 index 0000000..60f94f8 --- /dev/null +++ b/third_party/libzip/README.md @@ -0,0 +1,39 @@ +This is libzip, a C library for reading, creating, and modifying zip +archives. Files can be added from data buffers, files, or compressed +data copied directly from other zip archives. Changes made without +closing the archive can be reverted. Decryption and encryption of +Winzip AES and decryption of legacy PKware encrypted files is +supported. The API is documented by man pages. + +libzip is fully documented via man pages. HTML versions of the man +pages are on [libzip.org](https://libzip.org/documentation/) and +in the [man](man) directory. You can start with +[libzip(3)](https://libzip.org/documentation/libzip.html), which +lists +all others. Example source code is in the [examples](examples) and +[src](src) subdirectories. + +If you have developed an application using libzip, you can find out +about API changes and how to adapt your code for them in the included +file [API-CHANGES.md](API-CHANGES.md). + +See the [INSTALL.md](INSTALL.md) file for installation instructions and +dependencies. + +If you make a binary distribution, please include a pointer to the +distribution site: +> https://libzip.org/ + +The latest version can always be found there. The official repository +is at [github](https://github.com/nih-at/libzip/). + +There is a mailing list for developers using libzip. You can +subscribe to it by sending a mail with the subject "subscribe +libzip-discuss" to minimalist at nih.at. List mail should be sent +to libzip-discuss at nih.at. Use this for bug reports or questions. + +If you want to reach the authors in private, use . + +[![Travis Build Status](https://api.travis-ci.org/nih-at/libzip.svg?branch=master)](https://travis-ci.org/nih-at/libzip) +[![Appveyor Build status](https://ci.appveyor.com/api/projects/status/5x1raqqjro4wny7r?svg=true)](https://ci.appveyor.com/project/0-wiz-0/libzip) +[![Coverity Status](https://scan.coverity.com/projects/127/badge.svg)](https://scan.coverity.com/projects/libzip) diff --git a/third_party/libzip/THANKS b/third_party/libzip/THANKS new file mode 100644 index 0000000..e8f3b3d --- /dev/null +++ b/third_party/libzip/THANKS @@ -0,0 +1,87 @@ +Thanks to Info-ZIP for info on the DOS-time/date conversion code, +and some other general information gathered from their sources. + +Thanks to these people for suggestions, testing, and bug reports: + +Agostino Sarubbo +Alexander Galanin +Alexandr Shadchin +Andreas Falkenhahn +Andrew Brampton +Andrew Molyneux +Ankur Kothari +BALATON Zoltan +Benjamin Gilbert +Boaz Stolk +Bogdan +Brian 'geeknik' Carpenter +Carl Mastrangelo +Cédric Tabin +Chris Nehren +Coverity +Dane Springmeyer +David Demelier +Del Merritt +Dmytro Rybachenko +Elvis Angelaccio +Erwin Haid +Eun-cheol Joo +Florian Delizy +François Simon +Frederik Ramm +Hanno Böck +HeeMyung +Heiko Becker +Heiko Hund +Ilya Voronin +Info-ZIP group +Jan Weiß +Jay Freeman (saurik) +João Custódio +Joel Ebrahimi +Jono Spiro +Julien Schueller +Keith Jones +Kohei Yoshida +Leith Bade +Lubomir I. Ivanov +Maël Nison +Martin Buchholz +Martin Herkt +Martin Szulecki +Michael Balzer +Michael Beck +MichaÅ‚ Janiszewski +Michal Vyskocil +Mikhail Gusarov . +Miklos Vajna +Oliver Kaiser +Oliver Kuckertz +Pascal Terjan +Patrick Spendrin +Paul Harris +Paul Sheppard +Pavel Raiskup +Pierre Joye +Pierre-Louis Cabelguen +Remi Collet +Richard Schütz +Rick Carback +Robert Norris +Roberto Tirabassi +Roland Ortloff +Sergei Ozerov +Simon Talbot +Stephen Bryant +Tarmo Pikaro +TC +Tim Lunn +Timo Warns +Tom Callaway +Tomas Hoger +Tomáš Malý +Torsten Paul +Vassili Courzakis +William Lee +Wojciech Michalski +Wolfgang Glunz diff --git a/third_party/libzip/TODO.md b/third_party/libzip/TODO.md new file mode 100644 index 0000000..3a6c5c4 --- /dev/null +++ b/third_party/libzip/TODO.md @@ -0,0 +1,189 @@ +# Soon + +* review guidelines/community standards + - (Linux Foundation Core Infrastructure Initiative Best Practices)[https://bestpractices.coreinfrastructure.org/] + - (Readme Maturity Level)[https://github.com/LappleApple/feedmereadmes/blob/master/README-maturity-model.md] + - (Github Community Profile)[https://github.com/nih-at/libzip/community] + +* test different crypto backends with TravisCI. + +* test for zipcmp reading directory (requires fts) + +* improve man page formatting of tagged lists on webpage (`
`) + +* test error cases with special source + - tell it which command should fail + - use it both as source for `zip_add` and `zip_open_from_source` + - `ziptool_regress`: + - `-e error_spec`: source containing zip fails depending on `error_spec` + - `add_with_error name content error_spec`: add content to archive, where source fails depending on `error_spec` + - `add_file_with_error name file_to_add offset len error_spec`: add file to archive, len bytes starting from offset, where source fails depending on `error_spec` + - `error_spec`: + - source command that fails + - error code that source returns + - conditions that must be met for error to trigger + - Nth call of command + - read/write: total byte count so far + - state of source (opened, EOF reached, ...) + +# Later + +## macOS / iOS framework + +* get cmake to optionally build frameworks + +## Prefixes + +For example for adding extractors for self-extracting zip archives. +````c +zip_set_archive_prefix(struct zip *za, const zip_uint8_t *data, zip_uint64_t length); +const zip_uint8_t *zip_get_archive_prefix(struct zip *za, zip_uint64_t *lengthp); +```` + +## Compression + +* add lzma support + +## API Issues + +* `zip_get_archive_comment` has `int *lenp` argument. Cleaner would be `zip_uint32_t *`. + rename and fix. which other functions for naming consistency? +* rename remaining `zip_XXX_{file,archive}_*` to `zip_{file,archive}_XXX_*`? +* compression/crypt implementations: how to set error code on failure +* compression/crypt error messages a la `ZIP_ER_ZLIB` (no detailed info passing) + +## Features + +* add seek support for AES-encrypted files +* consistently use `_zip_crypto_clear()` for passwords +* support setting extra fields from `zip_source` + * introduce layers of extra fields: + * original + * from `zip_source` + * manually set + * when querying extra fields, search all of them in reverse order + * add whiteout (deleted) flag + * allow invalid data flag, used when computing extra field size before writing data + * new command `ZIP_SOURCE_EXTRA_FIELDS` + * no support for multiple copies of same extra field +* delete all extra fields during `zip_replace()` +* function to copy file from one archive to another +* set `O_CLOEXEC` flag after fopen and mkstemp +* `zip_file_set_mtime()`: support InfoZIP time stamps +* support streaming output (creating new archive to e.g. stdout) +* add function to read/set ASCII file flag +* `zip_commit()` (to finish changes without closing archive) +* add custom compression function support +* `zip_source_zip()`: allow rewinding +* add `zip_abort()` to allow aborting `zip_close()` (can be called from progress callback) +* `zipcmp`: add option for file content comparison +* `zipcmp`: add more paranoid checks: + * external attributes/opsys + * last_mod + * version needed/made by + * general purpose bit flags +* add more consistency checks: + * for stored files, test compressed = uncompressed + * data descriptor + * local headers come before central dir +* support for old compression methods? + +## Bugs + +* support InfoZIP encryption header extension (copy data descriptor for encrypted files) +* ensure that nentries is small enough not to cause overflow (size_t for entry, uint64 for CD on disk) +* check for limits imposed by format (central dir size, file size, extra fields, ...) +* `_zip_u2d_time()`: handle `localtime(3)` failure +* POSIX: `zip_open()`: check whether file can be created and fail if not +* fix inconsistent usage of valid flags (not checked in many places) +* `cdr == NULL` -> `ER_NOENT` vs. `idx > cdir->nentry` -> `ER_INVAL` inconsistent (still there?) + + +## Cleanup + +* drop _LIBZIP suffixes in cmake defines (no longer needed since they no longer appear in zipconf.h) +* go over cdir parser and rename various offset/size variables to make it clearer +* use bool +* use `ZIP_SOURCE_SUPPORTS_{READABLE,SEEKABLE,WRITABLE}` +* use `zip_source_seek_compute_offset()` +* get rid of `zip_get_{compression,encryption}_implementation()` +* use `zip_*int*_t` internally + +## Infrastructure + +* rewrite `make_zip_errors.sh` in cmake +* rewrite `make_zip_err_str.sh` in cmake +* configure appveyor for Windows builds of libzip + +## Test Case Issues + +* add test case for clone with files > 4k +* consider testing for malloc/realloc failures +* Winzip AES support + * test cases decryption: <=20, >20, stat for both + * test cases encryption: no password, default password, file-specific password, 128/192/256, <=20, >20 + * support testing on macOS +* add test cases for lots of files (including too many) +* add test cases for holes (between files, between files and cdir, between cdir and eocd, + zip64 where appropriate) +* unchange on added file +* test seek in `zip_source_crc()` +* test cases for `set_extra*`, `delete_extra*`, `*extra_field*` +* test cases for in memory archives + * add + * delete + * delete all + * modify +* use gcov output to increase test coverage +* add test case to change values for newly added files (name, compression method, comment, mtime, . . .) +* `zip_open()` file less than `EOCDLEN` bytes long +* test calls against old API +* run regression tests also from CMake framework +* rename file to dir/ and vice versa (fails) +* fix comment test to be newline insensitive +* check if http://bugs.python.org/issue20078 provides ideas for new tests + +* (`add`, `replace`) + * add to empty zip + * add to existing zip + * add w/ existing file name [E] + * replace ok + * replace w/ illegal index [E] + * replace w/ deleted name [E] + * unchange added/replaced file +* (`close`) + * copy zip file + * open copy + * rename, delete, replace, add w/ new name, add w/ deleted name + * close + * zipcmp copy expected + * remove copy +* (`error_get) +* (`error_get_sys_type`) +* (`error_to_str`) +* (`extra_fields`) +* (`file_error_get`) +* (`file_strerror`) +* (`replace`) +* (`source_buffer`) +* (`source_file`) +* (`source_filep`) +* (`source_free`) +* (`source_function`) +* (`source_zip`) +* (`strerror`) +* (`unchange`) +* (`unchange_all`) +* `open(ZIP_RDONLY)` +* I/O abstraction layer + * `zip_open_from_source` +* read two zip entries interleaved + +## Unsorted + +* `zip_source_file()`: don't allow write if start/len specify a part of the file +* script to check if all exported symbols are marked with `ZIP_EXTERN`, add to make distcheck + +* document: `zip_source_write()`: length can't be > `ZIP_INT64_MAX` +* document: `ZIP_SOURCE_CLOSE` implementation can't return error +* keep error codes in man pages in sync +* document error codes in new man pages diff --git a/third_party/libzip/appveyor.yml b/third_party/libzip/appveyor.yml new file mode 100644 index 0000000..2061365 --- /dev/null +++ b/third_party/libzip/appveyor.yml @@ -0,0 +1,57 @@ +os: +- Visual Studio 2017 +environment: + matrix: + - GENERATOR: "Visual Studio 15 2017 Win64" + TRIPLET: x64-windows + CMAKE_OPTS: "-DBUILD_SHARED_LIBS=off" + - GENERATOR: "Visual Studio 15 2017" + TRIPLET: x86-windows + CMAKE_OPTS: "-DBUILD_SHARED_LIBS=off" + - GENERATOR: "Visual Studio 15 2017 ARM" + TRIPLET: arm-windows + CMAKE_OPTS: "-DENABLE_OPENSSL=off" + - GENERATOR: "Visual Studio 15 2017" + TRIPLET: x86-uwp + CMAKE_OPTS: "-DCMAKE_SYSTEM_NAME=WindowsStore" + - GENERATOR: "Visual Studio 15 2017 Win64" + TRIPLET: x64-uwp + CMAKE_OPTS: "-DCMAKE_SYSTEM_NAME=WindowsStore" + - GENERATOR: "Visual Studio 15 2017 ARM" + TRIPLET: arm-uwp + CMAKE_OPTS: "-DCMAKE_SYSTEM_NAME=WindowsStore -DENABLE_OPENSSL=off" + - GENERATOR: "Visual Studio 15 2017" + TRIPLET: arm64-windows + CMAKE_OPTS: "-AARM64 -DENABLE_OPENSSL=off" + - GENERATOR: "Visual Studio 15 2017" + TRIPLET: arm64-uwp + CMAKE_OPTS: "-AARM64 -DCMAKE_SYSTEM_NAME=WindowsStore -DENABLE_OPENSSL=off" +before_build: + cmd: >- + git clone https://github.com/Microsoft/vcpkg + + cd vcpkg + + .\bootstrap-vcpkg.bat + + .\vcpkg integrate install + + .\vcpkg install zlib:%TRIPLET% bzip2:%TRIPLET% + + cd .. + + mkdir build + + cd build + + cmake -DCMAKE_TOOLCHAIN_FILE=%cd%/../vcpkg/scripts/buildsystems/vcpkg.cmake .. -G "%GENERATOR%" %CMAKE_OPTS% + + appveyor PushArtifact config.h + + appveyor PushArtifact CMakeCache.txt + +build_script: + cmd: >- + cmake --build . --config Release --target INSTALL + + cmake --build . --config Debug --target INSTALL diff --git a/third_party/libzip/cmake-config.h.in b/third_party/libzip/cmake-config.h.in new file mode 100644 index 0000000..51efe61 --- /dev/null +++ b/third_party/libzip/cmake-config.h.in @@ -0,0 +1,92 @@ +#ifndef HAD_CONFIG_H +#define HAD_CONFIG_H +#ifndef _HAD_ZIPCONF_H +#include "zipconf.h" +#endif +/* BEGIN DEFINES */ +#cmakedefine HAVE___PROGNAME +#cmakedefine HAVE__CHMOD +#cmakedefine HAVE__CLOSE +#cmakedefine HAVE__DUP +#cmakedefine HAVE__FDOPEN +#cmakedefine HAVE__FILENO +#cmakedefine HAVE__OPEN +#cmakedefine HAVE__SETMODE +#cmakedefine HAVE__SNPRINTF +#cmakedefine HAVE__STRDUP +#cmakedefine HAVE__STRICMP +#cmakedefine HAVE__STRTOI64 +#cmakedefine HAVE__STRTOUI64 +#cmakedefine HAVE__UMASK +#cmakedefine HAVE__UNLINK +#cmakedefine HAVE_CLONEFILE +#cmakedefine HAVE_COMMONCRYPTO +#cmakedefine HAVE_CRYPTO +#cmakedefine HAVE_FICLONERANGE +#cmakedefine HAVE_FILENO +#cmakedefine HAVE_FSEEKO +#cmakedefine HAVE_FTELLO +#cmakedefine HAVE_GETPROGNAME +#cmakedefine HAVE_GNUTLS +#cmakedefine HAVE_LIBBZ2 +#cmakedefine HAVE_MBEDTLS +#cmakedefine HAVE_MKSTEMP +#cmakedefine HAVE_NULLABLE +#cmakedefine HAVE_OPEN +#cmakedefine HAVE_OPENSSL +#cmakedefine HAVE_SETMODE +#cmakedefine HAVE_SNPRINTF +#cmakedefine HAVE_SSIZE_T_LIBZIP +#cmakedefine HAVE_STRCASECMP +#cmakedefine HAVE_STRDUP +#cmakedefine HAVE_STRICMP +#cmakedefine HAVE_STRTOLL +#cmakedefine HAVE_STRTOULL +#cmakedefine HAVE_STRUCT_TM_TM_ZONE +#cmakedefine HAVE_STDBOOL_H +#cmakedefine HAVE_STRINGS_H +#cmakedefine HAVE_UNISTD_H +#cmakedefine HAVE_WINDOWS_CRYPTO +#cmakedefine __INT8_LIBZIP ${__INT8_LIBZIP} +#cmakedefine INT8_T_LIBZIP ${INT8_T_LIBZIP} +#cmakedefine UINT8_T_LIBZIP ${UINT8_T_LIBZIP} +#cmakedefine __INT16_LIBZIP ${__INT16_LIBZIP} +#cmakedefine INT16_T_LIBZIP ${INT16_T_LIBZIP} +#cmakedefine UINT16_T_LIBZIP ${UINT16_T_LIBZIP} +#cmakedefine __INT32_LIBZIP ${__INT32_LIBZIP} +#cmakedefine INT32_T_LIBZIP ${INT32_T_LIBZIP} +#cmakedefine UINT32_T_LIBZIP ${UINT32_T_LIBZIP} +#cmakedefine __INT64_LIBZIP ${__INT64_LIBZIP} +#cmakedefine INT64_T_LIBZIP ${INT64_T_LIBZIP} +#cmakedefine UINT64_T_LIBZIP ${UINT64_T_LIBZIP} +#cmakedefine SHORT_LIBZIP ${SHORT_LIBZIP} +#cmakedefine INT_LIBZIP ${INT_LIBZIP} +#cmakedefine LONG_LIBZIP ${LONG_LIBZIP} +#cmakedefine LONG_LONG_LIBZIP ${LONG_LONG_LIBZIP} +#cmakedefine SIZEOF_OFF_T ${SIZEOF_OFF_T} +#cmakedefine SIZE_T_LIBZIP ${SIZE_T_LIBZIP} +#cmakedefine SSIZE_T_LIBZIP ${SSIZE_T_LIBZIP} +#cmakedefine HAVE_DIRENT_H +#cmakedefine HAVE_FTS_H +#cmakedefine HAVE_NDIR_H +#cmakedefine HAVE_SYS_DIR_H +#cmakedefine HAVE_SYS_NDIR_H +#cmakedefine WORDS_BIGENDIAN +#cmakedefine HAVE_SHARED +/* END DEFINES */ +#define PACKAGE "@PACKAGE@" +#define VERSION "@VERSION@" + +#ifndef HAVE_SSIZE_T_LIBZIP +# if SIZE_T_LIBZIP == INT_LIBZIP +typedef int ssize_t; +# elif SIZE_T_LIBZIP == LONG_LIBZIP +typedef long ssize_t; +# elif SIZE_T_LIBZIP == LONG_LONG_LIBZIP +typedef long long ssize_t; +# else +#error no suitable type for ssize_t found +# endif +#endif + +#endif /* HAD_CONFIG_H */ diff --git a/third_party/libzip/cmake-zipconf.h.in b/third_party/libzip/cmake-zipconf.h.in new file mode 100644 index 0000000..197b1c3 --- /dev/null +++ b/third_party/libzip/cmake-zipconf.h.in @@ -0,0 +1,47 @@ +#ifndef _HAD_ZIPCONF_H +#define _HAD_ZIPCONF_H + +/* + zipconf.h -- platform specific include file + + This file was generated automatically by CMake + based on ../cmake-zipconf.h.in. + */ + +#cmakedefine LIBZIP_VERSION "@PACKAGE_VERSION@" +#cmakedefine LIBZIP_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@ +#cmakedefine LIBZIP_VERSION_MINOR @PACKAGE_VERSION_MINOR@ +#cmakedefine LIBZIP_VERSION_MICRO @PACKAGE_VERSION_MICRO@ + +#cmakedefine ZIP_STATIC + +${ZIP_NULLABLE_DEFINES} + +${LIBZIP_TYPES_INCLUDE} + +typedef ${ZIP_INT8_T} zip_int8_t; +typedef ${ZIP_UINT8_T} zip_uint8_t; +typedef ${ZIP_INT16_T} zip_int16_t; +typedef ${ZIP_UINT16_T} zip_uint16_t; +typedef ${ZIP_INT32_T} zip_int32_t; +typedef ${ZIP_UINT32_T} zip_uint32_t; +typedef ${ZIP_INT64_T} zip_int64_t; +typedef ${ZIP_UINT64_T} zip_uint64_t; + +#define ZIP_INT8_MIN (-ZIP_INT8_MAX-1) +#define ZIP_INT8_MAX 0x7f +#define ZIP_UINT8_MAX 0xff + +#define ZIP_INT16_MIN (-ZIP_INT16_MAX-1) +#define ZIP_INT16_MAX 0x7fff +#define ZIP_UINT16_MAX 0xffff + +#define ZIP_INT32_MIN (-ZIP_INT32_MAX-1L) +#define ZIP_INT32_MAX 0x7fffffffL +#define ZIP_UINT32_MAX 0xffffffffLU + +#define ZIP_INT64_MIN (-ZIP_INT64_MAX-1LL) +#define ZIP_INT64_MAX 0x7fffffffffffffffLL +#define ZIP_UINT64_MAX 0xffffffffffffffffULL + +#endif /* zipconf.h */ diff --git a/third_party/libzip/examples/CMakeLists.txt b/third_party/libzip/examples/CMakeLists.txt new file mode 100644 index 0000000..db1e686 --- /dev/null +++ b/third_party/libzip/examples/CMakeLists.txt @@ -0,0 +1,13 @@ +CHECK_FUNCTION_EXISTS(getopt HAVE_GETOPT) +IF(NOT HAVE_GETOPT) + SET(SRC_EXTRA_FILES ../src/getopt.c) +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/../src) +ENDIF(NOT HAVE_GETOPT) + +ADD_EXECUTABLE(in-memory in-memory.c) +TARGET_LINK_LIBRARIES(in-memory zip) + +INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../lib + ${CMAKE_CURRENT_SOURCE_DIR}/../src + ${CMAKE_CURRENT_BINARY_DIR}/..) diff --git a/third_party/libzip/examples/in-memory.c b/third_party/libzip/examples/in-memory.c new file mode 100644 index 0000000..625e280 --- /dev/null +++ b/third_party/libzip/examples/in-memory.c @@ -0,0 +1,217 @@ +/* + in-memory.c -- modify zip file in memory + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include + +static int +get_data(void **datap, size_t *sizep, const char *archive) { + /* example implementation that reads data from file */ + struct stat st; + FILE *fp; + + if ((fp = fopen(archive, "r")) == NULL) { + if (errno != ENOENT) { + fprintf(stderr, "can't open %s: %s\n", archive, strerror(errno)); + return -1; + } + + *datap = NULL; + *sizep = 0; + + return 0; + } + + if (fstat(fileno(fp), &st) < 0) { + fprintf(stderr, "can't stat %s: %s\n", archive, strerror(errno)); + fclose(fp); + return -1; + } + + if ((*datap = malloc((size_t)st.st_size)) == NULL) { + fprintf(stderr, "can't allocate buffer\n"); + fclose(fp); + return -1; + } + + if (fread(*datap, 1, (size_t)st.st_size, fp) < (size_t)st.st_size) { + fprintf(stderr, "can't read %s: %s\n", archive, strerror(errno)); + free(*datap); + fclose(fp); + return -1; + } + + fclose(fp); + + *sizep = (size_t)st.st_size; + return 0; +} + +static int +modify_archive(zip_t *za) { + /* modify the archive */ + return 0; +} + + +static int +use_data(void *data, size_t size, const char *archive) { + /* example implementation that writes data to file */ + FILE *fp; + + if (data == NULL) { + if (remove(archive) < 0 && errno != ENOENT) { + fprintf(stderr, "can't remove %s: %s\n", archive, strerror(errno)); + return -1; + } + return 0; + } + + if ((fp = fopen(archive, "wb")) == NULL) { + fprintf(stderr, "can't open %s: %s\n", archive, strerror(errno)); + return -1; + } + if (fwrite(data, 1, size, fp) < size) { + fprintf(stderr, "can't write %s: %s\n", archive, strerror(errno)); + fclose(fp); + return -1; + } + if (fclose(fp) < 0) { + fprintf(stderr, "can't write %s: %s\n", archive, strerror(errno)); + return -1; + } + + return 0; +} + + +int +main(int argc, char *argv[]) { + const char *archive; + zip_source_t *src; + zip_t *za; + zip_error_t error; + void *data; + size_t size; + + if (argc < 2) { + fprintf(stderr, "usage: %s archive\n", argv[0]); + return 1; + } + archive = argv[1]; + + /* get buffer with zip archive inside */ + if (get_data(&data, &size, archive) < 0) { + return 1; + } + + zip_error_init(&error); + /* create source from buffer */ + if ((src = zip_source_buffer_create(data, size, 1, &error)) == NULL) { + fprintf(stderr, "can't create source: %s\n", zip_error_strerror(&error)); + free(data); + zip_error_fini(&error); + return 1; + } + + /* open zip archive from source */ + if ((za = zip_open_from_source(src, 0, &error)) == NULL) { + fprintf(stderr, "can't open zip from source: %s\n", zip_error_strerror(&error)); + zip_source_free(src); + zip_error_fini(&error); + return 1; + } + zip_error_fini(&error); + + /* we'll want to read the data back after zip_close */ + zip_source_keep(src); + + /* modify archive */ + modify_archive(za); + + /* close archive */ + if (zip_close(za) < 0) { + fprintf(stderr, "can't close zip archive '%s': %s\n", archive, zip_strerror(za)); + return 1; + } + + + /* copy new archive to buffer */ + + if (zip_source_is_deleted(src)) { + /* new archive is empty, thus no data */ + data = NULL; + } + else { + zip_stat_t zst; + + if (zip_source_stat(src, &zst) < 0) { + fprintf(stderr, "can't stat source: %s\n", zip_error_strerror(zip_source_error(src))); + return 1; + } + + size = zst.size; + + if (zip_source_open(src) < 0) { + fprintf(stderr, "can't open source: %s\n", zip_error_strerror(zip_source_error(src))); + return 1; + } + if ((data = malloc(size)) == NULL) { + fprintf(stderr, "malloc failed: %s\n", strerror(errno)); + zip_source_close(src); + return 1; + } + if ((zip_uint64_t)zip_source_read(src, data, size) < size) { + fprintf(stderr, "can't read data from source: %s\n", zip_error_strerror(zip_source_error(src))); + zip_source_close(src); + free(data); + return 1; + } + zip_source_close(src); + } + + /* we're done with src */ + zip_source_free(src); + + /* use new data */ + use_data(data, size, archive); + + free(data); + + return 0; +} diff --git a/third_party/libzip/examples/windows-open.c b/third_party/libzip/examples/windows-open.c new file mode 100644 index 0000000..5108af5 --- /dev/null +++ b/third_party/libzip/examples/windows-open.c @@ -0,0 +1,60 @@ +/* + windows-open.c -- open zip archive using Windows UTF-16/Unicode file name + Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +zip_t * +windows_open(const wchar_t *name, int flags) { + zip_source_t *src; + zip_t *za; + zip_error_t error; + + zip_error_init(&error); + /* create source from buffer */ + if ((src = zip_source_win32w_create(name, 0, -1, &error)) == NULL) { + fprintf(stderr, "can't create source: %s\n", zip_error_strerror(&error)); + zip_error_fini(&error); + return NULL; + } + + /* open zip archive from source */ + if ((za = zip_open_from_source(src, flags, &error)) == NULL) { + fprintf(stderr, "can't open zip from source: %s\n", zip_error_strerror(&error)); + zip_source_free(src); + zip_error_fini(&error); + return NULL; + } + zip_error_fini(&error); + + return za; +} diff --git a/third_party/libzip/lib/CMakeLists.txt b/third_party/libzip/lib/CMakeLists.txt new file mode 100644 index 0000000..8be48a0 --- /dev/null +++ b/third_party/libzip/lib/CMakeLists.txt @@ -0,0 +1,230 @@ +INCLUDE(CheckFunctionExists) + +INSTALL(FILES zip.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + +SET(CMAKE_C_VISIBILITY_PRESET hidden) + +# from http://www.cmake.org/Wiki/CMakeMacroLibtoolFile +MACRO(GET_TARGET_PROPERTY_WITH_DEFAULT _variable _target _property _default_value) + GET_TARGET_PROPERTY(${_variable} ${_target} ${_property}) + IF(${_variable} STREQUAL NOTFOUND) + SET(${_variable} ${_default_value}) + ENDIF() + +ENDMACRO() + +MACRO(CREATE_LIBTOOL_FILE _target _install_DIR) + GET_TARGET_PROPERTY(_target_location ${_target} LOCATION) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_static_lib ${_target} STATIC_LIB "") + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_dependency_libs ${_target} LT_DEPENDENCY_LIBS "") + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_current ${_target} LT_VERSION_CURRENT 4) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_revision ${_target} LT_VERSION_REVISION 0) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_age ${_target} LT_VERSION_AGE 0) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_installed ${_target} LT_INSTALLED yes) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_shouldnotlink ${_target} LT_SHOULDNOTLINK yes) + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_dlopen ${_target} LT_DLOPEN "") + GET_TARGET_PROPERTY_WITH_DEFAULT(_target_dlpreopen ${_target} LT_DLPREOPEN "") + GET_FILENAME_COMPONENT(_laname ${_target_location} NAME_WE) + GET_FILENAME_COMPONENT(_soname ${_target_location} NAME) + SET(_laname ${_laname}.la) + FILE(WRITE ${_laname} "# ${_laname} - a libtool library file, generated by cmake \n") + FILE(APPEND ${_laname} "# The name that we can dlopen(3).\n") + FILE(APPEND ${_laname} "dlname='${_soname}'\n") + FILE(APPEND ${_laname} "# Names of this library\n") + FILE(APPEND ${_laname} "library_names='${_soname}.${_target_current}.${_target_age}.${_target_revision} ${_soname}.${_target_current} ${_soname}'\n") + FILE(APPEND ${_laname} "# The name of the static archive\n") + FILE(APPEND ${_laname} "old_library='${_target_static_lib}'\n") + FILE(APPEND ${_laname} "# Libraries that this one depends upon.\n") + FILE(APPEND ${_laname} "dependency_libs='${_target_dependency_libs}'\n") + FILE(APPEND ${_laname} "# Version information.\n") + FILE(APPEND ${_laname} "current=${_target_current}\n") + FILE(APPEND ${_laname} "age=${_target_age}\n") + FILE(APPEND ${_laname} "revision=${_target_revision}\n") + FILE(APPEND ${_laname} "# Is this an already installed library?\n") + FILE(APPEND ${_laname} "installed=${_target_installed}\n") + FILE(APPEND ${_laname} "# Should we warn about portability when linking against -modules?\n") + FILE(APPEND ${_laname} "shouldnotlink=${_target_shouldnotlink}\n") + FILE(APPEND ${_laname} "# Files to dlopen/dlpreopen\n") + FILE(APPEND ${_laname} "dlopen='${_target_dlopen}'\n") + FILE(APPEND ${_laname} "dlpreopen='${_target_dlpreopen}'\n") + FILE(APPEND ${_laname} "# Directory that this library needs to be installed in:\n") + FILE(APPEND ${_laname} "libdir='${CMAKE_INSTALL_PREFIX}/${_install_DIR}'\n") + INSTALL( FILES ${_laname} ${_soname} DESTINATION ${CMAKE_INSTALL_PREFIX}${_install_DIR}) +ENDMACRO() + +SET(LIBZIP_SOURCES + zip_add.c + zip_add_dir.c + zip_add_entry.c + zip_algorithm_deflate.c + zip_buffer.c + zip_close.c + zip_delete.c + zip_dir_add.c + zip_dirent.c + zip_discard.c + zip_entry.c + zip_err_str.c + zip_error.c + zip_error_clear.c + zip_error_get.c + zip_error_get_sys_type.c + zip_error_strerror.c + zip_error_to_str.c + zip_extra_field.c + zip_extra_field_api.c + zip_fclose.c + zip_fdopen.c + zip_file_add.c + zip_file_error_clear.c + zip_file_error_get.c + zip_file_get_comment.c + zip_file_get_external_attributes.c + zip_file_get_offset.c + zip_file_rename.c + zip_file_replace.c + zip_file_set_comment.c + zip_file_set_encryption.c + zip_file_set_external_attributes.c + zip_file_set_mtime.c + zip_file_strerror.c + zip_filerange_crc.c + zip_fopen.c + zip_fopen_encrypted.c + zip_fopen_index.c + zip_fopen_index_encrypted.c + zip_fread.c + zip_fseek.c + zip_ftell.c + zip_get_archive_comment.c + zip_get_archive_flag.c + zip_get_encryption_implementation.c + zip_get_file_comment.c + zip_get_name.c + zip_get_num_entries.c + zip_get_num_files.c + zip_hash.c + zip_io_util.c + zip_libzip_version.c + zip_memdup.c + zip_name_locate.c + zip_new.c + zip_open.c + zip_progress.c + zip_rename.c + zip_replace.c + zip_set_archive_comment.c + zip_set_archive_flag.c + zip_set_default_password.c + zip_set_file_comment.c + zip_set_file_compression.c + zip_set_name.c + zip_source_begin_write.c + zip_source_begin_write_cloning.c + zip_source_buffer.c + zip_source_call.c + zip_source_close.c + zip_source_commit_write.c + zip_source_compress.c + zip_source_crc.c + zip_source_error.c + zip_source_filep.c + zip_source_free.c + zip_source_function.c + zip_source_get_compression_flags.c + zip_source_is_deleted.c + zip_source_layered.c + zip_source_open.c + zip_source_pkware.c + zip_source_read.c + zip_source_remove.c + zip_source_rollback_write.c + zip_source_seek.c + zip_source_seek_write.c + zip_source_stat.c + zip_source_supports.c + zip_source_tell.c + zip_source_tell_write.c + zip_source_window.c + zip_source_write.c + zip_source_zip.c + zip_source_zip_new.c + zip_stat.c + zip_stat_index.c + zip_stat_init.c + zip_strerror.c + zip_string.c + zip_unchange.c + zip_unchange_all.c + zip_unchange_archive.c + zip_unchange_data.c + zip_utf-8.c +) + +IF(WIN32) + SET(LIBZIP_OPSYS_FILES + zip_source_win32handle.c + zip_source_win32utf8.c + zip_source_win32w.c + ) + IF(CMAKE_SYSTEM_NAME MATCHES WindowsPhone OR CMAKE_SYSTEM_NAME MATCHES WindowsStore) + ELSE() + SET(LIBZIP_OPSYS_FILES "${LIBZIP_OPSYS_FILES}" + zip_source_win32a.c + ) + ENDIF() +ELSE(WIN32) + SET(LIBZIP_OPSYS_FILES + zip_source_file.c + ) +ENDIF(WIN32) + +INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/..) + +ADD_CUSTOM_TARGET(update_zip_err_str + COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/make_zip_err_str.sh ${CMAKE_CURRENT_SOURCE_DIR}/zip.h ${CMAKE_CURRENT_SOURCE_DIR}/zip_err_str.c + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/zip.h ${CMAKE_CURRENT_SOURCE_DIR}/make_zip_err_str.sh +) +CHECK_FUNCTION_EXISTS(mkstemp HAVE_MKSTEMP) +IF(NOT HAVE_MKSTEMP) + SET(LIBZIP_EXTRA_FILES mkstemp.c) +ENDIF(NOT HAVE_MKSTEMP) +IF(HAVE_LIBBZ2) + SET(LIBZIP_OPTIONAL_FILES zip_algorithm_bzip2.c) +ENDIF() + +IF(HAVE_COMMONCRYPTO) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_crypto_commoncrypto.c +) +ELSEIF(HAVE_WINDOWS_CRYPTO) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_crypto_win.c +) +ELSEIF(HAVE_GNUTLS) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_crypto_gnutls.c +) +ELSEIF(HAVE_OPENSSL) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_crypto_openssl.c +) +ELSEIF(HAVE_MBEDTLS) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_crypto_mbedtls.c +) +ENDIF() + +IF(HAVE_CRYPTO) + SET(LIBZIP_OPTIONAL_FILES ${LIBZIP_OPTIONAL_FILES} zip_winzip_aes.c zip_source_winzip_aes_decode.c zip_source_winzip_aes_encode.c +) +ENDIF() + +ADD_LIBRARY(zip ${LIBZIP_SOURCES} ${LIBZIP_EXTRA_FILES} ${LIBZIP_OPTIONAL_FILES} ${LIBZIP_OPSYS_FILES}) + +IF(SHARED_LIB_VERSIONNING) +SET_TARGET_PROPERTIES(zip PROPERTIES VERSION 5.0 SOVERSION 5) +ENDIF() + + +TARGET_LINK_LIBRARIES(zip ${ZLIB_LIBRARY} ${OPTIONAL_LIBRARY}) +INSTALL(TARGETS zip + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +#CREATE_LIBTOOL_FILE(zip lib) diff --git a/third_party/libzip/lib/compat.h b/third_party/libzip/lib/compat.h new file mode 100644 index 0000000..79f94db --- /dev/null +++ b/third_party/libzip/lib/compat.h @@ -0,0 +1,202 @@ +#ifndef _HAD_LIBZIP_COMPAT_H +#define _HAD_LIBZIP_COMPAT_H + +/* + compat.h -- compatibility defines. + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipconf.h" + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +/* to have *_MAX definitions for all types when compiling with g++ */ +#define __STDC_LIMIT_MACROS + +#ifdef _WIN32 +#ifndef ZIP_EXTERN +#ifndef ZIP_STATIC +#define ZIP_EXTERN __declspec(dllexport) +#endif +#endif +/* for dup(), close(), etc. */ +#include +#endif + +#ifdef HAVE_STDBOOL_H +#include +#else +typedef char bool; +#define true 1 +#define false 0 +#endif + +#include + +/* at least MinGW does not provide EOPNOTSUPP, see + * http://sourceforge.net/p/mingw/bugs/263/ + */ +#ifndef EOPNOTSUPP +#define EOPNOTSUPP EINVAL +#endif + +/* at least MinGW does not provide EOVERFLOW, see + * http://sourceforge.net/p/mingw/bugs/242/ + */ +#ifndef EOVERFLOW +#define EOVERFLOW EFBIG +#endif + +#ifdef _WIN32 +#if defined(HAVE__CHMOD) +#define chmod _chmod +#endif +#if defined(HAVE__CLOSE) +#define close _close +#endif +#if defined(HAVE__DUP) +#define dup _dup +#endif +/* crashes reported when using fdopen instead of _fdopen on Windows/Visual Studio 10/Win64 */ +#if defined(HAVE__FDOPEN) +#define fdopen _fdopen +#endif +#if !defined(HAVE_FILENO) && defined(HAVE__FILENO) +#define fileno _fileno +#endif +/* Windows' open() doesn't understand Unix permissions */ +#if defined(HAVE__OPEN) +#define open(a, b, c) _open((a), (b)) +#endif +#if defined(HAVE__SNPRINTF) +#define snprintf _snprintf +#endif +#if defined(HAVE__STRDUP) +#if !defined(HAVE_STRDUP) || defined(_WIN32) +#undef strdup +#define strdup _strdup +#endif +#endif +#if !defined(HAVE__SETMODE) && defined(HAVE_SETMODE) +#define _setmode setmode +#endif +#if !defined(HAVE_STRTOLL) && defined(HAVE__STRTOI64) +#define strtoll _strtoi64 +#endif +#if !defined(HAVE_STRTOULL) && defined(HAVE__STRTOUI64) +#define strtoull _strtoui64 +#endif +#if defined(HAVE__UMASK) +#define umask _umask +#endif +#if defined(HAVE__UNLINK) +#define unlink _unlink +#endif +#endif + +#ifndef HAVE_FSEEKO +#define fseeko(s, o, w) (fseek((s), (long int)(o), (w))) +#endif + +#ifndef HAVE_FTELLO +#define ftello(s) ((long)ftell((s))) +#endif + +#ifndef HAVE_MKSTEMP +int _zip_mkstemp(char *); +#define mkstemp _zip_mkstemp +#endif + +#if !defined(HAVE_STRCASECMP) +#if defined(HAVE__STRICMP) +#define strcasecmp _stricmp +#elif defined(HAVE_STRICMP) +#define strcasecmp stricmp +#endif +#endif + +#if SIZEOF_OFF_T == 8 +#define ZIP_OFF_MAX ZIP_INT64_MAX +#define ZIP_OFF_MIN ZIP_INT64_MIN +#elif SIZEOF_OFF_T == 4 +#define ZIP_OFF_MAX ZIP_INT32_MAX +#define ZIP_OFF_MIN ZIP_INT32_MIN +#elif SIZEOF_OFF_T == 2 +#define ZIP_OFF_MAX ZIP_INT16_MAX +#define ZIP_OFF_MIN ZIP_INT16_MIN +#else +#error unsupported size of off_t +#endif + +#if defined(HAVE_FTELLO) && defined(HAVE_FSEEKO) +#define ZIP_FSEEK_MAX ZIP_OFF_MAX +#define ZIP_FSEEK_MIN ZIP_OFF_MIN +#else +#include +#define ZIP_FSEEK_MAX LONG_MAX +#define ZIP_FSEEK_MIN LONG_MIN +#endif + +#ifndef SIZE_MAX +#if SIZEOF_SIZE_T == 8 +#define SIZE_MAX ZIP_INT64_MAX +#elif SIZEOF_SIZE_T == 4 +#define SIZE_MAX ZIP_INT32_MAX +#elif SIZEOF_SIZE_T == 2 +#define SIZE_MAX ZIP_INT16_MAX +#else +#error unsupported size of size_t +#endif +#endif + +#ifndef PRId64 +#ifdef _MSC_VER +#define PRId64 "I64d" +#else +#define PRId64 "lld" +#endif +#endif + +#ifndef PRIu64 +#ifdef _MSC_VER +#define PRIu64 "I64u" +#else +#define PRIu64 "llu" +#endif +#endif + +#ifndef S_ISDIR +#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) +#endif + +#endif /* compat.h */ diff --git a/third_party/libzip/lib/make_zip_err_str.sh b/third_party/libzip/lib/make_zip_err_str.sh new file mode 100644 index 0000000..8d98f23 --- /dev/null +++ b/third_party/libzip/lib/make_zip_err_str.sh @@ -0,0 +1,79 @@ +#!/bin/sh + +# make_zip_err_str.sh: create zip_err_str.c from zip.h +# Copyright (C) 1999-2014 Dieter Baron and Thomas Klausner +# +# This file is part of libzip, a library to manipulate ZIP archives. +# The authors can be contacted at +# +# 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. +# 3. The names of the authors may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. + + +if [ "$#" -ne 2 ] +then + echo "Usage: $0 in_file out_file" >&2 + echo " e.g. $0 zip.h zip_err_str.c" >&2 + exit 1 +fi + +if [ "$1" = "$2" ] +then + echo "$0: error: output file = input file" >&2 + exit 1 +fi + +cat <> "$2.$$" || exit 1 +/* + This file was generated automatically by $0 + from $1; make changes there. + */ + +#include "zipint.h" + +const char * const _zip_err_str[] = { +EOF + +sed -n '/^#define ZIP_ER_/ s/.*\/\* . \([^*]*\) \*\// "\1",/p' "$1" \ + >> "$2.$$" || exit 1 + +cat <> "$2.$$" || exit 1 +}; + +const int _zip_nerr_str = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]); + +#define N ZIP_ET_NONE +#define S ZIP_ET_SYS +#define Z ZIP_ET_ZLIB + +const int _zip_err_type[] = { +EOF + +sed -n '/^#define ZIP_ER_/ s/.*\/\* \(.\) \([^*]*\) \*\// \1,/p' "$1" \ + >> "$2.$$" || exit 1 + +echo '};' >> "$2.$$" || exit 1 + +mv "$2.$$" "$2" || exit 1 diff --git a/third_party/libzip/lib/make_zipconf.sh b/third_party/libzip/lib/make_zipconf.sh new file mode 100644 index 0000000..cdf83f4 --- /dev/null +++ b/third_party/libzip/lib/make_zipconf.sh @@ -0,0 +1,163 @@ +#!/bin/sh + +# make_zipconf.sh: create platform specific include file zipconf.h +# Copyright (C) 1999-2011 Dieter Baron and Thomas Klausner +# +# This file is part of libzip, a library to manipulate ZIP archives. +# The authors can be contacted at +# +# 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. +# 3. The names of the authors may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. + + +set -e + +define_type() +{ + short=$1 + long=$2 + bytes=$3 + infile="$4" + outfile="$5" + + bits=`expr $bytes '*' 8` + type="${short}int${bits}" + TYPE=`echo $type | tr '[a-z]' '[A-Z]'` + if grep "define HAVE_${TYPE}_T" "$infile" > /dev/null + then + echo "typedef ${type}_t zip_${type}_t;" >> "$outfile" + LTYPE="$TYPE" + else + SHORT=`echo $short | tr '[a-z]' '[A-Z]'` + if [ -z "$SHORT" ] + then + SHORT='S' + fi + if [ "$bytes" -eq 1 ] + then + if [ -z "$long" ] + then + long='signed' + fi + echo "typedef $long char ${type}_t;" >> $outfile + LTYPE="${SHORT}CHAR" + else + ctype=`sed -n "s/.define SIZEOF_\([A-Z_]*\) $bytes/\1/p" "$infile" \ + | head -1 | tr '[A-Z_]' '[a-z ]'` + if [ -z "$ctype" ] + then + echo "$0: no $bits bit type found" >&2 + exit 1 + fi + echo "typedef $long $ctype ${type}_t;" >> "$outfile" + case "$ctype" in + short) LTYPE=${SHORT}SHRT;; + int) LTYPE=${SHORT}INT;; + long) LTYPE=${SHORT}LONG;; + "long long") LTYPE=${SHORT}LLONG;; + esac + fi + fi + + if [ -z "$long" ] + then + echo "#define ZIP_${TYPE}_MIN ${LTYPE}_MIN" >> "$outfile" + fi + echo "#define ZIP_${TYPE}_MAX ${LTYPE}_MAX" >> "$outfile" + echo >> "$outfile" +} + + +if [ "$#" -ne 2 ] +then + echo "Usage: $0 config_h_file out_file" >&2 + echo " e.g. $0 ../config.h zip_err_str.c" >&2 + exit 1 +fi + +if [ "$1" = "$2" ] +then + echo "$0: error: output file = input file" >&2 + exit 1 +fi + +cat < "$2.$$" +#ifndef _HAD_ZIPCONF_H +#define _HAD_ZIPCONF_H + +/* + zipconf.h -- platform specific include file + + This file was generated automatically by $0 + based on $1. + */ + +EOF + +version=`sed -n 's/^#define VERSION "\(.*\)"/\1/p' "$1"` + +version_major=`expr "$version" : '^\([0-9]*\)' || true` +version_minor=`expr "$version" : '^[0-9]*\.\([0-9]*\)' || true` +version_micro=`expr "$version" : '^[0-9]*\.[0-9]\.\([0-9]*\)' || true` + +if [ -z "$version_major" ] +then + version_major=0 +fi +if [ -z "$version_minor" ] +then + version_minor=0 +fi +if [ -z "$version_micro" ] +then + version_micro=0 +fi + +cat <> "$2.$$" +#define LIBZIP_VERSION "$version" +#define LIBZIP_VERSION_MAJOR $version_major +#define LIBZIP_VERSION_MINOR $version_minor +#define LIBZIP_VERSION_MICRO $version_micro + +EOF + +if grep 'define HAVE_INTTYPES_H' "$1" > /dev/null +then + echo '#include ' >> "$2.$$" +else + echo '#include ' >> "$2.$$" +fi +echo >> "$2.$$" + +for size in 1 2 4 8 +do + define_type '' '' $size "$1" "$2.$$" + define_type u unsigned $size "$1" "$2.$$" +done + +echo >> "$2.$$" +echo '#endif /* zipconf.h */' >> "$2.$$" + +mv "$2.$$" "$2" diff --git a/third_party/libzip/lib/mkstemp.c b/third_party/libzip/lib/mkstemp.c new file mode 100644 index 0000000..f18f10b --- /dev/null +++ b/third_party/libzip/lib/mkstemp.c @@ -0,0 +1,153 @@ +/* Adapted from NetBSB libc by Dieter Baron */ + +/* NetBSD: gettemp.c,v 1.13 2003/12/05 00:57:36 uebayasi Exp */ + +/* + * Copyright (c) 1987, 1993 + * The Regents of the University of California. 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. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +#include +#include + +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#endif +#include +#include + +#ifndef O_BINARY +#define O_BINARY 0 +#endif + + +int +_zip_mkstemp(char *path) { +#ifdef _WIN32 + int ret; + ret = _creat(_mktemp(path), _S_IREAD | _S_IWRITE); + if (ret == -1) { + return 0; + } + else { + return ret; + } +#else + int fd; + char *start, *trv; + struct stat sbuf; + pid_t pid; + + /* To guarantee multiple calls generate unique names even if + the file is not created. 676 different possibilities with 7 + or more X's, 26 with 6 or less. */ + static char xtra[2] = "aa"; + int xcnt = 0; + + pid = getpid(); + + /* Move to end of path and count trailing X's. */ + for (trv = path; *trv; ++trv) + if (*trv == 'X') + xcnt++; + else + xcnt = 0; + + /* Use at least one from xtra. Use 2 if more than 6 X's. */ + if (*(trv - 1) == 'X') + *--trv = xtra[0]; + if (xcnt > 6 && *(trv - 1) == 'X') + *--trv = xtra[1]; + + /* Set remaining X's to pid digits with 0's to the left. */ + while (*--trv == 'X') { + *trv = (pid % 10) + '0'; + pid /= 10; + } + + /* update xtra for next call. */ + if (xtra[0] != 'z') + xtra[0]++; + else { + xtra[0] = 'a'; + if (xtra[1] != 'z') + xtra[1]++; + else + xtra[1] = 'a'; + } + + /* + * check the target directory; if you have six X's and it + * doesn't exist this runs for a *very* long time. + */ + for (start = trv + 1;; --trv) { + if (trv <= path) + break; + if (*trv == '/') { + *trv = '\0'; + if (stat(path, &sbuf)) + return (0); + if (!S_ISDIR(sbuf.st_mode)) { + errno = ENOTDIR; + return (0); + } + *trv = '/'; + break; + } + } + + for (;;) { + if ((fd = open(path, O_CREAT | O_EXCL | O_RDWR | O_BINARY, 0600)) >= 0) + return (fd); + if (errno != EEXIST) + return (0); + + /* tricky little algorithm for backward compatibility */ + for (trv = start;;) { + if (!*trv) + return (0); + if (*trv == 'z') + *trv++ = 'a'; + else { + if (isdigit((unsigned char)*trv)) + *trv = 'a'; + else + ++*trv; + break; + } + } + } + /*NOTREACHED*/ +#endif +} diff --git a/third_party/libzip/lib/zip.h b/third_party/libzip/lib/zip.h new file mode 100644 index 0000000..42c3e14 --- /dev/null +++ b/third_party/libzip/lib/zip.h @@ -0,0 +1,450 @@ +#ifndef _HAD_ZIP_H +#define _HAD_ZIP_H + +/* + zip.h -- exported declarations. + Copyright (C) 1999-2019 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* fix autoindent */ +#endif +#endif + +#include + +#ifndef ZIP_EXTERN +#ifndef ZIP_STATIC +#ifdef _WIN32 +#define ZIP_EXTERN __declspec(dllimport) +#elif defined(__GNUC__) && __GNUC__ >= 4 +#define ZIP_EXTERN __attribute__((visibility("default"))) +#else +#define ZIP_EXTERN +#endif +#else +#define ZIP_EXTERN +#endif +#endif + +#include +#include +#include + +/* flags for zip_open */ + +#define ZIP_CREATE 1 +#define ZIP_EXCL 2 +#define ZIP_CHECKCONS 4 +#define ZIP_TRUNCATE 8 +#define ZIP_RDONLY 16 + + +/* flags for zip_name_locate, zip_fopen, zip_stat, ... */ + +#define ZIP_FL_NOCASE 1u /* ignore case on name lookup */ +#define ZIP_FL_NODIR 2u /* ignore directory component */ +#define ZIP_FL_COMPRESSED 4u /* read compressed data */ +#define ZIP_FL_UNCHANGED 8u /* use original data, ignoring changes */ +#define ZIP_FL_RECOMPRESS 16u /* force recompression of data */ +#define ZIP_FL_ENCRYPTED 32u /* read encrypted data (implies ZIP_FL_COMPRESSED) */ +#define ZIP_FL_ENC_GUESS 0u /* guess string encoding (is default) */ +#define ZIP_FL_ENC_RAW 64u /* get unmodified string */ +#define ZIP_FL_ENC_STRICT 128u /* follow specification strictly */ +#define ZIP_FL_LOCAL 256u /* in local header */ +#define ZIP_FL_CENTRAL 512u /* in central directory */ +/* 1024u reserved for internal use */ +#define ZIP_FL_ENC_UTF_8 2048u /* string is UTF-8 encoded */ +#define ZIP_FL_ENC_CP437 4096u /* string is CP437 encoded */ +#define ZIP_FL_OVERWRITE 8192u /* zip_file_add: if file with name exists, overwrite (replace) it */ + +/* archive global flags flags */ + +#define ZIP_AFL_RDONLY 2u /* read only -- cannot be cleared */ + + +/* create a new extra field */ + +#define ZIP_EXTRA_FIELD_ALL ZIP_UINT16_MAX +#define ZIP_EXTRA_FIELD_NEW ZIP_UINT16_MAX + + +/* libzip error codes */ + +#define ZIP_ER_OK 0 /* N No error */ +#define ZIP_ER_MULTIDISK 1 /* N Multi-disk zip archives not supported */ +#define ZIP_ER_RENAME 2 /* S Renaming temporary file failed */ +#define ZIP_ER_CLOSE 3 /* S Closing zip archive failed */ +#define ZIP_ER_SEEK 4 /* S Seek error */ +#define ZIP_ER_READ 5 /* S Read error */ +#define ZIP_ER_WRITE 6 /* S Write error */ +#define ZIP_ER_CRC 7 /* N CRC error */ +#define ZIP_ER_ZIPCLOSED 8 /* N Containing zip archive was closed */ +#define ZIP_ER_NOENT 9 /* N No such file */ +#define ZIP_ER_EXISTS 10 /* N File already exists */ +#define ZIP_ER_OPEN 11 /* S Can't open file */ +#define ZIP_ER_TMPOPEN 12 /* S Failure to create temporary file */ +#define ZIP_ER_ZLIB 13 /* Z Zlib error */ +#define ZIP_ER_MEMORY 14 /* N Malloc failure */ +#define ZIP_ER_CHANGED 15 /* N Entry has been changed */ +#define ZIP_ER_COMPNOTSUPP 16 /* N Compression method not supported */ +#define ZIP_ER_EOF 17 /* N Premature end of file */ +#define ZIP_ER_INVAL 18 /* N Invalid argument */ +#define ZIP_ER_NOZIP 19 /* N Not a zip archive */ +#define ZIP_ER_INTERNAL 20 /* N Internal error */ +#define ZIP_ER_INCONS 21 /* N Zip archive inconsistent */ +#define ZIP_ER_REMOVE 22 /* S Can't remove file */ +#define ZIP_ER_DELETED 23 /* N Entry has been deleted */ +#define ZIP_ER_ENCRNOTSUPP 24 /* N Encryption method not supported */ +#define ZIP_ER_RDONLY 25 /* N Read-only archive */ +#define ZIP_ER_NOPASSWD 26 /* N No password provided */ +#define ZIP_ER_WRONGPASSWD 27 /* N Wrong password provided */ +#define ZIP_ER_OPNOTSUPP 28 /* N Operation not supported */ +#define ZIP_ER_INUSE 29 /* N Resource still in use */ +#define ZIP_ER_TELL 30 /* S Tell error */ +#define ZIP_ER_COMPRESSED_DATA 31 /* N Compressed data invalid */ + +/* type of system error value */ + +#define ZIP_ET_NONE 0 /* sys_err unused */ +#define ZIP_ET_SYS 1 /* sys_err is errno */ +#define ZIP_ET_ZLIB 2 /* sys_err is zlib error code */ + +/* compression methods */ + +#define ZIP_CM_DEFAULT -1 /* better of deflate or store */ +#define ZIP_CM_STORE 0 /* stored (uncompressed) */ +#define ZIP_CM_SHRINK 1 /* shrunk */ +#define ZIP_CM_REDUCE_1 2 /* reduced with factor 1 */ +#define ZIP_CM_REDUCE_2 3 /* reduced with factor 2 */ +#define ZIP_CM_REDUCE_3 4 /* reduced with factor 3 */ +#define ZIP_CM_REDUCE_4 5 /* reduced with factor 4 */ +#define ZIP_CM_IMPLODE 6 /* imploded */ +/* 7 - Reserved for Tokenizing compression algorithm */ +#define ZIP_CM_DEFLATE 8 /* deflated */ +#define ZIP_CM_DEFLATE64 9 /* deflate64 */ +#define ZIP_CM_PKWARE_IMPLODE 10 /* PKWARE imploding */ +/* 11 - Reserved by PKWARE */ +#define ZIP_CM_BZIP2 12 /* compressed using BZIP2 algorithm */ +/* 13 - Reserved by PKWARE */ +#define ZIP_CM_LZMA 14 /* LZMA (EFS) */ +/* 15-17 - Reserved by PKWARE */ +#define ZIP_CM_TERSE 18 /* compressed using IBM TERSE (new) */ +#define ZIP_CM_LZ77 19 /* IBM LZ77 z Architecture (PFS) */ +#define ZIP_CM_XZ 95 /* XZ compressed data */ +#define ZIP_CM_JPEG 96 /* Compressed Jpeg data */ +#define ZIP_CM_WAVPACK 97 /* WavPack compressed data */ +#define ZIP_CM_PPMD 98 /* PPMd version I, Rev 1 */ + +/* encryption methods */ + +#define ZIP_EM_NONE 0 /* not encrypted */ +#define ZIP_EM_TRAD_PKWARE 1 /* traditional PKWARE encryption */ +#if 0 /* Strong Encryption Header not parsed yet */ +#define ZIP_EM_DES 0x6601 /* strong encryption: DES */ +#define ZIP_EM_RC2_OLD 0x6602 /* strong encryption: RC2, version < 5.2 */ +#define ZIP_EM_3DES_168 0x6603 +#define ZIP_EM_3DES_112 0x6609 +#define ZIP_EM_PKZIP_AES_128 0x660e +#define ZIP_EM_PKZIP_AES_192 0x660f +#define ZIP_EM_PKZIP_AES_256 0x6610 +#define ZIP_EM_RC2 0x6702 /* strong encryption: RC2, version >= 5.2 */ +#define ZIP_EM_RC4 0x6801 +#endif +#define ZIP_EM_AES_128 0x0101 /* Winzip AES encryption */ +#define ZIP_EM_AES_192 0x0102 +#define ZIP_EM_AES_256 0x0103 +#define ZIP_EM_UNKNOWN 0xffff /* unknown algorithm */ + +#define ZIP_OPSYS_DOS 0x00u +#define ZIP_OPSYS_AMIGA 0x01u +#define ZIP_OPSYS_OPENVMS 0x02u +#define ZIP_OPSYS_UNIX 0x03u +#define ZIP_OPSYS_VM_CMS 0x04u +#define ZIP_OPSYS_ATARI_ST 0x05u +#define ZIP_OPSYS_OS_2 0x06u +#define ZIP_OPSYS_MACINTOSH 0x07u +#define ZIP_OPSYS_Z_SYSTEM 0x08u +#define ZIP_OPSYS_CPM 0x09u +#define ZIP_OPSYS_WINDOWS_NTFS 0x0au +#define ZIP_OPSYS_MVS 0x0bu +#define ZIP_OPSYS_VSE 0x0cu +#define ZIP_OPSYS_ACORN_RISC 0x0du +#define ZIP_OPSYS_VFAT 0x0eu +#define ZIP_OPSYS_ALTERNATE_MVS 0x0fu +#define ZIP_OPSYS_BEOS 0x10u +#define ZIP_OPSYS_TANDEM 0x11u +#define ZIP_OPSYS_OS_400 0x12u +#define ZIP_OPSYS_OS_X 0x13u + +#define ZIP_OPSYS_DEFAULT ZIP_OPSYS_UNIX + + +enum zip_source_cmd { + ZIP_SOURCE_OPEN, /* prepare for reading */ + ZIP_SOURCE_READ, /* read data */ + ZIP_SOURCE_CLOSE, /* reading is done */ + ZIP_SOURCE_STAT, /* get meta information */ + ZIP_SOURCE_ERROR, /* get error information */ + ZIP_SOURCE_FREE, /* cleanup and free resources */ + ZIP_SOURCE_SEEK, /* set position for reading */ + ZIP_SOURCE_TELL, /* get read position */ + ZIP_SOURCE_BEGIN_WRITE, /* prepare for writing */ + ZIP_SOURCE_COMMIT_WRITE, /* writing is done */ + ZIP_SOURCE_ROLLBACK_WRITE, /* discard written changes */ + ZIP_SOURCE_WRITE, /* write data */ + ZIP_SOURCE_SEEK_WRITE, /* set position for writing */ + ZIP_SOURCE_TELL_WRITE, /* get write position */ + ZIP_SOURCE_SUPPORTS, /* check whether source supports command */ + ZIP_SOURCE_REMOVE, /* remove file */ + ZIP_SOURCE_GET_COMPRESSION_FLAGS, /* get compression flags, internal only */ + ZIP_SOURCE_BEGIN_WRITE_CLONING /* like ZIP_SOURCE_BEGIN_WRITE, but keep part of original file */ +}; +typedef enum zip_source_cmd zip_source_cmd_t; + +#define ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd) (((zip_int64_t)1) << (cmd)) + +// clang-format off + +#define ZIP_SOURCE_SUPPORTS_READABLE (ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_OPEN) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_READ) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_CLOSE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_STAT) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ERROR) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_FREE)) + +#define ZIP_SOURCE_SUPPORTS_SEEKABLE (ZIP_SOURCE_SUPPORTS_READABLE \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_TELL) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SUPPORTS)) + +#define ZIP_SOURCE_SUPPORTS_WRITABLE (ZIP_SOURCE_SUPPORTS_SEEKABLE \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_COMMIT_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_ROLLBACK_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_TELL_WRITE) \ + | ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_REMOVE)) + +// clang-format on + +/* for use by sources */ +struct zip_source_args_seek { + zip_int64_t offset; + int whence; +}; + +typedef struct zip_source_args_seek zip_source_args_seek_t; +#define ZIP_SOURCE_GET_ARGS(type, data, len, error) ((len) < sizeof(type) ? zip_error_set((error), ZIP_ER_INVAL, 0), (type *)NULL : (type *)(data)) + + +/* error information */ +/* use zip_error_*() to access */ +struct zip_error { + int zip_err; /* libzip error code (ZIP_ER_*) */ + int sys_err; /* copy of errno (E*) or zlib error code */ + char * _Nullable str; /* string representation or NULL */ +}; + +#define ZIP_STAT_NAME 0x0001u +#define ZIP_STAT_INDEX 0x0002u +#define ZIP_STAT_SIZE 0x0004u +#define ZIP_STAT_COMP_SIZE 0x0008u +#define ZIP_STAT_MTIME 0x0010u +#define ZIP_STAT_CRC 0x0020u +#define ZIP_STAT_COMP_METHOD 0x0040u +#define ZIP_STAT_ENCRYPTION_METHOD 0x0080u +#define ZIP_STAT_FLAGS 0x0100u + +struct zip_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char * _Nullable name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; + +struct zip_buffer_fragment { + zip_uint8_t * _Nonnull data; + zip_uint64_t length; +}; + +struct zip; +struct zip_file; +struct zip_source; + +typedef struct zip zip_t; +typedef struct zip_error zip_error_t; +typedef struct zip_file zip_file_t; +typedef struct zip_source zip_source_t; +typedef struct zip_stat zip_stat_t; +typedef struct zip_buffer_fragment zip_buffer_fragment_t; + +typedef zip_uint32_t zip_flags_t; + +typedef zip_int64_t (*zip_source_callback)(void * _Nullable, void * _Nullable, zip_uint64_t, zip_source_cmd_t); +typedef void (*zip_progress_callback)(zip_t * _Nonnull, double, void * _Nullable); + +#ifndef ZIP_DISABLE_DEPRECATED +typedef void (*zip_progress_callback_t)(double); +ZIP_EXTERN void zip_register_progress_callback(zip_t * _Nonnull, zip_progress_callback_t _Nullable); /* use zip_register_progress_callback_with_state */ + +ZIP_EXTERN zip_int64_t zip_add(zip_t * _Nonnull, const char * _Nonnull, zip_source_t * _Nonnull); /* use zip_file_add */ +ZIP_EXTERN zip_int64_t zip_add_dir(zip_t * _Nonnull, const char * _Nonnull); /* use zip_dir_add */ +ZIP_EXTERN const char * _Nullable zip_get_file_comment(zip_t * _Nonnull, zip_uint64_t, int * _Nullable, int); /* use zip_file_get_comment */ +ZIP_EXTERN int zip_get_num_files(zip_t * _Nonnull); /* use zip_get_num_entries instead */ +ZIP_EXTERN int zip_rename(zip_t * _Nonnull, zip_uint64_t, const char * _Nonnull); /* use zip_file_rename */ +ZIP_EXTERN int zip_replace(zip_t * _Nonnull, zip_uint64_t, zip_source_t * _Nonnull); /* use zip_file_replace */ +ZIP_EXTERN int zip_set_file_comment(zip_t * _Nonnull, zip_uint64_t, const char * _Nullable, int); /* use zip_file_set_comment */ +ZIP_EXTERN int zip_error_get_sys_type(int); /* use zip_error_system_type */ +ZIP_EXTERN void zip_error_get(zip_t * _Nonnull, int * _Nullable, int * _Nullable); /* use zip_get_error, zip_error_code_zip / zip_error_code_system */ +ZIP_EXTERN int zip_error_to_str(char * _Nonnull, zip_uint64_t, int, int); /* use zip_error_init_with_code / zip_error_strerror */ +ZIP_EXTERN void zip_file_error_get(zip_file_t * _Nonnull, int * _Nullable, int * _Nullable); /* use zip_file_get_error, zip_error_code_zip / zip_error_code_system */ +#endif + +ZIP_EXTERN int zip_close(zip_t * _Nonnull); +ZIP_EXTERN int zip_delete(zip_t * _Nonnull, zip_uint64_t); +ZIP_EXTERN zip_int64_t zip_dir_add(zip_t * _Nonnull, const char * _Nonnull, zip_flags_t); +ZIP_EXTERN void zip_discard(zip_t * _Nonnull); + +ZIP_EXTERN zip_error_t * _Nonnull zip_get_error(zip_t * _Nonnull); +ZIP_EXTERN void zip_error_clear(zip_t * _Nonnull); +ZIP_EXTERN int zip_error_code_zip(const zip_error_t * _Nonnull); +ZIP_EXTERN int zip_error_code_system(const zip_error_t * _Nonnull); +ZIP_EXTERN void zip_error_fini(zip_error_t * _Nonnull); +ZIP_EXTERN void zip_error_init(zip_error_t * _Nonnull); +ZIP_EXTERN void zip_error_init_with_code(zip_error_t * _Nonnull, int); +ZIP_EXTERN void zip_error_set(zip_error_t * _Nullable, int, int); +ZIP_EXTERN const char * _Nonnull zip_error_strerror(zip_error_t * _Nonnull); +ZIP_EXTERN int zip_error_system_type(const zip_error_t * _Nonnull); +ZIP_EXTERN zip_int64_t zip_error_to_data(const zip_error_t * _Nonnull, void * _Nonnull, zip_uint64_t); + +ZIP_EXTERN int zip_fclose(zip_file_t * _Nonnull); +ZIP_EXTERN zip_t * _Nullable zip_fdopen(int, int, int * _Nullable); +ZIP_EXTERN zip_int64_t zip_file_add(zip_t * _Nonnull, const char * _Nonnull, zip_source_t * _Nonnull, zip_flags_t); +ZIP_EXTERN void zip_file_error_clear(zip_file_t * _Nonnull); +ZIP_EXTERN int zip_file_extra_field_delete(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_extra_field_delete_by_id(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_extra_field_set(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, const zip_uint8_t * _Nullable, zip_uint16_t, zip_flags_t); +ZIP_EXTERN zip_int16_t zip_file_extra_fields_count(zip_t * _Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_int16_t zip_file_extra_fields_count_by_id(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_flags_t); +ZIP_EXTERN const zip_uint8_t * _Nullable zip_file_extra_field_get(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t * _Nullable, zip_uint16_t * _Nullable, zip_flags_t); +ZIP_EXTERN const zip_uint8_t * _Nullable zip_file_extra_field_get_by_id(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, zip_uint16_t, zip_uint16_t * _Nullable, zip_flags_t); +ZIP_EXTERN const char * _Nullable zip_file_get_comment(zip_t * _Nonnull, zip_uint64_t, zip_uint32_t * _Nullable, zip_flags_t); +ZIP_EXTERN zip_error_t * _Nonnull zip_file_get_error(zip_file_t * _Nonnull); +ZIP_EXTERN int zip_file_get_external_attributes(zip_t * _Nonnull, zip_uint64_t, zip_flags_t, zip_uint8_t * _Nullable, zip_uint32_t * _Nullable); +ZIP_EXTERN int zip_file_rename(zip_t * _Nonnull, zip_uint64_t, const char * _Nonnull, zip_flags_t); +ZIP_EXTERN int zip_file_replace(zip_t * _Nonnull, zip_uint64_t, zip_source_t * _Nonnull, zip_flags_t); +ZIP_EXTERN int zip_file_set_comment(zip_t * _Nonnull, zip_uint64_t, const char * _Nullable, zip_uint16_t, zip_flags_t); +ZIP_EXTERN int zip_file_set_encryption(zip_t * _Nonnull, zip_uint64_t, zip_uint16_t, const char * _Nullable); +ZIP_EXTERN int zip_file_set_external_attributes(zip_t * _Nonnull, zip_uint64_t, zip_flags_t, zip_uint8_t, zip_uint32_t); +ZIP_EXTERN int zip_file_set_mtime(zip_t * _Nonnull, zip_uint64_t, time_t, zip_flags_t); +ZIP_EXTERN const char * _Nonnull zip_file_strerror(zip_file_t * _Nonnull); +ZIP_EXTERN zip_file_t * _Nullable zip_fopen(zip_t * _Nonnull, const char * _Nonnull, zip_flags_t); +ZIP_EXTERN zip_file_t * _Nullable zip_fopen_encrypted(zip_t * _Nonnull, const char * _Nonnull, zip_flags_t, const char * _Nullable); +ZIP_EXTERN zip_file_t * _Nullable zip_fopen_index(zip_t * _Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_file_t * _Nullable zip_fopen_index_encrypted(zip_t * _Nonnull, zip_uint64_t, zip_flags_t, const char * _Nullable); +ZIP_EXTERN zip_int64_t zip_fread(zip_file_t * _Nonnull, void * _Nonnull, zip_uint64_t); +ZIP_EXTERN zip_int8_t zip_fseek(zip_file_t * _Nonnull, zip_int64_t, int); +ZIP_EXTERN zip_int64_t zip_ftell(zip_file_t * _Nonnull); +ZIP_EXTERN const char * _Nullable zip_get_archive_comment(zip_t * _Nonnull, int * _Nullable, zip_flags_t); +ZIP_EXTERN int zip_get_archive_flag(zip_t * _Nonnull, zip_flags_t, zip_flags_t); +ZIP_EXTERN const char * _Nullable zip_get_name(zip_t * _Nonnull, zip_uint64_t, zip_flags_t); +ZIP_EXTERN zip_int64_t zip_get_num_entries(zip_t * _Nonnull, zip_flags_t); +ZIP_EXTERN const char * _Nonnull zip_libzip_version(void); +ZIP_EXTERN zip_int64_t zip_name_locate(zip_t * _Nonnull, const char * _Nonnull, zip_flags_t); +ZIP_EXTERN zip_t * _Nullable zip_open(const char * _Nonnull, int, int * _Nullable); +ZIP_EXTERN zip_t * _Nullable zip_open_from_source(zip_source_t * _Nonnull, int, zip_error_t * _Nullable); +ZIP_EXTERN int zip_register_progress_callback_with_state(zip_t * _Nonnull, double, zip_progress_callback _Nullable, void (* _Nullable)(void * _Nullable), void * _Nullable); +ZIP_EXTERN int zip_set_archive_comment(zip_t * _Nonnull, const char * _Nullable, zip_uint16_t); +ZIP_EXTERN int zip_set_archive_flag(zip_t * _Nonnull, zip_flags_t, int); +ZIP_EXTERN int zip_set_default_password(zip_t * _Nonnull, const char * _Nullable); +ZIP_EXTERN int zip_set_file_compression(zip_t * _Nonnull, zip_uint64_t, zip_int32_t, zip_uint32_t); +ZIP_EXTERN int zip_source_begin_write(zip_source_t * _Nonnull); +ZIP_EXTERN int zip_source_begin_write_cloning(zip_source_t * _Nonnull, zip_uint64_t); +ZIP_EXTERN zip_source_t * _Nullable zip_source_buffer(zip_t * _Nonnull, const void * _Nullable, zip_uint64_t, int); +ZIP_EXTERN zip_source_t * _Nullable zip_source_buffer_create(const void * _Nullable, zip_uint64_t, int, zip_error_t * _Nullable); +ZIP_EXTERN zip_source_t * _Nullable zip_source_buffer_fragment(zip_t * _Nonnull, const zip_buffer_fragment_t * _Nonnull, zip_uint64_t, int); +ZIP_EXTERN zip_source_t * _Nullable zip_source_buffer_fragment_create(const zip_buffer_fragment_t * _Nonnull, zip_uint64_t, int, zip_error_t * _Nullable); +ZIP_EXTERN int zip_source_close(zip_source_t * _Nonnull); +ZIP_EXTERN int zip_source_commit_write(zip_source_t * _Nonnull); +ZIP_EXTERN zip_error_t * _Nonnull zip_source_error(zip_source_t * _Nonnull); +ZIP_EXTERN zip_source_t * _Nullable zip_source_file(zip_t * _Nonnull, const char * _Nonnull, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t * _Nullable zip_source_file_create(const char * _Nonnull, zip_uint64_t, zip_int64_t, zip_error_t * _Nullable); +ZIP_EXTERN zip_source_t * _Nullable zip_source_filep(zip_t * _Nonnull, FILE * _Nonnull, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t * _Nullable zip_source_filep_create(FILE * _Nonnull, zip_uint64_t, zip_int64_t, zip_error_t * _Nullable); +ZIP_EXTERN void zip_source_free(zip_source_t * _Nullable); +ZIP_EXTERN zip_source_t * _Nullable zip_source_function(zip_t * _Nonnull, zip_source_callback _Nonnull , void * _Nullable); +ZIP_EXTERN zip_source_t * _Nullable zip_source_function_create(zip_source_callback _Nonnull , void * _Nullable, zip_error_t * _Nullable); +ZIP_EXTERN int zip_source_is_deleted(zip_source_t * _Nonnull); +ZIP_EXTERN void zip_source_keep(zip_source_t * _Nonnull); +ZIP_EXTERN zip_int64_t zip_source_make_command_bitmap(zip_source_cmd_t, ...); +ZIP_EXTERN int zip_source_open(zip_source_t * _Nonnull); +ZIP_EXTERN zip_int64_t zip_source_read(zip_source_t * _Nonnull, void * _Nonnull, zip_uint64_t); +ZIP_EXTERN void zip_source_rollback_write(zip_source_t * _Nonnull); +ZIP_EXTERN int zip_source_seek(zip_source_t * _Nonnull, zip_int64_t, int); +ZIP_EXTERN zip_int64_t zip_source_seek_compute_offset(zip_uint64_t, zip_uint64_t, void * _Nonnull, zip_uint64_t, zip_error_t * _Nullable); +ZIP_EXTERN int zip_source_seek_write(zip_source_t * _Nonnull, zip_int64_t, int); +ZIP_EXTERN int zip_source_stat(zip_source_t * _Nonnull, zip_stat_t * _Nonnull); +ZIP_EXTERN zip_int64_t zip_source_tell(zip_source_t * _Nonnull); +ZIP_EXTERN zip_int64_t zip_source_tell_write(zip_source_t * _Nonnull); +#ifdef _WIN32 +ZIP_EXTERN zip_source_t *zip_source_win32a(zip_t *, const char *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32a_create(const char *, zip_uint64_t, zip_int64_t, zip_error_t *); +ZIP_EXTERN zip_source_t *zip_source_win32handle(zip_t *, void *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32handle_create(void *, zip_uint64_t, zip_int64_t, zip_error_t *); +ZIP_EXTERN zip_source_t *zip_source_win32w(zip_t *, const wchar_t *, zip_uint64_t, zip_int64_t); +ZIP_EXTERN zip_source_t *zip_source_win32w_create(const wchar_t *, zip_uint64_t, zip_int64_t, zip_error_t *); +#endif +ZIP_EXTERN zip_int64_t zip_source_write(zip_source_t * _Nonnull, const void * _Nullable, zip_uint64_t); +ZIP_EXTERN zip_source_t * _Nullable zip_source_zip(zip_t * _Nonnull, zip_t * _Nonnull, zip_uint64_t, zip_flags_t, zip_uint64_t, zip_int64_t); +ZIP_EXTERN int zip_stat(zip_t * _Nonnull, const char * _Nonnull, zip_flags_t, zip_stat_t * _Nonnull); +ZIP_EXTERN int zip_stat_index(zip_t * _Nonnull, zip_uint64_t, zip_flags_t, zip_stat_t * _Nonnull); +ZIP_EXTERN void zip_stat_init( zip_stat_t * _Nonnull); +ZIP_EXTERN const char * _Nonnull zip_strerror(zip_t * _Nonnull); +ZIP_EXTERN int zip_unchange(zip_t * _Nonnull, zip_uint64_t); +ZIP_EXTERN int zip_unchange_all(zip_t * _Nonnull); +ZIP_EXTERN int zip_unchange_archive(zip_t * _Nonnull); + +#ifdef __cplusplus +} +#endif + +#endif /* _HAD_ZIP_H */ diff --git a/third_party/libzip/lib/zip_add.c b/third_party/libzip/lib/zip_add.c new file mode 100644 index 0000000..f09c9ff --- /dev/null +++ b/third_party/libzip/lib/zip_add.c @@ -0,0 +1,49 @@ +/* + zip_add.c -- add file via callback function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +/* + NOTE: Return type is signed so we can return -1 on error. + The index can not be larger than ZIP_INT64_MAX since the size + of the central directory cannot be larger than + ZIP_UINT64_MAX, and each entry is larger than 2 bytes. +*/ + +ZIP_EXTERN zip_int64_t +zip_add(zip_t *za, const char *name, zip_source_t *source) { + return zip_file_add(za, name, source, 0); +} diff --git a/third_party/libzip/lib/zip_add_dir.c b/third_party/libzip/lib/zip_add_dir.c new file mode 100644 index 0000000..6beb929 --- /dev/null +++ b/third_party/libzip/lib/zip_add_dir.c @@ -0,0 +1,44 @@ +/* + zip_add_dir.c -- add directory + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +ZIP_EXTERN zip_int64_t +zip_add_dir(zip_t *za, const char *name) { + return zip_dir_add(za, name, 0); +} diff --git a/third_party/libzip/lib/zip_add_entry.c b/third_party/libzip/lib/zip_add_entry.c new file mode 100644 index 0000000..45def7a --- /dev/null +++ b/third_party/libzip/lib/zip_add_entry.c @@ -0,0 +1,80 @@ +/* + zip_add_entry.c -- create and init struct zip_entry + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +zip_int64_t +_zip_add_entry(zip_t *za) { + zip_uint64_t idx; + + if (za->nentry + 1 >= za->nentry_alloc) { + zip_entry_t *rentries; + zip_uint64_t nalloc = za->nentry_alloc; + zip_uint64_t additional_entries = 2 * nalloc; + zip_uint64_t realloc_size; + + if (additional_entries < 16) { + additional_entries = 16; + } + else if (additional_entries > 1024) { + additional_entries = 1024; + } + /* neither + nor * overflows can happen: nentry_alloc * sizeof(struct zip_entry) < UINT64_MAX */ + nalloc += additional_entries; + realloc_size = sizeof(struct zip_entry) * (size_t)nalloc; + + if (sizeof(struct zip_entry) * (size_t)za->nentry_alloc > realloc_size) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + rentries = (zip_entry_t *)realloc(za->entry, sizeof(struct zip_entry) * (size_t)nalloc); + if (!rentries) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + za->entry = rentries; + za->nentry_alloc = nalloc; + } + + idx = za->nentry++; + + _zip_entry_init(za->entry + idx); + + return (zip_int64_t)idx; +} diff --git a/third_party/libzip/lib/zip_algorithm_bzip2.c b/third_party/libzip/lib/zip_algorithm_bzip2.c new file mode 100644 index 0000000..72fbad1 --- /dev/null +++ b/third_party/libzip/lib/zip_algorithm_bzip2.c @@ -0,0 +1,270 @@ +/* + zip_algorithm_bzip2.c -- bzip2 (de)compression routines + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include +#include + +struct ctx { + zip_error_t *error; + bool compress; + int compression_flags; + bool end_of_input; + bz_stream zstr; +}; + + +static void * +allocate(bool compress, int compression_flags, zip_error_t *error) { + struct ctx *ctx; + + if ((ctx = (struct ctx *)malloc(sizeof(*ctx))) == NULL) { + return NULL; + } + + ctx->error = error; + ctx->compress = compress; + ctx->compression_flags = compression_flags; + if (ctx->compression_flags < 1 || ctx->compression_flags > 9) { + ctx->compression_flags = 9; + } + ctx->end_of_input = false; + + ctx->zstr.bzalloc = NULL; + ctx->zstr.bzfree = NULL; + ctx->zstr.opaque = NULL; + + return ctx; +} + + +static void * +compress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(true, compression_flags, error); +} + + +static void * +decompress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(false, compression_flags, error); +} + + +static void +deallocate(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + free(ctx); +} + + +static int +compression_flags(void *ud) { + return 0; +} + + +static int +map_error(int ret) { + switch (ret) { + case BZ_FINISH_OK: + case BZ_FLUSH_OK: + case BZ_OK: + case BZ_RUN_OK: + case BZ_STREAM_END: + return ZIP_ER_OK; + + case BZ_DATA_ERROR: + case BZ_DATA_ERROR_MAGIC: + case BZ_UNEXPECTED_EOF: + return ZIP_ER_COMPRESSED_DATA; + + case BZ_MEM_ERROR: + return ZIP_ER_MEMORY; + + case BZ_PARAM_ERROR: + return ZIP_ER_INVAL; + + case BZ_CONFIG_ERROR: /* actually, bzip2 miscompiled */ + case BZ_IO_ERROR: + case BZ_OUTBUFF_FULL: + case BZ_SEQUENCE_ERROR: + return ZIP_ER_INTERNAL; + + default: + return ZIP_ER_INTERNAL; + } +} + +static bool +start(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + int ret; + + ctx->zstr.avail_in = 0; + ctx->zstr.next_in = NULL; + ctx->zstr.avail_out = 0; + ctx->zstr.next_out = NULL; + + if (ctx->compress) { + ret = BZ2_bzCompressInit(&ctx->zstr, ctx->compression_flags, 0, 30); + } + else { + ret = BZ2_bzDecompressInit(&ctx->zstr, 0, 0); + } + + if (ret != BZ_OK) { + zip_error_set(ctx->error, map_error(ret), 0); + return false; + } + + return true; +} + + +static bool +end(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + int err; + + if (ctx->compress) { + err = BZ2_bzCompressEnd(&ctx->zstr); + } + else { + err = BZ2_bzDecompressEnd(&ctx->zstr); + } + + if (err != BZ_OK) { + zip_error_set(ctx->error, map_error(err), 0); + return false; + } + + return true; +} + + +static bool +input(void *ud, zip_uint8_t *data, zip_uint64_t length) { + struct ctx *ctx = (struct ctx *)ud; + + if (length > UINT_MAX || ctx->zstr.avail_in > 0) { + zip_error_set(ctx->error, ZIP_ER_INVAL, 0); + return false; + } + + ctx->zstr.avail_in = (unsigned int)length; + ctx->zstr.next_in = (char *)data; + + return true; +} + + +static void +end_of_input(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + ctx->end_of_input = true; +} + + +static zip_compression_status_t +process(void *ud, zip_uint8_t *data, zip_uint64_t *length) { + struct ctx *ctx = (struct ctx *)ud; + + int ret; + + if (ctx->zstr.avail_in == 0 && !ctx->end_of_input) { + *length = 0; + return ZIP_COMPRESSION_NEED_DATA; + } + + ctx->zstr.avail_out = (unsigned int)ZIP_MIN(UINT_MAX, *length); + ctx->zstr.next_out = (char *)data; + + if (ctx->compress) { + ret = BZ2_bzCompress(&ctx->zstr, ctx->end_of_input ? BZ_FINISH : BZ_RUN); + } + else { + ret = BZ2_bzDecompress(&ctx->zstr); + } + + *length = *length - ctx->zstr.avail_out; + + switch (ret) { + case BZ_FINISH_OK: /* compression */ + return ZIP_COMPRESSION_OK; + + case BZ_OK: /* decompression */ + case BZ_RUN_OK: /* compression */ + if (ctx->zstr.avail_in == 0) { + return ZIP_COMPRESSION_NEED_DATA; + } + return ZIP_COMPRESSION_OK; + + case BZ_STREAM_END: + return ZIP_COMPRESSION_END; + + default: + zip_error_set(ctx->error, map_error(ret), 0); + return ZIP_COMPRESSION_ERROR; + } +} + +// clang-format off + +zip_compression_algorithm_t zip_algorithm_bzip2_compress = { + compress_allocate, + deallocate, + compression_flags, + start, + end, + input, + end_of_input, + process +}; + + +zip_compression_algorithm_t zip_algorithm_bzip2_decompress = { + decompress_allocate, + deallocate, + compression_flags, + start, + end, + input, + end_of_input, + process +}; + +// clang-format on diff --git a/third_party/libzip/lib/zip_algorithm_deflate.c b/third_party/libzip/lib/zip_algorithm_deflate.c new file mode 100644 index 0000000..ba5ad43 --- /dev/null +++ b/third_party/libzip/lib/zip_algorithm_deflate.c @@ -0,0 +1,247 @@ +/* + zip_algorithm_deflate.c -- deflate (de)compression routines + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include +#include + +struct ctx { + zip_error_t *error; + bool compress; + int compression_flags; + bool end_of_input; + z_stream zstr; +}; + + +static void * +allocate(bool compress, int compression_flags, zip_error_t *error) { + struct ctx *ctx; + + if ((ctx = (struct ctx *)malloc(sizeof(*ctx))) == NULL) { + return NULL; + } + + ctx->error = error; + ctx->compress = compress; + ctx->compression_flags = compression_flags; + if (ctx->compression_flags < 1 || ctx->compression_flags > 9) { + ctx->compression_flags = Z_BEST_COMPRESSION; + } + ctx->end_of_input = false; + + ctx->zstr.zalloc = Z_NULL; + ctx->zstr.zfree = Z_NULL; + ctx->zstr.opaque = NULL; + + return ctx; +} + + +static void * +compress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(true, compression_flags, error); +} + + +static void * +decompress_allocate(zip_uint16_t method, int compression_flags, zip_error_t *error) { + return allocate(false, compression_flags, error); +} + + +static void +deallocate(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + free(ctx); +} + + +static int +compression_flags(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + if (!ctx->compress) { + return 0; + } + + if (ctx->compression_flags < 3) { + return 2; + } + else if (ctx->compression_flags > 7) { + return 1; + } + return 0; +} + + +static bool +start(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + int ret; + + ctx->zstr.avail_in = 0; + ctx->zstr.next_in = NULL; + ctx->zstr.avail_out = 0; + ctx->zstr.next_out = NULL; + + if (ctx->compress) { + /* negative value to tell zlib not to write a header */ + ret = deflateInit2(&ctx->zstr, ctx->compression_flags, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + else { + ret = inflateInit2(&ctx->zstr, -MAX_WBITS); + } + + if (ret != Z_OK) { + zip_error_set(ctx->error, ZIP_ER_ZLIB, ret); + return false; + } + + + return true; +} + + +static bool +end(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + int err; + + if (ctx->compress) { + err = deflateEnd(&ctx->zstr); + } + else { + err = inflateEnd(&ctx->zstr); + } + + if (err != Z_OK) { + zip_error_set(ctx->error, ZIP_ER_ZLIB, err); + return false; + } + + return true; +} + + +static bool +input(void *ud, zip_uint8_t *data, zip_uint64_t length) { + struct ctx *ctx = (struct ctx *)ud; + + if (length > UINT_MAX || ctx->zstr.avail_in > 0) { + zip_error_set(ctx->error, ZIP_ER_INVAL, 0); + return false; + } + + ctx->zstr.avail_in = (uInt)length; + ctx->zstr.next_in = (Bytef *)data; + + return true; +} + + +static void +end_of_input(void *ud) { + struct ctx *ctx = (struct ctx *)ud; + + ctx->end_of_input = true; +} + + +static zip_compression_status_t +process(void *ud, zip_uint8_t *data, zip_uint64_t *length) { + struct ctx *ctx = (struct ctx *)ud; + + int ret; + + ctx->zstr.avail_out = (uInt)ZIP_MIN(UINT_MAX, *length); + ctx->zstr.next_out = (Bytef *)data; + + if (ctx->compress) { + ret = deflate(&ctx->zstr, ctx->end_of_input ? Z_FINISH : 0); + } + else { + ret = inflate(&ctx->zstr, Z_SYNC_FLUSH); + } + + *length = *length - ctx->zstr.avail_out; + + switch (ret) { + case Z_OK: + return ZIP_COMPRESSION_OK; + + case Z_STREAM_END: + return ZIP_COMPRESSION_END; + + case Z_BUF_ERROR: + if (ctx->zstr.avail_in == 0) { + return ZIP_COMPRESSION_NEED_DATA; + } + + /* fallthrough */ + + default: + zip_error_set(ctx->error, ZIP_ER_ZLIB, ret); + return ZIP_COMPRESSION_ERROR; + } +} + +// clang-format off + +zip_compression_algorithm_t zip_algorithm_deflate_compress = { + compress_allocate, + deallocate, + compression_flags, + start, + end, + input, + end_of_input, + process +}; + + +zip_compression_algorithm_t zip_algorithm_deflate_decompress = { + decompress_allocate, + deallocate, + compression_flags, + start, + end, + input, + end_of_input, + process +}; + +// clang-format on diff --git a/third_party/libzip/lib/zip_buffer.c b/third_party/libzip/lib/zip_buffer.c new file mode 100644 index 0000000..37977f0 --- /dev/null +++ b/third_party/libzip/lib/zip_buffer.c @@ -0,0 +1,324 @@ +/* + zip_buffer.c -- bounds checked access to memory buffer + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +zip_uint8_t * +_zip_buffer_data(zip_buffer_t *buffer) { + return buffer->data; +} + + +void +_zip_buffer_free(zip_buffer_t *buffer) { + if (buffer == NULL) { + return; + } + + if (buffer->free_data) { + free(buffer->data); + } + + free(buffer); +} + + +bool +_zip_buffer_eof(zip_buffer_t *buffer) { + return buffer->ok && buffer->offset == buffer->size; +} + + +zip_uint8_t * +_zip_buffer_get(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint8_t *data; + + data = _zip_buffer_peek(buffer, length); + + if (data != NULL) { + buffer->offset += length; + } + + return data; +} + + +zip_uint16_t +_zip_buffer_get_16(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 2); + + if (data == NULL) { + return 0; + } + + return (zip_uint16_t)(data[0] + (data[1] << 8)); +} + + +zip_uint32_t +_zip_buffer_get_32(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 4); + + if (data == NULL) { + return 0; + } + + return ((((((zip_uint32_t)data[3] << 8) + data[2]) << 8) + data[1]) << 8) + data[0]; +} + + +zip_uint64_t +_zip_buffer_get_64(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 8); + + if (data == NULL) { + return 0; + } + + return ((zip_uint64_t)data[7] << 56) + ((zip_uint64_t)data[6] << 48) + ((zip_uint64_t)data[5] << 40) + ((zip_uint64_t)data[4] << 32) + ((zip_uint64_t)data[3] << 24) + ((zip_uint64_t)data[2] << 16) + ((zip_uint64_t)data[1] << 8) + (zip_uint64_t)data[0]; +} + + +zip_uint8_t +_zip_buffer_get_8(zip_buffer_t *buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, 1); + + if (data == NULL) { + return 0; + } + + return data[0]; +} + + +zip_uint64_t +_zip_buffer_left(zip_buffer_t *buffer) { + return buffer->ok ? buffer->size - buffer->offset : 0; +} + + +zip_uint64_t +_zip_buffer_read(zip_buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length) { + if (_zip_buffer_left(buffer) < length) { + length = _zip_buffer_left(buffer); + } + + memcpy(data, _zip_buffer_get(buffer, length), length); + + return length; +} + + +zip_buffer_t * +_zip_buffer_new(zip_uint8_t *data, zip_uint64_t size) { + bool free_data = (data == NULL); + zip_buffer_t *buffer; + + if (data == NULL) { + if ((data = (zip_uint8_t *)malloc(size)) == NULL) { + return NULL; + } + } + + if ((buffer = (zip_buffer_t *)malloc(sizeof(*buffer))) == NULL) { + if (free_data) { + free(data); + } + return NULL; + } + + buffer->ok = true; + buffer->data = data; + buffer->size = size; + buffer->offset = 0; + buffer->free_data = free_data; + + return buffer; +} + + +zip_buffer_t * +_zip_buffer_new_from_source(zip_source_t *src, zip_uint64_t size, zip_uint8_t *buf, zip_error_t *error) { + zip_buffer_t *buffer; + + if ((buffer = _zip_buffer_new(buf, size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if (_zip_read(src, buffer->data, size, error) < 0) { + _zip_buffer_free(buffer); + return NULL; + } + + return buffer; +} + + +zip_uint64_t +_zip_buffer_offset(zip_buffer_t *buffer) { + return buffer->ok ? buffer->offset : 0; +} + + +bool +_zip_buffer_ok(zip_buffer_t *buffer) { + return buffer->ok; +} + + +zip_uint8_t * +_zip_buffer_peek(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint8_t *data; + + if (!buffer->ok || buffer->offset + length < length || buffer->offset + length > buffer->size) { + buffer->ok = false; + return NULL; + } + + data = buffer->data + buffer->offset; + return data; +} + +int +_zip_buffer_put(zip_buffer_t *buffer, const void *src, size_t length) { + zip_uint8_t *dst = _zip_buffer_get(buffer, length); + + if (dst == NULL) { + return -1; + } + + memcpy(dst, src, length); + return 0; +} + + +int +_zip_buffer_put_16(zip_buffer_t *buffer, zip_uint16_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 2); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_32(zip_buffer_t *buffer, zip_uint32_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 4); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + data[2] = (zip_uint8_t)((i >> 16) & 0xff); + data[3] = (zip_uint8_t)((i >> 24) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_64(zip_buffer_t *buffer, zip_uint64_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 8); + + if (data == NULL) { + return -1; + } + + data[0] = (zip_uint8_t)(i & 0xff); + data[1] = (zip_uint8_t)((i >> 8) & 0xff); + data[2] = (zip_uint8_t)((i >> 16) & 0xff); + data[3] = (zip_uint8_t)((i >> 24) & 0xff); + data[4] = (zip_uint8_t)((i >> 32) & 0xff); + data[5] = (zip_uint8_t)((i >> 40) & 0xff); + data[6] = (zip_uint8_t)((i >> 48) & 0xff); + data[7] = (zip_uint8_t)((i >> 56) & 0xff); + + return 0; +} + + +int +_zip_buffer_put_8(zip_buffer_t *buffer, zip_uint8_t i) { + zip_uint8_t *data = _zip_buffer_get(buffer, 1); + + if (data == NULL) { + return -1; + } + + data[0] = i; + + return 0; +} + + +int +_zip_buffer_set_offset(zip_buffer_t *buffer, zip_uint64_t offset) { + if (offset > buffer->size) { + buffer->ok = false; + return -1; + } + + buffer->ok = true; + buffer->offset = offset; + + return 0; +} + + +int +_zip_buffer_skip(zip_buffer_t *buffer, zip_uint64_t length) { + zip_uint64_t offset = buffer->offset + length; + + if (offset < buffer->offset) { + buffer->ok = false; + return -1; + } + return _zip_buffer_set_offset(buffer, offset); +} + +zip_uint64_t +_zip_buffer_size(zip_buffer_t *buffer) { + return buffer->size; +} diff --git a/third_party/libzip/lib/zip_close.c b/third_party/libzip/lib/zip_close.c new file mode 100644 index 0000000..2657226 --- /dev/null +++ b/third_party/libzip/lib/zip_close.c @@ -0,0 +1,641 @@ +/* + zip_close.c -- close zip archive and update changes + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include +#include +#ifdef HAVE_STRINGS_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#endif +#include +#include +#ifdef _WIN32 +#include +#include +#endif + + +static int add_data(zip_t *, zip_source_t *, zip_dirent_t *); +static int copy_data(zip_t *, zip_uint64_t); +static int copy_source(zip_t *, zip_source_t *, zip_int64_t); +static int write_cdir(zip_t *, const zip_filelist_t *, zip_uint64_t); + +ZIP_EXTERN int +zip_close(zip_t *za) { + zip_uint64_t i, j, survivors, unchanged_offset; + zip_int64_t off; + int error; + zip_filelist_t *filelist; + int changed; + + if (za == NULL) + return -1; + + changed = _zip_changed(za, &survivors); + + /* don't create zip files with no entries */ + if (survivors == 0) { + if ((za->open_flags & ZIP_TRUNCATE) || changed) { + if (zip_source_remove(za->src) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + } + zip_discard(za); + return 0; + } + + if (!changed) { + zip_discard(za); + return 0; + } + + if (survivors > za->nentry) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((filelist = (zip_filelist_t *)malloc(sizeof(filelist[0]) * (size_t)survivors)) == NULL) + return -1; + + unchanged_offset = ZIP_UINT64_MAX; + /* create list of files with index into original archive */ + for (i = j = 0; i < za->nentry; i++) { + if (za->entry[i].orig != NULL && ZIP_ENTRY_HAS_CHANGES(&za->entry[i])) { + unchanged_offset = ZIP_MIN(unchanged_offset, za->entry[i].orig->offset); + } + if (za->entry[i].deleted) { + continue; + } + + if (j >= survivors) { + free(filelist); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + filelist[j].idx = i; + j++; + } + if (j < survivors) { + free(filelist); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((zip_source_supports(za->src) & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE_CLONING)) == 0) { + unchanged_offset = 0; + } + else { + if (unchanged_offset == ZIP_UINT64_MAX) { + /* we're keeping all file data, find the end of the last one */ + zip_uint64_t last_index = ZIP_UINT64_MAX; + unchanged_offset = 0; + + for (i = 0; i < za->nentry; i++) { + if (za->entry[i].orig != NULL) { + if (za->entry[i].orig->offset >= unchanged_offset) { + unchanged_offset = za->entry[i].orig->offset; + last_index = i; + } + } + } + if (last_index != ZIP_UINT64_MAX) { + if ((unchanged_offset = _zip_file_get_end(za, last_index, &za->error)) == 0) { + free(filelist); + return -1; + } + } + } + if (unchanged_offset > 0) { + if (zip_source_begin_write_cloning(za->src, unchanged_offset) < 0) { + /* cloning not supported, need to copy everything */ + unchanged_offset = 0; + } + } + } + if (unchanged_offset == 0) { + if (zip_source_begin_write(za->src) < 0) { + _zip_error_set_from_source(&za->error, za->src); + free(filelist); + return -1; + } + } + + _zip_progress_start(za->progress); + error = 0; + for (j = 0; j < survivors; j++) { + int new_data; + zip_entry_t *entry; + zip_dirent_t *de; + + _zip_progress_subrange(za->progress, (double)j / (double)survivors, (double)(j + 1) / (double)survivors); + + i = filelist[j].idx; + entry = za->entry + i; + + if (entry->orig != NULL && entry->orig->offset < unchanged_offset) { + /* already implicitly copied by cloning */ + continue; + } + + new_data = (ZIP_ENTRY_DATA_CHANGED(entry) || ZIP_ENTRY_CHANGED(entry, ZIP_DIRENT_COMP_METHOD) || ZIP_ENTRY_CHANGED(entry, ZIP_DIRENT_ENCRYPTION_METHOD)); + + /* create new local directory entry */ + if (entry->changes == NULL) { + if ((entry->changes = _zip_dirent_clone(entry->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + error = 1; + break; + } + } + de = entry->changes; + + if (_zip_read_local_ef(za, i) < 0) { + error = 1; + break; + } + + if ((off = zip_source_tell_write(za->src)) < 0) { + error = 1; + break; + } + de->offset = (zip_uint64_t)off; + + if (new_data) { + zip_source_t *zs; + + zs = NULL; + if (!ZIP_ENTRY_DATA_CHANGED(entry)) { + if ((zs = _zip_source_zip_new(za, za, i, ZIP_FL_UNCHANGED, 0, 0, NULL)) == NULL) { + error = 1; + break; + } + } + + /* add_data writes dirent */ + if (add_data(za, zs ? zs : entry->source, de) < 0) { + error = 1; + if (zs) + zip_source_free(zs); + break; + } + if (zs) + zip_source_free(zs); + } + else { + zip_uint64_t offset; + + /* when copying data, all sizes are known -> no data descriptor needed */ + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR; + if (_zip_dirent_write(za, de, ZIP_FL_LOCAL) < 0) { + error = 1; + break; + } + if ((offset = _zip_file_get_offset(za, i, &za->error)) == 0) { + error = 1; + break; + } + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + error = 1; + break; + } + if (copy_data(za, de->comp_size) < 0) { + error = 1; + break; + } + } + } + + if (!error) { + if (write_cdir(za, filelist, survivors) < 0) + error = 1; + } + + free(filelist); + + if (!error) { + if (zip_source_commit_write(za->src) != 0) { + _zip_error_set_from_source(&za->error, za->src); + error = 1; + } + } + + _zip_progress_end(za->progress); + + if (error) { + zip_source_rollback_write(za->src); + return -1; + } + + zip_discard(za); + + return 0; +} + + +static int +add_data(zip_t *za, zip_source_t *src, zip_dirent_t *de) { + zip_int64_t offstart, offdata, offend, data_length; + struct zip_stat st; + zip_source_t *src_final, *src_tmp; + int ret; + int is_zip64; + zip_flags_t flags; + zip_int8_t compression_flags; + bool needs_recompress, needs_decompress, needs_crc, needs_compress, needs_reencrypt, needs_decrypt, needs_encrypt; + + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(&za->error, src); + return -1; + } + + if ((st.valid & ZIP_STAT_COMP_METHOD) == 0) { + st.valid |= ZIP_STAT_COMP_METHOD; + st.comp_method = ZIP_CM_STORE; + } + + if (ZIP_CM_IS_DEFAULT(de->comp_method) && st.comp_method != ZIP_CM_STORE) + de->comp_method = st.comp_method; + else if (de->comp_method == ZIP_CM_STORE && (st.valid & ZIP_STAT_SIZE)) { + st.valid |= ZIP_STAT_COMP_SIZE; + st.comp_size = st.size; + } + else { + /* we'll recompress */ + st.valid &= ~ZIP_STAT_COMP_SIZE; + } + + if ((st.valid & ZIP_STAT_ENCRYPTION_METHOD) == 0) { + st.valid |= ZIP_STAT_ENCRYPTION_METHOD; + st.encryption_method = ZIP_EM_NONE; + } + + flags = ZIP_EF_LOCAL; + + if ((st.valid & ZIP_STAT_SIZE) == 0) { + flags |= ZIP_FL_FORCE_ZIP64; + data_length = -1; + } + else { + de->uncomp_size = st.size; + /* this is technically incorrect (copy_source counts compressed data), but it's the best we have */ + data_length = (zip_int64_t)st.size; + + if ((st.valid & ZIP_STAT_COMP_SIZE) == 0) { + zip_uint64_t max_size; + + switch (ZIP_CM_ACTUAL(de->comp_method)) { + case ZIP_CM_BZIP2: + /* computed by looking at increase of 10 random files of size 1MB when + * compressed with bzip2, rounded up: 1.006 */ + max_size = 4269351188u; + break; + + case ZIP_CM_DEFLATE: + /* max deflate size increase: size + ceil(size/16k)*5+6 */ + max_size = 4293656963u; + break; + + case ZIP_CM_STORE: + max_size = 0xffffffffu; + break; + + default: + max_size = 0; + } + + if (st.size > max_size) { + flags |= ZIP_FL_FORCE_ZIP64; + } + } + else + de->comp_size = st.comp_size; + } + + if ((offstart = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + /* as long as we don't support non-seekable output, clear data descriptor bit */ + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_DATA_DESCRIPTOR; + if ((is_zip64 = _zip_dirent_write(za, de, flags)) < 0) { + return -1; + } + + needs_recompress = st.comp_method != ZIP_CM_ACTUAL(de->comp_method); + needs_decompress = needs_recompress && (st.comp_method != ZIP_CM_STORE); + needs_crc = (st.comp_method == ZIP_CM_STORE) || needs_decompress; + needs_compress = needs_recompress && (de->comp_method != ZIP_CM_STORE); + + needs_reencrypt = needs_recompress || (de->changed & ZIP_DIRENT_PASSWORD) || (de->encryption_method != st.encryption_method); + needs_decrypt = needs_reencrypt && (st.encryption_method != ZIP_EM_NONE); + needs_encrypt = needs_reencrypt && (de->encryption_method != ZIP_EM_NONE); + + src_final = src; + zip_source_keep(src_final); + + if (needs_decrypt) { + zip_encryption_implementation impl; + + if ((impl = _zip_get_encryption_implementation(st.encryption_method, ZIP_CODEC_DECODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + zip_source_free(src_final); + return -1; + } + if ((src_tmp = impl(za, src_final, st.encryption_method, ZIP_CODEC_DECODE, za->default_password)) == NULL) { + /* error set by impl */ + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_decompress) { + if ((src_tmp = zip_source_decompress(za, src_final, st.comp_method)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_crc) { + if ((src_tmp = zip_source_crc(za, src_final, 0)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + if (needs_compress) { + if ((src_tmp = zip_source_compress(za, src_final, de->comp_method, de->compression_level)) == NULL) { + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + + if (needs_encrypt) { + zip_encryption_implementation impl; + const char *password = NULL; + + if (de->password) { + password = de->password; + } + else if (za->default_password) { + password = za->default_password; + } + + if ((impl = _zip_get_encryption_implementation(de->encryption_method, ZIP_CODEC_ENCODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + zip_source_free(src_final); + return -1; + } + if ((src_tmp = impl(za, src_final, de->encryption_method, ZIP_CODEC_ENCODE, password)) == NULL) { + /* error set by impl */ + zip_source_free(src_final); + return -1; + } + + zip_source_free(src_final); + src_final = src_tmp; + } + + + if ((offdata = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + ret = copy_source(za, src_final, data_length); + + if (zip_source_stat(src_final, &st) < 0) { + _zip_error_set_from_source(&za->error, src_final); + ret = -1; + } + + if ((compression_flags = zip_source_get_compression_flags(src_final)) < 0) { + _zip_error_set_from_source(&za->error, src_final); + ret = -1; + } + + zip_source_free(src_final); + + if (ret < 0) { + return -1; + } + + if ((offend = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if (zip_source_seek_write(za->src, offstart, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if ((st.valid & (ZIP_STAT_COMP_METHOD | ZIP_STAT_CRC | ZIP_STAT_SIZE)) != (ZIP_STAT_COMP_METHOD | ZIP_STAT_CRC | ZIP_STAT_SIZE)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((de->changed & ZIP_DIRENT_LAST_MOD) == 0) { + if (st.valid & ZIP_STAT_MTIME) + de->last_mod = st.mtime; + else + time(&de->last_mod); + } + de->comp_method = st.comp_method; + de->crc = st.crc; + de->uncomp_size = st.size; + de->comp_size = (zip_uint64_t)(offend - offdata); + de->bitflags = (zip_uint16_t)((de->bitflags & (zip_uint16_t)~6) | ((zip_uint8_t)compression_flags << 1)); + _zip_dirent_set_version_needed(de, (flags & ZIP_FL_FORCE_ZIP64) != 0); + + if ((ret = _zip_dirent_write(za, de, flags)) < 0) + return -1; + + if (is_zip64 != ret) { + /* Zip64 mismatch between preliminary file header written before data and final file header written afterwards */ + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if (zip_source_seek_write(za->src, offend, SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + return 0; +} + + +static int +copy_data(zip_t *za, zip_uint64_t len) { + DEFINE_BYTE_ARRAY(buf, BUFSIZE); + size_t n; + double total = (double)len; + + if (!byte_array_init(buf, BUFSIZE)) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + while (len > 0) { + n = len > BUFSIZE ? BUFSIZE : len; + if (_zip_read(za->src, buf, n, &za->error) < 0) { + byte_array_fini(buf); + return -1; + } + + if (_zip_write(za, buf, n) < 0) { + byte_array_fini(buf); + return -1; + } + + len -= n; + + _zip_progress_update(za->progress, (total - (double)len) / total); + } + + byte_array_fini(buf); + return 0; +} + + +static int +copy_source(zip_t *za, zip_source_t *src, zip_int64_t data_length) { + DEFINE_BYTE_ARRAY(buf, BUFSIZE); + zip_int64_t n, current; + int ret; + + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(&za->error, src); + return -1; + } + + if (!byte_array_init(buf, BUFSIZE)) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + ret = 0; + current = 0; + while ((n = zip_source_read(src, buf, BUFSIZE)) > 0) { + if (_zip_write(za, buf, (zip_uint64_t)n) < 0) { + ret = -1; + break; + } + if (n == BUFSIZE && za->progress && data_length > 0) { + current += n; + _zip_progress_update(za->progress, (double)current / (double)data_length); + } + } + + if (n < 0) { + _zip_error_set_from_source(&za->error, src); + ret = -1; + } + + byte_array_fini(buf); + + zip_source_close(src); + + return ret; +} + +static int +write_cdir(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { + zip_int64_t cd_start, end, size; + + if ((cd_start = zip_source_tell_write(za->src)) < 0) { + return -1; + } + + if ((size = _zip_cdir_write(za, filelist, survivors)) < 0) { + return -1; + } + + if ((end = zip_source_tell_write(za->src)) < 0) { + return -1; + } + + return 0; +} + + +int +_zip_changed(const zip_t *za, zip_uint64_t *survivorsp) { + int changed; + zip_uint64_t i, survivors; + + changed = 0; + survivors = 0; + + if (za->comment_changed || za->ch_flags != za->flags) { + changed = 1; + } + + for (i = 0; i < za->nentry; i++) { + if (ZIP_ENTRY_HAS_CHANGES(&za->entry[i])) { + changed = 1; + } + if (!za->entry[i].deleted) { + survivors++; + } + } + + if (survivorsp) { + *survivorsp = survivors; + } + + return changed; +} diff --git a/third_party/libzip/lib/zip_crypto.h b/third_party/libzip/lib/zip_crypto.h new file mode 100644 index 0000000..585de21 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto.h @@ -0,0 +1,54 @@ +/* + zip_crypto.h -- crypto definitions + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_H +#define HAD_ZIP_CRYPTO_H + +#define ZIP_CRYPTO_SHA1_LENGTH 20 +#define ZIP_CRYPTO_AES_BLOCK_LENGTH 16 + +#if defined(HAVE_WINDOWS_CRYPTO) +#include "zip_crypto_win.h" +#elif defined(HAVE_COMMONCRYPTO) +#include "zip_crypto_commoncrypto.h" +#elif defined(HAVE_GNUTLS) +#include "zip_crypto_gnutls.h" +#elif defined(HAVE_OPENSSL) +#include "zip_crypto_openssl.h" +#elif defined(HAVE_MBEDTLS) +#include "zip_crypto_mbedtls.h" +#else +#error "no crypto backend found" +#endif + +#endif /* HAD_ZIP_CRYPTO_H */ diff --git a/third_party/libzip/lib/zip_crypto_commoncrypto.c b/third_party/libzip/lib/zip_crypto_commoncrypto.c new file mode 100644 index 0000000..10f7700 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_commoncrypto.c @@ -0,0 +1,128 @@ +/* + zip_crypto_commoncrypto.c -- CommonCrypto wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#include "zip_crypto.h" + +#include +#include + +void +_zip_crypto_aes_free(_zip_crypto_aes_t *aes) { + if (aes == NULL) { + return; + } + + CCCryptorRelease(aes); +} + + +bool +_zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out) { + size_t len; + CCCryptorUpdate(aes, in, ZIP_CRYPTO_AES_BLOCK_LENGTH, out, ZIP_CRYPTO_AES_BLOCK_LENGTH, &len); + return true; +} + + +_zip_crypto_aes_t * +_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) { + _zip_crypto_aes_t *aes; + CCCryptorStatus ret; + + ret = CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES, kCCOptionECBMode, key, key_size / 8, NULL, &aes); + + switch (ret) { + case kCCSuccess: + return aes; + + case kCCMemoryFailure: + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + + case kCCParamError: + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + + default: + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return NULL; + } +} + + +void +_zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) { + if (hmac == NULL) { + return; + } + + _zip_crypto_clear(hmac, sizeof(*hmac)); + free(hmac); +} + + +_zip_crypto_hmac_t * +_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) { + _zip_crypto_hmac_t *hmac; + + if ((hmac = (_zip_crypto_hmac_t *)malloc(sizeof(*hmac))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + CCHmacInit(hmac, kCCHmacAlgSHA1, secret, secret_length); + + return hmac; +} + + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + int fd; + + if ((fd = open("/dev/urandom", O_RDONLY)) < 0) { + return false; + } + + if (read(fd, buffer, length) != length) { + close(fd); + return false; + } + + close(fd); + return true; +} diff --git a/third_party/libzip/lib/zip_crypto_commoncrypto.h b/third_party/libzip/lib/zip_crypto_commoncrypto.h new file mode 100644 index 0000000..1eae1b7 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_commoncrypto.h @@ -0,0 +1,53 @@ +/* + zip_crypto_commoncrypto.h -- definitions for CommonCrypto wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_COMMONCRYPTO_H +#define HAD_ZIP_CRYPTO_COMMONCRYPTO_H + +#include + +#define _zip_crypto_aes_t struct _CCCryptor +#define _zip_crypto_hmac_t CCHmacContext + +void _zip_crypto_aes_free(_zip_crypto_aes_t *aes); +bool _zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out); +_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error); + +#define _zip_crypto_hmac(hmac, data, length) (CCHmacUpdate((hmac), (data), (length)), true) +void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac); +_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error); +#define _zip_crypto_hmac_output(hmac, data) (CCHmacFinal((hmac), (data)), true) + +#define _zip_crypto_pbkdf2(key, key_length, salt, salt_length, iterations, output, output_length) (CCKeyDerivationPBKDF(kCCPBKDF2, (const char *)(key), (key_length), (salt), (salt_length), kCCPRFHmacAlgSHA1, (iterations), (output), (output_length)) == kCCSuccess) + +#endif /* HAD_ZIP_CRYPTO_COMMONCRYPTO_H */ diff --git a/third_party/libzip/lib/zip_crypto_gnutls.c b/third_party/libzip/lib/zip_crypto_gnutls.c new file mode 100644 index 0000000..9184867 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_gnutls.c @@ -0,0 +1,135 @@ +/* + zip_crypto_gnutls.c -- GnuTLS wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#include "zip_crypto.h" + +_zip_crypto_aes_t * +_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) { + _zip_crypto_aes_t *aes; + + if ((aes = (_zip_crypto_aes_t *)malloc(sizeof(*aes))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + aes->key_size = key_size; + + switch (aes->key_size) { + case 128: + nettle_aes128_set_encrypt_key(&aes->ctx.ctx_128, key); + break; + case 192: + nettle_aes192_set_encrypt_key(&aes->ctx.ctx_192, key); + break; + case 256: + nettle_aes256_set_encrypt_key(&aes->ctx.ctx_256, key); + break; + default: + zip_error_set(error, ZIP_ER_INVAL, 0); + free(aes); + return NULL; + } + + return aes; +} + +bool +_zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out) { + switch (aes->key_size) { + case 128: + nettle_aes128_encrypt(&aes->ctx.ctx_128, ZIP_CRYPTO_AES_BLOCK_LENGTH, out, in); + break; + case 192: + nettle_aes192_encrypt(&aes->ctx.ctx_192, ZIP_CRYPTO_AES_BLOCK_LENGTH, out, in); + break; + case 256: + nettle_aes256_encrypt(&aes->ctx.ctx_256, ZIP_CRYPTO_AES_BLOCK_LENGTH, out, in); + break; + } + + return true; +} + +void +_zip_crypto_aes_free(_zip_crypto_aes_t *aes) { + if (aes == NULL) { + return; + } + + _zip_crypto_clear(aes, sizeof(*aes)); + free(aes); +} + + +_zip_crypto_hmac_t * +_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) { + _zip_crypto_hmac_t *hmac; + int ret; + + if ((hmac = (_zip_crypto_hmac_t *)malloc(sizeof(*hmac))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ret = gnutls_hmac_init(hmac, GNUTLS_MAC_SHA1, secret, secret_length)) < 0) { + // TODO: set error + free(hmac); + return NULL; + } + + return hmac; +} + + +void +_zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) { + zip_uint8_t buf[ZIP_CRYPTO_SHA1_LENGTH]; + + if (hmac == NULL) { + return; + } + + gnutls_hmac_deinit(*hmac, buf); + _zip_crypto_clear(hmac, sizeof(*hmac)); + free(hmac); +} + + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + return gnutls_rnd(GNUTLS_RND_KEY, buffer, length) == 0; +} diff --git a/third_party/libzip/lib/zip_crypto_gnutls.h b/third_party/libzip/lib/zip_crypto_gnutls.h new file mode 100644 index 0000000..40d34a5 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_gnutls.h @@ -0,0 +1,65 @@ +/* + zip_crypto_gnutls.h -- definitions for GnuTLS wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_GNUTLS_H +#define HAD_ZIP_CRYPTO_GNUTLS_H + +#include +#include + +#include +#include + +typedef struct { + union { + struct aes128_ctx ctx_128; + struct aes192_ctx ctx_192; + struct aes256_ctx ctx_256; + } ctx; + zip_uint16_t key_size; +} _zip_crypto_aes_t; + +#define _zip_crypto_hmac_t gnutls_hmac_hd_t + +void _zip_crypto_aes_free(_zip_crypto_aes_t *aes); +bool _zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out); +_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error); + +#define _zip_crypto_hmac(hmac, data, length) (gnutls_hmac(*(hmac), (data), (length)) == 0) +void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac); +_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error); +#define _zip_crypto_hmac_output(hmac, data) (gnutls_hmac_output(*(hmac), (data)), true) + +#define _zip_crypto_pbkdf2(key, key_length, salt, salt_length, iterations, output, output_length) (pbkdf2_hmac_sha1((key_length), (key), (iterations), (salt_length), (salt), (output_length), (output)), true) + +#endif /* HAD_ZIP_CRYPTO_GNUTLS_H */ diff --git a/third_party/libzip/lib/zip_crypto_mbedtls.c b/third_party/libzip/lib/zip_crypto_mbedtls.c new file mode 100644 index 0000000..8e74fbc --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_mbedtls.c @@ -0,0 +1,160 @@ +/* + zip_crypto_mbedtls.c -- mbed TLS wrapper + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" +#include "zip_crypto.h" + +#include +#include +#include + + +_zip_crypto_aes_t * +_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) { + _zip_crypto_aes_t *aes; + + if ((aes = (_zip_crypto_aes_t *)malloc(sizeof(*aes))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + mbedtls_aes_init(aes); + mbedtls_aes_setkey_enc(aes, (const unsigned char *)key, (unsigned int)key_size); + + return aes; +} + +void +_zip_crypto_aes_free(_zip_crypto_aes_t *aes) { + if (aes == NULL) { + return; + } + + mbedtls_aes_free(aes); + free(aes); +} + + +_zip_crypto_hmac_t * +_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) { + _zip_crypto_hmac_t *hmac; + + if (secret_length > INT_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((hmac = (_zip_crypto_hmac_t *)malloc(sizeof(*hmac))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + mbedtls_md_init(hmac); + + if (mbedtls_md_setup(hmac, mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), 1) != 0) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + free(hmac); + return NULL; + } + + if (mbedtls_md_hmac_starts(hmac, (const unsigned char *)secret, (size_t)secret_length) != 0) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + free(hmac); + return NULL; + } + + return hmac; +} + + +void +_zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) { + if (hmac == NULL) { + return; + } + + mbedtls_md_free(hmac); + free(hmac); +} + + +bool +_zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, int iterations, zip_uint8_t *output, zip_uint64_t output_length) { + mbedtls_md_context_t sha1_ctx; + bool ok = true; + + mbedtls_md_init(&sha1_ctx); + + if (mbedtls_md_setup(&sha1_ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), 1) != 0) { + ok = false; + } + + if (ok && mbedtls_pkcs5_pbkdf2_hmac(&sha1_ctx, (const unsigned char *)key, (size_t)key_length, (const unsigned char *)salt, (size_t)salt_length, (unsigned int)iterations, (uint32_t)output_length, (unsigned char *)output) != 0) { + ok = false; + } + + mbedtls_md_free(&sha1_ctx); + return ok; +} + + +typedef struct { + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; +} zip_random_context_t; + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + static zip_random_context_t *ctx = NULL; + const unsigned char *pers = "zip_crypto_mbedtls"; + + if (!ctx) { + ctx = (zip_random_context_t *)malloc(sizeof(zip_random_context_t)); + if (!ctx) { + return false; + } + mbedtls_entropy_init(&ctx->entropy); + mbedtls_ctr_drbg_init(&ctx->ctr_drbg); + if (mbedtls_ctr_drbg_seed(&ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy, pers, strlen(pers)) != 0) { + mbedtls_ctr_drbg_free(&ctx->ctr_drbg); + mbedtls_entropy_free(&ctx->entropy); + free(ctx); + ctx = NULL; + return false; + } + } + + return mbedtls_ctr_drbg_random(&ctx->ctr_drbg, (unsigned char *)buffer, (size_t)length) == 0; +} diff --git a/third_party/libzip/lib/zip_crypto_mbedtls.h b/third_party/libzip/lib/zip_crypto_mbedtls.h new file mode 100644 index 0000000..af22d5b --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_mbedtls.h @@ -0,0 +1,54 @@ +/* + zip_crypto_mbedtls.h -- definitions for mbedtls wrapper + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_MBEDTLS_H +#define HAD_ZIP_CRYPTO_MBEDTLS_H + +#include +#include + +#define _zip_crypto_aes_t mbedtls_aes_context +#define _zip_crypto_hmac_t mbedtls_md_context_t + +_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error); +#define _zip_crypto_aes_encrypt_block(aes, in, out) (mbedtls_aes_crypt_ecb((aes), MBEDTLS_AES_ENCRYPT, (in), (out)) == 0) +void _zip_crypto_aes_free(_zip_crypto_aes_t *aes); + +_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error); +#define _zip_crypto_hmac(hmac, data, length) (mbedtls_md_hmac_update((hmac), (data), (length)) == 0) +#define _zip_crypto_hmac_output(hmac, data) (mbedtls_md_hmac_finish((hmac), (data)) == 0) +void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac); + +bool _zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, int iterations, zip_uint8_t *output, zip_uint64_t output_length); + +#endif /* HAD_ZIP_CRYPTO_MBEDTLS_H */ diff --git a/third_party/libzip/lib/zip_crypto_openssl.c b/third_party/libzip/lib/zip_crypto_openssl.c new file mode 100644 index 0000000..a1766bf --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_openssl.c @@ -0,0 +1,136 @@ +/* + zip_crypto_openssl.c -- OpenSSL wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#include "zip_crypto.h" + +#include + +#if OPENSSL_VERSION_NUMBER < 0x1010000fL || defined(LIBRESSL_VERSION_NUMBER) +#define USE_OPENSSL_1_0_API +#endif + + +_zip_crypto_aes_t * +_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) { + _zip_crypto_aes_t *aes; + + if ((aes = (_zip_crypto_aes_t *)malloc(sizeof(*aes))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + AES_set_encrypt_key(key, key_size, aes); + + return aes; +} + +void +_zip_crypto_aes_free(_zip_crypto_aes_t *aes) { + if (aes == NULL) { + return; + } + + _zip_crypto_clear(aes, sizeof(*aes)); + free(aes); +} + + +_zip_crypto_hmac_t * +_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) { + _zip_crypto_hmac_t *hmac; + + if (secret_length > INT_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + +#ifdef USE_OPENSSL_1_0_API + if ((hmac = (_zip_crypto_hmac_t *)malloc(sizeof(*hmac))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + HMAC_CTX_init(hmac); +#else + if ((hmac = HMAC_CTX_new()) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } +#endif + + if (HMAC_Init_ex(hmac, secret, (int)secret_length, EVP_sha1(), NULL) != 1) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); +#ifdef USE_OPENSSL_1_0_API + free(hmac); +#else + HMAC_CTX_free(hmac); +#endif + return NULL; + } + + return hmac; +} + + +void +_zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) { + if (hmac == NULL) { + return; + } + +#ifdef USE_OPENSSL_1_0_API + HMAC_CTX_cleanup(hmac); + _zip_crypto_clear(hmac, sizeof(*hmac)); + free(hmac); +#else + HMAC_CTX_free(hmac); +#endif +} + + +bool +_zip_crypto_hmac_output(_zip_crypto_hmac_t *hmac, zip_uint8_t *data) { + unsigned int length; + + return HMAC_Final(hmac, data, &length) == 1; +} + + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + return RAND_bytes(buffer, length) == 1; +} diff --git a/third_party/libzip/lib/zip_crypto_openssl.h b/third_party/libzip/lib/zip_crypto_openssl.h new file mode 100644 index 0000000..906890e --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_openssl.h @@ -0,0 +1,54 @@ +/* + zip_crypto_openssl.h -- definitions for OpenSSL wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_OPENSSL_H +#define HAD_ZIP_CRYPTO_OPENSSL_H + +#include +#include + +#define _zip_crypto_aes_t AES_KEY +#define _zip_crypto_hmac_t HMAC_CTX + +void _zip_crypto_aes_free(_zip_crypto_aes_t *aes); +#define _zip_crypto_aes_encrypt_block(aes, in, out) (AES_encrypt((in), (out), (aes)), true) +_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error); + +#define _zip_crypto_hmac(hmac, data, length) (HMAC_Update((hmac), (data), (length)) == 1) +void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac); +_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error); +bool _zip_crypto_hmac_output(_zip_crypto_hmac_t *hmac, zip_uint8_t *data); + +#define _zip_crypto_pbkdf2(key, key_length, salt, salt_length, iterations, output, output_length) (PKCS5_PBKDF2_HMAC_SHA1((const char *)(key), (key_length), (salt), (salt_length), (iterations), (output_length), (output))) + +#endif /* HAD_ZIP_CRYPTO_OPENSSL_H */ diff --git a/third_party/libzip/lib/zip_crypto_win.c b/third_party/libzip/lib/zip_crypto_win.c new file mode 100644 index 0000000..a596540 --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_win.c @@ -0,0 +1,465 @@ +/* + zip_crypto_win.c -- Windows Crypto API wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#include "zip_crypto.h" + +#define WIN32_LEAN_AND_MEAN +#define NOCRYPT + +#include +#include + +#pragma comment(lib, "bcrypt.lib") + +/* + +This code is using the Cryptography API: Next Generation (CNG) +https://docs.microsoft.com/en-us/windows/desktop/seccng/cng-portal + +This API is supported on + - Windows Vista or later (client OS) + - Windows Server 2008 (server OS) + - Windows Embedded Compact 2013 (don't know about Windows Embedded Compact 7) + +The code was developed for Windows Embedded Compact 2013 (WEC2013), +but should be working for all of the above mentioned OSes. + +There are 2 restrictions for WEC2013, Windows Vista and Windows Server 2008: + +1.) The function "BCryptDeriveKeyPBKDF2" is not available + +I found some code which is implementing this function using the deprecated Crypto API here: +https://www.idrix.fr/Root/content/view/37/54/ + +I took this code and converted it to the newer CNG API. The original code was more +flexible, but this is not needed here so i refactored it a bit and just kept what is needed. + +The define "HAS_BCRYPTDERIVEKEYPBKDF2" controls whether "BCryptDeriveKeyPBKDF2" +of the CNG API is used or not. This define must not be set if you are compiling for WEC2013 or Windows Vista. + + +2.) "BCryptCreateHash" can't manage the memory needed for the hash object internally + +On Windows 7 or later it is possible to pass NULL for the hash object buffer. +This is not supported on WEC2013, so we have to handle the memory allocation/deallocation ourselves. +There is no #ifdef to control that, because this is working for all supported OSes. + +*/ + +#if !defined(WINCE) && !defined(__MINGW32__) +#define HAS_BCRYPTDERIVEKEYPBKDF2 +#endif + +#ifdef HAS_BCRYPTDERIVEKEYPBKDF2 + +bool +_zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, zip_uint16_t iterations, zip_uint8_t *output, zip_uint16_t output_length) { + BCRYPT_ALG_HANDLE hAlgorithm = NULL; + + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG))) { + return false; + } + + bool result = BCRYPT_SUCCESS(BCryptDeriveKeyPBKDF2(hAlgorithm, (PUCHAR)key, (ULONG)key_length, (PUCHAR)salt, salt_length, iterations, output, output_length, 0)); + + BCryptCloseAlgorithmProvider(hAlgorithm, 0); + + return result; +} + +#else + +#include + +#define DIGEST_SIZE 20 +#define BLOCK_SIZE 64 + +typedef struct { + BCRYPT_ALG_HANDLE hAlgorithm; + BCRYPT_HASH_HANDLE hInnerHash; + BCRYPT_HASH_HANDLE hOuterHash; + ULONG cbHashObject; + PUCHAR pbInnerHash; + PUCHAR pbOuterHash; +} PRF_CTX; + +static void +hmacFree(PRF_CTX *pContext) { + if (pContext->hOuterHash) + BCryptDestroyHash(pContext->hOuterHash); + if (pContext->hInnerHash) + BCryptDestroyHash(pContext->hInnerHash); + free(pContext->pbOuterHash); + free(pContext->pbInnerHash); + if (pContext->hAlgorithm) + BCryptCloseAlgorithmProvider(pContext->hAlgorithm, 0); +} + +static BOOL +hmacPrecomputeDigest(BCRYPT_HASH_HANDLE hHash, PUCHAR pbPassword, DWORD cbPassword, BYTE mask) { + BYTE buffer[BLOCK_SIZE]; + DWORD i; + + if (cbPassword > BLOCK_SIZE) { + return FALSE; + } + + memset(buffer, mask, sizeof(buffer)); + + for (i = 0; i < cbPassword; ++i) { + buffer[i] = (char)(pbPassword[i] ^ mask); + } + + return BCRYPT_SUCCESS(BCryptHashData(hHash, buffer, sizeof(buffer), 0)); +} + +static BOOL +hmacInit(PRF_CTX *pContext, PUCHAR pbPassword, DWORD cbPassword) { + BOOL bStatus = FALSE; + ULONG cbResult; + BYTE key[DIGEST_SIZE]; + + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&pContext->hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, 0)) || !BCRYPT_SUCCESS(BCryptGetProperty(pContext->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&pContext->cbHashObject, sizeof(pContext->cbHashObject), &cbResult, 0)) || ((pContext->pbInnerHash = malloc(pContext->cbHashObject)) == NULL) || ((pContext->pbOuterHash = malloc(pContext->cbHashObject)) == NULL) || !BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &pContext->hInnerHash, pContext->pbInnerHash, pContext->cbHashObject, NULL, 0, 0)) || !BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &pContext->hOuterHash, pContext->pbOuterHash, pContext->cbHashObject, NULL, 0, 0))) { + goto hmacInit_end; + } + + if (cbPassword > BLOCK_SIZE) { + BCRYPT_HASH_HANDLE hHash = NULL; + PUCHAR pbHashObject = malloc(pContext->cbHashObject); + + bStatus = BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &hHash, pbHashObject, pContext->cbHashObject, NULL, 0, 0)) && BCRYPT_SUCCESS(BCryptHashData(hHash, pbPassword, cbPassword, 0)) && BCRYPT_SUCCESS(BCryptGetProperty(hHash, BCRYPT_HASH_LENGTH, (PUCHAR)&cbPassword, sizeof(cbPassword), &cbResult, 0)) && BCRYPT_SUCCESS(BCryptFinishHash(hHash, key, cbPassword, 0)); + + if (hHash) + BCryptDestroyHash(hHash); + free(pbHashObject); + + if (!bStatus) { + goto hmacInit_end; + } + + pbPassword = key; + } + + bStatus = hmacPrecomputeDigest(pContext->hInnerHash, pbPassword, cbPassword, 0x36) && hmacPrecomputeDigest(pContext->hOuterHash, pbPassword, cbPassword, 0x5C); + +hmacInit_end: + + if (bStatus == FALSE) + hmacFree(pContext); + + return bStatus; +} + +static BOOL +hmacCalculateInternal(BCRYPT_HASH_HANDLE hHashTemplate, PUCHAR pbData, DWORD cbData, PUCHAR pbOutput, DWORD cbOutput, DWORD cbHashObject) { + BOOL success = FALSE; + BCRYPT_HASH_HANDLE hHash = NULL; + PUCHAR pbHashObject = malloc(cbHashObject); + + if (BCRYPT_SUCCESS(BCryptDuplicateHash(hHashTemplate, &hHash, pbHashObject, cbHashObject, 0))) { + success = BCRYPT_SUCCESS(BCryptHashData(hHash, pbData, cbData, 0)) && BCRYPT_SUCCESS(BCryptFinishHash(hHash, pbOutput, cbOutput, 0)); + + BCryptDestroyHash(hHash); + } + + free(pbHashObject); + + return success; +} + +static BOOL +hmacCalculate(PRF_CTX *pContext, PUCHAR pbData, DWORD cbData, PUCHAR pbDigest) { + DWORD cbResult; + DWORD cbHashObject; + + return BCRYPT_SUCCESS(BCryptGetProperty(pContext->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&cbHashObject, sizeof(cbHashObject), &cbResult, 0)) && hmacCalculateInternal(pContext->hInnerHash, pbData, cbData, pbDigest, DIGEST_SIZE, cbHashObject) && hmacCalculateInternal(pContext->hOuterHash, pbDigest, DIGEST_SIZE, pbDigest, DIGEST_SIZE, cbHashObject); +} + +static void xor + (LPBYTE ptr1, LPBYTE ptr2, DWORD dwLen) { + while (dwLen--) + *ptr1++ ^= *ptr2++; + } + + BOOL pbkdf2(PUCHAR pbPassword, ULONG cbPassword, PUCHAR pbSalt, ULONG cbSalt, DWORD cIterations, PUCHAR pbDerivedKey, ULONG cbDerivedKey) { + BOOL bStatus = FALSE; + DWORD l, r, dwULen, i, j; + BYTE Ti[DIGEST_SIZE]; + BYTE V[DIGEST_SIZE]; + LPBYTE U = malloc(max((cbSalt + 4), DIGEST_SIZE)); + PRF_CTX prfCtx = {0}; + + if (pbPassword == NULL || cbPassword == 0 || pbSalt == NULL || cbSalt == 0 || cIterations == 0 || pbDerivedKey == NULL || cbDerivedKey == 0) { + free(U); + return FALSE; + } + + if (!hmacInit(&prfCtx, pbPassword, cbPassword)) { + goto PBKDF2_end; + } + + l = (DWORD)ceil((double)cbDerivedKey / (double)DIGEST_SIZE); + r = cbDerivedKey - (l - 1) * DIGEST_SIZE; + + for (i = 1; i <= l; i++) { + ZeroMemory(Ti, DIGEST_SIZE); + for (j = 0; j < cIterations; j++) { + if (j == 0) { + // construct first input for PRF + memcpy(U, pbSalt, cbSalt); + U[cbSalt] = (BYTE)((i & 0xFF000000) >> 24); + U[cbSalt + 1] = (BYTE)((i & 0x00FF0000) >> 16); + U[cbSalt + 2] = (BYTE)((i & 0x0000FF00) >> 8); + U[cbSalt + 3] = (BYTE)((i & 0x000000FF)); + dwULen = cbSalt + 4; + } + else { + memcpy(U, V, DIGEST_SIZE); + dwULen = DIGEST_SIZE; + } + + if (!hmacCalculate(&prfCtx, U, dwULen, V)) { + goto PBKDF2_end; + } + + xor(Ti, V, DIGEST_SIZE); + } + + if (i != l) { + memcpy(&pbDerivedKey[(i - 1) * DIGEST_SIZE], Ti, DIGEST_SIZE); + } + else { + // Take only the first r bytes + memcpy(&pbDerivedKey[(i - 1) * DIGEST_SIZE], Ti, r); + } + } + + bStatus = TRUE; + +PBKDF2_end: + + hmacFree(&prfCtx); + free(U); + return bStatus; +} + +bool +_zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, zip_uint16_t iterations, zip_uint8_t *output, zip_uint16_t output_length) { + return (key_length <= ZIP_UINT32_MAX) && pbkdf2((PUCHAR)key, (ULONG)key_length, (PUCHAR)salt, salt_length, iterations, output, output_length); +} + +#endif + + +struct _zip_crypto_aes_s { + BCRYPT_ALG_HANDLE hAlgorithm; + BCRYPT_KEY_HANDLE hKey; + ULONG cbKeyObject; + PUCHAR pbKeyObject; +}; + +_zip_crypto_aes_t * +_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) { + _zip_crypto_aes_t *aes = (_zip_crypto_aes_t *)calloc(1, sizeof(*aes)); + + ULONG cbResult; + ULONG key_length = key_size / 8; + + if (aes == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&aes->hAlgorithm, BCRYPT_AES_ALGORITHM, NULL, 0))) { + _zip_crypto_aes_free(aes); + return NULL; + } + + if (!BCRYPT_SUCCESS(BCryptSetProperty(aes->hAlgorithm, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0))) { + _zip_crypto_aes_free(aes); + return NULL; + } + + if (!BCRYPT_SUCCESS(BCryptGetProperty(aes->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&aes->cbKeyObject, sizeof(aes->cbKeyObject), &cbResult, 0))) { + _zip_crypto_aes_free(aes); + return NULL; + } + + aes->pbKeyObject = malloc(aes->cbKeyObject); + + if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(aes->hAlgorithm, &aes->hKey, aes->pbKeyObject, aes->cbKeyObject, (PUCHAR)key, key_length, 0))) { + _zip_crypto_aes_free(aes); + return NULL; + } + + return aes; +} + +void +_zip_crypto_aes_free(_zip_crypto_aes_t *aes) { + if (aes == NULL) { + return; + } + + if (aes->hKey != NULL) { + BCryptDestroyKey(aes->hKey); + } + + if (aes->pbKeyObject != NULL) { + free(aes->pbKeyObject); + } + + if (aes->hAlgorithm != NULL) { + BCryptCloseAlgorithmProvider(aes->hAlgorithm, 0); + } + + free(aes); +} + +bool +_zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out) { + ULONG cbResult; + NTSTATUS status = BCryptEncrypt(aes->hKey, (PUCHAR)in, ZIP_CRYPTO_AES_BLOCK_LENGTH, NULL, NULL, 0, (PUCHAR)out, ZIP_CRYPTO_AES_BLOCK_LENGTH, &cbResult, 0); + return BCRYPT_SUCCESS(status); +} + +struct _zip_crypto_hmac_s { + BCRYPT_ALG_HANDLE hAlgorithm; + BCRYPT_HASH_HANDLE hHash; + DWORD cbHashObject; + PUCHAR pbHashObject; + DWORD cbHash; + PUCHAR pbHash; +}; + +// https://code.msdn.microsoft.com/windowsdesktop/Hmac-Computation-Sample-11fe8ec1/sourcecode?fileId=42820&pathId=283874677 + +_zip_crypto_hmac_t * +_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) { + NTSTATUS status; + ULONG cbResult; + _zip_crypto_hmac_t *hmac; + + if (secret_length > INT_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + hmac = (_zip_crypto_hmac_t *)calloc(1, sizeof(*hmac)); + + if (hmac == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + status = BCryptOpenAlgorithmProvider(&hmac->hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG); + if (!BCRYPT_SUCCESS(status)) { + _zip_crypto_hmac_free(hmac); + return NULL; + } + + status = BCryptGetProperty(hmac->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&hmac->cbHashObject, sizeof(hmac->cbHashObject), &cbResult, 0); + if (!BCRYPT_SUCCESS(status)) { + _zip_crypto_hmac_free(hmac); + return NULL; + } + + hmac->pbHashObject = malloc(hmac->cbHashObject); + + status = BCryptGetProperty(hmac->hAlgorithm, BCRYPT_HASH_LENGTH, (PUCHAR)&hmac->cbHash, sizeof(hmac->cbHash), &cbResult, 0); + if (!BCRYPT_SUCCESS(status)) { + _zip_crypto_hmac_free(hmac); + return NULL; + } + + hmac->pbHash = malloc(hmac->cbHash); + + status = BCryptCreateHash(hmac->hAlgorithm, &hmac->hHash, hmac->pbHashObject, hmac->cbHashObject, (PUCHAR)secret, (ULONG)secret_length, 0); + if (!BCRYPT_SUCCESS(status)) { + _zip_crypto_hmac_free(hmac); + return NULL; + } + + return hmac; +} + +void +_zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) { + if (hmac == NULL) { + return; + } + + if (hmac->hHash != NULL) { + BCryptDestroyHash(hmac->hHash); + } + + if (hmac->pbHash != NULL) { + free(hmac->pbHash); + } + + if (hmac->pbHashObject != NULL) { + free(hmac->pbHashObject); + } + + if (hmac->hAlgorithm) { + BCryptCloseAlgorithmProvider(hmac->hAlgorithm, 0); + } + + free(hmac); +} + +bool +_zip_crypto_hmac(_zip_crypto_hmac_t *hmac, zip_uint8_t *data, zip_uint64_t length) { + if (hmac == NULL || length > ULONG_MAX) { + return false; + } + + return BCRYPT_SUCCESS(BCryptHashData(hmac->hHash, data, (ULONG)length, 0)); +} + +bool +_zip_crypto_hmac_output(_zip_crypto_hmac_t *hmac, zip_uint8_t *data) { + if (hmac == NULL) { + return false; + } + + return BCRYPT_SUCCESS(BCryptFinishHash(hmac->hHash, data, hmac->cbHash, 0)); +} + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + return BCRYPT_SUCCESS(BCryptGenRandom(NULL, buffer, length, BCRYPT_USE_SYSTEM_PREFERRED_RNG)); +} diff --git a/third_party/libzip/lib/zip_crypto_win.h b/third_party/libzip/lib/zip_crypto_win.h new file mode 100644 index 0000000..9a239af --- /dev/null +++ b/third_party/libzip/lib/zip_crypto_win.h @@ -0,0 +1,51 @@ +/* + zip_crypto_win.h -- Windows Crypto API wrapper. + Copyright (C) 2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifndef HAD_ZIP_CRYPTO_WIN_H +#define HAD_ZIP_CRYPTO_WIN_H + +typedef struct _zip_crypto_aes_s _zip_crypto_aes_t; +typedef struct _zip_crypto_hmac_s _zip_crypto_hmac_t; + +void _zip_crypto_aes_free(_zip_crypto_aes_t *aes); +_zip_crypto_aes_t *_zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error); +bool _zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out); + +bool _zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, zip_uint16_t iterations, zip_uint8_t *output, zip_uint16_t output_length); + +_zip_crypto_hmac_t *_zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error); +void _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac); +bool _zip_crypto_hmac(_zip_crypto_hmac_t *hmac, zip_uint8_t *data, zip_uint64_t length); +bool _zip_crypto_hmac_output(_zip_crypto_hmac_t *hmac, zip_uint8_t *data); + +#endif /* HAD_ZIP_CRYPTO_WIN_H */ diff --git a/third_party/libzip/lib/zip_delete.c b/third_party/libzip/lib/zip_delete.c new file mode 100644 index 0000000..458a1b8 --- /dev/null +++ b/third_party/libzip/lib/zip_delete.c @@ -0,0 +1,68 @@ +/* + zip_delete.c -- delete file from zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_delete(zip_t *za, zip_uint64_t idx) { + const char *name; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((name = _zip_get_name(za, idx, 0, &za->error)) == NULL) { + return -1; + } + + if (!_zip_hash_delete(za->names, (const zip_uint8_t *)name, &za->error)) { + return -1; + } + + /* allow duplicate file names, because the file will + * be removed directly afterwards */ + if (_zip_unchange(za, idx, 1) != 0) + return -1; + + za->entry[idx].deleted = 1; + + return 0; +} diff --git a/third_party/libzip/lib/zip_dir_add.c b/third_party/libzip/lib/zip_dir_add.c new file mode 100644 index 0000000..46c76cf --- /dev/null +++ b/third_party/libzip/lib/zip_dir_add.c @@ -0,0 +1,92 @@ +/* + zip_dir_add.c -- add directory + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +ZIP_EXTERN zip_int64_t +zip_dir_add(zip_t *za, const char *name, zip_flags_t flags) { + size_t len; + zip_int64_t idx; + char *s; + zip_source_t *source; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (name == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + s = NULL; + len = strlen(name); + + if (name[len - 1] != '/') { + if ((s = (char *)malloc(len + 2)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + strcpy(s, name); + s[len] = '/'; + s[len + 1] = '\0'; + } + + if ((source = zip_source_buffer(za, NULL, 0, 0)) == NULL) { + free(s); + return -1; + } + + idx = _zip_file_replace(za, ZIP_UINT64_MAX, s ? s : name, source, flags); + + free(s); + + if (idx < 0) + zip_source_free(source); + else { + if (zip_file_set_external_attributes(za, (zip_uint64_t)idx, 0, ZIP_OPSYS_DEFAULT, ZIP_EXT_ATTRIB_DEFAULT_DIR) < 0) { + zip_delete(za, (zip_uint64_t)idx); + return -1; + } + } + + return idx; +} diff --git a/third_party/libzip/lib/zip_dirent.c b/third_party/libzip/lib/zip_dirent.c new file mode 100644 index 0000000..4dcb339 --- /dev/null +++ b/third_party/libzip/lib/zip_dirent.c @@ -0,0 +1,1122 @@ +/* + zip_dirent.c -- read directory entry (local or central), clean dirent + Copyright (C) 1999-2019 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include +#include + +#include "zipint.h" + +static time_t _zip_d2u_time(zip_uint16_t, zip_uint16_t); +static zip_string_t *_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str); +static zip_extra_field_t *_zip_ef_utf8(zip_uint16_t, zip_string_t *, zip_error_t *); +static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error); + + +void +_zip_cdir_free(zip_cdir_t *cd) { + zip_uint64_t i; + + if (!cd) + return; + + for (i = 0; i < cd->nentry; i++) + _zip_entry_finalize(cd->entry + i); + free(cd->entry); + _zip_string_free(cd->comment); + free(cd); +} + + +zip_cdir_t * +_zip_cdir_new(zip_uint64_t nentry, zip_error_t *error) { + zip_cdir_t *cd; + + if ((cd = (zip_cdir_t *)malloc(sizeof(*cd))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + cd->entry = NULL; + cd->nentry = cd->nentry_alloc = 0; + cd->size = cd->offset = 0; + cd->comment = NULL; + cd->is_zip64 = false; + + if (!_zip_cdir_grow(cd, nentry, error)) { + _zip_cdir_free(cd); + return NULL; + } + + return cd; +} + + +bool +_zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error) { + zip_uint64_t i, new_alloc; + zip_entry_t *new_entry; + + if (additional_entries == 0) { + return true; + } + + new_alloc = cd->nentry_alloc + additional_entries; + + if (new_alloc < additional_entries || new_alloc > SIZE_MAX / sizeof(*(cd->entry))) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + if ((new_entry = (zip_entry_t *)realloc(cd->entry, sizeof(*(cd->entry)) * (size_t)new_alloc)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + cd->entry = new_entry; + + for (i = cd->nentry; i < new_alloc; i++) { + _zip_entry_init(cd->entry + i); + } + + cd->nentry = cd->nentry_alloc = new_alloc; + + return true; +} + + +zip_int64_t +_zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { + zip_uint64_t offset, size; + zip_string_t *comment; + zip_uint8_t buf[EOCDLEN + EOCD64LEN + EOCD64LOCLEN]; + zip_buffer_t *buffer; + zip_int64_t off; + zip_uint64_t i; + bool is_zip64; + int ret; + + if ((off = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + offset = (zip_uint64_t)off; + + is_zip64 = false; + + for (i = 0; i < survivors; i++) { + zip_entry_t *entry = za->entry + filelist[i].idx; + + if ((ret = _zip_dirent_write(za, entry->changes ? entry->changes : entry->orig, ZIP_FL_CENTRAL)) < 0) + return -1; + if (ret) + is_zip64 = true; + } + + if ((off = zip_source_tell_write(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + size = (zip_uint64_t)off - offset; + + if (offset > ZIP_UINT32_MAX || survivors > ZIP_UINT16_MAX) + is_zip64 = true; + + + if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + if (is_zip64) { + _zip_buffer_put(buffer, EOCD64_MAGIC, 4); + _zip_buffer_put_64(buffer, EOCD64LEN - 12); + _zip_buffer_put_16(buffer, 45); + _zip_buffer_put_16(buffer, 45); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_64(buffer, survivors); + _zip_buffer_put_64(buffer, survivors); + _zip_buffer_put_64(buffer, size); + _zip_buffer_put_64(buffer, offset); + _zip_buffer_put(buffer, EOCD64LOC_MAGIC, 4); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_64(buffer, offset + size); + _zip_buffer_put_32(buffer, 1); + } + + _zip_buffer_put(buffer, EOCD_MAGIC, 4); + _zip_buffer_put_32(buffer, 0); + _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); + _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); + _zip_buffer_put_32(buffer, size >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)size); + _zip_buffer_put_32(buffer, offset >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)offset); + + comment = za->comment_changed ? za->comment_changes : za->comment_orig; + + _zip_buffer_put_16(buffer, (zip_uint16_t)(comment ? comment->length : 0)); + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + + if (_zip_write(za, _zip_buffer_data(buffer), _zip_buffer_offset(buffer)) < 0) { + _zip_buffer_free(buffer); + return -1; + } + + _zip_buffer_free(buffer); + + if (comment) { + if (_zip_write(za, comment->raw, comment->length) < 0) { + return -1; + } + } + + return (zip_int64_t)size; +} + + +zip_dirent_t * +_zip_dirent_clone(const zip_dirent_t *sde) { + zip_dirent_t *tde; + + if ((tde = (zip_dirent_t *)malloc(sizeof(*tde))) == NULL) + return NULL; + + if (sde) + memcpy(tde, sde, sizeof(*sde)); + else + _zip_dirent_init(tde); + + tde->changed = 0; + tde->cloned = 1; + + return tde; +} + + +void +_zip_dirent_finalize(zip_dirent_t *zde) { + if (!zde->cloned || zde->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(zde->filename); + zde->filename = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_EXTRA_FIELD) { + _zip_ef_free(zde->extra_fields); + zde->extra_fields = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_COMMENT) { + _zip_string_free(zde->comment); + zde->comment = NULL; + } + if (!zde->cloned || zde->changed & ZIP_DIRENT_PASSWORD) { + if (zde->password) { + _zip_crypto_clear(zde->password, strlen(zde->password)); + } + free(zde->password); + zde->password = NULL; + } +} + + +void +_zip_dirent_free(zip_dirent_t *zde) { + if (zde == NULL) + return; + + _zip_dirent_finalize(zde); + free(zde); +} + + +void +_zip_dirent_init(zip_dirent_t *de) { + de->changed = 0; + de->local_extra_fields_read = 0; + de->cloned = 0; + + de->crc_valid = true; + de->version_madeby = 63 | (ZIP_OPSYS_DEFAULT << 8); + de->version_needed = 10; /* 1.0 */ + de->bitflags = 0; + de->comp_method = ZIP_CM_DEFAULT; + de->last_mod = 0; + de->crc = 0; + de->comp_size = 0; + de->uncomp_size = 0; + de->filename = NULL; + de->extra_fields = NULL; + de->comment = NULL; + de->disk_number = 0; + de->int_attrib = 0; + de->ext_attrib = ZIP_EXT_ATTRIB_DEFAULT; + de->offset = 0; + de->compression_level = 0; + de->encryption_method = ZIP_EM_NONE; + de->password = NULL; +} + + +bool +_zip_dirent_needs_zip64(const zip_dirent_t *de, zip_flags_t flags) { + if (de->uncomp_size >= ZIP_UINT32_MAX || de->comp_size >= ZIP_UINT32_MAX || ((flags & ZIP_FL_CENTRAL) && de->offset >= ZIP_UINT32_MAX)) + return true; + + return false; +} + + +zip_dirent_t * +_zip_dirent_new(void) { + zip_dirent_t *de; + + if ((de = (zip_dirent_t *)malloc(sizeof(*de))) == NULL) + return NULL; + + _zip_dirent_init(de); + return de; +} + + +/* _zip_dirent_read(zde, fp, bufp, left, localp, error): + Fills the zip directory entry zde. + + If buffer is non-NULL, data is taken from there; otherwise data is read from fp as needed. + + If local is true, it reads a local header instead of a central directory entry. + + Returns size of dirent read if successful. On error, error is filled in and -1 is returned. +*/ + +zip_int64_t +_zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error) { + zip_uint8_t buf[CDENTRYSIZE]; + zip_uint16_t dostime, dosdate; + zip_uint32_t size, variable_size; + zip_uint16_t filename_len, comment_len, ef_len; + + bool from_buffer = (buffer != NULL); + + size = local ? LENTRYSIZE : CDENTRYSIZE; + + if (buffer) { + if (_zip_buffer_left(buffer) < size) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + } + else { + if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) { + return -1; + } + } + + if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + /* convert buffercontents to zip_dirent */ + + _zip_dirent_init(zde); + if (!local) + zde->version_madeby = _zip_buffer_get_16(buffer); + else + zde->version_madeby = 0; + zde->version_needed = _zip_buffer_get_16(buffer); + zde->bitflags = _zip_buffer_get_16(buffer); + zde->comp_method = _zip_buffer_get_16(buffer); + + /* convert to time_t */ + dostime = _zip_buffer_get_16(buffer); + dosdate = _zip_buffer_get_16(buffer); + zde->last_mod = _zip_d2u_time(dostime, dosdate); + + zde->crc = _zip_buffer_get_32(buffer); + zde->comp_size = _zip_buffer_get_32(buffer); + zde->uncomp_size = _zip_buffer_get_32(buffer); + + filename_len = _zip_buffer_get_16(buffer); + ef_len = _zip_buffer_get_16(buffer); + + if (local) { + comment_len = 0; + zde->disk_number = 0; + zde->int_attrib = 0; + zde->ext_attrib = 0; + zde->offset = 0; + } + else { + comment_len = _zip_buffer_get_16(buffer); + zde->disk_number = _zip_buffer_get_16(buffer); + zde->int_attrib = _zip_buffer_get_16(buffer); + zde->ext_attrib = _zip_buffer_get_32(buffer); + zde->offset = _zip_buffer_get_32(buffer); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->bitflags & ZIP_GPBF_ENCRYPTED) { + if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { + /* TODO */ + zde->encryption_method = ZIP_EM_UNKNOWN; + } + else { + zde->encryption_method = ZIP_EM_TRAD_PKWARE; + } + } + else { + zde->encryption_method = ZIP_EM_NONE; + } + + zde->filename = NULL; + zde->extra_fields = NULL; + zde->comment = NULL; + + variable_size = (zip_uint32_t)filename_len + (zip_uint32_t)ef_len + (zip_uint32_t)comment_len; + + if (from_buffer) { + if (_zip_buffer_left(buffer) < variable_size) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return -1; + } + } + else { + _zip_buffer_free(buffer); + + if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) { + return -1; + } + } + + if (filename_len) { + zde->filename = _zip_read_string(buffer, src, filename_len, 1, error); + if (!zde->filename) { + if (zip_error_code_zip(error) == ZIP_ER_EOF) { + zip_error_set(error, ZIP_ER_INCONS, 0); + } + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { + if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + } + } + + if (ef_len) { + zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error); + + if (ef == NULL) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) { + free(ef); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + free(ef); + if (local) + zde->local_extra_fields_read = 1; + } + + if (comment_len) { + zde->comment = _zip_read_string(buffer, src, comment_len, 0, error); + if (!zde->comment) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { + if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + } + } + + zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename); + zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment); + + /* Zip64 */ + + if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) { + zip_uint16_t got_len; + zip_buffer_t *ef_buffer; + const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error); + /* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */ + if (ef == NULL) { + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + + if (zde->uncomp_size == ZIP_UINT32_MAX) + zde->uncomp_size = _zip_buffer_get_64(ef_buffer); + else if (local) { + /* From appnote.txt: This entry in the Local header MUST + include BOTH original and compressed file size fields. */ + (void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */ + } + if (zde->comp_size == ZIP_UINT32_MAX) + zde->comp_size = _zip_buffer_get_64(ef_buffer); + if (!local) { + if (zde->offset == ZIP_UINT32_MAX) + zde->offset = _zip_buffer_get_64(ef_buffer); + if (zde->disk_number == ZIP_UINT16_MAX) + zde->disk_number = _zip_buffer_get_32(ef_buffer); + } + + if (!_zip_buffer_eof(ef_buffer)) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(ef_buffer); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + _zip_buffer_free(ef_buffer); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (!from_buffer) { + _zip_buffer_free(buffer); + } + return -1; + } + if (!from_buffer) { + _zip_buffer_free(buffer); + } + + /* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */ + if (zde->offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return -1; + } + + if (!_zip_dirent_process_winzip_aes(zde, error)) { + return -1; + } + + zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields); + + return (zip_int64_t)(size + variable_size); +} + + +static zip_string_t * +_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str) { + zip_uint16_t ef_len; + zip_uint32_t ef_crc; + zip_buffer_t *buffer; + + const zip_uint8_t *ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, id, 0, ZIP_EF_BOTH, NULL); + + if (ef == NULL || ef_len < 5 || ef[0] != 1) { + return str; + } + + if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { + return str; + } + + _zip_buffer_get_8(buffer); + ef_crc = _zip_buffer_get_32(buffer); + + if (_zip_string_crc32(str) == ef_crc) { + zip_uint16_t len = (zip_uint16_t)_zip_buffer_left(buffer); + zip_string_t *ef_str = _zip_string_new(_zip_buffer_get(buffer, len), len, ZIP_FL_ENC_UTF_8, NULL); + + if (ef_str != NULL) { + _zip_string_free(str); + str = ef_str; + } + } + + _zip_buffer_free(buffer); + + return str; +} + + +static bool +_zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error) { + zip_uint16_t ef_len; + zip_buffer_t *buffer; + const zip_uint8_t *ef; + bool crc_valid; + zip_uint16_t enc_method; + + + if (de->comp_method != ZIP_CM_WINZIP_AES) { + return true; + } + + ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, ZIP_EF_WINZIP_AES, 0, ZIP_EF_BOTH, NULL); + + if (ef == NULL || ef_len < 7) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return false; + } + + if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return false; + } + + /* version */ + + crc_valid = true; + switch (_zip_buffer_get_16(buffer)) { + case 1: + break; + + case 2: + if (de->uncomp_size < 20 /* TODO: constant */) { + crc_valid = false; + } + break; + + default: + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + /* vendor */ + if (memcmp(_zip_buffer_get(buffer, 2), "AE", 2) != 0) { + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + /* mode */ + switch (_zip_buffer_get_8(buffer)) { + case 1: + enc_method = ZIP_EM_AES_128; + break; + case 2: + enc_method = ZIP_EM_AES_192; + break; + case 3: + enc_method = ZIP_EM_AES_256; + break; + default: + zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); + _zip_buffer_free(buffer); + return false; + } + + if (ef_len != 7) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + return false; + } + + de->crc_valid = crc_valid; + de->encryption_method = enc_method; + de->comp_method = _zip_buffer_get_16(buffer); + + _zip_buffer_free(buffer); + return true; +} + + +zip_int32_t +_zip_dirent_size(zip_source_t *src, zip_uint16_t flags, zip_error_t *error) { + zip_int32_t size; + bool local = (flags & ZIP_EF_LOCAL) != 0; + int i; + zip_uint8_t b[6]; + zip_buffer_t *buffer; + + size = local ? LENTRYSIZE : CDENTRYSIZE; + + if (zip_source_seek(src, local ? 26 : 28, SEEK_CUR) < 0) { + _zip_error_set_from_source(error, src); + return -1; + } + + if ((buffer = _zip_buffer_new_from_source(src, local ? 4 : 6, b, error)) == NULL) { + return -1; + } + + for (i = 0; i < (local ? 2 : 3); i++) { + size += _zip_buffer_get_16(buffer); + } + + if (!_zip_buffer_eof(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + + _zip_buffer_free(buffer); + return size; +} + + +/* _zip_dirent_write + Writes zip directory entry. + + If flags & ZIP_EF_LOCAL, it writes a local header instead of a central + directory entry. If flags & ZIP_EF_FORCE_ZIP64, a ZIP64 extra field is written, even if not needed. + + Returns 0 if successful, 1 if successful and wrote ZIP64 extra field. On error, error is filled in and -1 is + returned. +*/ + +int +_zip_dirent_write(zip_t *za, zip_dirent_t *de, zip_flags_t flags) { + zip_uint16_t dostime, dosdate; + zip_encoding_type_t com_enc, name_enc; + zip_extra_field_t *ef; + zip_extra_field_t *ef64; + zip_uint32_t ef_total_size; + bool is_zip64; + bool is_really_zip64; + bool is_winzip_aes; + zip_uint8_t buf[CDENTRYSIZE]; + zip_buffer_t *buffer; + + ef = NULL; + + name_enc = _zip_guess_encoding(de->filename, ZIP_ENCODING_UNKNOWN); + com_enc = _zip_guess_encoding(de->comment, ZIP_ENCODING_UNKNOWN); + + if ((name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_ASCII) || (name_enc == ZIP_ENCODING_ASCII && com_enc == ZIP_ENCODING_UTF8_KNOWN) || (name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_UTF8_KNOWN)) + de->bitflags |= ZIP_GPBF_ENCODING_UTF_8; + else { + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCODING_UTF_8; + if (name_enc == ZIP_ENCODING_UTF8_KNOWN) { + ef = _zip_ef_utf8(ZIP_EF_UTF_8_NAME, de->filename, &za->error); + if (ef == NULL) + return -1; + } + if ((flags & ZIP_FL_LOCAL) == 0 && com_enc == ZIP_ENCODING_UTF8_KNOWN) { + zip_extra_field_t *ef2 = _zip_ef_utf8(ZIP_EF_UTF_8_COMMENT, de->comment, &za->error); + if (ef2 == NULL) { + _zip_ef_free(ef); + return -1; + } + ef2->next = ef; + ef = ef2; + } + } + + if (de->encryption_method == ZIP_EM_NONE) { + de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCRYPTED; + } + else { + de->bitflags |= (zip_uint16_t)ZIP_GPBF_ENCRYPTED; + } + + is_really_zip64 = _zip_dirent_needs_zip64(de, flags); + is_zip64 = (flags & (ZIP_FL_LOCAL | ZIP_FL_FORCE_ZIP64)) == (ZIP_FL_LOCAL | ZIP_FL_FORCE_ZIP64) || is_really_zip64; + is_winzip_aes = de->encryption_method == ZIP_EM_AES_128 || de->encryption_method == ZIP_EM_AES_192 || de->encryption_method == ZIP_EM_AES_256; + + if (is_zip64) { + zip_uint8_t ef_zip64[EFZIP64SIZE]; + zip_buffer_t *ef_buffer = _zip_buffer_new(ef_zip64, sizeof(ef_zip64)); + if (ef_buffer == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + if (flags & ZIP_FL_LOCAL) { + if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->uncomp_size); + _zip_buffer_put_64(ef_buffer, de->comp_size); + } + } + else { + if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX || de->offset > ZIP_UINT32_MAX) { + if (de->uncomp_size >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->uncomp_size); + } + if (de->comp_size >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->comp_size); + } + if (de->offset >= ZIP_UINT32_MAX) { + _zip_buffer_put_64(ef_buffer, de->offset); + } + } + } + + if (!_zip_buffer_ok(ef_buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(ef_buffer); + _zip_ef_free(ef); + return -1; + } + + ef64 = _zip_ef_new(ZIP_EF_ZIP64, (zip_uint16_t)(_zip_buffer_offset(ef_buffer)), ef_zip64, ZIP_EF_BOTH); + _zip_buffer_free(ef_buffer); + ef64->next = ef; + ef = ef64; + } + + if (is_winzip_aes) { + zip_uint8_t data[EF_WINZIP_AES_SIZE]; + zip_buffer_t *ef_buffer = _zip_buffer_new(data, sizeof(data)); + zip_extra_field_t *ef_winzip; + + if (ef_buffer == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_put_16(ef_buffer, 2); + _zip_buffer_put(ef_buffer, "AE", 2); + _zip_buffer_put_8(ef_buffer, (zip_uint8_t)(de->encryption_method & 0xff)); + _zip_buffer_put_16(ef_buffer, (zip_uint16_t)de->comp_method); + + if (!_zip_buffer_ok(ef_buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(ef_buffer); + _zip_ef_free(ef); + return -1; + } + + ef_winzip = _zip_ef_new(ZIP_EF_WINZIP_AES, EF_WINZIP_AES_SIZE, data, ZIP_EF_BOTH); + _zip_buffer_free(ef_buffer); + ef_winzip->next = ef; + ef = ef_winzip; + } + + if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_put(buffer, (flags & ZIP_FL_LOCAL) ? LOCAL_MAGIC : CENTRAL_MAGIC, 4); + + if ((flags & ZIP_FL_LOCAL) == 0) { + _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_madeby)); + } + _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_needed)); + _zip_buffer_put_16(buffer, de->bitflags); + if (is_winzip_aes) { + _zip_buffer_put_16(buffer, ZIP_CM_WINZIP_AES); + } + else { + _zip_buffer_put_16(buffer, (zip_uint16_t)de->comp_method); + } + + _zip_u2d_time(de->last_mod, &dostime, &dosdate); + _zip_buffer_put_16(buffer, dostime); + _zip_buffer_put_16(buffer, dosdate); + + if (is_winzip_aes && de->uncomp_size < 20) { + _zip_buffer_put_32(buffer, 0); + } + else { + _zip_buffer_put_32(buffer, de->crc); + } + + if (((flags & ZIP_FL_LOCAL) == ZIP_FL_LOCAL) && ((de->comp_size >= ZIP_UINT32_MAX) || (de->uncomp_size >= ZIP_UINT32_MAX))) { + /* In local headers, if a ZIP64 EF is written, it MUST contain + * both compressed and uncompressed sizes (even if one of the + * two is smaller than 0xFFFFFFFF); on the other hand, those + * may only appear when the corresponding standard entry is + * 0xFFFFFFFF. (appnote.txt 4.5.3) */ + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + else { + if (de->comp_size < ZIP_UINT32_MAX) { + _zip_buffer_put_32(buffer, (zip_uint32_t)de->comp_size); + } + else { + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + if (de->uncomp_size < ZIP_UINT32_MAX) { + _zip_buffer_put_32(buffer, (zip_uint32_t)de->uncomp_size); + } + else { + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + } + + _zip_buffer_put_16(buffer, _zip_string_length(de->filename)); + /* TODO: check for overflow */ + ef_total_size = (zip_uint32_t)_zip_ef_size(de->extra_fields, flags) + (zip_uint32_t)_zip_ef_size(ef, ZIP_EF_BOTH); + _zip_buffer_put_16(buffer, (zip_uint16_t)ef_total_size); + + if ((flags & ZIP_FL_LOCAL) == 0) { + _zip_buffer_put_16(buffer, _zip_string_length(de->comment)); + _zip_buffer_put_16(buffer, (zip_uint16_t)de->disk_number); + _zip_buffer_put_16(buffer, de->int_attrib); + _zip_buffer_put_32(buffer, de->ext_attrib); + if (de->offset < ZIP_UINT32_MAX) + _zip_buffer_put_32(buffer, (zip_uint32_t)de->offset); + else + _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); + } + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef); + return -1; + } + + if (_zip_write(za, buf, _zip_buffer_offset(buffer)) < 0) { + _zip_buffer_free(buffer); + _zip_ef_free(ef); + return -1; + } + + _zip_buffer_free(buffer); + + if (de->filename) { + if (_zip_string_write(za, de->filename) < 0) { + _zip_ef_free(ef); + return -1; + } + } + + if (ef) { + if (_zip_ef_write(za, ef, ZIP_EF_BOTH) < 0) { + _zip_ef_free(ef); + return -1; + } + } + _zip_ef_free(ef); + if (de->extra_fields) { + if (_zip_ef_write(za, de->extra_fields, flags) < 0) { + return -1; + } + } + + if ((flags & ZIP_FL_LOCAL) == 0) { + if (de->comment) { + if (_zip_string_write(za, de->comment) < 0) { + return -1; + } + } + } + + + return is_zip64; +} + + +static time_t +_zip_d2u_time(zip_uint16_t dtime, zip_uint16_t ddate) { + struct tm tm; + + memset(&tm, 0, sizeof(tm)); + + /* let mktime decide if DST is in effect */ + tm.tm_isdst = -1; + + tm.tm_year = ((ddate >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((ddate >> 5) & 15) - 1; + tm.tm_mday = ddate & 31; + + tm.tm_hour = (dtime >> 11) & 31; + tm.tm_min = (dtime >> 5) & 63; + tm.tm_sec = (dtime << 1) & 62; + + return mktime(&tm); +} + + +static zip_extra_field_t * +_zip_ef_utf8(zip_uint16_t id, zip_string_t *str, zip_error_t *error) { + const zip_uint8_t *raw; + zip_uint32_t len; + zip_buffer_t *buffer; + zip_extra_field_t *ef; + + if ((raw = _zip_string_get(str, &len, ZIP_FL_ENC_RAW, NULL)) == NULL) { + /* error already set */ + return NULL; + } + + if (len + 5 > ZIP_UINT16_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); /* TODO: better error code? */ + return NULL; + } + + if ((buffer = _zip_buffer_new(NULL, len + 5)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + _zip_buffer_put_8(buffer, 1); + _zip_buffer_put_32(buffer, _zip_string_crc32(str)); + _zip_buffer_put(buffer, raw, len); + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return NULL; + } + + ef = _zip_ef_new(id, (zip_uint16_t)(_zip_buffer_offset(buffer)), _zip_buffer_data(buffer), ZIP_EF_BOTH); + _zip_buffer_free(buffer); + + return ef; +} + + +zip_dirent_t * +_zip_get_dirent(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { + if (error == NULL) + error = &za->error; + + if (idx >= za->nentry) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((flags & ZIP_FL_UNCHANGED) || za->entry[idx].changes == NULL) { + if (za->entry[idx].orig == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if (za->entry[idx].deleted && (flags & ZIP_FL_UNCHANGED) == 0) { + zip_error_set(error, ZIP_ER_DELETED, 0); + return NULL; + } + return za->entry[idx].orig; + } + else + return za->entry[idx].changes; +} + + +void +_zip_u2d_time(time_t intime, zip_uint16_t *dtime, zip_uint16_t *ddate) { + struct tm *tm; + + tm = localtime(&intime); + if (tm == NULL) { + /* if localtime() fails, return an arbitrary date (1980-01-01 00:00:00) */ + *ddate = (1 << 5) + 1; + *dtime = 0; + return; + } + if (tm->tm_year < 80) { + tm->tm_year = 80; + } + + *ddate = (zip_uint16_t)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); + *dtime = (zip_uint16_t)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + + return; +} + + +void +_zip_dirent_set_version_needed(zip_dirent_t *de, bool force_zip64) { + zip_uint16_t length; + + if (de->comp_method == ZIP_CM_LZMA) { + de->version_needed = 63; + return; + } + + if (de->comp_method == ZIP_CM_BZIP2) { + de->version_needed = 46; + return; + } + + if (force_zip64 || _zip_dirent_needs_zip64(de, 0)) { + de->version_needed = 45; + return; + } + + if (de->comp_method == ZIP_CM_DEFLATE || de->encryption_method == ZIP_EM_TRAD_PKWARE) { + de->version_needed = 20; + return; + } + + /* directory */ + if ((length = _zip_string_length(de->filename)) > 0) { + if (de->filename->raw[length - 1] == '/') { + de->version_needed = 20; + return; + } + } + + de->version_needed = 10; +} diff --git a/third_party/libzip/lib/zip_discard.c b/third_party/libzip/lib/zip_discard.c new file mode 100644 index 0000000..94972cf --- /dev/null +++ b/third_party/libzip/lib/zip_discard.c @@ -0,0 +1,80 @@ +/* + zip_discard.c -- discard and free struct zip + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +/* zip_discard: + frees the space allocated to a zipfile struct, and closes the + corresponding file. */ + +void +zip_discard(zip_t *za) { + zip_uint64_t i; + + if (za == NULL) + return; + + if (za->src) { + zip_source_close(za->src); + zip_source_free(za->src); + } + + free(za->default_password); + _zip_string_free(za->comment_orig); + _zip_string_free(za->comment_changes); + + _zip_hash_free(za->names); + + if (za->entry) { + for (i = 0; i < za->nentry; i++) + _zip_entry_finalize(za->entry + i); + free(za->entry); + } + + for (i = 0; i < za->nopen_source; i++) { + _zip_source_invalidate(za->open_source[i]); + } + free(za->open_source); + + _zip_progress_free(za->progress); + + zip_error_fini(&za->error); + + free(za); + + return; +} diff --git a/third_party/libzip/lib/zip_entry.c b/third_party/libzip/lib/zip_entry.c new file mode 100644 index 0000000..55f6458 --- /dev/null +++ b/third_party/libzip/lib/zip_entry.c @@ -0,0 +1,51 @@ +/* + zip_entry.c -- struct zip_entry helper functions + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +void +_zip_entry_finalize(zip_entry_t *e) { + _zip_unchange_data(e); + _zip_dirent_free(e->orig); + _zip_dirent_free(e->changes); +} + + +void +_zip_entry_init(zip_entry_t *e) { + e->orig = NULL; + e->changes = NULL; + e->source = NULL; + e->deleted = 0; +} diff --git a/third_party/libzip/lib/zip_err_str.c b/third_party/libzip/lib/zip_err_str.c new file mode 100644 index 0000000..3d9ee54 --- /dev/null +++ b/third_party/libzip/lib/zip_err_str.c @@ -0,0 +1,20 @@ +/* + This file was generated automatically by ./make_zip_err_str.sh + from ./zip.h; make changes there. + */ + +#include "zipint.h" + +const char *const _zip_err_str[] = { + "No error", "Multi-disk zip archives not supported", "Renaming temporary file failed", "Closing zip archive failed", "Seek error", "Read error", "Write error", "CRC error", "Containing zip archive was closed", "No such file", "File already exists", "Can't open file", "Failure to create temporary file", "Zlib error", "Malloc failure", "Entry has been changed", "Compression method not supported", "Premature end of file", "Invalid argument", "Not a zip archive", "Internal error", "Zip archive inconsistent", "Can't remove file", "Entry has been deleted", "Encryption method not supported", "Read-only archive", "No password provided", "Wrong password provided", "Operation not supported", "Resource still in use", "Tell error", "Compressed data invalid", +}; + +const int _zip_nerr_str = sizeof(_zip_err_str) / sizeof(_zip_err_str[0]); + +#define N ZIP_ET_NONE +#define S ZIP_ET_SYS +#define Z ZIP_ET_ZLIB + +const int _zip_err_type[] = { + N, N, S, S, S, S, S, N, N, N, N, S, S, Z, N, N, N, N, N, N, N, N, S, N, N, N, N, N, N, N, S, N, +}; diff --git a/third_party/libzip/lib/zip_error.c b/third_party/libzip/lib/zip_error.c new file mode 100644 index 0000000..e05ae50 --- /dev/null +++ b/third_party/libzip/lib/zip_error.c @@ -0,0 +1,150 @@ +/* + zip_error.c -- zip_error_t helper functions + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_error_code_system(const zip_error_t *error) { + return error->sys_err; +} + + +ZIP_EXTERN int +zip_error_code_zip(const zip_error_t *error) { + return error->zip_err; +} + + +ZIP_EXTERN void +zip_error_fini(zip_error_t *err) { + free(err->str); + err->str = NULL; +} + + +ZIP_EXTERN void +zip_error_init(zip_error_t *err) { + err->zip_err = ZIP_ER_OK; + err->sys_err = 0; + err->str = NULL; +} + +ZIP_EXTERN void +zip_error_init_with_code(zip_error_t *error, int ze) { + zip_error_init(error); + error->zip_err = ze; + switch (zip_error_system_type(error)) { + case ZIP_ET_SYS: + error->sys_err = errno; + break; + + default: + error->sys_err = 0; + break; + } +} + + +ZIP_EXTERN int +zip_error_system_type(const zip_error_t *error) { + if (error->zip_err < 0 || error->zip_err >= _zip_nerr_str) + return ZIP_ET_NONE; + + return _zip_err_type[error->zip_err]; +} + + +void +_zip_error_clear(zip_error_t *err) { + if (err == NULL) + return; + + err->zip_err = ZIP_ER_OK; + err->sys_err = 0; +} + + +void +_zip_error_copy(zip_error_t *dst, const zip_error_t *src) { + if (dst == NULL) { + return; + } + + dst->zip_err = src->zip_err; + dst->sys_err = src->sys_err; +} + + +void +_zip_error_get(const zip_error_t *err, int *zep, int *sep) { + if (zep) + *zep = err->zip_err; + if (sep) { + if (zip_error_system_type(err) != ZIP_ET_NONE) + *sep = err->sys_err; + else + *sep = 0; + } +} + + +void +zip_error_set(zip_error_t *err, int ze, int se) { + if (err) { + err->zip_err = ze; + err->sys_err = se; + } +} + + +void +_zip_error_set_from_source(zip_error_t *err, zip_source_t *src) { + _zip_error_copy(err, zip_source_error(src)); +} + + +zip_int64_t +zip_error_to_data(const zip_error_t *error, void *data, zip_uint64_t length) { + int *e = (int *)data; + + if (length < sizeof(int) * 2) { + return -1; + } + + e[0] = zip_error_code_zip(error); + e[1] = zip_error_code_system(error); + return sizeof(int) * 2; +} diff --git a/third_party/libzip/lib/zip_error_clear.c b/third_party/libzip/lib/zip_error_clear.c new file mode 100644 index 0000000..6b3a8da --- /dev/null +++ b/third_party/libzip/lib/zip_error_clear.c @@ -0,0 +1,44 @@ +/* + zip_error_clear.c -- clear zip error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_error_clear(zip_t *za) { + if (za == NULL) + return; + + _zip_error_clear(&za->error); +} diff --git a/third_party/libzip/lib/zip_error_get.c b/third_party/libzip/lib/zip_error_get.c new file mode 100644 index 0000000..12341d1 --- /dev/null +++ b/third_party/libzip/lib/zip_error_get.c @@ -0,0 +1,54 @@ +/* + zip_error_get.c -- get zip error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN void +zip_error_get(zip_t *za, int *zep, int *sep) { + _zip_error_get(&za->error, zep, sep); +} + + +ZIP_EXTERN zip_error_t * +zip_get_error(zip_t *za) { + return &za->error; +} + + +ZIP_EXTERN zip_error_t * +zip_file_get_error(zip_file_t *f) { + return &f->error; +} diff --git a/third_party/libzip/lib/zip_error_get_sys_type.c b/third_party/libzip/lib/zip_error_get_sys_type.c new file mode 100644 index 0000000..80bfc0c --- /dev/null +++ b/third_party/libzip/lib/zip_error_get_sys_type.c @@ -0,0 +1,44 @@ +/* + zip_error_get_sys_type.c -- return type of system error code + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_error_get_sys_type(int ze) { + if (ze < 0 || ze >= _zip_nerr_str) + return 0; + + return _zip_err_type[ze]; +} diff --git a/third_party/libzip/lib/zip_error_strerror.c b/third_party/libzip/lib/zip_error_strerror.c new file mode 100644 index 0000000..0f650b5 --- /dev/null +++ b/third_party/libzip/lib/zip_error_strerror.c @@ -0,0 +1,82 @@ +/* + zip_error_sterror.c -- get string representation of struct zip_error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_error_strerror(zip_error_t *err) { + const char *zs, *ss; + char buf[128], *s; + + zip_error_fini(err); + + if (err->zip_err < 0 || err->zip_err >= _zip_nerr_str) { + sprintf(buf, "Unknown error %d", err->zip_err); + zs = NULL; + ss = buf; + } + else { + zs = _zip_err_str[err->zip_err]; + + switch (_zip_err_type[err->zip_err]) { + case ZIP_ET_SYS: + ss = strerror(err->sys_err); + break; + + case ZIP_ET_ZLIB: + ss = zError(err->sys_err); + break; + + default: + ss = NULL; + } + } + + if (ss == NULL) + return zs; + else { + if ((s = (char *)malloc(strlen(ss) + (zs ? strlen(zs) + 2 : 0) + 1)) == NULL) + return _zip_err_str[ZIP_ER_MEMORY]; + + sprintf(s, "%s%s%s", (zs ? zs : ""), (zs ? ": " : ""), ss); + err->str = s; + + return s; + } +} diff --git a/third_party/libzip/lib/zip_error_to_str.c b/third_party/libzip/lib/zip_error_to_str.c new file mode 100644 index 0000000..bf51569 --- /dev/null +++ b/third_party/libzip/lib/zip_error_to_str.c @@ -0,0 +1,66 @@ +/* + zip_error_to_str.c -- get string representation of zip error code + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_error_to_str(char *buf, zip_uint64_t len, int ze, int se) { + const char *zs, *ss; + + if (ze < 0 || ze >= _zip_nerr_str) + return snprintf(buf, len, "Unknown error %d", ze); + + zs = _zip_err_str[ze]; + + switch (_zip_err_type[ze]) { + case ZIP_ET_SYS: + ss = strerror(se); + break; + + case ZIP_ET_ZLIB: + ss = zError(se); + break; + + default: + ss = NULL; + } + + return snprintf(buf, len, "%s%s%s", zs, (ss ? ": " : ""), (ss ? ss : "")); +} diff --git a/third_party/libzip/lib/zip_extra_field.c b/third_party/libzip/lib/zip_extra_field.c new file mode 100644 index 0000000..a17e491 --- /dev/null +++ b/third_party/libzip/lib/zip_extra_field.c @@ -0,0 +1,426 @@ +/* + zip_extra_field.c -- manipulate extra fields + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +zip_extra_field_t * +_zip_ef_clone(const zip_extra_field_t *ef, zip_error_t *error) { + zip_extra_field_t *head, *prev, *def; + + head = prev = NULL; + + while (ef) { + if ((def = _zip_ef_new(ef->id, ef->size, ef->data, ef->flags)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_ef_free(head); + return NULL; + } + + if (head == NULL) + head = def; + if (prev) + prev->next = def; + prev = def; + + ef = ef->next; + } + + return head; +} + + +zip_extra_field_t * +_zip_ef_delete_by_id(zip_extra_field_t *ef, zip_uint16_t id, zip_uint16_t id_idx, zip_flags_t flags) { + zip_extra_field_t *head, *prev; + int i; + + i = 0; + head = ef; + prev = NULL; + for (; ef; ef = (prev ? prev->next : head)) { + if ((ef->flags & flags & ZIP_EF_BOTH) && ((ef->id == id) || (id == ZIP_EXTRA_FIELD_ALL))) { + if (id_idx == ZIP_EXTRA_FIELD_ALL || i == id_idx) { + ef->flags &= ~(flags & ZIP_EF_BOTH); + if ((ef->flags & ZIP_EF_BOTH) == 0) { + if (prev) + prev->next = ef->next; + else + head = ef->next; + ef->next = NULL; + _zip_ef_free(ef); + + if (id_idx == ZIP_EXTRA_FIELD_ALL) + continue; + } + } + + i++; + if (i > id_idx) + break; + } + prev = ef; + } + + return head; +} + + +void +_zip_ef_free(zip_extra_field_t *ef) { + zip_extra_field_t *ef2; + + while (ef) { + ef2 = ef->next; + free(ef->data); + free(ef); + ef = ef2; + } +} + + +const zip_uint8_t * +_zip_ef_get_by_id(const zip_extra_field_t *ef, zip_uint16_t *lenp, zip_uint16_t id, zip_uint16_t id_idx, zip_flags_t flags, zip_error_t *error) { + static const zip_uint8_t empty[1] = {'\0'}; + + int i; + + i = 0; + for (; ef; ef = ef->next) { + if (ef->id == id && (ef->flags & flags & ZIP_EF_BOTH)) { + if (i < id_idx) { + i++; + continue; + } + + if (lenp) + *lenp = ef->size; + if (ef->size > 0) + return ef->data; + else + return empty; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return NULL; +} + + +zip_extra_field_t * +_zip_ef_merge(zip_extra_field_t *to, zip_extra_field_t *from) { + zip_extra_field_t *ef2, *tt, *tail; + int duplicate; + + if (to == NULL) + return from; + + for (tail = to; tail->next; tail = tail->next) + ; + + for (; from; from = ef2) { + ef2 = from->next; + + duplicate = 0; + for (tt = to; tt; tt = tt->next) { + if (tt->id == from->id && tt->size == from->size && (tt->size == 0 || memcmp(tt->data, from->data, tt->size) == 0)) { + tt->flags |= (from->flags & ZIP_EF_BOTH); + duplicate = 1; + break; + } + } + + from->next = NULL; + if (duplicate) + _zip_ef_free(from); + else + tail = tail->next = from; + } + + return to; +} + + +zip_extra_field_t * +_zip_ef_new(zip_uint16_t id, zip_uint16_t size, const zip_uint8_t *data, zip_flags_t flags) { + zip_extra_field_t *ef; + + if ((ef = (zip_extra_field_t *)malloc(sizeof(*ef))) == NULL) + return NULL; + + ef->next = NULL; + ef->flags = flags; + ef->id = id; + ef->size = size; + if (size > 0) { + if ((ef->data = (zip_uint8_t *)_zip_memdup(data, size, NULL)) == NULL) { + free(ef); + return NULL; + } + } + else + ef->data = NULL; + + return ef; +} + + +bool +_zip_ef_parse(const zip_uint8_t *data, zip_uint16_t len, zip_flags_t flags, zip_extra_field_t **ef_head_p, zip_error_t *error) { + zip_buffer_t *buffer; + zip_extra_field_t *ef, *ef2, *ef_head; + + if ((buffer = _zip_buffer_new((zip_uint8_t *)data, len)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + ef_head = ef = NULL; + + while (_zip_buffer_ok(buffer) && _zip_buffer_left(buffer) >= 4) { + zip_uint16_t fid, flen; + zip_uint8_t *ef_data; + + fid = _zip_buffer_get_16(buffer); + flen = _zip_buffer_get_16(buffer); + ef_data = _zip_buffer_get(buffer, flen); + + if (ef_data == NULL) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + + if ((ef2 = _zip_ef_new(fid, flen, ef_data, flags)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + + if (ef_head) { + ef->next = ef2; + ef = ef2; + } + else + ef_head = ef = ef2; + } + + if (!_zip_buffer_eof(buffer)) { + /* Android APK files align stored file data with padding in extra fields; ignore. */ + /* see https://android.googlesource.com/platform/build/+/master/tools/zipalign/ZipAlign.cpp */ + size_t glen = _zip_buffer_left(buffer); + zip_uint8_t *garbage; + garbage = _zip_buffer_get(buffer, glen); + if (glen >= 4 || garbage == NULL || memcmp(garbage, "\0\0\0", glen) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(buffer); + _zip_ef_free(ef_head); + return false; + } + } + + _zip_buffer_free(buffer); + + if (ef_head_p) { + *ef_head_p = ef_head; + } + else { + _zip_ef_free(ef_head); + } + + return true; +} + + +zip_extra_field_t * +_zip_ef_remove_internal(zip_extra_field_t *ef) { + zip_extra_field_t *ef_head; + zip_extra_field_t *prev, *next; + + ef_head = ef; + prev = NULL; + + while (ef) { + if (ZIP_EF_IS_INTERNAL(ef->id)) { + next = ef->next; + if (ef_head == ef) + ef_head = next; + ef->next = NULL; + _zip_ef_free(ef); + if (prev) + prev->next = next; + ef = next; + } + else { + prev = ef; + ef = ef->next; + } + } + + return ef_head; +} + + +zip_uint16_t +_zip_ef_size(const zip_extra_field_t *ef, zip_flags_t flags) { + zip_uint16_t size; + + size = 0; + for (; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) + size = (zip_uint16_t)(size + 4 + ef->size); + } + + return size; +} + + +int +_zip_ef_write(zip_t *za, const zip_extra_field_t *ef, zip_flags_t flags) { + zip_uint8_t b[4]; + zip_buffer_t *buffer = _zip_buffer_new(b, sizeof(b)); + + if (buffer == NULL) { + return -1; + } + + for (; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) { + _zip_buffer_set_offset(buffer, 0); + _zip_buffer_put_16(buffer, ef->id); + _zip_buffer_put_16(buffer, ef->size); + if (!_zip_buffer_ok(buffer)) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + _zip_buffer_free(buffer); + return -1; + } + if (_zip_write(za, b, 4) < 0) { + _zip_buffer_free(buffer); + return -1; + } + if (ef->size > 0) { + if (_zip_write(za, ef->data, ef->size) < 0) { + _zip_buffer_free(buffer); + return -1; + } + } + } + } + + _zip_buffer_free(buffer); + return 0; +} + + +int +_zip_read_local_ef(zip_t *za, zip_uint64_t idx) { + zip_entry_t *e; + unsigned char b[4]; + zip_buffer_t *buffer; + zip_uint16_t fname_len, ef_len; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + e = za->entry + idx; + + if (e->orig == NULL || e->orig->local_extra_fields_read) + return 0; + + if (e->orig->offset + 26 > ZIP_INT64_MAX) { + zip_error_set(&za->error, ZIP_ER_SEEK, EFBIG); + return -1; + } + + if (zip_source_seek(za->src, (zip_int64_t)(e->orig->offset + 26), SEEK_SET) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + + if ((buffer = _zip_buffer_new_from_source(za->src, sizeof(b), b, &za->error)) == NULL) { + return -1; + } + + fname_len = _zip_buffer_get_16(buffer); + ef_len = _zip_buffer_get_16(buffer); + + if (!_zip_buffer_eof(buffer)) { + _zip_buffer_free(buffer); + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + _zip_buffer_free(buffer); + + if (ef_len > 0) { + zip_extra_field_t *ef; + zip_uint8_t *ef_raw; + + if (zip_source_seek(za->src, fname_len, SEEK_CUR) < 0) { + zip_error_set(&za->error, ZIP_ER_SEEK, errno); + return -1; + } + + ef_raw = _zip_read_data(NULL, za->src, ef_len, 0, &za->error); + + if (ef_raw == NULL) + return -1; + + if (!_zip_ef_parse(ef_raw, ef_len, ZIP_EF_LOCAL, &ef, &za->error)) { + free(ef_raw); + return -1; + } + free(ef_raw); + + if (ef) { + ef = _zip_ef_remove_internal(ef); + e->orig->extra_fields = _zip_ef_merge(e->orig->extra_fields, ef); + } + } + + e->orig->local_extra_fields_read = 1; + + if (e->changes && e->changes->local_extra_fields_read == 0) { + e->changes->extra_fields = e->orig->extra_fields; + e->changes->local_extra_fields_read = 1; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_extra_field_api.c b/third_party/libzip/lib/zip_extra_field_api.c new file mode 100644 index 0000000..31808de --- /dev/null +++ b/third_party/libzip/lib/zip_extra_field_api.c @@ -0,0 +1,355 @@ +/* + zip_extra_field_api.c -- public extra fields API functions + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_extra_field_delete(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_idx, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (((flags & ZIP_EF_BOTH) == ZIP_EF_BOTH) && (ef_idx != ZIP_EXTRA_FIELD_ALL)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + de->extra_fields = _zip_ef_delete_by_id(de->extra_fields, ZIP_EXTRA_FIELD_ALL, ef_idx, flags); + return 0; +} + + +ZIP_EXTERN int +zip_file_extra_field_delete_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (((flags & ZIP_EF_BOTH) == ZIP_EF_BOTH) && (ef_idx != ZIP_EXTRA_FIELD_ALL)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + de->extra_fields = _zip_ef_delete_by_id(de->extra_fields, ef_id, ef_idx, flags); + return 0; +} + + +ZIP_EXTERN const zip_uint8_t * +zip_file_extra_field_get(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_idx, zip_uint16_t *idp, zip_uint16_t *lenp, zip_flags_t flags) { + static const zip_uint8_t empty[1] = {'\0'}; + + zip_dirent_t *de; + zip_extra_field_t *ef; + int i; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return NULL; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return NULL; + + i = 0; + for (ef = de->extra_fields; ef; ef = ef->next) { + if (ef->flags & flags & ZIP_EF_BOTH) { + if (i < ef_idx) { + i++; + continue; + } + + if (idp) + *idp = ef->id; + if (lenp) + *lenp = ef->size; + if (ef->size > 0) + return ef->data; + else + return empty; + } + } + + zip_error_set(&za->error, ZIP_ER_NOENT, 0); + return NULL; +} + + +ZIP_EXTERN const zip_uint8_t * +zip_file_extra_field_get_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, zip_uint16_t *lenp, zip_flags_t flags) { + zip_dirent_t *de; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return NULL; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return NULL; + + return _zip_ef_get_by_id(de->extra_fields, lenp, ef_id, ef_idx, flags, &za->error); +} + + +ZIP_EXTERN zip_int16_t +zip_file_extra_fields_count(zip_t *za, zip_uint64_t idx, zip_flags_t flags) { + zip_dirent_t *de; + zip_extra_field_t *ef; + zip_uint16_t n; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return -1; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return -1; + + n = 0; + for (ef = de->extra_fields; ef; ef = ef->next) + if (ef->flags & flags & ZIP_EF_BOTH) + n++; + + return (zip_int16_t)n; +} + + +ZIP_EXTERN zip_int16_t +zip_file_extra_fields_count_by_id(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_flags_t flags) { + zip_dirent_t *de; + zip_extra_field_t *ef; + zip_uint16_t n; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((de = _zip_get_dirent(za, idx, flags, &za->error)) == NULL) + return -1; + + if (flags & ZIP_FL_LOCAL) + if (_zip_read_local_ef(za, idx) < 0) + return -1; + + n = 0; + for (ef = de->extra_fields; ef; ef = ef->next) + if (ef->id == ef_id && (ef->flags & flags & ZIP_EF_BOTH)) + n++; + + return (zip_int16_t)n; +} + + +ZIP_EXTERN int +zip_file_extra_field_set(zip_t *za, zip_uint64_t idx, zip_uint16_t ef_id, zip_uint16_t ef_idx, const zip_uint8_t *data, zip_uint16_t len, zip_flags_t flags) { + zip_dirent_t *de; + zip_uint16_t ls, cs; + zip_extra_field_t *ef, *ef_prev, *ef_new; + int i, found, new_len; + + if ((flags & ZIP_EF_BOTH) == 0) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (ZIP_EF_IS_INTERNAL(ef_id)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_file_extra_field_prepare_for_change(za, idx) < 0) + return -1; + + de = za->entry[idx].changes; + + ef = de->extra_fields; + ef_prev = NULL; + i = 0; + found = 0; + + for (; ef; ef = ef->next) { + if (ef->id == ef_id && (ef->flags & flags & ZIP_EF_BOTH)) { + if (i == ef_idx) { + found = 1; + break; + } + i++; + } + ef_prev = ef; + } + + if (i < ef_idx && ef_idx != ZIP_EXTRA_FIELD_NEW) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (flags & ZIP_EF_LOCAL) + ls = _zip_ef_size(de->extra_fields, ZIP_EF_LOCAL); + else + ls = 0; + if (flags & ZIP_EF_CENTRAL) + cs = _zip_ef_size(de->extra_fields, ZIP_EF_CENTRAL); + else + cs = 0; + + new_len = ls > cs ? ls : cs; + if (found) + new_len -= ef->size + 4; + new_len += len + 4; + + if (new_len > ZIP_UINT16_MAX) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((ef_new = _zip_ef_new(ef_id, len, data, flags)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + + if (found) { + if ((ef->flags & ZIP_EF_BOTH) == (flags & ZIP_EF_BOTH)) { + ef_new->next = ef->next; + ef->next = NULL; + _zip_ef_free(ef); + if (ef_prev) + ef_prev->next = ef_new; + else + de->extra_fields = ef_new; + } + else { + ef->flags &= ~(flags & ZIP_EF_BOTH); + ef_new->next = ef->next; + ef->next = ef_new; + } + } + else if (ef_prev) { + ef_new->next = ef_prev->next; + ef_prev->next = ef_new; + } + else + de->extra_fields = ef_new; + + return 0; +} + + +int +_zip_file_extra_field_prepare_for_change(zip_t *za, zip_uint64_t idx) { + zip_entry_t *e; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + e = za->entry + idx; + + if (e->changes && (e->changes->changed & ZIP_DIRENT_EXTRA_FIELD)) + return 0; + + if (e->orig) { + if (_zip_read_local_ef(za, idx) < 0) + return -1; + } + + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + if (e->orig && e->orig->extra_fields) { + if ((e->changes->extra_fields = _zip_ef_clone(e->orig->extra_fields, &za->error)) == NULL) + return -1; + } + e->changes->changed |= ZIP_DIRENT_EXTRA_FIELD; + + return 0; +} diff --git a/third_party/libzip/lib/zip_fclose.c b/third_party/libzip/lib/zip_fclose.c new file mode 100644 index 0000000..1c69a96 --- /dev/null +++ b/third_party/libzip/lib/zip_fclose.c @@ -0,0 +1,54 @@ +/* + zip_fclose.c -- close file in zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_fclose(zip_file_t *zf) { + int ret; + + if (zf->src) + zip_source_free(zf->src); + + ret = 0; + if (zf->error.zip_err) + ret = zf->error.zip_err; + + zip_error_fini(&zf->error); + free(zf); + return ret; +} diff --git a/third_party/libzip/lib/zip_fdopen.c b/third_party/libzip/lib/zip_fdopen.c new file mode 100644 index 0000000..3270935 --- /dev/null +++ b/third_party/libzip/lib/zip_fdopen.c @@ -0,0 +1,86 @@ +/* + zip_fdopen.c -- open read-only archive from file descriptor + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#ifdef HAVE_UNISTD_H +#include +#endif + + +ZIP_EXTERN zip_t * +zip_fdopen(int fd_orig, int _flags, int *zep) { + int fd; + FILE *fp; + zip_t *za; + zip_source_t *src; + struct zip_error error; + + if (_flags < 0 || (_flags & ~(ZIP_CHECKCONS | ZIP_RDONLY))) { + _zip_set_open_error(zep, NULL, ZIP_ER_INVAL); + return NULL; + } + + /* We dup() here to avoid messing with the passed in fd. + We could not restore it to the original state in case of error. */ + + if ((fd = dup(fd_orig)) < 0) { + _zip_set_open_error(zep, NULL, ZIP_ER_OPEN); + return NULL; + } + + if ((fp = fdopen(fd, "rb")) == NULL) { + close(fd); + _zip_set_open_error(zep, NULL, ZIP_ER_OPEN); + return NULL; + } + + zip_error_init(&error); + if ((src = zip_source_filep_create(fp, 0, -1, &error)) == NULL) { + fclose(fp); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + if ((za = zip_open_from_source(src, _flags, &error)) == NULL) { + zip_source_free(src); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + zip_error_fini(&error); + close(fd_orig); + return za; +} diff --git a/third_party/libzip/lib/zip_file_add.c b/third_party/libzip/lib/zip_file_add.c new file mode 100644 index 0000000..c2c13d6 --- /dev/null +++ b/third_party/libzip/lib/zip_file_add.c @@ -0,0 +1,52 @@ +/* + zip_file_add.c -- add file via callback function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +/* + NOTE: Return type is signed so we can return -1 on error. + The index can not be larger than ZIP_INT64_MAX since the size + of the central directory cannot be larger than + ZIP_UINT64_MAX, and each entry is larger than 2 bytes. +*/ + +ZIP_EXTERN zip_int64_t +zip_file_add(zip_t *za, const char *name, zip_source_t *source, zip_flags_t flags) { + if (name == NULL || source == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_file_replace(za, ZIP_UINT64_MAX, name, source, flags); +} diff --git a/third_party/libzip/lib/zip_file_error_clear.c b/third_party/libzip/lib/zip_file_error_clear.c new file mode 100644 index 0000000..2e7dcea --- /dev/null +++ b/third_party/libzip/lib/zip_file_error_clear.c @@ -0,0 +1,44 @@ +/* + zip_file_error_clear.c -- clear zip file error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_file_error_clear(zip_file_t *zf) { + if (zf == NULL) + return; + + _zip_error_clear(&zf->error); +} diff --git a/third_party/libzip/lib/zip_file_error_get.c b/third_party/libzip/lib/zip_file_error_get.c new file mode 100644 index 0000000..1d13807 --- /dev/null +++ b/third_party/libzip/lib/zip_file_error_get.c @@ -0,0 +1,41 @@ +/* + zip_file_error_get.c -- get zip file error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN void +zip_file_error_get(zip_file_t *zf, int *zep, int *sep) { + _zip_error_get(&zf->error, zep, sep); +} diff --git a/third_party/libzip/lib/zip_file_get_comment.c b/third_party/libzip/lib/zip_file_get_comment.c new file mode 100644 index 0000000..ad944aa --- /dev/null +++ b/third_party/libzip/lib/zip_file_get_comment.c @@ -0,0 +1,55 @@ +/* + zip_file_get_comment.c -- get file comment + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +/* lenp is 32 bit because converted comment can be longer than ZIP_UINT16_MAX */ + +ZIP_EXTERN const char * +zip_file_get_comment(zip_t *za, zip_uint64_t idx, zip_uint32_t *lenp, zip_flags_t flags) { + zip_dirent_t *de; + zip_uint32_t len; + const zip_uint8_t *str; + + if ((de = _zip_get_dirent(za, idx, flags, NULL)) == NULL) + return NULL; + + if ((str = _zip_string_get(de->comment, &len, flags, &za->error)) == NULL) + return NULL; + + if (lenp) + *lenp = len; + + return (const char *)str; +} diff --git a/third_party/libzip/lib/zip_file_get_external_attributes.c b/third_party/libzip/lib/zip_file_get_external_attributes.c new file mode 100644 index 0000000..e2e5535 --- /dev/null +++ b/third_party/libzip/lib/zip_file_get_external_attributes.c @@ -0,0 +1,50 @@ +/* + zip_file_get_external_attributes.c -- get opsys/external attributes + Copyright (C) 2013-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +int +zip_file_get_external_attributes(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_uint8_t *opsys, zip_uint32_t *attributes) { + zip_dirent_t *de; + + if ((de = _zip_get_dirent(za, idx, flags, NULL)) == NULL) + return -1; + + if (opsys) + *opsys = (zip_uint8_t)((de->version_madeby >> 8) & 0xff); + + if (attributes) + *attributes = de->ext_attrib; + + return 0; +} diff --git a/third_party/libzip/lib/zip_file_get_offset.c b/third_party/libzip/lib/zip_file_get_offset.c new file mode 100644 index 0000000..858a78a --- /dev/null +++ b/third_party/libzip/lib/zip_file_get_offset.c @@ -0,0 +1,120 @@ +/* + zip_file_get_offset.c -- get offset of file data in archive. + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include "zipint.h" + + +/* _zip_file_get_offset(za, ze): + Returns the offset of the file data for entry ze. + + On error, fills in za->error and returns 0. +*/ + +zip_uint64_t +_zip_file_get_offset(const zip_t *za, zip_uint64_t idx, zip_error_t *error) { + zip_uint64_t offset; + zip_int32_t size; + + if (za->entry[idx].orig == NULL) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return 0; + } + + offset = za->entry[idx].orig->offset; + + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return 0; + } + + /* TODO: cache? */ + if ((size = _zip_dirent_size(za->src, ZIP_EF_LOCAL, error)) < 0) + return 0; + + if (offset + (zip_uint32_t)size > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + + return offset + (zip_uint32_t)size; +} + +zip_uint64_t +_zip_file_get_end(const zip_t *za, zip_uint64_t index, zip_error_t *error) { + zip_uint64_t offset; + zip_dirent_t *entry; + + if ((offset = _zip_file_get_offset(za, index, error)) == 0) { + return 0; + } + + entry = za->entry[index].orig; + + if (offset + entry->comp_size < offset || offset + entry->comp_size > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + offset += entry->comp_size; + + if (entry->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) { + zip_uint8_t buf[4]; + if (zip_source_seek(za->src, (zip_int64_t)offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return 0; + } + if (zip_source_read(za->src, buf, 4) != 4) { + _zip_error_set_from_source(error, za->src); + return 0; + } + if (memcmp(buf, DATADES_MAGIC, 4) == 0) { + offset += 4; + } + offset += 12; + if (_zip_dirent_needs_zip64(entry, 0)) { + offset += 8; + } + if (offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return 0; + } + } + + return offset; +} diff --git a/third_party/libzip/lib/zip_file_rename.c b/third_party/libzip/lib/zip_file_rename.c new file mode 100644 index 0000000..cc42dfc --- /dev/null +++ b/third_party/libzip/lib/zip_file_rename.c @@ -0,0 +1,67 @@ +/* + zip_file_rename.c -- rename file in zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_file_rename(zip_t *za, zip_uint64_t idx, const char *name, zip_flags_t flags) { + const char *old_name; + int old_is_dir, new_is_dir; + + if (idx >= za->nentry || (name != NULL && strlen(name) > ZIP_UINT16_MAX)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((old_name = zip_get_name(za, idx, 0)) == NULL) + return -1; + + new_is_dir = (name != NULL && name[strlen(name) - 1] == '/'); + old_is_dir = (old_name[strlen(old_name) - 1] == '/'); + + if (new_is_dir != old_is_dir) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_set_name(za, idx, name, flags); +} diff --git a/third_party/libzip/lib/zip_file_replace.c b/third_party/libzip/lib/zip_file_replace.c new file mode 100644 index 0000000..70b379a --- /dev/null +++ b/third_party/libzip/lib/zip_file_replace.c @@ -0,0 +1,105 @@ +/* + zip_file_replace.c -- replace file via callback function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_file_replace(zip_t *za, zip_uint64_t idx, zip_source_t *source, zip_flags_t flags) { + if (idx >= za->nentry || source == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_file_replace(za, idx, NULL, source, flags) == -1) + return -1; + + return 0; +} + + +/* NOTE: Signed due to -1 on error. See zip_add.c for more details. */ + +zip_int64_t +_zip_file_replace(zip_t *za, zip_uint64_t idx, const char *name, zip_source_t *source, zip_flags_t flags) { + zip_uint64_t za_nentry_prev; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + za_nentry_prev = za->nentry; + if (idx == ZIP_UINT64_MAX) { + zip_int64_t i = -1; + + if (flags & ZIP_FL_OVERWRITE) + i = _zip_name_locate(za, name, flags, NULL); + + if (i == -1) { + /* create and use new entry, used by zip_add */ + if ((i = _zip_add_entry(za)) < 0) + return -1; + } + idx = (zip_uint64_t)i; + } + + if (name && _zip_set_name(za, idx, name, flags) != 0) { + if (za->nentry != za_nentry_prev) { + _zip_entry_finalize(za->entry + idx); + za->nentry = za_nentry_prev; + } + return -1; + } + + /* does not change any name related data, so we can do it here; + * needed for a double add of the same file name */ + _zip_unchange_data(za->entry + idx); + + if (za->entry[idx].orig != NULL && (za->entry[idx].changes == NULL || (za->entry[idx].changes->changed & ZIP_DIRENT_COMP_METHOD) == 0)) { + if (za->entry[idx].changes == NULL) { + if ((za->entry[idx].changes = _zip_dirent_clone(za->entry[idx].orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + za->entry[idx].changes->comp_method = ZIP_CM_REPLACED_DEFAULT; + za->entry[idx].changes->changed |= ZIP_DIRENT_COMP_METHOD; + } + + za->entry[idx].source = source; + + return (zip_int64_t)idx; +} diff --git a/third_party/libzip/lib/zip_file_set_comment.c b/third_party/libzip/lib/zip_file_set_comment.c new file mode 100644 index 0000000..ae6b602 --- /dev/null +++ b/third_party/libzip/lib/zip_file_set_comment.c @@ -0,0 +1,101 @@ +/* + zip_file_set_comment.c -- set comment for file in archive + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_file_set_comment(zip_t *za, zip_uint64_t idx, const char *comment, zip_uint16_t len, zip_flags_t flags) { + zip_entry_t *e; + zip_string_t *cstr; + int changed; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (len > 0 && comment == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (len > 0) { + if ((cstr = _zip_string_new((const zip_uint8_t *)comment, len, flags, &za->error)) == NULL) + return -1; + if ((flags & ZIP_FL_ENCODING_ALL) == ZIP_FL_ENC_GUESS && _zip_guess_encoding(cstr, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_UTF8_GUESSED) + cstr->encoding = ZIP_ENCODING_UTF8_KNOWN; + } + else + cstr = NULL; + + e = za->entry + idx; + + if (e->changes) { + _zip_string_free(e->changes->comment); + e->changes->comment = NULL; + e->changes->changed &= ~ZIP_DIRENT_COMMENT; + } + + if (e->orig && e->orig->comment) + changed = !_zip_string_equal(e->orig->comment, cstr); + else + changed = (cstr != NULL); + + if (changed) { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_string_free(cstr); + return -1; + } + } + e->changes->comment = cstr; + e->changes->changed |= ZIP_DIRENT_COMMENT; + } + else { + _zip_string_free(cstr); + if (e->changes && e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_file_set_encryption.c b/third_party/libzip/lib/zip_file_set_encryption.c new file mode 100644 index 0000000..7e7a9b1 --- /dev/null +++ b/third_party/libzip/lib/zip_file_set_encryption.c @@ -0,0 +1,116 @@ +/* + zip_file_set_encryption.c -- set encryption for file in archive + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include + +ZIP_EXTERN int +zip_file_set_encryption(zip_t *za, zip_uint64_t idx, zip_uint16_t method, const char *password) { + zip_entry_t *e; + zip_uint16_t old_method; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (method != ZIP_EM_NONE && _zip_get_encryption_implementation(method, ZIP_CODEC_ENCODE) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return -1; + } + + e = za->entry + idx; + + old_method = (e->orig == NULL ? ZIP_EM_NONE : e->orig->encryption_method); + + if (method == old_method && password == NULL) { + if (e->changes) { + if (e->changes->changed & ZIP_DIRENT_PASSWORD) { + _zip_crypto_clear(e->changes->password, strlen(e->changes->password)); + free(e->changes->password); + e->changes->password = (e->orig == NULL ? NULL : e->orig->password); + } + e->changes->changed &= ~(ZIP_DIRENT_ENCRYPTION_METHOD | ZIP_DIRENT_PASSWORD); + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + } + else { + char *our_password = NULL; + + if (password) { + if ((our_password = strdup(password)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + if (our_password) { + _zip_crypto_clear(our_password, strlen(our_password)); + } + free(our_password); + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + e->changes->encryption_method = method; + e->changes->changed |= ZIP_DIRENT_ENCRYPTION_METHOD; + if (password) { + e->changes->password = our_password; + e->changes->changed |= ZIP_DIRENT_PASSWORD; + } + else { + if (e->changes->changed & ZIP_DIRENT_PASSWORD) { + _zip_crypto_clear(e->changes->password, strlen(e->changes->password)); + free(e->changes->password); + e->changes->password = e->orig ? e->orig->password : NULL; + e->changes->changed &= ~ZIP_DIRENT_PASSWORD; + } + } + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_file_set_external_attributes.c b/third_party/libzip/lib/zip_file_set_external_attributes.c new file mode 100644 index 0000000..c412f27 --- /dev/null +++ b/third_party/libzip/lib/zip_file_set_external_attributes.c @@ -0,0 +1,82 @@ +/* + zip_file_set_external_attributes.c -- set external attributes for entry + Copyright (C) 2013-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_file_set_external_attributes(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_uint8_t opsys, zip_uint32_t attributes) { + zip_entry_t *e; + int changed; + zip_uint8_t unchanged_opsys; + zip_uint32_t unchanged_attributes; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + e = za->entry + idx; + + unchanged_opsys = (e->orig ? (zip_uint8_t)(e->orig->version_madeby >> 8) : (zip_uint8_t)ZIP_OPSYS_DEFAULT); + unchanged_attributes = e->orig ? e->orig->ext_attrib : ZIP_EXT_ATTRIB_DEFAULT; + + changed = (opsys != unchanged_opsys || attributes != unchanged_attributes); + + if (changed) { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + e->changes->version_madeby = (zip_uint16_t)((opsys << 8) | (e->changes->version_madeby & 0xff)); + e->changes->ext_attrib = attributes; + e->changes->changed |= ZIP_DIRENT_ATTRIBUTES; + } + else if (e->changes) { + e->changes->changed &= ~ZIP_DIRENT_ATTRIBUTES; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + else { + e->changes->version_madeby = (zip_uint16_t)((unchanged_opsys << 8) | (e->changes->version_madeby & 0xff)); + e->changes->ext_attrib = unchanged_attributes; + } + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_file_set_mtime.c b/third_party/libzip/lib/zip_file_set_mtime.c new file mode 100644 index 0000000..f8d6c20 --- /dev/null +++ b/third_party/libzip/lib/zip_file_set_mtime.c @@ -0,0 +1,74 @@ +/* + zip_file_set_mtime.c -- set modification time of entry. + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_file_set_mtime(zip_t *za, zip_uint64_t idx, time_t mtime, zip_flags_t flags) { + zip_entry_t *e; + int changed; + + if (_zip_get_dirent(za, idx, 0, NULL) == NULL) + return -1; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + e = za->entry + idx; + + changed = e->orig == NULL || mtime != e->orig->last_mod; + + if (changed) { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + e->changes->last_mod = mtime; + e->changes->changed |= ZIP_DIRENT_LAST_MOD; + } + else { + if (e->changes) { + e->changes->changed &= ~ZIP_DIRENT_LAST_MOD; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_file_strerror.c b/third_party/libzip/lib/zip_file_strerror.c new file mode 100644 index 0000000..189c556 --- /dev/null +++ b/third_party/libzip/lib/zip_file_strerror.c @@ -0,0 +1,41 @@ +/* + zip_file_sterror.c -- get string representation of zip file error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_file_strerror(zip_file_t *zf) { + return zip_error_strerror(&zf->error); +} diff --git a/third_party/libzip/lib/zip_filerange_crc.c b/third_party/libzip/lib/zip_filerange_crc.c new file mode 100644 index 0000000..33bf5d8 --- /dev/null +++ b/third_party/libzip/lib/zip_filerange_crc.c @@ -0,0 +1,84 @@ +/* + zip_filerange_crc.c -- compute CRC32 for a range of a file + Copyright (C) 2008-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +int +_zip_filerange_crc(zip_source_t *src, zip_uint64_t start, zip_uint64_t len, uLong *crcp, zip_error_t *error) { + DEFINE_BYTE_ARRAY(buf, BUFSIZE); + + zip_int64_t n; + + *crcp = crc32(0L, Z_NULL, 0); + + if (start > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return -1; + } + + if (zip_source_seek(src, (zip_int64_t)start, SEEK_SET) != 0) { + _zip_error_set_from_source(error, src); + return -1; + } + + if (!byte_array_init(buf, BUFSIZE)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + + while (len > 0) { + n = (zip_int64_t)(len > BUFSIZE ? BUFSIZE : len); + if ((n = zip_source_read(src, buf, (zip_uint64_t)n)) < 0) { + _zip_error_set_from_source(error, src); + byte_array_fini(buf); + return -1; + } + if (n == 0) { + zip_error_set(error, ZIP_ER_EOF, 0); + byte_array_fini(buf); + return -1; + } + + *crcp = crc32(*crcp, buf, (uInt)n); + + len -= (zip_uint64_t)n; + } + + byte_array_fini(buf); + + return 0; +} diff --git a/third_party/libzip/lib/zip_fopen.c b/third_party/libzip/lib/zip_fopen.c new file mode 100644 index 0000000..4ef76ba --- /dev/null +++ b/third_party/libzip/lib/zip_fopen.c @@ -0,0 +1,46 @@ +/* + zip_fopen.c -- open file in zip archive for reading + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen(zip_t *za, const char *fname, zip_flags_t flags) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return NULL; + + return zip_fopen_index_encrypted(za, (zip_uint64_t)idx, flags, za->default_password); +} diff --git a/third_party/libzip/lib/zip_fopen_encrypted.c b/third_party/libzip/lib/zip_fopen_encrypted.c new file mode 100644 index 0000000..47cd377 --- /dev/null +++ b/third_party/libzip/lib/zip_fopen_encrypted.c @@ -0,0 +1,46 @@ +/* + zip_fopen_encrypted.c -- open file for reading with password + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen_encrypted(zip_t *za, const char *fname, zip_flags_t flags, const char *password) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return NULL; + + return zip_fopen_index_encrypted(za, (zip_uint64_t)idx, flags, password); +} diff --git a/third_party/libzip/lib/zip_fopen_index.c b/third_party/libzip/lib/zip_fopen_index.c new file mode 100644 index 0000000..5f0dc2a --- /dev/null +++ b/third_party/libzip/lib/zip_fopen_index.c @@ -0,0 +1,44 @@ +/* + zip_fopen_index.c -- open file in zip archive for reading by index + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +ZIP_EXTERN zip_file_t * +zip_fopen_index(zip_t *za, zip_uint64_t index, zip_flags_t flags) { + return zip_fopen_index_encrypted(za, index, flags, za->default_password); +} diff --git a/third_party/libzip/lib/zip_fopen_index_encrypted.c b/third_party/libzip/lib/zip_fopen_index_encrypted.c new file mode 100644 index 0000000..4d4aee3 --- /dev/null +++ b/third_party/libzip/lib/zip_fopen_index_encrypted.c @@ -0,0 +1,83 @@ +/* + zip_fopen_index_encrypted.c -- open file for reading by index w/ password + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +static zip_file_t *_zip_file_new(zip_t *za); + + +ZIP_EXTERN zip_file_t * +zip_fopen_index_encrypted(zip_t *za, zip_uint64_t index, zip_flags_t flags, const char *password) { + zip_file_t *zf; + zip_source_t *src; + + if ((src = _zip_source_zip_new(za, za, index, flags, 0, 0, password)) == NULL) + return NULL; + + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(&za->error, src); + zip_source_free(src); + return NULL; + } + + if ((zf = _zip_file_new(za)) == NULL) { + zip_source_free(src); + return NULL; + } + + zf->src = src; + + return zf; +} + + +static zip_file_t * +_zip_file_new(zip_t *za) { + zip_file_t *zf; + + if ((zf = (zip_file_t *)malloc(sizeof(struct zip_file))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + zf->za = za; + zip_error_init(&zf->error); + zf->eof = 0; + zf->src = NULL; + + return zf; +} diff --git a/third_party/libzip/lib/zip_fread.c b/third_party/libzip/lib/zip_fread.c new file mode 100644 index 0000000..3020a16 --- /dev/null +++ b/third_party/libzip/lib/zip_fread.c @@ -0,0 +1,62 @@ +/* + zip_fread.c -- read from file + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_fread(zip_file_t *zf, void *outbuf, zip_uint64_t toread) { + zip_int64_t n; + + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + if (toread > ZIP_INT64_MAX) { + zip_error_set(&zf->error, ZIP_ER_INVAL, 0); + return -1; + } + + if ((zf->eof) || (toread == 0)) + return 0; + + if ((n = zip_source_read(zf->src, outbuf, toread)) < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return n; +} diff --git a/third_party/libzip/lib/zip_fseek.c b/third_party/libzip/lib/zip_fseek.c new file mode 100644 index 0000000..3557401 --- /dev/null +++ b/third_party/libzip/lib/zip_fseek.c @@ -0,0 +1,52 @@ +/* + zip_fseek.c -- seek in file + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#include + +ZIP_EXTERN zip_int8_t +zip_fseek(zip_file_t *zf, zip_int64_t offset, int whence) { + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + if (zip_source_seek(zf->src, offset, whence) < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_ftell.c b/third_party/libzip/lib/zip_ftell.c new file mode 100644 index 0000000..f4e4550 --- /dev/null +++ b/third_party/libzip/lib/zip_ftell.c @@ -0,0 +1,55 @@ +/* + zip_ftell.c -- tell position in file + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#include + +ZIP_EXTERN zip_int64_t +zip_ftell(zip_file_t *zf) { + zip_int64_t res; + + if (!zf) + return -1; + + if (zf->error.zip_err != 0) + return -1; + + res = zip_source_tell(zf->src); + if (res < 0) { + _zip_error_set_from_source(&zf->error, zf->src); + return -1; + } + + return res; +} diff --git a/third_party/libzip/lib/zip_get_archive_comment.c b/third_party/libzip/lib/zip_get_archive_comment.c new file mode 100644 index 0000000..c51148d --- /dev/null +++ b/third_party/libzip/lib/zip_get_archive_comment.c @@ -0,0 +1,58 @@ +/* + zip_get_archive_comment.c -- get archive comment + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_get_archive_comment(zip_t *za, int *lenp, zip_flags_t flags) { + zip_string_t *comment; + zip_uint32_t len; + const zip_uint8_t *str; + + if ((flags & ZIP_FL_UNCHANGED) || (za->comment_changes == NULL)) + comment = za->comment_orig; + else + comment = za->comment_changes; + + if ((str = _zip_string_get(comment, &len, flags, &za->error)) == NULL) + return NULL; + + if (lenp) + *lenp = (int)len; + + return (const char *)str; +} diff --git a/third_party/libzip/lib/zip_get_archive_flag.c b/third_party/libzip/lib/zip_get_archive_flag.c new file mode 100644 index 0000000..1aaca72 --- /dev/null +++ b/third_party/libzip/lib/zip_get_archive_flag.c @@ -0,0 +1,45 @@ +/* + zip_get_archive_flag.c -- get archive global flag + Copyright (C) 2008-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_get_archive_flag(zip_t *za, zip_flags_t flag, zip_flags_t flags) { + unsigned int fl; + + fl = (flags & ZIP_FL_UNCHANGED) ? za->flags : za->ch_flags; + + return (fl & flag) ? 1 : 0; +} diff --git a/third_party/libzip/lib/zip_get_encryption_implementation.c b/third_party/libzip/lib/zip_get_encryption_implementation.c new file mode 100644 index 0000000..07e4316 --- /dev/null +++ b/third_party/libzip/lib/zip_get_encryption_implementation.c @@ -0,0 +1,57 @@ +/* + zip_get_encryption_implementation.c -- get encryption implementation + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_encryption_implementation +_zip_get_encryption_implementation(zip_uint16_t em, int operation) { + switch (em) { + case ZIP_EM_TRAD_PKWARE: + if (operation == ZIP_CODEC_ENCODE) { + return NULL; + } + return zip_source_pkware; + +#if defined(HAVE_CRYPTO) + case ZIP_EM_AES_128: + case ZIP_EM_AES_192: + case ZIP_EM_AES_256: + return operation == ZIP_CODEC_DECODE ? zip_source_winzip_aes_decode : zip_source_winzip_aes_encode; +#endif + + default: + return NULL; + } +} diff --git a/third_party/libzip/lib/zip_get_file_comment.c b/third_party/libzip/lib/zip_get_file_comment.c new file mode 100644 index 0000000..6e85a58 --- /dev/null +++ b/third_party/libzip/lib/zip_get_file_comment.c @@ -0,0 +1,50 @@ +/* + zip_get_file_comment.c -- get file comment + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_get_file_comment(zip_t *za, zip_uint64_t idx, int *lenp, int flags) { + zip_uint32_t len; + const char *s; + + if ((s = zip_file_get_comment(za, idx, &len, (zip_flags_t)flags)) != NULL) { + if (lenp) + *lenp = (int)len; + } + + return s; +} diff --git a/third_party/libzip/lib/zip_get_name.c b/third_party/libzip/lib/zip_get_name.c new file mode 100644 index 0000000..2ac005a --- /dev/null +++ b/third_party/libzip/lib/zip_get_name.c @@ -0,0 +1,58 @@ +/* + zip_get_name.c -- get filename for a file in zip file + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN const char * +zip_get_name(zip_t *za, zip_uint64_t idx, zip_flags_t flags) { + return _zip_get_name(za, idx, flags, &za->error); +} + + +const char * +_zip_get_name(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { + zip_dirent_t *de; + const zip_uint8_t *str; + + if ((de = _zip_get_dirent(za, idx, flags, error)) == NULL) + return NULL; + + if ((str = _zip_string_get(de->filename, NULL, flags, error)) == NULL) + return NULL; + + return (const char *)str; +} diff --git a/third_party/libzip/lib/zip_get_num_entries.c b/third_party/libzip/lib/zip_get_num_entries.c new file mode 100644 index 0000000..99dfc7a --- /dev/null +++ b/third_party/libzip/lib/zip_get_num_entries.c @@ -0,0 +1,52 @@ +/* + zip_get_num_entries.c -- get number of entries in archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_get_num_entries(zip_t *za, zip_flags_t flags) { + zip_uint64_t n; + + if (za == NULL) + return -1; + + if (flags & ZIP_FL_UNCHANGED) { + n = za->nentry; + while (n > 0 && za->entry[n - 1].orig == NULL) + --n; + return (zip_int64_t)n; + } + return (zip_int64_t)za->nentry; +} diff --git a/third_party/libzip/lib/zip_get_num_files.c b/third_party/libzip/lib/zip_get_num_files.c new file mode 100644 index 0000000..b6e910e --- /dev/null +++ b/third_party/libzip/lib/zip_get_num_files.c @@ -0,0 +1,51 @@ +/* + zip_get_num_files.c -- get number of files in archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" +#include + + +ZIP_EXTERN int +zip_get_num_files(zip_t *za) { + if (za == NULL) + return -1; + + if (za->nentry > INT_MAX) { + zip_error_set(&za->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + + return (int)za->nentry; +} diff --git a/third_party/libzip/lib/zip_hash.c b/third_party/libzip/lib/zip_hash.c new file mode 100644 index 0000000..7288453 --- /dev/null +++ b/third_party/libzip/lib/zip_hash.c @@ -0,0 +1,410 @@ +/* + zip_hash.c -- hash table string -> uint64 + Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#include +#include + +/* parameter for the string hash function */ +#define HASH_MULTIPLIER 33 +#define HASH_START 5381 + +/* hash table's fill ratio is kept between these by doubling/halfing its size as necessary */ +#define HASH_MAX_FILL .75 +#define HASH_MIN_FILL .01 + +/* but hash table size is kept between these */ +#define HASH_MIN_SIZE 256 +#define HASH_MAX_SIZE 0x80000000ul + +struct zip_hash_entry { + const zip_uint8_t *name; + zip_int64_t orig_index; + zip_int64_t current_index; + struct zip_hash_entry *next; + zip_uint32_t hash_value; +}; +typedef struct zip_hash_entry zip_hash_entry_t; + +struct zip_hash { + zip_uint32_t table_size; + zip_uint64_t nentries; + zip_hash_entry_t **table; +}; + + +/* free list of entries */ +static void +free_list(zip_hash_entry_t *entry) { + while (entry != NULL) { + zip_hash_entry_t *next = entry->next; + free(entry); + entry = next; + } +} + + +/* compute hash of string, full 32 bit value */ +static zip_uint32_t +hash_string(const zip_uint8_t *name) { + zip_uint64_t value = HASH_START; + + if (name == NULL) { + return 0; + } + + while (*name != 0) { + value = (zip_uint64_t)(((value * HASH_MULTIPLIER) + (zip_uint8_t)*name) % 0x100000000ul); + name++; + } + + return (zip_uint32_t)value; +} + + +/* resize hash table; new_size must be a power of 2, can be larger or smaller than current size */ +static bool +hash_resize(zip_hash_t *hash, zip_uint32_t new_size, zip_error_t *error) { + zip_hash_entry_t **new_table; + + if (new_size == hash->table_size) { + return true; + } + + if ((new_table = (zip_hash_entry_t **)calloc(new_size, sizeof(zip_hash_entry_t *))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + + if (hash->nentries > 0) { + zip_uint32_t i; + + for (i = 0; i < hash->table_size; i++) { + zip_hash_entry_t *entry = hash->table[i]; + while (entry) { + zip_hash_entry_t *next = entry->next; + + zip_uint32_t new_index = entry->hash_value % new_size; + + entry->next = new_table[new_index]; + new_table[new_index] = entry; + + entry = next; + } + } + } + + free(hash->table); + hash->table = new_table; + hash->table_size = new_size; + + return true; +} + + +static zip_uint32_t +size_for_capacity(zip_uint64_t capacity) { + double needed_size = capacity / HASH_MAX_FILL; + zip_uint32_t v; + + if (needed_size > ZIP_UINT32_MAX) { + v = ZIP_UINT32_MAX; + } + else { + v = (zip_uint32_t)needed_size; + } + + if (v > HASH_MAX_SIZE) { + return HASH_MAX_SIZE; + } + + /* From Bit Twiddling Hacks by Sean Eron Anderson + (http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2). */ + + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + + return v; +} + + +zip_hash_t * +_zip_hash_new(zip_error_t *error) { + zip_hash_t *hash; + + if ((hash = (zip_hash_t *)malloc(sizeof(zip_hash_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + hash->table_size = 0; + hash->nentries = 0; + hash->table = NULL; + + return hash; +} + + +void +_zip_hash_free(zip_hash_t *hash) { + zip_uint32_t i; + + if (hash == NULL) { + return; + } + + if (hash->table != NULL) { + for (i = 0; i < hash->table_size; i++) { + if (hash->table[i] != NULL) { + free_list(hash->table[i]); + } + } + free(hash->table); + } + free(hash); +} + + +/* insert into hash, return error on existence or memory issues */ +bool +_zip_hash_add(zip_hash_t *hash, const zip_uint8_t *name, zip_uint64_t index, zip_flags_t flags, zip_error_t *error) { + zip_uint32_t hash_value, table_index; + zip_hash_entry_t *entry; + + if (hash == NULL || name == NULL || index > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return false; + } + + if (hash->table_size == 0) { + if (!hash_resize(hash, HASH_MIN_SIZE, error)) { + return false; + } + } + + hash_value = hash_string(name); + table_index = hash_value % hash->table_size; + + for (entry = hash->table[table_index]; entry != NULL; entry = entry->next) { + if (entry->hash_value == hash_value && strcmp((const char *)name, (const char *)entry->name) == 0) { + if (((flags & ZIP_FL_UNCHANGED) && entry->orig_index != -1) || entry->current_index != -1) { + zip_error_set(error, ZIP_ER_EXISTS, 0); + return false; + } + else { + break; + } + } + } + + if (entry == NULL) { + if ((entry = (zip_hash_entry_t *)malloc(sizeof(zip_hash_entry_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + entry->name = name; + entry->next = hash->table[table_index]; + hash->table[table_index] = entry; + entry->hash_value = hash_value; + entry->orig_index = -1; + hash->nentries++; + if (hash->nentries > hash->table_size * HASH_MAX_FILL && hash->table_size < HASH_MAX_SIZE) { + if (!hash_resize(hash, hash->table_size * 2, error)) { + return false; + } + } + } + + if (flags & ZIP_FL_UNCHANGED) { + entry->orig_index = (zip_int64_t)index; + } + entry->current_index = (zip_int64_t)index; + + return true; +} + + +/* remove entry from hash, error if not found */ +bool +_zip_hash_delete(zip_hash_t *hash, const zip_uint8_t *name, zip_error_t *error) { + zip_uint32_t hash_value, index; + zip_hash_entry_t *entry, *previous; + + if (hash == NULL || name == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return false; + } + + if (hash->nentries > 0) { + hash_value = hash_string(name); + index = hash_value % hash->table_size; + previous = NULL; + entry = hash->table[index]; + while (entry) { + if (entry->hash_value == hash_value && strcmp((const char *)name, (const char *)entry->name) == 0) { + if (entry->orig_index == -1) { + if (previous) { + previous->next = entry->next; + } + else { + hash->table[index] = entry->next; + } + free(entry); + hash->nentries--; + if (hash->nentries < hash->table_size * HASH_MIN_FILL && hash->table_size > HASH_MIN_SIZE) { + if (!hash_resize(hash, hash->table_size / 2, error)) { + return false; + } + } + } + else { + entry->current_index = -1; + } + return true; + } + previous = entry; + entry = entry->next; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return false; +} + + +/* find value for entry in hash, -1 if not found */ +zip_int64_t +_zip_hash_lookup(zip_hash_t *hash, const zip_uint8_t *name, zip_flags_t flags, zip_error_t *error) { + zip_uint32_t hash_value, index; + zip_hash_entry_t *entry; + + if (hash == NULL || name == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (hash->nentries > 0) { + hash_value = hash_string(name); + index = hash_value % hash->table_size; + for (entry = hash->table[index]; entry != NULL; entry = entry->next) { + if (strcmp((const char *)name, (const char *)entry->name) == 0) { + if (flags & ZIP_FL_UNCHANGED) { + if (entry->orig_index != -1) { + return entry->orig_index; + } + } + else { + if (entry->current_index != -1) { + return entry->current_index; + } + } + break; + } + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return -1; +} + + +bool +_zip_hash_reserve_capacity(zip_hash_t *hash, zip_uint64_t capacity, zip_error_t *error) { + zip_uint32_t new_size; + + if (capacity == 0) { + return true; + } + + new_size = size_for_capacity(capacity); + + if (new_size <= hash->table_size) { + return true; + } + + if (!hash_resize(hash, new_size, error)) { + return false; + } + + return true; +} + + +bool +_zip_hash_revert(zip_hash_t *hash, zip_error_t *error) { + zip_uint32_t i; + zip_hash_entry_t *entry, *previous; + + for (i = 0; i < hash->table_size; i++) { + previous = NULL; + entry = hash->table[i]; + while (entry) { + if (entry->orig_index == -1) { + zip_hash_entry_t *p; + if (previous) { + previous->next = entry->next; + } + else { + hash->table[i] = entry->next; + } + p = entry; + entry = entry->next; + /* previous does not change */ + free(p); + hash->nentries--; + } + else { + entry->current_index = entry->orig_index; + previous = entry; + entry = entry->next; + } + } + } + + if (hash->nentries < hash->table_size * HASH_MIN_FILL && hash->table_size > HASH_MIN_SIZE) { + zip_uint32_t new_size = hash->table_size / 2; + while (hash->nentries < new_size * HASH_MIN_FILL && new_size > HASH_MIN_SIZE) { + new_size /= 2; + } + if (!hash_resize(hash, new_size, error)) { + return false; + } + } + + return true; +} diff --git a/third_party/libzip/lib/zip_io_util.c b/third_party/libzip/lib/zip_io_util.c new file mode 100644 index 0000000..53f4437 --- /dev/null +++ b/third_party/libzip/lib/zip_io_util.c @@ -0,0 +1,134 @@ +/* + zip_io_util.c -- I/O helper functions + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +int +_zip_read(zip_source_t *src, zip_uint8_t *b, zip_uint64_t length, zip_error_t *error) { + zip_int64_t n; + + if (length > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((n = zip_source_read(src, b, length)) < 0) { + _zip_error_set_from_source(error, src); + return -1; + } + + if (n < (zip_int64_t)length) { + zip_error_set(error, ZIP_ER_EOF, 0); + return -1; + } + + return 0; +} + + +zip_uint8_t * +_zip_read_data(zip_buffer_t *buffer, zip_source_t *src, size_t length, bool nulp, zip_error_t *error) { + zip_uint8_t *r; + + if (length == 0 && !nulp) { + return NULL; + } + + r = (zip_uint8_t *)malloc(length + (nulp ? 1 : 0)); + if (!r) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if (buffer) { + zip_uint8_t *data = _zip_buffer_get(buffer, length); + + if (data == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(r); + return NULL; + } + memcpy(r, data, length); + } + else { + if (_zip_read(src, r, length, error) < 0) { + free(r); + return NULL; + } + } + + if (nulp) { + zip_uint8_t *o; + /* replace any in-string NUL characters with spaces */ + r[length] = 0; + for (o = r; o < r + length; o++) + if (*o == '\0') + *o = ' '; + } + + return r; +} + + +zip_string_t * +_zip_read_string(zip_buffer_t *buffer, zip_source_t *src, zip_uint16_t len, bool nulp, zip_error_t *error) { + zip_uint8_t *raw; + zip_string_t *s; + + if ((raw = _zip_read_data(buffer, src, len, nulp, error)) == NULL) + return NULL; + + s = _zip_string_new(raw, len, ZIP_FL_ENC_GUESS, error); + free(raw); + return s; +} + + +int +_zip_write(zip_t *za, const void *data, zip_uint64_t length) { + zip_int64_t n; + + if ((n = zip_source_write(za->src, data, length)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return -1; + } + if ((zip_uint64_t)n != length) { + zip_error_set(&za->error, ZIP_ER_WRITE, EINTR); + return -1; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_libzip_version.c b/third_party/libzip/lib/zip_libzip_version.c new file mode 100644 index 0000000..c6787a9 --- /dev/null +++ b/third_party/libzip/lib/zip_libzip_version.c @@ -0,0 +1,41 @@ +/* + zip_libzip_version.c -- return run-time version of library + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_libzip_version(void) { + return LIBZIP_VERSION; +} diff --git a/third_party/libzip/lib/zip_memdup.c b/third_party/libzip/lib/zip_memdup.c new file mode 100644 index 0000000..d604408 --- /dev/null +++ b/third_party/libzip/lib/zip_memdup.c @@ -0,0 +1,56 @@ +/* + zip_memdup.c -- internal zip function, "strdup" with len + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +void * +_zip_memdup(const void *mem, size_t len, zip_error_t *error) { + void *ret; + + if (len == 0) + return NULL; + + ret = malloc(len); + if (!ret) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + memcpy(ret, mem, len); + + return ret; +} diff --git a/third_party/libzip/lib/zip_name_locate.c b/third_party/libzip/lib/zip_name_locate.c new file mode 100644 index 0000000..37b1ffe --- /dev/null +++ b/third_party/libzip/lib/zip_name_locate.c @@ -0,0 +1,92 @@ +/* + zip_name_locate.c -- get index by name + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#ifdef HAVE_STRINGS_H +#include +#endif + +#include "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_name_locate(zip_t *za, const char *fname, zip_flags_t flags) { + return _zip_name_locate(za, fname, flags, &za->error); +} + + +zip_int64_t +_zip_name_locate(zip_t *za, const char *fname, zip_flags_t flags, zip_error_t *error) { + int (*cmp)(const char *, const char *); + const char *fn, *p; + zip_uint64_t i; + + if (za == NULL) + return -1; + + if (fname == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (flags & (ZIP_FL_NOCASE | ZIP_FL_NODIR | ZIP_FL_ENC_CP437)) { + /* can't use hash table */ + cmp = (flags & ZIP_FL_NOCASE) ? strcasecmp : strcmp; + + for (i = 0; i < za->nentry; i++) { + fn = _zip_get_name(za, i, flags, error); + + /* newly added (partially filled) entry or error */ + if (fn == NULL) + continue; + + if (flags & ZIP_FL_NODIR) { + p = strrchr(fn, '/'); + if (p) + fn = p + 1; + } + + if (cmp(fname, fn) == 0) { + _zip_error_clear(error); + return (zip_int64_t)i; + } + } + + zip_error_set(error, ZIP_ER_NOENT, 0); + return -1; + } + else { + return _zip_hash_lookup(za->names, (const zip_uint8_t *)fname, flags, error); + } +} diff --git a/third_party/libzip/lib/zip_new.c b/third_party/libzip/lib/zip_new.c new file mode 100644 index 0000000..1cd614d --- /dev/null +++ b/third_party/libzip/lib/zip_new.c @@ -0,0 +1,73 @@ +/* + zip_new.c -- create and init struct zip + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +/* _zip_new: + creates a new zipfile struct, and sets the contents to zero; returns + the new struct. */ + +zip_t * +_zip_new(zip_error_t *error) { + zip_t *za; + + za = (zip_t *)malloc(sizeof(struct zip)); + if (!za) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((za->names = _zip_hash_new(error)) == NULL) { + free(za); + return NULL; + } + + za->src = NULL; + za->open_flags = 0; + zip_error_init(&za->error); + za->flags = za->ch_flags = 0; + za->default_password = NULL; + za->comment_orig = za->comment_changes = NULL; + za->comment_changed = 0; + za->nentry = za->nentry_alloc = 0; + za->entry = NULL; + za->nopen_source = za->nopen_source_alloc = 0; + za->open_source = NULL; + za->progress = NULL; + + return za; +} diff --git a/third_party/libzip/lib/zip_open.c b/third_party/libzip/lib/zip_open.c new file mode 100644 index 0000000..593bfde --- /dev/null +++ b/third_party/libzip/lib/zip_open.c @@ -0,0 +1,848 @@ +/* + zip_open.c -- open zip archive by name + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include "zipint.h" + +typedef enum { + EXISTS_ERROR = -1, + EXISTS_NOT = 0, + EXISTS_EMPTY, + EXISTS_NONEMPTY, +} exists_t; +static zip_t *_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error); +static zip_int64_t _zip_checkcons(zip_t *za, zip_cdir_t *cdir, zip_error_t *error); +static zip_cdir_t *_zip_find_central_dir(zip_t *za, zip_uint64_t len); +static exists_t _zip_file_exists(zip_source_t *src, zip_error_t *error); +static int _zip_headercomp(const zip_dirent_t *, const zip_dirent_t *); +static unsigned char *_zip_memmem(const unsigned char *, size_t, const unsigned char *, size_t); +static zip_cdir_t *_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error); +static zip_cdir_t *_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error); +static zip_cdir_t *_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error); + + +ZIP_EXTERN zip_t * +zip_open(const char *fn, int _flags, int *zep) { + zip_t *za; + zip_source_t *src; + struct zip_error error; + + zip_error_init(&error); + if ((src = zip_source_file_create(fn, 0, -1, &error)) == NULL) { + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + if ((za = zip_open_from_source(src, _flags, &error)) == NULL) { + zip_source_free(src); + _zip_set_open_error(zep, &error, 0); + zip_error_fini(&error); + return NULL; + } + + zip_error_fini(&error); + return za; +} + + +ZIP_EXTERN zip_t * +zip_open_from_source(zip_source_t *src, int _flags, zip_error_t *error) { + static zip_int64_t needed_support_read = -1; + static zip_int64_t needed_support_write = -1; + + unsigned int flags; + zip_int64_t supported; + exists_t exists; + + if (_flags < 0 || src == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + flags = (unsigned int)_flags; + + supported = zip_source_supports(src); + if (needed_support_read == -1) { + needed_support_read = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_STAT, -1); + needed_support_write = zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, -1); + } + if ((supported & needed_support_read) != needed_support_read) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + if ((supported & needed_support_write) != needed_support_write) { + flags |= ZIP_RDONLY; + } + + if ((flags & (ZIP_RDONLY | ZIP_TRUNCATE)) == (ZIP_RDONLY | ZIP_TRUNCATE)) { + zip_error_set(error, ZIP_ER_RDONLY, 0); + return NULL; + } + + exists = _zip_file_exists(src, error); + switch (exists) { + case EXISTS_ERROR: + return NULL; + + case EXISTS_NOT: + if ((flags & ZIP_CREATE) == 0) { + zip_error_set(error, ZIP_ER_NOENT, 0); + return NULL; + } + return _zip_allocate_new(src, flags, error); + + default: { + zip_t *za; + if (flags & ZIP_EXCL) { + zip_error_set(error, ZIP_ER_EXISTS, 0); + return NULL; + } + if (zip_source_open(src) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + + if (flags & ZIP_TRUNCATE) { + za = _zip_allocate_new(src, flags, error); + } + else { + /* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL, just like open() */ + za = _zip_open(src, flags, error); + } + + if (za == NULL) { + zip_source_close(src); + return NULL; + } + return za; + } + } +} + + +zip_t * +_zip_open(zip_source_t *src, unsigned int flags, zip_error_t *error) { + zip_t *za; + zip_cdir_t *cdir; + struct zip_stat st; + zip_uint64_t len, idx; + + zip_stat_init(&st); + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + if ((st.valid & ZIP_STAT_SIZE) == 0) { + zip_error_set(error, ZIP_ER_SEEK, EOPNOTSUPP); + return NULL; + } + len = st.size; + + /* treat empty files as empty archives */ + if (len == 0) { + if ((za = _zip_allocate_new(src, flags, error)) == NULL) { + return NULL; + } + + return za; + } + + if ((za = _zip_allocate_new(src, flags, error)) == NULL) { + return NULL; + } + + if ((cdir = _zip_find_central_dir(za, len)) == NULL) { + _zip_error_copy(error, &za->error); + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + + za->entry = cdir->entry; + za->nentry = cdir->nentry; + za->nentry_alloc = cdir->nentry_alloc; + za->comment_orig = cdir->comment; + + free(cdir); + + _zip_hash_reserve_capacity(za->names, za->nentry, &za->error); + + for (idx = 0; idx < za->nentry; idx++) { + const zip_uint8_t *name = _zip_string_get(za->entry[idx].orig->filename, NULL, 0, error); + if (name == NULL) { + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + + if (_zip_hash_add(za->names, name, idx, ZIP_FL_UNCHANGED, &za->error) == false) { + if (za->error.zip_err != ZIP_ER_EXISTS || (flags & ZIP_CHECKCONS)) { + _zip_error_copy(error, &za->error); + /* keep src so discard does not get rid of it */ + zip_source_keep(src); + zip_discard(za); + return NULL; + } + } + } + + za->ch_flags = za->flags; + + return za; +} + + +void +_zip_set_open_error(int *zep, const zip_error_t *err, int ze) { + if (err) { + ze = zip_error_code_zip(err); + if (zip_error_system_type(err) == ZIP_ET_SYS) { + errno = zip_error_code_system(err); + } + } + + if (zep) + *zep = ze; +} + + +/* _zip_readcdir: + tries to find a valid end-of-central-directory at the beginning of + buf, and then the corresponding central directory entries. + Returns a struct zip_cdir which contains the central directory + entries, or NULL if unsuccessful. */ + +static zip_cdir_t * +_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint16_t comment_len; + zip_uint64_t i, left; + zip_uint64_t eocd_offset = _zip_buffer_offset(buffer); + zip_buffer_t *cd_buffer; + + if (_zip_buffer_left(buffer) < EOCDLEN) { + /* not enough bytes left for comment */ + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + /* check for end-of-central-dir magic */ + if (memcmp(_zip_buffer_get(buffer, 4), EOCD_MAGIC, 4) != 0) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + if (eocd_offset >= EOCD64LOCLEN && memcmp(_zip_buffer_data(buffer) + eocd_offset - EOCD64LOCLEN, EOCD64LOC_MAGIC, 4) == 0) { + _zip_buffer_set_offset(buffer, eocd_offset - EOCD64LOCLEN); + cd = _zip_read_eocd64(za->src, buffer, buf_offset, za->flags, error); + } + else { + _zip_buffer_set_offset(buffer, eocd_offset); + cd = _zip_read_eocd(buffer, buf_offset, za->flags, error); + } + + if (cd == NULL) + return NULL; + + _zip_buffer_set_offset(buffer, eocd_offset + 20); + comment_len = _zip_buffer_get_16(buffer); + + if (cd->offset + cd->size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + + if (comment_len || (za->open_flags & ZIP_CHECKCONS)) { + zip_uint64_t tail_len; + + _zip_buffer_set_offset(buffer, eocd_offset + EOCDLEN); + tail_len = _zip_buffer_left(buffer); + + if (tail_len < comment_len || ((za->open_flags & ZIP_CHECKCONS) && tail_len != comment_len)) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + + if (comment_len) { + if ((cd->comment = _zip_string_new(_zip_buffer_get(buffer, comment_len), comment_len, ZIP_FL_ENC_GUESS, error)) == NULL) { + _zip_cdir_free(cd); + return NULL; + } + } + } + + if (cd->offset >= buf_offset) { + zip_uint8_t *data; + /* if buffer already read in, use it */ + _zip_buffer_set_offset(buffer, cd->offset - buf_offset); + + if ((data = _zip_buffer_get(buffer, cd->size)) == NULL) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_cdir_free(cd); + return NULL; + } + if ((cd_buffer = _zip_buffer_new(data, cd->size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + _zip_cdir_free(cd); + return NULL; + } + } + else { + cd_buffer = NULL; + + if (zip_source_seek(za->src, (zip_int64_t)cd->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + _zip_cdir_free(cd); + return NULL; + } + + /* possible consistency check: cd->offset = len-(cd->size+cd->comment_len+EOCDLEN) ? */ + if (zip_source_tell(za->src) != (zip_int64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + _zip_cdir_free(cd); + return NULL; + } + } + + left = (zip_uint64_t)cd->size; + i = 0; + while (left > 0) { + bool grown = false; + zip_int64_t entry_size; + + if (i == cd->nentry) { + /* InfoZIP has a hack to avoid using Zip64: it stores nentries % 0x10000 */ + /* This hack isn't applicable if we're using Zip64, or if there is no central directory entry following. */ + + if (cd->is_zip64 || left < CDENTRYSIZE) { + break; + } + + if (!_zip_cdir_grow(cd, 0x10000, error)) { + _zip_cdir_free(cd); + _zip_buffer_free(cd_buffer); + return NULL; + } + grown = true; + } + + if ((cd->entry[i].orig = _zip_dirent_new()) == NULL || (entry_size = _zip_dirent_read(cd->entry[i].orig, za->src, cd_buffer, false, error)) < 0) { + if (grown && zip_error_code_zip(error) == ZIP_ER_NOZIP) { + zip_error_set(error, ZIP_ER_INCONS, 0); + } + _zip_cdir_free(cd); + _zip_buffer_free(cd_buffer); + return NULL; + } + i++; + left -= (zip_uint64_t)entry_size; + } + + if (i != cd->nentry || left > 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(cd_buffer); + _zip_cdir_free(cd); + return NULL; + } + + if (za->open_flags & ZIP_CHECKCONS) { + bool ok; + + if (cd_buffer) { + ok = _zip_buffer_eof(cd_buffer); + } + else { + zip_int64_t offset = zip_source_tell(za->src); + + if (offset < 0) { + _zip_error_set_from_source(error, za->src); + _zip_cdir_free(cd); + return NULL; + } + ok = ((zip_uint64_t)offset == cd->offset + cd->size); + } + + if (!ok) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_buffer_free(cd_buffer); + _zip_cdir_free(cd); + return NULL; + } + } + + _zip_buffer_free(cd_buffer); + return cd; +} + + +/* _zip_checkcons: + Checks the consistency of the central directory by comparing central + directory entries with local headers and checking for plausible + file and header offsets. Returns -1 if not plausible, else the + difference between the lowest and the highest fileposition reached */ + +static zip_int64_t +_zip_checkcons(zip_t *za, zip_cdir_t *cd, zip_error_t *error) { + zip_uint64_t i; + zip_uint64_t min, max, j; + struct zip_dirent temp; + + _zip_dirent_init(&temp); + if (cd->nentry) { + max = cd->entry[0].orig->offset; + min = cd->entry[0].orig->offset; + } + else + min = max = 0; + + for (i = 0; i < cd->nentry; i++) { + if (cd->entry[i].orig->offset < min) + min = cd->entry[i].orig->offset; + if (min > (zip_uint64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + + j = cd->entry[i].orig->offset + cd->entry[i].orig->comp_size + _zip_string_length(cd->entry[i].orig->filename) + LENTRYSIZE; + if (j > max) + max = j; + if (max > (zip_uint64_t)cd->offset) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return -1; + } + + if (zip_source_seek(za->src, (zip_int64_t)cd->entry[i].orig->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, za->src); + return -1; + } + + if (_zip_dirent_read(&temp, za->src, NULL, true, error) == -1) { + _zip_dirent_finalize(&temp); + return -1; + } + + if (_zip_headercomp(cd->entry[i].orig, &temp) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + _zip_dirent_finalize(&temp); + return -1; + } + + cd->entry[i].orig->extra_fields = _zip_ef_merge(cd->entry[i].orig->extra_fields, temp.extra_fields); + cd->entry[i].orig->local_extra_fields_read = 1; + temp.extra_fields = NULL; + + _zip_dirent_finalize(&temp); + } + + return (max - min) < ZIP_INT64_MAX ? (zip_int64_t)(max - min) : ZIP_INT64_MAX; +} + + +/* _zip_headercomp: + compares a central directory entry and a local file header + Return 0 if they are consistent, -1 if not. */ + +static int +_zip_headercomp(const zip_dirent_t *central, const zip_dirent_t *local) { + if ((central->version_needed < local->version_needed) +#if 0 + /* some zip-files have different values in local + and global headers for the bitflags */ + || (central->bitflags != local->bitflags) +#endif + || (central->comp_method != local->comp_method) || (central->last_mod != local->last_mod) || !_zip_string_equal(central->filename, local->filename)) + return -1; + + if ((central->crc != local->crc) || (central->comp_size != local->comp_size) || (central->uncomp_size != local->uncomp_size)) { + /* InfoZip stores valid values in local header even when data descriptor is used. + This is in violation of the appnote. */ + if (((local->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local->crc != 0 || local->comp_size != 0 || local->uncomp_size != 0)) + return -1; + } + + return 0; +} + + +static zip_t * +_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error) { + zip_t *za; + + if ((za = _zip_new(error)) == NULL) { + return NULL; + } + + za->src = src; + za->open_flags = flags; + if (flags & ZIP_RDONLY) { + za->flags |= ZIP_AFL_RDONLY; + za->ch_flags |= ZIP_AFL_RDONLY; + } + return za; +} + + +/* + * tests for file existence + */ +static exists_t +_zip_file_exists(zip_source_t *src, zip_error_t *error) { + struct zip_stat st; + + zip_stat_init(&st); + if (zip_source_stat(src, &st) != 0) { + zip_error_t *src_error = zip_source_error(src); + if (zip_error_code_zip(src_error) == ZIP_ER_READ && zip_error_code_system(src_error) == ENOENT) { + return EXISTS_NOT; + } + _zip_error_copy(error, src_error); + return EXISTS_ERROR; + } + + return (st.valid & ZIP_STAT_SIZE) && st.size == 0 ? EXISTS_EMPTY : EXISTS_NONEMPTY; +} + + +static zip_cdir_t * +_zip_find_central_dir(zip_t *za, zip_uint64_t len) { + zip_cdir_t *cdir, *cdirnew; + zip_uint8_t *match; + zip_int64_t buf_offset; + zip_uint64_t buflen; + zip_int64_t a; + zip_int64_t best; + zip_error_t error; + zip_buffer_t *buffer; + + if (len < EOCDLEN) { + zip_error_set(&za->error, ZIP_ER_NOZIP, 0); + return NULL; + } + + buflen = (len < CDBUFSIZE ? len : CDBUFSIZE); + if (zip_source_seek(za->src, -(zip_int64_t)buflen, SEEK_END) < 0) { + zip_error_t *src_error = zip_source_error(za->src); + if (zip_error_code_zip(src_error) != ZIP_ER_SEEK || zip_error_code_system(src_error) != EFBIG) { + /* seek before start of file on my machine */ + _zip_error_copy(&za->error, src_error); + return NULL; + } + } + if ((buf_offset = zip_source_tell(za->src)) < 0) { + _zip_error_set_from_source(&za->error, za->src); + return NULL; + } + + if ((buffer = _zip_buffer_new_from_source(za->src, buflen, NULL, &za->error)) == NULL) { + return NULL; + } + + best = -1; + cdir = NULL; + if (buflen >= CDBUFSIZE) { + /* EOCD64 locator is before EOCD, so leave place for it */ + _zip_buffer_set_offset(buffer, EOCD64LOCLEN); + } + zip_error_set(&error, ZIP_ER_NOZIP, 0); + + match = _zip_buffer_get(buffer, 0); + while ((match = _zip_memmem(match, _zip_buffer_left(buffer) - (EOCDLEN - 4), (const unsigned char *)EOCD_MAGIC, 4)) != NULL) { + _zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer))); + if ((cdirnew = _zip_read_cdir(za, buffer, (zip_uint64_t)buf_offset, &error)) != NULL) { + if (cdir) { + if (best <= 0) { + best = _zip_checkcons(za, cdir, &error); + } + + a = _zip_checkcons(za, cdirnew, &error); + if (best < a) { + _zip_cdir_free(cdir); + cdir = cdirnew; + best = a; + } + else { + _zip_cdir_free(cdirnew); + } + } + else { + cdir = cdirnew; + if (za->open_flags & ZIP_CHECKCONS) + best = _zip_checkcons(za, cdir, &error); + else { + best = 0; + } + } + cdirnew = NULL; + } + + match++; + _zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer))); + } + + _zip_buffer_free(buffer); + + if (best < 0) { + _zip_error_copy(&za->error, &error); + _zip_cdir_free(cdir); + return NULL; + } + + return cdir; +} + + +static unsigned char * +_zip_memmem(const unsigned char *big, size_t biglen, const unsigned char *little, size_t littlelen) { + const unsigned char *p; + + if ((biglen < littlelen) || (littlelen == 0)) + return NULL; + p = big - 1; + while ((p = (const unsigned char *)memchr(p + 1, little[0], (size_t)(big - (p + 1)) + (size_t)(biglen - littlelen) + 1)) != NULL) { + if (memcmp(p + 1, little + 1, littlelen - 1) == 0) + return (unsigned char *)p; + } + + return NULL; +} + + +static zip_cdir_t * +_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint64_t i, nentry, size, offset, eocd_offset; + + if (_zip_buffer_left(buffer) < EOCDLEN) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + eocd_offset = _zip_buffer_offset(buffer); + + _zip_buffer_get(buffer, 4); /* magic already verified */ + + if (_zip_buffer_get_32(buffer) != 0) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + return NULL; + } + + /* number of cdir-entries on this disk */ + i = _zip_buffer_get_16(buffer); + /* number of cdir-entries */ + nentry = _zip_buffer_get_16(buffer); + + if (nentry != i) { + zip_error_set(error, ZIP_ER_NOZIP, 0); + return NULL; + } + + size = _zip_buffer_get_32(buffer); + offset = _zip_buffer_get_32(buffer); + + if (offset + size < offset) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + + if (offset + size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((flags & ZIP_CHECKCONS) && offset + size != buf_offset + eocd_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((cd = _zip_cdir_new(nentry, error)) == NULL) + return NULL; + + cd->is_zip64 = false; + cd->size = size; + cd->offset = offset; + + return cd; +} + + +static zip_cdir_t * +_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error) { + zip_cdir_t *cd; + zip_uint64_t offset; + zip_uint8_t eocd[EOCD64LEN]; + zip_uint64_t eocd_offset; + zip_uint64_t size, nentry, i, eocdloc_offset; + bool free_buffer; + zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64; + + eocdloc_offset = _zip_buffer_offset(buffer); + + _zip_buffer_get(buffer, 4); /* magic already verified */ + + num_disks = _zip_buffer_get_16(buffer); + eocd_disk = _zip_buffer_get_16(buffer); + eocd_offset = _zip_buffer_get_64(buffer); + + if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + + if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) { + _zip_buffer_set_offset(buffer, eocd_offset - buf_offset); + free_buffer = false; + } + else { + if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) { + _zip_error_set_from_source(error, src); + return NULL; + } + if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) { + return NULL; + } + free_buffer = true; + } + + if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + size = _zip_buffer_get_64(buffer); + + if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + _zip_buffer_get(buffer, 4); /* skip version made by/needed */ + + num_disks64 = _zip_buffer_get_32(buffer); + eocd_disk64 = _zip_buffer_get_32(buffer); + + /* if eocd values are 0xffff, we have to use eocd64 values. + otherwise, if the values are not the same, it's inconsistent; + in any case, if the value is not 0, we don't support it */ + if (num_disks == 0xffff) { + num_disks = num_disks64; + } + if (eocd_disk == 0xffff) { + eocd_disk = eocd_disk64; + } + if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) { + zip_error_set(error, ZIP_ER_INCONS, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + if (num_disks != 0 || eocd_disk != 0) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + nentry = _zip_buffer_get_64(buffer); + i = _zip_buffer_get_64(buffer); + + if (nentry != i) { + zip_error_set(error, ZIP_ER_MULTIDISK, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + size = _zip_buffer_get_64(buffer); + offset = _zip_buffer_get_64(buffer); + + if (!_zip_buffer_ok(buffer)) { + zip_error_set(error, ZIP_ER_INTERNAL, 0); + if (free_buffer) { + _zip_buffer_free(buffer); + } + return NULL; + } + + if (free_buffer) { + _zip_buffer_free(buffer); + } + + if (offset > ZIP_INT64_MAX || offset + size < offset) { + zip_error_set(error, ZIP_ER_SEEK, EFBIG); + return NULL; + } + if (offset + size > buf_offset + eocd_offset) { + /* cdir spans past EOCD record */ + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + if ((flags & ZIP_CHECKCONS) && offset + size != buf_offset + eocd_offset) { + zip_error_set(error, ZIP_ER_INCONS, 0); + return NULL; + } + + if ((cd = _zip_cdir_new(nentry, error)) == NULL) + return NULL; + + cd->is_zip64 = true; + cd->size = size; + cd->offset = offset; + + return cd; +} diff --git a/third_party/libzip/lib/zip_progress.c b/third_party/libzip/lib/zip_progress.c new file mode 100644 index 0000000..9b11694 --- /dev/null +++ b/third_party/libzip/lib/zip_progress.c @@ -0,0 +1,183 @@ +/* + zip_progress.c -- progress reporting + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + +struct zip_progress { + zip_t *za; + zip_progress_callback callback; + void (*ud_free)(void *); + + void *ud; + + double precision; + + /* state */ + double last_update; /* last value callback function was called with */ + + double start; /* start of sub-progress section */ + double end; /* end of sub-progress section */ +}; + + +void +_zip_progress_end(zip_progress_t *progress) { + _zip_progress_update(progress, 1.0); +} + + +void +_zip_progress_free(zip_progress_t *progress) { + if (progress == NULL) { + return; + } + + if (progress->ud_free) { + progress->ud_free(progress->ud); + } + + free(progress); +} + + +zip_progress_t * +_zip_progress_new(zip_t *za, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) { + zip_progress_t *progress = (zip_progress_t *)malloc(sizeof(*progress)); + + if (progress == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + progress->za = za; + progress->callback = callback; + progress->ud_free = ud_free; + progress->ud = ud; + progress->precision = precision; + + return progress; +} + + +void +_zip_progress_start(zip_progress_t *progress) { + if (progress == NULL) { + return; + } + + progress->last_update = 0.0; + progress->callback(progress->za, 0.0, progress->ud); +} + + +void +_zip_progress_subrange(zip_progress_t *progress, double start, double end) { + if (progress == NULL) { + return; + } + + progress->start = start; + progress->end = end; + + _zip_progress_update(progress, 0.0); +} + +void +_zip_progress_update(zip_progress_t *progress, double sub_current) { + double current; + + if (progress == NULL) { + return; + } + + current = ZIP_MIN(ZIP_MAX(sub_current, 0.0), 1.0) * (progress->end - progress->start) + progress->start; + + if (current - progress->last_update > progress->precision) { + progress->callback(progress->za, current, progress->ud); + progress->last_update = current; + } +} + + +ZIP_EXTERN int +zip_register_progress_callback_with_state(zip_t *za, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud) { + zip_progress_t *progress = NULL; + + if (callback != NULL) { + if ((progress = _zip_progress_new(za, precision, callback, ud_free, ud)) == NULL) { + return -1; + } + } + + _zip_progress_free(za->progress); + za->progress = progress; + + return 0; +} + + +struct legacy_ud { + zip_progress_callback_t callback; +}; + + +static void +_zip_legacy_progress_callback(zip_t *za, double progress, void *vud) { + struct legacy_ud *ud = (struct legacy_ud *)vud; + + ud->callback(progress); +} + +ZIP_EXTERN void +zip_register_progress_callback(zip_t *za, zip_progress_callback_t progress_callback) { + struct legacy_ud *ud; + + if (progress_callback == NULL) { + zip_register_progress_callback_with_state(za, 0, NULL, NULL, NULL); + } + + if ((ud = (struct legacy_ud *)malloc(sizeof(*ud))) == NULL) { + return; + } + + ud->callback = progress_callback; + + if (zip_register_progress_callback_with_state(za, 0.001, _zip_legacy_progress_callback, free, ud) < 0) { + free(ud); + } +} diff --git a/third_party/libzip/lib/zip_random_unix.c b/third_party/libzip/lib/zip_random_unix.c new file mode 100644 index 0000000..8e289df --- /dev/null +++ b/third_party/libzip/lib/zip_random_unix.c @@ -0,0 +1,54 @@ +/* + zip_random_unix.c -- fill the user's buffer with random stuff (Unix version) + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + int fd; + + if ((fd = open("/dev/urandom", O_RDONLY)) < 0) { + return false; + } + + if (read(fd, buffer, length) != length) { + close(fd); + return false; + } + + close(fd); + return true; +} diff --git a/third_party/libzip/lib/zip_random_uwp.c b/third_party/libzip/lib/zip_random_uwp.c new file mode 100644 index 0000000..42b96a0 --- /dev/null +++ b/third_party/libzip/lib/zip_random_uwp.c @@ -0,0 +1,54 @@ +/* + zip_random_uwp.c -- fill the user's buffer with random stuff (UWP version) + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#include "zipint.h" +#include "zipwin32.h" + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + BCRYPT_ALG_HANDLE hAlg = NULL; + NTSTATUS hr = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_RNG_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0); + if (hr != STATUS_SUCCESS || hAlg == NULL) { + return false; + } + hr = BCryptGenRandom(&hAlg, buffer, length, 0); + BCryptCloseAlgorithmProvider(&hAlg, 0); + if (hr != STATUS_SUCCESS) { + return false; + } + return true; +} diff --git a/third_party/libzip/lib/zip_random_win32.c b/third_party/libzip/lib/zip_random_win32.c new file mode 100644 index 0000000..3b92978 --- /dev/null +++ b/third_party/libzip/lib/zip_random_win32.c @@ -0,0 +1,52 @@ +/* + zip_random_win32.c -- fill the user's buffer with random stuff (Windows version) + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" +#include "zipwin32.h" + +#include + +ZIP_EXTERN bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + HCRYPTPROV hprov; + if (!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + return false; + } + if (!CryptGenRandom(hprov, length, buffer)) { + return false; + } + if (!CryptReleaseContext(hprov, 0)) { + return false; + } + return true; +} diff --git a/third_party/libzip/lib/zip_rename.c b/third_party/libzip/lib/zip_rename.c new file mode 100644 index 0000000..4fdf636 --- /dev/null +++ b/third_party/libzip/lib/zip_rename.c @@ -0,0 +1,44 @@ +/* + zip_rename.c -- rename file in zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_rename(zip_t *za, zip_uint64_t idx, const char *name) { + return zip_file_rename(za, idx, name, 0); +} diff --git a/third_party/libzip/lib/zip_replace.c b/third_party/libzip/lib/zip_replace.c new file mode 100644 index 0000000..2e982af --- /dev/null +++ b/third_party/libzip/lib/zip_replace.c @@ -0,0 +1,42 @@ +/* + zip_replace.c -- replace file via callback function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_replace(zip_t *za, zip_uint64_t idx, zip_source_t *source) { + return zip_file_replace(za, idx, source, 0); +} diff --git a/third_party/libzip/lib/zip_set_archive_comment.c b/third_party/libzip/lib/zip_set_archive_comment.c new file mode 100644 index 0000000..166a2c0 --- /dev/null +++ b/third_party/libzip/lib/zip_set_archive_comment.c @@ -0,0 +1,80 @@ +/* + zip_set_archive_comment.c -- set archive comment + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_set_archive_comment(zip_t *za, const char *comment, zip_uint16_t len) { + zip_string_t *cstr; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (len > 0 && comment == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (len > 0) { + if ((cstr = _zip_string_new((const zip_uint8_t *)comment, len, ZIP_FL_ENC_GUESS, &za->error)) == NULL) + return -1; + + if (_zip_guess_encoding(cstr, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_CP437) { + _zip_string_free(cstr); + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + } + else + cstr = NULL; + + _zip_string_free(za->comment_changes); + za->comment_changes = NULL; + + if (((za->comment_orig && _zip_string_equal(za->comment_orig, cstr)) || (za->comment_orig == NULL && cstr == NULL))) { + _zip_string_free(cstr); + za->comment_changed = 0; + } + else { + za->comment_changes = cstr; + za->comment_changed = 1; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_set_archive_flag.c b/third_party/libzip/lib/zip_set_archive_flag.c new file mode 100644 index 0000000..facf614 --- /dev/null +++ b/third_party/libzip/lib/zip_set_archive_flag.c @@ -0,0 +1,65 @@ +/* + zip_get_archive_flag.c -- set archive global flag + Copyright (C) 2008-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_archive_flag(zip_t *za, zip_flags_t flag, int value) { + unsigned int new_flags; + + if (value) + new_flags = za->ch_flags | flag; + else + new_flags = za->ch_flags & ~flag; + + if (new_flags == za->ch_flags) + return 0; + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if ((flag & ZIP_AFL_RDONLY) && value && (za->ch_flags & ZIP_AFL_RDONLY) == 0) { + if (_zip_changed(za, NULL)) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return -1; + } + } + + za->ch_flags = new_flags; + + return 0; +} diff --git a/third_party/libzip/lib/zip_set_default_password.c b/third_party/libzip/lib/zip_set_default_password.c new file mode 100644 index 0000000..8081657 --- /dev/null +++ b/third_party/libzip/lib/zip_set_default_password.c @@ -0,0 +1,58 @@ +/* + zip_set_default_password.c -- set default password for decryption + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +ZIP_EXTERN int +zip_set_default_password(zip_t *za, const char *passwd) { + if (za == NULL) + return -1; + + free(za->default_password); + + if (passwd) { + if ((za->default_password = strdup(passwd)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + else + za->default_password = NULL; + + return 0; +} diff --git a/third_party/libzip/lib/zip_set_file_comment.c b/third_party/libzip/lib/zip_set_file_comment.c new file mode 100644 index 0000000..e4e0331 --- /dev/null +++ b/third_party/libzip/lib/zip_set_file_comment.c @@ -0,0 +1,48 @@ +/* + zip_set_file_comment.c -- set comment for file in archive + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#define _ZIP_COMPILING_DEPRECATED +#include "zipint.h" + + +ZIP_EXTERN int +zip_set_file_comment(zip_t *za, zip_uint64_t idx, const char *comment, int len) { + if (len < 0 || len > ZIP_UINT16_MAX) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + return zip_file_set_comment(za, idx, comment, (zip_uint16_t)len, 0); +} diff --git a/third_party/libzip/lib/zip_set_file_compression.c b/third_party/libzip/lib/zip_set_file_compression.c new file mode 100644 index 0000000..054dd1f --- /dev/null +++ b/third_party/libzip/lib/zip_set_file_compression.c @@ -0,0 +1,91 @@ +/* + zip_set_file_compression.c -- set compression for file in archive + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_set_file_compression(zip_t *za, zip_uint64_t idx, zip_int32_t method, zip_uint32_t flags) { + zip_entry_t *e; + zip_int32_t old_method; + + if (idx >= za->nentry || flags > 9) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (!zip_compression_method_supported(method, true)) { + zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0); + return -1; + } + + e = za->entry + idx; + + old_method = (e->orig == NULL ? ZIP_CM_DEFAULT : e->orig->comp_method); + + /* TODO: do we want to recompress if level is set? Only if it's + * different than what bit flags tell us, but those are not + * defined for all compression methods, or not directly mappable + * to levels */ + + if (method == old_method) { + if (e->changes) { + e->changes->changed &= ~ZIP_DIRENT_COMP_METHOD; + e->changes->compression_level = 0; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + } + } + else { + if (e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + e->changes->comp_method = method; + e->changes->compression_level = (zip_uint16_t)flags; + e->changes->changed |= ZIP_DIRENT_COMP_METHOD; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_set_name.c b/third_party/libzip/lib/zip_set_name.c new file mode 100644 index 0000000..aa1dd8e --- /dev/null +++ b/third_party/libzip/lib/zip_set_name.c @@ -0,0 +1,157 @@ +/* + zip_set_name.c -- rename helper function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +int +_zip_set_name(zip_t *za, zip_uint64_t idx, const char *name, zip_flags_t flags) { + zip_entry_t *e; + zip_string_t *str; + bool same_as_orig; + zip_int64_t i; + const zip_uint8_t *old_name, *new_name; + zip_string_t *old_str; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (ZIP_IS_RDONLY(za)) { + zip_error_set(&za->error, ZIP_ER_RDONLY, 0); + return -1; + } + + if (name && name[0] != '\0') { + /* TODO: check for string too long */ + if ((str = _zip_string_new((const zip_uint8_t *)name, (zip_uint16_t)strlen(name), flags, &za->error)) == NULL) + return -1; + if ((flags & ZIP_FL_ENCODING_ALL) == ZIP_FL_ENC_GUESS && _zip_guess_encoding(str, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_UTF8_GUESSED) + str->encoding = ZIP_ENCODING_UTF8_KNOWN; + } + else + str = NULL; + + /* TODO: encoding flags needed for CP437? */ + if ((i = _zip_name_locate(za, name, 0, NULL)) >= 0 && (zip_uint64_t)i != idx) { + _zip_string_free(str); + zip_error_set(&za->error, ZIP_ER_EXISTS, 0); + return -1; + } + + /* no effective name change */ + if (i >= 0 && (zip_uint64_t)i == idx) { + _zip_string_free(str); + return 0; + } + + e = za->entry + idx; + + if (e->orig) + same_as_orig = _zip_string_equal(e->orig->filename, str); + else + same_as_orig = false; + + if (!same_as_orig && e->changes == NULL) { + if ((e->changes = _zip_dirent_clone(e->orig)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + _zip_string_free(str); + return -1; + } + } + + if ((new_name = _zip_string_get(same_as_orig ? e->orig->filename : str, NULL, 0, &za->error)) == NULL) { + _zip_string_free(str); + return -1; + } + + if (e->changes) { + old_str = e->changes->filename; + } + else if (e->orig) { + old_str = e->orig->filename; + } + else { + old_str = NULL; + } + + if (old_str) { + if ((old_name = _zip_string_get(old_str, NULL, 0, &za->error)) == NULL) { + _zip_string_free(str); + return -1; + } + } + else { + old_name = NULL; + } + + if (_zip_hash_add(za->names, new_name, idx, 0, &za->error) == false) { + _zip_string_free(str); + return -1; + } + if (old_name) { + _zip_hash_delete(za->names, old_name, NULL); + } + + if (same_as_orig) { + if (e->changes) { + if (e->changes->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(e->changes->filename); + e->changes->changed &= ~ZIP_DIRENT_FILENAME; + if (e->changes->changed == 0) { + _zip_dirent_free(e->changes); + e->changes = NULL; + } + else { + /* TODO: what if not cloned? can that happen? */ + e->changes->filename = e->orig->filename; + } + } + } + _zip_string_free(str); + } + else { + if (e->changes->changed & ZIP_DIRENT_FILENAME) { + _zip_string_free(e->changes->filename); + } + e->changes->changed |= ZIP_DIRENT_FILENAME; + e->changes->filename = str; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_begin_write.c b/third_party/libzip/lib/zip_source_begin_write.c new file mode 100644 index 0000000..a8b90b5 --- /dev/null +++ b/third_party/libzip/lib/zip_source_begin_write.c @@ -0,0 +1,52 @@ +/* + zip_source_begin_write.c -- start a new file for writing + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_begin_write(zip_source_t *src) { + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_BEGIN_WRITE) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_OPEN; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_begin_write_cloning.c b/third_party/libzip/lib/zip_source_begin_write_cloning.c new file mode 100644 index 0000000..b38de04 --- /dev/null +++ b/third_party/libzip/lib/zip_source_begin_write_cloning.c @@ -0,0 +1,52 @@ +/* + zip_source_begin_write_cloning.c -- clone part of file for writing + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_begin_write_cloning(zip_source_t *src, zip_uint64_t offset) { + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (_zip_source_call(src, NULL, offset, ZIP_SOURCE_BEGIN_WRITE_CLONING) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_OPEN; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_buffer.c b/third_party/libzip/lib/zip_source_buffer.c new file mode 100644 index 0000000..119bc02 --- /dev/null +++ b/third_party/libzip/lib/zip_source_buffer.c @@ -0,0 +1,579 @@ +/* + zip_source_buffer.c -- create zip data source from buffer + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +#ifndef WRITE_FRAGMENT_SIZE +#define WRITE_FRAGMENT_SIZE (64 * 1024) +#endif + +struct buffer { + zip_buffer_fragment_t *fragments; /* fragments */ + zip_uint64_t *fragment_offsets; /* offset of each fragment from start of buffer, nfragments+1 entries */ + zip_uint64_t nfragments; /* number of allocated fragments */ + zip_uint64_t fragments_capacity; /* size of fragments (number of pointers) */ + + zip_uint64_t first_owned_fragment; /* first fragment to free data from */ + + zip_uint64_t shared_fragments; /* number of shared fragments */ + struct buffer *shared_buffer; /* buffer fragments are shared with */ + zip_uint64_t size; /* size of buffer */ + + zip_uint64_t offset; /* current offset in buffer */ + zip_uint64_t current_fragment; /* fragment current offset is in */ +}; + +typedef struct buffer buffer_t; + +struct read_data { + zip_error_t error; + time_t mtime; + buffer_t *in; + buffer_t *out; +}; + +#define buffer_capacity(buffer) ((buffer)->fragment_offsets[(buffer)->nfragments]) +#define buffer_size(buffer) ((buffer)->size) + +static buffer_t *buffer_clone(buffer_t *buffer, zip_uint64_t length, zip_error_t *error); +static zip_uint64_t buffer_find_fragment(const buffer_t *buffer, zip_uint64_t offset); +static void buffer_free(buffer_t *buffer); +static bool buffer_grow_fragments(buffer_t *buffer, zip_uint64_t capacity, zip_error_t *error); +static buffer_t *buffer_new(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int free_data, zip_error_t *error); +static zip_int64_t buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length); +static int buffer_seek(buffer_t *buffer, void *data, zip_uint64_t len, zip_error_t *error); +static zip_int64_t buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *); + +static zip_int64_t read_data(void *, void *, zip_uint64_t, zip_source_cmd_t); + + +ZIP_EXTERN zip_source_t * +zip_source_buffer(zip_t *za, const void *data, zip_uint64_t len, int freep) { + if (za == NULL) + return NULL; + + return zip_source_buffer_create(data, len, freep, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_create(const void *data, zip_uint64_t len, int freep, zip_error_t *error) { + zip_buffer_fragment_t fragment; + + if (data == NULL && len > 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + fragment.data = (zip_uint8_t *)data; + fragment.length = len; + + return zip_source_buffer_fragment_create(&fragment, 1, freep, error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_fragment(zip_t *za, const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep) { + if (za == NULL) { + return NULL; + } + + return zip_source_buffer_fragment_create(fragments, nfragments, freep, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_buffer_fragment_create(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int freep, zip_error_t *error) { + struct read_data *ctx; + zip_source_t *zs; + buffer_t *buffer; + + if (fragments == NULL && nfragments > 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((buffer = buffer_new(fragments, nfragments, freep, error)) == NULL) { + return NULL; + } + + if ((ctx = (struct read_data *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + buffer_free(buffer); + return NULL; + } + + ctx->in = buffer; + ctx->out = NULL; + ctx->mtime = time(NULL); + zip_error_init(&ctx->error); + + if ((zs = zip_source_function_create(read_data, ctx, error)) == NULL) { + buffer_free(ctx->in); + free(ctx); + return NULL; + } + + return zs; +} + + +static zip_int64_t +read_data(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct read_data *ctx = (struct read_data *)state; + + switch (cmd) { + case ZIP_SOURCE_BEGIN_WRITE: + if ((ctx->out = buffer_new(NULL, 0, 0, &ctx->error)) == NULL) { + return -1; + } + ctx->out->offset = 0; + ctx->out->current_fragment = 0; + return 0; + + case ZIP_SOURCE_BEGIN_WRITE_CLONING: + if ((ctx->out = buffer_clone(ctx->in, len, &ctx->error)) == NULL) { + return -1; + } + ctx->out->offset = len; + ctx->out->current_fragment = ctx->out->nfragments; + return 0; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_COMMIT_WRITE: + buffer_free(ctx->in); + ctx->in = ctx->out; + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + buffer_free(ctx->in); + buffer_free(ctx->out); + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + ctx->in->offset = 0; + ctx->in->current_fragment = 0; + return 0; + + case ZIP_SOURCE_READ: + if (len > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + return buffer_read(ctx->in, data, len); + + case ZIP_SOURCE_REMOVE: { + buffer_t *empty = buffer_new(NULL, 0, 0, &ctx->error); + if (empty == NULL) { + return -1; + } + + buffer_free(ctx->in); + ctx->in = empty; + return 0; + } + + case ZIP_SOURCE_ROLLBACK_WRITE: + buffer_free(ctx->out); + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_SEEK: + return buffer_seek(ctx->in, data, len, &ctx->error); + + case ZIP_SOURCE_SEEK_WRITE: + return buffer_seek(ctx->out, data, len, &ctx->error); + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + if (len < sizeof(*st)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + st = (zip_stat_t *)data; + + zip_stat_init(st); + st->mtime = ctx->mtime; + st->size = ctx->in->size; + st->comp_size = st->size; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; + st->valid = ZIP_STAT_MTIME | ZIP_STAT_SIZE | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + + return sizeof(*st); + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_BEGIN_WRITE_CLONING, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_REMOVE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_WRITE, -1); + + case ZIP_SOURCE_TELL: + if (ctx->in->offset > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_TELL, EOVERFLOW); + return -1; + } + return (zip_int64_t)ctx->in->offset; + + + case ZIP_SOURCE_TELL_WRITE: + if (ctx->out->offset > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_TELL, EOVERFLOW); + return -1; + } + return (zip_int64_t)ctx->out->offset; + + case ZIP_SOURCE_WRITE: + if (len > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + return buffer_write(ctx->out, data, len, &ctx->error); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +static buffer_t * +buffer_clone(buffer_t *buffer, zip_uint64_t offset, zip_error_t *error) { + zip_uint64_t fragment, fragment_offset, waste; + buffer_t *clone; + + if (offset == 0) { + return buffer_new(NULL, 0, 1, error); + } + + if (offset > buffer->size) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if (buffer->shared_buffer != NULL) { + zip_error_set(error, ZIP_ER_INUSE, 0); + return NULL; + } + + fragment = buffer_find_fragment(buffer, offset); + fragment_offset = offset - buffer->fragment_offsets[fragment]; + + if (fragment_offset == 0) { + fragment--; + fragment_offset = buffer->fragments[fragment].length; + } + + waste = buffer->fragments[fragment].length - fragment_offset; + if (waste > offset) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + + if ((clone = buffer_new(buffer->fragments, fragment + 1, 0, error)) == NULL) { + return NULL; + } + +#ifndef __clang_analyzer__ + /* clone->fragments can't be null, since it was created with at least one fragment */ + clone->fragments[clone->nfragments - 1].length = fragment_offset; +#endif + clone->fragment_offsets[clone->nfragments] = offset; + clone->size = offset; + + clone->first_owned_fragment = ZIP_MIN(buffer->first_owned_fragment, clone->nfragments - 1); + + buffer->shared_buffer = clone; + clone->shared_buffer = buffer; + buffer->shared_fragments = clone->nfragments; + clone->shared_fragments = fragment + 1; + + return clone; +} + + +static zip_uint64_t +buffer_find_fragment(const buffer_t *buffer, zip_uint64_t offset) { + zip_uint64_t low, high, mid; + + low = 0; + high = buffer->nfragments - 1; + + while (low < high) { + mid = (high - low) / 2 + low; + if (buffer->fragment_offsets[mid] > offset) { + high = mid - 1; + } + else if (mid == buffer->nfragments || buffer->fragment_offsets[mid + 1] > offset) { + return mid; + } + else { + low = mid + 1; + } + } + + return low; +} + + +static void +buffer_free(buffer_t *buffer) { + zip_uint64_t i; + + if (buffer == NULL) { + return; + } + + if (buffer->shared_buffer != NULL) { + buffer->shared_buffer->shared_buffer = NULL; + buffer->shared_buffer->shared_fragments = 0; + + buffer->first_owned_fragment = ZIP_MAX(buffer->first_owned_fragment, buffer->shared_fragments); + } + + for (i = buffer->first_owned_fragment; i < buffer->nfragments; i++) { + free(buffer->fragments[i].data); + } + free(buffer->fragments); + free(buffer->fragment_offsets); + free(buffer); +} + + +static bool +buffer_grow_fragments(buffer_t *buffer, zip_uint64_t capacity, zip_error_t *error) { + zip_buffer_fragment_t *fragments; + zip_uint64_t *offsets; + + if (capacity < buffer->fragments_capacity) { + return true; + } + + if ((fragments = realloc(buffer->fragments, sizeof(buffer->fragments[0]) * capacity)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + buffer->fragments = fragments; + if ((offsets = realloc(buffer->fragment_offsets, sizeof(buffer->fragment_offsets[0]) * (capacity + 1))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return false; + } + buffer->fragment_offsets = offsets; + buffer->fragments_capacity = capacity; + + return true; +} + + +static buffer_t * +buffer_new(const zip_buffer_fragment_t *fragments, zip_uint64_t nfragments, int free_data, zip_error_t *error) { + buffer_t *buffer; + + if ((buffer = malloc(sizeof(*buffer))) == NULL) { + return NULL; + } + + buffer->offset = 0; + buffer->first_owned_fragment = 0; + buffer->size = 0; + buffer->fragments = NULL; + buffer->fragment_offsets = NULL; + buffer->nfragments = 0; + buffer->fragments_capacity = 0; + buffer->shared_buffer = NULL; + buffer->shared_fragments = 0; + + if (nfragments == 0) { + if ((buffer->fragment_offsets = malloc(sizeof(buffer->fragment_offsets[0]))) == NULL) { + free(buffer); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + buffer->fragment_offsets[0] = 0; + } + else { + zip_uint64_t i, j, offset; + + if (!buffer_grow_fragments(buffer, nfragments, NULL)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + buffer_free(buffer); + return NULL; + } + + offset = 0; + for (i = 0, j = 0; i < nfragments; i++) { + if (fragments[i].length == 0) { + continue; + } + if (fragments[i].data == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + buffer_free(buffer); + return NULL; + } + buffer->fragments[j].data = fragments[i].data; + buffer->fragments[j].length = fragments[i].length; + buffer->fragment_offsets[i] = offset; + offset += fragments[i].length; + j++; + } + buffer->nfragments = j; + buffer->first_owned_fragment = free_data ? 0 : buffer->nfragments; + buffer->fragment_offsets[nfragments] = offset; + buffer->size = offset; + } + + return buffer; +} + +static zip_int64_t +buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length) { + zip_uint64_t n, i, fragment_offset; + + length = ZIP_MIN(length, buffer->size - buffer->offset); + + if (length == 0) { + return 0; + } + if (length > ZIP_INT64_MAX) { + return -1; + } + + i = buffer->current_fragment; + fragment_offset = buffer->offset - buffer->fragment_offsets[i]; + n = 0; + while (n < length) { + zip_uint64_t left = ZIP_MIN(length - n, buffer->fragments[i].length - fragment_offset); + + memcpy(data + n, buffer->fragments[i].data + fragment_offset, left); + + if (left == buffer->fragments[i].length - fragment_offset) { + i++; + } + n += left; + fragment_offset = 0; + } + + buffer->offset += n; + buffer->current_fragment = i; + return (zip_int64_t)n; +} + + +static int +buffer_seek(buffer_t *buffer, void *data, zip_uint64_t len, zip_error_t *error) { + zip_int64_t new_offset = zip_source_seek_compute_offset(buffer->offset, buffer->size, data, len, error); + + if (new_offset < 0) { + return -1; + } + + buffer->offset = (zip_uint64_t)new_offset; + buffer->current_fragment = buffer_find_fragment(buffer, buffer->offset); + return 0; +} + + +static zip_int64_t +buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *error) { + zip_uint64_t n, i, fragment_offset, capacity; + + if (buffer->offset + length + WRITE_FRAGMENT_SIZE - 1 < length) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + /* grow buffer if needed */ + capacity = buffer_capacity(buffer); + if (buffer->offset + length > capacity) { + zip_uint64_t needed_fragments = buffer->nfragments + (length - (capacity - buffer->offset) + WRITE_FRAGMENT_SIZE - 1) / WRITE_FRAGMENT_SIZE; + + if (needed_fragments > buffer->fragments_capacity) { + zip_uint64_t new_capacity = buffer->fragments_capacity; + + if (new_capacity == 0) { + new_capacity = 16; + } + while (new_capacity < needed_fragments) { + new_capacity *= 2; + } + + if (!buffer_grow_fragments(buffer, new_capacity, error)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + } + + while (buffer->nfragments < needed_fragments) { + if ((buffer->fragments[buffer->nfragments].data = malloc(WRITE_FRAGMENT_SIZE)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + buffer->fragments[buffer->nfragments].length = WRITE_FRAGMENT_SIZE; + buffer->nfragments++; + capacity += WRITE_FRAGMENT_SIZE; + buffer->fragment_offsets[buffer->nfragments] = capacity; + } + } + + i = buffer->current_fragment; + fragment_offset = buffer->offset - buffer->fragment_offsets[i]; + n = 0; + while (n < length) { + zip_uint64_t left = ZIP_MIN(length - n, buffer->fragments[i].length - fragment_offset); + + memcpy(buffer->fragments[i].data + fragment_offset, data + n, left); + + if (left == buffer->fragments[i].length - fragment_offset) { + i++; + } + n += left; + fragment_offset = 0; + } + + buffer->offset += n; + buffer->current_fragment = i; + if (buffer->offset > buffer->size) { + buffer->size = buffer->offset; + } + + return (zip_int64_t)n; +} diff --git a/third_party/libzip/lib/zip_source_call.c b/third_party/libzip/lib/zip_source_call.c new file mode 100644 index 0000000..3f374fc --- /dev/null +++ b/third_party/libzip/lib/zip_source_call.c @@ -0,0 +1,68 @@ +/* + zip_source_call.c -- invoke callback command on zip_source + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_int64_t +_zip_source_call(zip_source_t *src, void *data, zip_uint64_t length, zip_source_cmd_t command) { + zip_int64_t ret; + + if ((src->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(command)) == 0) { + zip_error_set(&src->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + + if (src->src == NULL) { + ret = src->cb.f(src->ud, data, length, command); + } + else { + ret = src->cb.l(src->src, src->ud, data, length, command); + } + + if (ret < 0) { + if (command != ZIP_SOURCE_ERROR && command != ZIP_SOURCE_SUPPORTS) { + int e[2]; + + if (_zip_source_call(src, e, sizeof(e), ZIP_SOURCE_ERROR) < 0) { + zip_error_set(&src->error, ZIP_ER_INTERNAL, 0); + } + else { + zip_error_set(&src->error, e[0], e[1]); + } + } + } + + return ret; +} diff --git a/third_party/libzip/lib/zip_source_close.c b/third_party/libzip/lib/zip_source_close.c new file mode 100644 index 0000000..7916550 --- /dev/null +++ b/third_party/libzip/lib/zip_source_close.c @@ -0,0 +1,57 @@ +/* + zip_source_close.c -- close zip_source (stop reading) + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +int +zip_source_close(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_READING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + src->open_count--; + if (src->open_count == 0) { + _zip_source_call(src, NULL, 0, ZIP_SOURCE_CLOSE); + + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_close(src->src) < 0) { + zip_error_set(&src->error, ZIP_ER_INTERNAL, 0); + } + } + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_commit_write.c b/third_party/libzip/lib/zip_source_commit_write.c new file mode 100644 index 0000000..67881f0 --- /dev/null +++ b/third_party/libzip/lib/zip_source_commit_write.c @@ -0,0 +1,63 @@ +/* + zip_source_commit_write.c -- commit changes to file + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_commit_write(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (src->open_count > 1) { + zip_error_set(&src->error, ZIP_ER_INUSE, 0); + return -1; + } + else if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if (zip_source_close(src) < 0) { + return -1; + } + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_COMMIT_WRITE) < 0) { + src->write_state = ZIP_SOURCE_WRITE_FAILED; + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_CLOSED; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_compress.c b/third_party/libzip/lib/zip_source_compress.c new file mode 100644 index 0000000..d2ae220 --- /dev/null +++ b/third_party/libzip/lib/zip_source_compress.c @@ -0,0 +1,367 @@ +/* + zip_source_compress.c -- (de)compression routines + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#include "zipint.h" + +struct context { + zip_error_t error; + + bool end_of_input; + bool end_of_stream; + bool can_store; + bool is_stored; /* only valid if end_of_stream is true */ + bool compress; + zip_int32_t method; + + zip_uint64_t size; + zip_int64_t first_read; + zip_uint8_t buffer[BUFSIZE]; + + zip_compression_algorithm_t *algorithm; + void *ud; +}; + + +struct implementation { + zip_uint16_t method; + zip_compression_algorithm_t *compress; + zip_compression_algorithm_t *decompress; +}; + +static struct implementation implementations[] = { + {ZIP_CM_DEFLATE, &zip_algorithm_deflate_compress, &zip_algorithm_deflate_decompress}, +#if defined(HAVE_LIBBZ2) + {ZIP_CM_BZIP2, &zip_algorithm_bzip2_compress, &zip_algorithm_bzip2_decompress}, +#endif +}; + +static size_t implementations_size = sizeof(implementations) / sizeof(implementations[0]); + +static zip_source_t *compression_source_new(zip_t *za, zip_source_t *src, zip_int32_t method, bool compress, int compression_flags); +static zip_int64_t compress_callback(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); +static void context_free(struct context *ctx); +static struct context *context_new(zip_int32_t method, bool compress, int compression_flags, zip_compression_algorithm_t *algorithm); +static zip_int64_t compress_read(zip_source_t *, struct context *, void *, zip_uint64_t); + +static zip_compression_algorithm_t * +get_algorithm(zip_int32_t method, bool compress) { + size_t i; + zip_uint16_t real_method = ZIP_CM_ACTUAL(method); + + for (i = 0; i < implementations_size; i++) { + if (implementations[i].method == real_method) { + if (compress) { + return implementations[i].compress; + } + else { + return implementations[i].decompress; + } + } + } + + return NULL; +} + +bool +zip_compression_method_supported(zip_int32_t method, bool compress) { + if (method == ZIP_CM_STORE) { + return true; + } + return get_algorithm(method, compress) != NULL; +} + +zip_source_t * +zip_source_compress(zip_t *za, zip_source_t *src, zip_int32_t method, int compression_flags) { + return compression_source_new(za, src, method, true, compression_flags); +} + +zip_source_t * +zip_source_decompress(zip_t *za, zip_source_t *src, zip_int32_t method) { + return compression_source_new(za, src, method, false, 0); +} + + +static zip_source_t * +compression_source_new(zip_t *za, zip_source_t *src, zip_int32_t method, bool compress, int compression_flags) { + struct context *ctx; + zip_source_t *s2; + zip_compression_algorithm_t *algorithm = NULL; + + if (src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((algorithm = get_algorithm(method, compress)) == NULL) { + zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0); + return NULL; + } + + if ((ctx = context_new(method, compress, compression_flags, algorithm)) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((s2 = zip_source_layered(za, src, compress_callback, ctx)) == NULL) { + context_free(ctx); + return NULL; + } + + return s2; +} + + +static struct context * +context_new(zip_int32_t method, bool compress, int compression_flags, zip_compression_algorithm_t *algorithm) { + struct context *ctx; + + if ((ctx = (struct context *)malloc(sizeof(*ctx))) == NULL) { + return NULL; + } + zip_error_init(&ctx->error); + ctx->can_store = compress ? ZIP_CM_IS_DEFAULT(method) : false; + ctx->algorithm = algorithm; + ctx->method = method; + ctx->compress = compress; + ctx->end_of_input = false; + ctx->end_of_stream = false; + ctx->is_stored = false; + + if ((ctx->ud = ctx->algorithm->allocate(ZIP_CM_ACTUAL(method), compression_flags, &ctx->error)) == NULL) { + zip_error_fini(&ctx->error); + free(ctx); + return NULL; + } + + return ctx; +} + + +static void +context_free(struct context *ctx) { + if (ctx == NULL) { + return; + } + + ctx->algorithm->deallocate(ctx->ud); + zip_error_fini(&ctx->error); + + free(ctx); +} + + +static zip_int64_t +compress_read(zip_source_t *src, struct context *ctx, void *data, zip_uint64_t len) { + zip_compression_status_t ret; + bool end; + zip_int64_t n; + zip_uint64_t out_offset; + zip_uint64_t out_len; + + if (zip_error_code_zip(&ctx->error) != ZIP_ER_OK) { + return -1; + } + + if (len == 0 || ctx->end_of_stream) { + return 0; + } + + out_offset = 0; + + end = false; + while (!end && out_offset < len) { + out_len = len - out_offset; + ret = ctx->algorithm->process(ctx->ud, (zip_uint8_t *)data + out_offset, &out_len); + + if (ret != ZIP_COMPRESSION_ERROR) { + out_offset += out_len; + } + + switch (ret) { + case ZIP_COMPRESSION_END: + ctx->end_of_stream = true; + + if (!ctx->end_of_input) { + /* TODO: garbage after stream, or compression ended before all data read */ + } + + if (ctx->first_read < 0) { + /* we got end of processed stream before reading any input data */ + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + end = true; + break; + } + if (ctx->can_store && (zip_uint64_t)ctx->first_read <= out_offset) { + ctx->is_stored = true; + ctx->size = (zip_uint64_t)ctx->first_read; + memcpy(data, ctx->buffer, ctx->size); + return (zip_int64_t)ctx->size; + } + end = true; + break; + + case ZIP_COMPRESSION_OK: + break; + + case ZIP_COMPRESSION_NEED_DATA: + if (ctx->end_of_input) { + /* TODO: error: stream not ended, but no more input */ + end = true; + break; + } + + if ((n = zip_source_read(src, ctx->buffer, sizeof(ctx->buffer))) < 0) { + _zip_error_set_from_source(&ctx->error, src); + end = true; + break; + } + else if (n == 0) { + ctx->end_of_input = true; + ctx->algorithm->end_of_input(ctx->ud); + if (ctx->first_read < 0) { + ctx->first_read = 0; + } + } + else { + if (ctx->first_read >= 0) { + /* we overwrote a previously filled ctx->buffer */ + ctx->can_store = false; + } + else { + ctx->first_read = n; + } + + ctx->algorithm->input(ctx->ud, ctx->buffer, (zip_uint64_t)n); + } + break; + + case ZIP_COMPRESSION_ERROR: + /* error set by algorithm */ + if (zip_error_code_zip(&ctx->error) == ZIP_ER_OK) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + } + end = true; + break; + } + } + + if (out_offset > 0) { + ctx->can_store = false; + ctx->size += out_offset; + return (zip_int64_t)out_offset; + } + + return (zip_error_code_zip(&ctx->error) == ZIP_ER_OK) ? 0 : -1; +} + + +static zip_int64_t +compress_callback(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct context *ctx; + + ctx = (struct context *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + ctx->size = 0; + ctx->end_of_input = false; + ctx->end_of_stream = false; + ctx->is_stored = false; + ctx->first_read = -1; + + if (!ctx->algorithm->start(ctx->ud)) { + return -1; + } + + return 0; + + case ZIP_SOURCE_READ: + return compress_read(src, ctx, data, len); + + case ZIP_SOURCE_CLOSE: + if (!ctx->algorithm->end(ctx->ud)) { + return -1; + } + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (ctx->compress) { + if (ctx->end_of_stream) { + st->comp_method = ctx->is_stored ? ZIP_CM_STORE : ZIP_CM_ACTUAL(ctx->method); + st->comp_size = ctx->size; + st->valid |= ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD; + } + else { + st->valid &= ~(ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD); + } + } + else { + st->comp_method = ZIP_CM_STORE; + st->valid |= ZIP_STAT_COMP_METHOD; + if (ctx->end_of_stream) { + st->size = ctx->size; + st->valid |= ZIP_STAT_SIZE; + } + else { + st->valid &= ~ZIP_STAT_SIZE; + } + } + } + return 0; + + case ZIP_SOURCE_GET_COMPRESSION_FLAGS: + return ctx->is_stored ? 0 : ctx->algorithm->compression_flags(ctx->ud); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + context_free(ctx); + return 0; + + case ZIP_SOURCE_SUPPORTS: + return ZIP_SOURCE_SUPPORTS_READABLE | zip_source_make_command_bitmap(ZIP_SOURCE_GET_COMPRESSION_FLAGS, -1); + + default: + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } +} diff --git a/third_party/libzip/lib/zip_source_crc.c b/third_party/libzip/lib/zip_source_crc.c new file mode 100644 index 0000000..e16f929 --- /dev/null +++ b/third_party/libzip/lib/zip_source_crc.c @@ -0,0 +1,197 @@ +/* + zip_source_crc.c -- pass-through source that calculates CRC32 and size + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include + +#include "zipint.h" + +struct crc_context { + int validate; /* whether to check CRC on EOF and return error on mismatch */ + int crc_complete; /* whether CRC was computed for complete file */ + zip_error_t error; + zip_uint64_t size; + zip_uint64_t position; /* current reading position */ + zip_uint64_t crc_position; /* how far we've computed the CRC */ + zip_uint32_t crc; +}; + +static zip_int64_t crc_read(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); + + +zip_source_t * +zip_source_crc(zip_t *za, zip_source_t *src, int validate) { + struct crc_context *ctx; + + if (src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (struct crc_context *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + zip_error_init(&ctx->error); + ctx->validate = validate; + ctx->crc_complete = 0; + ctx->crc_position = 0; + ctx->crc = (zip_uint32_t)crc32(0, NULL, 0); + ctx->size = 0; + + return zip_source_layered(za, src, crc_read, ctx); +} + + +static zip_int64_t +crc_read(zip_source_t *src, void *_ctx, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct crc_context *ctx; + zip_int64_t n; + + ctx = (struct crc_context *)_ctx; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + ctx->position = 0; + return 0; + + case ZIP_SOURCE_READ: + if ((n = zip_source_read(src, data, len)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (n == 0) { + if (ctx->crc_position == ctx->position) { + ctx->crc_complete = 1; + ctx->size = ctx->position; + + if (ctx->validate) { + struct zip_stat st; + + if (zip_source_stat(src, &st) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if ((st.valid & ZIP_STAT_CRC) && st.crc != ctx->crc) { + zip_error_set(&ctx->error, ZIP_ER_CRC, 0); + return -1; + } + if ((st.valid & ZIP_STAT_SIZE) && st.size != ctx->size) { + zip_error_set(&ctx->error, ZIP_ER_INCONS, 0); + return -1; + } + } + } + } + else if (!ctx->crc_complete && ctx->position <= ctx->crc_position) { + zip_uint64_t i, nn; + + for (i = ctx->crc_position - ctx->position; i < (zip_uint64_t)n; i += nn) { + nn = ZIP_MIN(UINT_MAX, (zip_uint64_t)n - i); + + ctx->crc = (zip_uint32_t)crc32(ctx->crc, (const Bytef *)data + i, (uInt)nn); + ctx->crc_position += nn; + } + } + ctx->position += (zip_uint64_t)n; + return n; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (ctx->crc_complete) { + /* TODO: Set comp_size, comp_method, encryption_method? + After all, this only works for uncompressed data. */ + st->size = ctx->size; + st->crc = ctx->crc; + st->comp_size = ctx->size; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; + st->valid |= ZIP_STAT_SIZE | ZIP_STAT_CRC | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + } + return 0; + } + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx); + return 0; + + case ZIP_SOURCE_SUPPORTS: { + zip_int64_t mask = zip_source_supports(src); + + if (mask < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + return mask & ~zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, ZIP_SOURCE_GET_COMPRESSION_FLAGS, -1); + } + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_position; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + + if (args == NULL) { + return -1; + } + if (zip_source_seek(src, args->offset, args->whence) < 0 || (new_position = zip_source_tell(src)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + ctx->position = (zip_uint64_t)new_position; + + return 0; + } + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->position; + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} diff --git a/third_party/libzip/lib/zip_source_error.c b/third_party/libzip/lib/zip_source_error.c new file mode 100644 index 0000000..1e0e0d4 --- /dev/null +++ b/third_party/libzip/lib/zip_source_error.c @@ -0,0 +1,46 @@ +/* + zip_source_error.c -- get last error from zip_source + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_error_t * +zip_source_error(zip_source_t *src) { + return &src->error; +} + +bool +_zip_source_had_error(zip_source_t *src) { + return zip_source_error(src)->zip_err != ZIP_ER_OK; +} diff --git a/third_party/libzip/lib/zip_source_file.c b/third_party/libzip/lib/zip_source_file.c new file mode 100644 index 0000000..8714785 --- /dev/null +++ b/third_party/libzip/lib/zip_source_file.c @@ -0,0 +1,61 @@ +/* + zip_source_file.c -- create data source from file + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + +#ifdef _WIN32 +#error This file is incompatible with Windows, use zip_source_win32utf8.c instead. +#error Something probably went wrong with configure/cmake. +#endif + +ZIP_EXTERN zip_source_t * +zip_source_file(zip_t *za, const char *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_file_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_file_create(const char *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return _zip_source_file_or_p(fname, NULL, start, length, NULL, error); +} diff --git a/third_party/libzip/lib/zip_source_filep.c b/third_party/libzip/lib/zip_source_filep.c new file mode 100644 index 0000000..cb3d151 --- /dev/null +++ b/third_party/libzip/lib/zip_source_filep.c @@ -0,0 +1,658 @@ +/* + zip_source_filep.c -- create data source from FILE * + Copyright (C) 1999-2019 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include "zipint.h" + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifdef HAVE_CLONEFILE +#include +#include +#define CAN_CLONE +#endif +#ifdef HAVE_FICLONERANGE +#include +#include +#define CAN_CLONE +#endif + +#ifdef _WIN32 +/* WIN32 needs for _O_BINARY */ +#include +#endif + +/* Windows sys/types.h does not provide these */ +#ifndef S_ISREG +#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG) +#endif +#if defined(S_IXUSR) && defined(S_IRWXG) && defined(S_IRWXO) +#define _SAFE_MASK (S_IXUSR | S_IRWXG | S_IRWXO) +#elif defined(_S_IWRITE) +#define _SAFE_MASK (_S_IWRITE) +#else +#error do not know safe values for umask, please report this +#endif + +#ifdef _MSC_VER +/* MSVC doesn't have mode_t */ +typedef int mode_t; +#endif + +struct read_file { + zip_error_t error; /* last error information */ + zip_int64_t supports; + + /* reading */ + char *fname; /* name of file to read from */ + FILE *f; /* file to read from */ + struct zip_stat st; /* stat information passed in */ + zip_error_t stat_error; /* error returned for stat */ + zip_uint64_t start; /* start offset of data to read */ + zip_uint64_t end; /* end offset of data to read relative to start, 0 for up to EOF */ + zip_uint64_t current; /* current offset relative to start (0 is beginning of part we read) */ + + /* writing */ + char *tmpname; + FILE *fout; +}; + +static zip_int64_t read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd); +static int create_temp_output(struct read_file *ctx); +#ifdef CAN_CLONE +static zip_int64_t create_temp_output_cloning(struct read_file *ctx, zip_uint64_t offset); +#endif +static int _zip_fseek_u(FILE *f, zip_uint64_t offset, int whence, zip_error_t *error); +static int _zip_fseek(FILE *f, zip_int64_t offset, int whence, zip_error_t *error); + + +ZIP_EXTERN zip_source_t * +zip_source_filep(zip_t *za, FILE *file, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_filep_create(file, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_filep_create(FILE *file, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (file == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return _zip_source_file_or_p(NULL, file, start, length, NULL, error); +} + + +zip_source_t * +_zip_source_file_or_p(const char *fname, FILE *file, zip_uint64_t start, zip_int64_t len, const zip_stat_t *st, zip_error_t *error) { + struct read_file *ctx; + zip_source_t *zs; + struct stat sb; + bool stat_valid; + + if (file == NULL && fname == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len < 0) { + len = 0; + } + + if (start > ZIP_INT64_MAX || start + (zip_uint64_t)len < start) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (struct read_file *)malloc(sizeof(struct read_file))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->fname = NULL; + if (fname) { + if ((ctx->fname = strdup(fname)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + } + ctx->f = file; + ctx->start = start; + ctx->end = (zip_uint64_t)len; + if (st) { + memcpy(&ctx->st, st, sizeof(ctx->st)); + ctx->st.name = NULL; + ctx->st.valid &= ~ZIP_STAT_NAME; + } + else { + zip_stat_init(&ctx->st); + } + + if (ctx->end > 0) { + ctx->st.size = ctx->end; + ctx->st.valid |= ZIP_STAT_SIZE; + } + + zip_error_init(&ctx->stat_error); + + ctx->tmpname = NULL; + ctx->fout = NULL; + + zip_error_init(&ctx->error); + + ctx->supports = ZIP_SOURCE_SUPPORTS_READABLE | zip_source_make_command_bitmap(ZIP_SOURCE_SUPPORTS, ZIP_SOURCE_TELL, -1); + + if (ctx->fname) { + stat_valid = stat(ctx->fname, &sb) >= 0; + + if (!stat_valid) { + if (ctx->start == 0 && ctx->end == 0) { + ctx->supports = ZIP_SOURCE_SUPPORTS_WRITABLE; + } + } + } + else { + stat_valid = fstat(fileno(ctx->f), &sb) >= 0; + } + + if (!stat_valid) { + zip_error_set(&ctx->stat_error, ZIP_ER_READ, errno); + } + else { + if ((ctx->st.valid & ZIP_STAT_MTIME) == 0) { + ctx->st.mtime = sb.st_mtime; + ctx->st.valid |= ZIP_STAT_MTIME; + } + if (S_ISREG(sb.st_mode)) { + ctx->supports = ZIP_SOURCE_SUPPORTS_SEEKABLE; + + if (ctx->start + ctx->end > (zip_uint64_t)sb.st_size) { + zip_error_set(error, ZIP_ER_INVAL, 0); + free(ctx->fname); + free(ctx); + return NULL; + } + + if (ctx->end == 0) { + ctx->st.size = (zip_uint64_t)sb.st_size - ctx->start; + ctx->st.valid |= ZIP_STAT_SIZE; + + if (ctx->fname && start == 0) { + ctx->supports = ZIP_SOURCE_SUPPORTS_WRITABLE; + } + } + } + } + +#ifdef CAN_CLONE + if (ctx->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE)) { + ctx->supports |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_BEGIN_WRITE_CLONING); + } +#endif + + if ((zs = zip_source_function_create(read_file, ctx, error)) == NULL) { + free(ctx->fname); + free(ctx); + return NULL; + } + + return zs; +} + + +static int +create_temp_output(struct read_file *ctx) { + char *temp; + int tfd; + mode_t mask; + FILE *tfp; + + if ((temp = (char *)malloc(strlen(ctx->fname) + 8)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + sprintf(temp, "%s.XXXXXX", ctx->fname); + + mask = umask(_SAFE_MASK); + if ((tfd = mkstemp(temp)) == -1) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + umask(mask); + free(temp); + return -1; + } + umask(mask); + + if ((tfp = fdopen(tfd, "r+b")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + close(tfd); + (void)remove(temp); + free(temp); + return -1; + } + +#ifdef _WIN32 + /* + According to Pierre Joye, Windows in some environments per + default creates text files, so force binary mode. + */ + _setmode(_fileno(tfp), _O_BINARY); +#endif + + ctx->fout = tfp; + ctx->tmpname = temp; + + return 0; +} + +#ifdef CAN_CLONE +zip_int64_t static create_temp_output_cloning(struct read_file *ctx, zip_uint64_t offset) { + char *temp; + FILE *tfp; + + if (offset > ZIP_OFF_MAX) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, E2BIG); + return -1; + } + + if ((temp = (char *)malloc(strlen(ctx->fname) + 8)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + sprintf(temp, "%s.XXXXXX", ctx->fname); + +#ifdef HAVE_CLONEFILE +#ifndef __clang_analyzer__ + /* we can't use mkstemp, since clonefile insists on creating the file */ + if (mktemp(temp) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } +#endif + + if (clonefile(ctx->fname, temp, 0) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + if ((tfp = fopen(temp, "r+b")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)remove(temp); + free(temp); + return -1; + } +#else + { + int fd; + struct file_clone_range range; + struct stat st; + + if (fstat(fileno(ctx->f), &st) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + return -1; + } + + if ((fd = mkstemp(temp)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + free(temp); + return -1; + } + + range.src_fd = fileno(ctx->f); + range.src_offset = 0; + range.src_length = ((offset + st.st_blksize - 1) / st.st_blksize) * st.st_blksize; + if (range.src_length > st.st_size) { + range.src_length = 0; + } + range.dest_offset = 0; + if (ioctl(fd, FICLONERANGE, &range) < 0) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)close(fd); + (void)remove(temp); + free(temp); + return -1; + } + + if ((tfp = fdopen(fd, "r+b")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + (void)close(fd); + (void)remove(temp); + free(temp); + return -1; + } + } +#endif + + if (ftruncate(fileno(tfp), (off_t)offset) < 0) { + (void)fclose(tfp); + (void)remove(temp); + free(temp); + return -1; + } + if (fseeko(tfp, (off_t)offset, SEEK_SET) < 0) { + (void)fclose(tfp); + (void)remove(temp); + free(temp); + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, errno); + } + + ctx->fout = tfp; + ctx->tmpname = temp; + + return 0; +} +#endif + + +static zip_int64_t +read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct read_file *ctx; + char *buf; + zip_uint64_t n; + size_t i; + + ctx = (struct read_file *)state; + buf = (char *)data; + + switch (cmd) { + case ZIP_SOURCE_BEGIN_WRITE: + if (ctx->fname == NULL) { + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + return create_temp_output(ctx); + +#ifdef CAN_CLONE + case ZIP_SOURCE_BEGIN_WRITE_CLONING: + if (ctx->fname == NULL) { + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + return create_temp_output_cloning(ctx, len); +#endif + + case ZIP_SOURCE_COMMIT_WRITE: { + mode_t mode; + struct stat st; + + if (fclose(ctx->fout) < 0) { + ctx->fout = NULL; + zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); + } + ctx->fout = NULL; + if (stat(ctx->fname, &st) == 0) { + mode = st.st_mode; + } else { + mode_t mask = umask(022); + umask(mask); + mode = 0666 & ~mask; + } + if (rename(ctx->tmpname, ctx->fname) < 0) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, errno); + return -1; + } + /* not much we can do if chmod fails except make the whole commit fail */ + (void)chmod(ctx->fname, mode); + free(ctx->tmpname); + ctx->tmpname = NULL; + return 0; + } + + case ZIP_SOURCE_CLOSE: + if (ctx->fname) { + fclose(ctx->f); + ctx->f = NULL; + } + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx->fname); + free(ctx->tmpname); + if (ctx->f) + fclose(ctx->f); + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + if (ctx->fname) { + if ((ctx->f = fopen(ctx->fname, "rb")) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_OPEN, errno); + return -1; + } + } + + if (ctx->start > 0) { + if (_zip_fseek_u(ctx->f, ctx->start, SEEK_SET, &ctx->error) < 0) { + /* TODO: skip by reading */ + return -1; + } + } + ctx->current = 0; + return 0; + + case ZIP_SOURCE_READ: + if (ctx->end > 0) { + n = ctx->end - ctx->current; + if (n > len) { + n = len; + } + } + else { + n = len; + } + + if (n > SIZE_MAX) + n = SIZE_MAX; + + if ((i = fread(buf, 1, (size_t)n, ctx->f)) == 0) { + if (ferror(ctx->f)) { + zip_error_set(&ctx->error, ZIP_ER_READ, errno); + return -1; + } + } + ctx->current += i; + + return (zip_int64_t)i; + + case ZIP_SOURCE_REMOVE: + if (remove(ctx->fname) < 0) { + zip_error_set(&ctx->error, ZIP_ER_REMOVE, errno); + return -1; + } + return 0; + + case ZIP_SOURCE_ROLLBACK_WRITE: + if (ctx->fout) { + fclose(ctx->fout); + ctx->fout = NULL; + } + (void)remove(ctx->tmpname); + free(ctx->tmpname); + ctx->tmpname = NULL; + return 0; + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_current; + int need_seek; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + + if (args == NULL) + return -1; + + need_seek = 1; + + switch (args->whence) { + case SEEK_SET: + new_current = args->offset; + break; + + case SEEK_END: + if (ctx->end == 0) { + if (_zip_fseek(ctx->f, args->offset, SEEK_END, &ctx->error) < 0) { + return -1; + } + if ((new_current = ftello(ctx->f)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, errno); + return -1; + } + new_current -= (zip_int64_t)ctx->start; + need_seek = 0; + } + else { + new_current = (zip_int64_t)ctx->end + args->offset; + } + break; + + case SEEK_CUR: + new_current = (zip_int64_t)ctx->current + args->offset; + break; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (new_current < 0 || (ctx->end != 0 && (zip_uint64_t)new_current > ctx->end) || (zip_uint64_t)new_current + ctx->start < ctx->start) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + ctx->current = (zip_uint64_t)new_current; + + if (need_seek) { + if (_zip_fseek_u(ctx->f, ctx->current + ctx->start, SEEK_SET, &ctx->error) < 0) { + return -1; + } + } + return 0; + } + + case ZIP_SOURCE_SEEK_WRITE: { + zip_source_args_seek_t *args; + + args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + if (args == NULL) { + return -1; + } + + if (_zip_fseek(ctx->fout, args->offset, args->whence, &ctx->error) < 0) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_STAT: { + if (len < sizeof(ctx->st)) + return -1; + + if (zip_error_code_zip(&ctx->stat_error) != 0) { + zip_error_set(&ctx->error, zip_error_code_zip(&ctx->stat_error), zip_error_code_system(&ctx->stat_error)); + return -1; + } + + memcpy(data, &ctx->st, sizeof(ctx->st)); + return sizeof(ctx->st); + } + + case ZIP_SOURCE_SUPPORTS: + return ctx->supports; + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->current; + + case ZIP_SOURCE_TELL_WRITE: { + off_t ret = ftello(ctx->fout); + + if (ret < 0) { + zip_error_set(&ctx->error, ZIP_ER_TELL, errno); + return -1; + } + return ret; + } + + case ZIP_SOURCE_WRITE: { + size_t ret; + + clearerr(ctx->fout); + ret = fwrite(data, 1, len, ctx->fout); + if (ret != len || ferror(ctx->fout)) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, errno); + return -1; + } + + return (zip_int64_t)ret; + } + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +static int +_zip_fseek_u(FILE *f, zip_uint64_t offset, int whence, zip_error_t *error) { + if (offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EOVERFLOW); + return -1; + } + return _zip_fseek(f, (zip_int64_t)offset, whence, error); +} + + +static int +_zip_fseek(FILE *f, zip_int64_t offset, int whence, zip_error_t *error) { + if (offset > ZIP_FSEEK_MAX || offset < ZIP_FSEEK_MIN) { + zip_error_set(error, ZIP_ER_SEEK, EOVERFLOW); + return -1; + } + if (fseeko(f, (off_t)offset, whence) < 0) { + zip_error_set(error, ZIP_ER_SEEK, errno); + return -1; + } + return 0; +} diff --git a/third_party/libzip/lib/zip_source_free.c b/third_party/libzip/lib/zip_source_free.c new file mode 100644 index 0000000..dd3c6df --- /dev/null +++ b/third_party/libzip/lib/zip_source_free.c @@ -0,0 +1,71 @@ +/* + zip_source_free.c -- free zip data source + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN void +zip_source_free(zip_source_t *src) { + if (src == NULL) + return; + + if (src->refcount > 0) { + src->refcount--; + } + if (src->refcount > 0) { + return; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + src->open_count = 1; /* force close */ + zip_source_close(src); + } + if (ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_source_rollback_write(src); + } + + if (src->source_archive && !src->source_closed) { + _zip_deregister_source(src->source_archive, src); + } + + (void)_zip_source_call(src, NULL, 0, ZIP_SOURCE_FREE); + + if (src->src) { + zip_source_free(src->src); + } + + free(src); +} diff --git a/third_party/libzip/lib/zip_source_function.c b/third_party/libzip/lib/zip_source_function.c new file mode 100644 index 0000000..c9730c9 --- /dev/null +++ b/third_party/libzip/lib/zip_source_function.c @@ -0,0 +1,97 @@ +/* + zip_source_function.c -- create zip data source from callback function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN zip_source_t * +zip_source_function(zip_t *za, zip_source_callback zcb, void *ud) { + if (za == NULL) { + return NULL; + } + + return zip_source_function_create(zcb, ud, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_function_create(zip_source_callback zcb, void *ud, zip_error_t *error) { + zip_source_t *zs; + + if ((zs = _zip_source_new(error)) == NULL) + return NULL; + + zs->cb.f = zcb; + zs->ud = ud; + + zs->supports = zcb(ud, NULL, 0, ZIP_SOURCE_SUPPORTS); + if (zs->supports < 0) { + zs->supports = ZIP_SOURCE_SUPPORTS_READABLE; + } + + return zs; +} + + +ZIP_EXTERN void +zip_source_keep(zip_source_t *src) { + src->refcount++; +} + + +zip_source_t * +_zip_source_new(zip_error_t *error) { + zip_source_t *src; + + if ((src = (zip_source_t *)malloc(sizeof(*src))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + src->src = NULL; + src->cb.f = NULL; + src->ud = NULL; + src->open_count = 0; + src->write_state = ZIP_SOURCE_WRITE_CLOSED; + src->source_closed = false; + src->source_archive = NULL; + src->refcount = 1; + zip_error_init(&src->error); + src->eof = false; + src->had_read_error = false; + + return src; +} diff --git a/third_party/libzip/lib/zip_source_get_compression_flags.c b/third_party/libzip/lib/zip_source_get_compression_flags.c new file mode 100644 index 0000000..a9442aa --- /dev/null +++ b/third_party/libzip/lib/zip_source_get_compression_flags.c @@ -0,0 +1,57 @@ +/* + zip_source_get_compression_flags.c -- get compression flags for entry + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#define ZIP_COMPRESSION_BITFLAG_MAX 3 + +zip_int8_t +zip_source_get_compression_flags(zip_source_t *src) { + while (src) { + if ((src->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_GET_COMPRESSION_FLAGS))) { + zip_int64_t ret = _zip_source_call(src, NULL, 0, ZIP_SOURCE_GET_COMPRESSION_FLAGS); + if (ret < 0) { + return -1; + } + if (ret > ZIP_COMPRESSION_BITFLAG_MAX) { + zip_error_set(&src->error, ZIP_ER_INTERNAL, 0); + return -1; + } + return (zip_int8_t)ret; + } + src = src->src; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_is_deleted.c b/third_party/libzip/lib/zip_source_is_deleted.c new file mode 100644 index 0000000..090a67b --- /dev/null +++ b/third_party/libzip/lib/zip_source_is_deleted.c @@ -0,0 +1,41 @@ +/* + zip_source_is_deleted.c -- was archive was removed? + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_is_deleted(zip_source_t *src) { + return src->write_state == ZIP_SOURCE_WRITE_REMOVED; +} diff --git a/third_party/libzip/lib/zip_source_layered.c b/third_party/libzip/lib/zip_source_layered.c new file mode 100644 index 0000000..580bff0 --- /dev/null +++ b/third_party/libzip/lib/zip_source_layered.c @@ -0,0 +1,67 @@ +/* + zip_source_layered.c -- create layered source + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +zip_source_t * +zip_source_layered(zip_t *za, zip_source_t *src, zip_source_layered_callback cb, void *ud) { + if (za == NULL) + return NULL; + + return zip_source_layered_create(src, cb, ud, &za->error); +} + + +zip_source_t * +zip_source_layered_create(zip_source_t *src, zip_source_layered_callback cb, void *ud, zip_error_t *error) { + zip_source_t *zs; + + if ((zs = _zip_source_new(error)) == NULL) + return NULL; + + zip_source_keep(src); + zs->src = src; + zs->cb.l = cb; + zs->ud = ud; + + zs->supports = cb(src, ud, NULL, 0, ZIP_SOURCE_SUPPORTS); + if (zs->supports < 0) { + zs->supports = ZIP_SOURCE_SUPPORTS_READABLE; + } + + return zs; +} diff --git a/third_party/libzip/lib/zip_source_open.c b/third_party/libzip/lib/zip_source_open.c new file mode 100644 index 0000000..d10a3c5 --- /dev/null +++ b/third_party/libzip/lib/zip_source_open.c @@ -0,0 +1,75 @@ +/* + zip_source_open.c -- open zip_source (prepare for reading) + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +ZIP_EXTERN int +zip_source_open(zip_source_t *src) { + if (src->source_closed) { + return -1; + } + if (src->write_state == ZIP_SOURCE_WRITE_REMOVED) { + zip_error_set(&src->error, ZIP_ER_DELETED, 0); + return -1; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if ((zip_source_supports(src) & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK)) == 0) { + zip_error_set(&src->error, ZIP_ER_INUSE, 0); + return -1; + } + } + else { + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_open(src->src) < 0) { + _zip_error_set_from_source(&src->error, src->src); + return -1; + } + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_OPEN) < 0) { + if (ZIP_SOURCE_IS_LAYERED(src)) { + zip_source_close(src->src); + } + return -1; + } + } + + src->eof = false; + src->had_read_error = false; + _zip_error_clear(&src->error); + src->open_count++; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_pkware.c b/third_party/libzip/lib/zip_source_pkware.c new file mode 100644 index 0000000..cc510ea --- /dev/null +++ b/third_party/libzip/lib/zip_source_pkware.c @@ -0,0 +1,215 @@ +/* + zip_source_pkware.c -- Traditional PKWARE de/encryption routines + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +struct trad_pkware { + zip_error_t error; + zip_uint32_t key[3]; +}; + +#define HEADERLEN 12 +#define KEY0 305419896 +#define KEY1 591751049 +#define KEY2 878082192 + + +static void decrypt(struct trad_pkware *, zip_uint8_t *, const zip_uint8_t *, zip_uint64_t, int); +static int decrypt_header(zip_source_t *, struct trad_pkware *); +static zip_int64_t pkware_decrypt(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); +static void pkware_free(struct trad_pkware *); + + +zip_source_t * +zip_source_pkware(zip_t *za, zip_source_t *src, zip_uint16_t em, int flags, const char *password) { + struct trad_pkware *ctx; + zip_source_t *s2; + + if (password == NULL || src == NULL || em != ZIP_EM_TRAD_PKWARE) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + if (flags & ZIP_CODEC_ENCODE) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + if ((ctx = (struct trad_pkware *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return NULL; + } + + zip_error_init(&ctx->error); + + ctx->key[0] = KEY0; + ctx->key[1] = KEY1; + ctx->key[2] = KEY2; + decrypt(ctx, NULL, (const zip_uint8_t *)password, strlen(password), 1); + + if ((s2 = zip_source_layered(za, src, pkware_decrypt, ctx)) == NULL) { + pkware_free(ctx); + return NULL; + } + + return s2; +} + + +static void +decrypt(struct trad_pkware *ctx, zip_uint8_t *out, const zip_uint8_t *in, zip_uint64_t len, int update_only) { + zip_uint16_t tmp; + zip_uint64_t i; + Bytef b; + + for (i = 0; i < len; i++) { + b = in[i]; + + if (!update_only) { + /* decrypt next byte */ + tmp = (zip_uint16_t)(ctx->key[2] | 2); + tmp = (zip_uint16_t)(((zip_uint32_t)tmp * (tmp ^ 1)) >> 8); + b ^= (Bytef)tmp; + } + + /* store cleartext */ + if (out) + out[i] = b; + + /* update keys */ + ctx->key[0] = (zip_uint32_t)crc32(ctx->key[0] ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL; + ctx->key[1] = (ctx->key[1] + (ctx->key[0] & 0xff)) * 134775813 + 1; + b = (Bytef)(ctx->key[1] >> 24); + ctx->key[2] = (zip_uint32_t)crc32(ctx->key[2] ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL; + } +} + + +static int +decrypt_header(zip_source_t *src, struct trad_pkware *ctx) { + zip_uint8_t header[HEADERLEN]; + struct zip_stat st; + zip_int64_t n; + unsigned short dostime, dosdate; + + if ((n = zip_source_read(src, header, HEADERLEN)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (n != HEADERLEN) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + + decrypt(ctx, header, header, HEADERLEN, 0); + + if (zip_source_stat(src, &st) < 0) { + /* stat failed, skip password validation */ + return 0; + } + + _zip_u2d_time(st.mtime, &dostime, &dosdate); + + if (header[HEADERLEN - 1] != st.crc >> 24 && header[HEADERLEN - 1] != dostime >> 8) { + zip_error_set(&ctx->error, ZIP_ER_WRONGPASSWD, 0); + return -1; + } + + return 0; +} + + +static zip_int64_t +pkware_decrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct trad_pkware *ctx; + zip_int64_t n; + + ctx = (struct trad_pkware *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + if (decrypt_header(src, ctx) < 0) + return -1; + return 0; + + case ZIP_SOURCE_READ: + if ((n = zip_source_read(src, data, len)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + decrypt((struct trad_pkware *)ud, (zip_uint8_t *)data, (zip_uint8_t *)data, (zip_uint64_t)n, 0); + return n; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + st->encryption_method = ZIP_EM_NONE; + st->valid |= ZIP_STAT_ENCRYPTION_METHOD; + /* TODO: deduce HEADERLEN from size for uncompressed */ + if (st->valid & ZIP_STAT_COMP_SIZE) + st->comp_size -= HEADERLEN; + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, -1); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + pkware_free(ctx); + return 0; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } +} + + +static void +pkware_free(struct trad_pkware *ctx) { + free(ctx); +} diff --git a/third_party/libzip/lib/zip_source_read.c b/third_party/libzip/lib/zip_source_read.c new file mode 100644 index 0000000..816fb3d --- /dev/null +++ b/third_party/libzip/lib/zip_source_read.c @@ -0,0 +1,90 @@ +/* + zip_source_read.c -- read data from zip_source + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +zip_int64_t +zip_source_read(zip_source_t *src, void *data, zip_uint64_t len) { + zip_uint64_t bytes_read; + zip_int64_t n; + + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src) || len > ZIP_INT64_MAX || (len > 0 && data == NULL)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (src->had_read_error) { + return -1; + } + + if (_zip_source_eof(src)) { + return 0; + } + + if (len == 0) { + return 0; + } + + bytes_read = 0; + while (bytes_read < len) { + if ((n = _zip_source_call(src, (zip_uint8_t *)data + bytes_read, len - bytes_read, ZIP_SOURCE_READ)) < 0) { + src->had_read_error = true; + if (bytes_read == 0) { + return -1; + } + else { + return (zip_int64_t)bytes_read; + } + } + + if (n == 0) { + src->eof = 1; + break; + } + + bytes_read += (zip_uint64_t)n; + } + + return (zip_int64_t)bytes_read; +} + + +bool +_zip_source_eof(zip_source_t *src) { + return src->eof; +} diff --git a/third_party/libzip/lib/zip_source_remove.c b/third_party/libzip/lib/zip_source_remove.c new file mode 100644 index 0000000..6841b74 --- /dev/null +++ b/third_party/libzip/lib/zip_source_remove.c @@ -0,0 +1,60 @@ +/* + zip_source_remove.c -- remove empty archive + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +int +zip_source_remove(zip_source_t *src) { + if (src->write_state == ZIP_SOURCE_WRITE_REMOVED) { + return 0; + } + + if (ZIP_SOURCE_IS_OPEN_READING(src)) { + if (zip_source_close(src) < 0) { + return -1; + } + } + if (src->write_state != ZIP_SOURCE_WRITE_CLOSED) { + zip_source_rollback_write(src); + } + + if (_zip_source_call(src, NULL, 0, ZIP_SOURCE_REMOVE) < 0) { + return -1; + } + + src->write_state = ZIP_SOURCE_WRITE_REMOVED; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_rollback_write.c b/third_party/libzip/lib/zip_source_rollback_write.c new file mode 100644 index 0000000..04aa938 --- /dev/null +++ b/third_party/libzip/lib/zip_source_rollback_write.c @@ -0,0 +1,46 @@ +/* + zip_source_rollback_write.c -- discard changes + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN void +zip_source_rollback_write(zip_source_t *src) { + if (src->write_state != ZIP_SOURCE_WRITE_OPEN && src->write_state != ZIP_SOURCE_WRITE_FAILED) { + return; + } + + _zip_source_call(src, NULL, 0, ZIP_SOURCE_ROLLBACK_WRITE); + src->write_state = ZIP_SOURCE_WRITE_CLOSED; +} diff --git a/third_party/libzip/lib/zip_source_seek.c b/third_party/libzip/lib/zip_source_seek.c new file mode 100644 index 0000000..c7bd8e6 --- /dev/null +++ b/third_party/libzip/lib/zip_source_seek.c @@ -0,0 +1,95 @@ +/* + zip_source_seek.c -- seek to offset + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_seek(zip_source_t *src, zip_int64_t offset, int whence) { + zip_source_args_seek_t args; + + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src) || (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + args.offset = offset; + args.whence = whence; + + if (_zip_source_call(src, &args, sizeof(args), ZIP_SOURCE_SEEK) < 0) { + return -1; + } + + src->eof = 0; + return 0; +} + + +zip_int64_t +zip_source_seek_compute_offset(zip_uint64_t offset, zip_uint64_t length, void *data, zip_uint64_t data_length, zip_error_t *error) { + zip_int64_t new_offset; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, data_length, error); + + if (args == NULL) { + return -1; + } + + switch (args->whence) { + case SEEK_CUR: + new_offset = (zip_int64_t)offset + args->offset; + break; + + case SEEK_END: + new_offset = (zip_int64_t)length + args->offset; + break; + + case SEEK_SET: + new_offset = args->offset; + break; + + default: + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + if (new_offset < 0 || (zip_uint64_t)new_offset > length) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return -1; + } + + return new_offset; +} diff --git a/third_party/libzip/lib/zip_source_seek_write.c b/third_party/libzip/lib/zip_source_seek_write.c new file mode 100644 index 0000000..a20dc82 --- /dev/null +++ b/third_party/libzip/lib/zip_source_seek_write.c @@ -0,0 +1,51 @@ +/* + zip_source_seek_write.c -- seek to offset for writing + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_seek_write(zip_source_t *src, zip_int64_t offset, int whence) { + zip_source_args_seek_t args; + + if (!ZIP_SOURCE_IS_OPEN_WRITING(src) || (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + args.offset = offset; + args.whence = whence; + + return (_zip_source_call(src, &args, sizeof(args), ZIP_SOURCE_SEEK_WRITE) < 0 ? -1 : 0); +} diff --git a/third_party/libzip/lib/zip_source_stat.c b/third_party/libzip/lib/zip_source_stat.c new file mode 100644 index 0000000..f3af3be --- /dev/null +++ b/third_party/libzip/lib/zip_source_stat.c @@ -0,0 +1,62 @@ +/* + zip_source_stat.c -- get meta information from zip_source + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_source_stat(zip_source_t *src, zip_stat_t *st) { + if (src->source_closed) { + return -1; + } + if (st == NULL) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + zip_stat_init(st); + + if (ZIP_SOURCE_IS_LAYERED(src)) { + if (zip_source_stat(src->src, st) < 0) { + _zip_error_set_from_source(&src->error, src->src); + return -1; + } + } + + if (_zip_source_call(src, st, sizeof(*st), ZIP_SOURCE_STAT) < 0) { + return -1; + } + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_supports.c b/third_party/libzip/lib/zip_source_supports.c new file mode 100644 index 0000000..394f06e --- /dev/null +++ b/third_party/libzip/lib/zip_source_supports.c @@ -0,0 +1,65 @@ +/* + zip_source_supports.c -- check for supported functions + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +zip_int64_t +zip_source_supports(zip_source_t *src) { + return src->supports; +} + + +ZIP_EXTERN zip_int64_t +zip_source_make_command_bitmap(zip_source_cmd_t cmd0, ...) { + zip_int64_t bitmap; + va_list ap; + + bitmap = ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd0); + + + va_start(ap, cmd0); + for (;;) { + int cmd = va_arg(ap, int); + if (cmd < 0) { + break; + } + bitmap |= ZIP_SOURCE_MAKE_COMMAND_BITMASK(cmd); + } + va_end(ap); + + return bitmap; +} diff --git a/third_party/libzip/lib/zip_source_tell.c b/third_party/libzip/lib/zip_source_tell.c new file mode 100644 index 0000000..da13cf5 --- /dev/null +++ b/third_party/libzip/lib/zip_source_tell.c @@ -0,0 +1,49 @@ +/* + zip_source_tell.c -- report current offset + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_tell(zip_source_t *src) { + if (src->source_closed) { + return -1; + } + if (!ZIP_SOURCE_IS_OPEN_READING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_source_call(src, NULL, 0, ZIP_SOURCE_TELL); +} diff --git a/third_party/libzip/lib/zip_source_tell_write.c b/third_party/libzip/lib/zip_source_tell_write.c new file mode 100644 index 0000000..d20139f --- /dev/null +++ b/third_party/libzip/lib/zip_source_tell_write.c @@ -0,0 +1,46 @@ +/* + zip_source_tell_write.c -- report current offset for writing + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_tell_write(zip_source_t *src) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src)) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_source_call(src, NULL, 0, ZIP_SOURCE_TELL_WRITE); +} diff --git a/third_party/libzip/lib/zip_source_win32a.c b/third_party/libzip/lib/zip_source_win32a.c new file mode 100644 index 0000000..79bb2e8 --- /dev/null +++ b/third_party/libzip/lib/zip_source_win32a.c @@ -0,0 +1,120 @@ +/* + zip_source_win32a.c -- create data source from Windows file (ANSI) + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" +#include "zipwin32.h" + +static void *_win32_strdup_a(const void *str); +static HANDLE _win32_open_a(_zip_source_win32_read_file_t *ctx); +static HANDLE _win32_create_temp_a(_zip_source_win32_read_file_t *ctx, void **temp, zip_uint32_t value, PSECURITY_ATTRIBUTES sa); +static int _win32_rename_temp_a(_zip_source_win32_read_file_t *ctx); +static int _win32_remove_a(const void *fname); + +// clang-format off +static _zip_source_win32_file_ops_t win32_ops_a = { + _win32_strdup_a, + _win32_open_a, + _win32_create_temp_a, + _win32_rename_temp_a, + _win32_remove_a +}; +// clang-format on + +ZIP_EXTERN zip_source_t * +zip_source_win32a(zip_t *za, const char *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_win32a_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_win32a_create(const char *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return _zip_source_win32_handle_or_name(fname, INVALID_HANDLE_VALUE, start, length, 1, NULL, &win32_ops_a, error); +} + + +static void * +_win32_strdup_a(const void *str) { + return strdup((const char *)str); +} + + +static HANDLE +_win32_open_a(_zip_source_win32_read_file_t *ctx) { + return CreateFileA(ctx->fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +} + + +static HANDLE +_win32_create_temp_a(_zip_source_win32_read_file_t *ctx, void **temp, zip_uint32_t value, PSECURITY_ATTRIBUTES sa) { + size_t len; + + len = strlen((const char *)ctx->fname) + 10; + if (*temp == NULL) { + if ((*temp = malloc(sizeof(char) * len)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return INVALID_HANDLE_VALUE; + } + } + if (sprintf((char *)*temp, "%s.%08x", (const char *)ctx->fname, value) != len - 1) { + return INVALID_HANDLE_VALUE; + } + + return CreateFileA((const char *)*temp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY, NULL); +} + + +static int +_win32_rename_temp_a(_zip_source_win32_read_file_t *ctx) { + if (!MoveFileExA(ctx->tmpname, ctx->fname, MOVEFILE_REPLACE_EXISTING)) + return -1; + return 0; +} + + +static int +_win32_remove_a(const void *fname) { + DeleteFileA((const char *)fname); + return 0; +} diff --git a/third_party/libzip/lib/zip_source_win32handle.c b/third_party/libzip/lib/zip_source_win32handle.c new file mode 100644 index 0000000..3a2f52e --- /dev/null +++ b/third_party/libzip/lib/zip_source_win32handle.c @@ -0,0 +1,597 @@ +/* + zip_source_win32file.c -- create data source from HANDLE (Win32) + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include + +#include "zipint.h" +#include "zipwin32.h" + +static zip_int64_t _win32_read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd); +static int _win32_create_temp_file(_zip_source_win32_read_file_t *ctx); +static int _zip_filetime_to_time_t(FILETIME ft, time_t *t); +static int _zip_seek_win32_u(void *h, zip_uint64_t offset, int whence, zip_error_t *error); +static int _zip_seek_win32(void *h, zip_int64_t offset, int whence, zip_error_t *error); +static int _zip_win32_error_to_errno(unsigned long win32err); +static int _zip_stat_win32(void *h, zip_stat_t *st, _zip_source_win32_read_file_t *ctx); + +ZIP_EXTERN zip_source_t * +zip_source_win32handle(zip_t *za, HANDLE h, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_win32handle_create(h, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_win32handle_create(HANDLE h, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (h == INVALID_HANDLE_VALUE || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return _zip_source_win32_handle_or_name(NULL, h, start, length, 1, NULL, NULL, error); +} + + +zip_source_t * +_zip_source_win32_handle_or_name(const void *fname, HANDLE h, zip_uint64_t start, zip_int64_t len, int closep, const zip_stat_t *st, _zip_source_win32_file_ops_t *ops, zip_error_t *error) { + _zip_source_win32_read_file_t *ctx; + zip_source_t *zs; + + if (h == INVALID_HANDLE_VALUE && fname == NULL) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (_zip_source_win32_read_file_t *)malloc(sizeof(_zip_source_win32_read_file_t))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->fname = NULL; + if (fname) { + if ((ctx->fname = ops->op_strdup(fname)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + } + + ctx->ops = ops; + ctx->h = h; + ctx->start = start; + ctx->end = (len < 0 ? 0 : start + (zip_uint64_t)len); + ctx->closep = ctx->fname ? 1 : closep; + if (st) { + memcpy(&ctx->st, st, sizeof(ctx->st)); + ctx->st.name = NULL; + ctx->st.valid &= ~ZIP_STAT_NAME; + } + else { + zip_stat_init(&ctx->st); + } + + ctx->tmpname = NULL; + ctx->hout = INVALID_HANDLE_VALUE; + + zip_error_init(&ctx->error); + + ctx->supports = ZIP_SOURCE_SUPPORTS_READABLE | zip_source_make_command_bitmap(ZIP_SOURCE_SUPPORTS, ZIP_SOURCE_TELL, -1); + if (ctx->fname) { + HANDLE th; + + th = ops->op_open(ctx); + if (th == INVALID_HANDLE_VALUE || GetFileType(th) == FILE_TYPE_DISK) { + ctx->supports = ZIP_SOURCE_SUPPORTS_WRITABLE; + } + if (th != INVALID_HANDLE_VALUE) { + CloseHandle(th); + } + } + else if (GetFileType(ctx->h) == FILE_TYPE_DISK) { + ctx->supports = ZIP_SOURCE_SUPPORTS_SEEKABLE; + } + + if ((zs = zip_source_function_create(_win32_read_file, ctx, error)) == NULL) { + free(ctx->fname); + free(ctx); + return NULL; + } + + return zs; +} + + +static zip_int64_t +_win32_read_file(void *state, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + _zip_source_win32_read_file_t *ctx; + char *buf; + zip_uint64_t n; + DWORD i; + + ctx = (_zip_source_win32_read_file_t *)state; + buf = (char *)data; + + switch (cmd) { + case ZIP_SOURCE_BEGIN_WRITE: + if (ctx->fname == NULL) { + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } + return _win32_create_temp_file(ctx); + + case ZIP_SOURCE_COMMIT_WRITE: { + if (!CloseHandle(ctx->hout)) { + ctx->hout = INVALID_HANDLE_VALUE; + zip_error_set(&ctx->error, ZIP_ER_WRITE, _zip_win32_error_to_errno(GetLastError())); + } + ctx->hout = INVALID_HANDLE_VALUE; + if (ctx->ops->op_rename_temp(ctx) < 0) { + zip_error_set(&ctx->error, ZIP_ER_RENAME, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + free(ctx->tmpname); + ctx->tmpname = NULL; + return 0; + } + + case ZIP_SOURCE_CLOSE: + if (ctx->fname) { + CloseHandle(ctx->h); + ctx->h = INVALID_HANDLE_VALUE; + } + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx->fname); + free(ctx->tmpname); + if (ctx->closep && ctx->h != INVALID_HANDLE_VALUE) + CloseHandle(ctx->h); + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + if (ctx->fname) { + if ((ctx->h = ctx->ops->op_open(ctx)) == INVALID_HANDLE_VALUE) { + zip_error_set(&ctx->error, ZIP_ER_OPEN, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + } + + if (ctx->closep && ctx->start > 0) { + if (_zip_seek_win32_u(ctx->h, ctx->start, SEEK_SET, &ctx->error) < 0) { + return -1; + } + } + ctx->current = ctx->start; + return 0; + + case ZIP_SOURCE_READ: + if (ctx->end > 0) { + n = ctx->end - ctx->current; + if (n > len) { + n = len; + } + } + else { + n = len; + } + + if (n > SIZE_MAX) + n = SIZE_MAX; + + if (!ctx->closep) { + if (_zip_seek_win32_u(ctx->h, ctx->current, SEEK_SET, &ctx->error) < 0) { + return -1; + } + } + + if (!ReadFile(ctx->h, buf, (DWORD)n, &i, NULL)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + ctx->current += i; + + return (zip_int64_t)i; + + case ZIP_SOURCE_REMOVE: + if (ctx->ops->op_remove(ctx->fname) < 0) { + zip_error_set(&ctx->error, ZIP_ER_REMOVE, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + return 0; + + case ZIP_SOURCE_ROLLBACK_WRITE: + if (ctx->hout) { + CloseHandle(ctx->hout); + ctx->hout = INVALID_HANDLE_VALUE; + } + ctx->ops->op_remove(ctx->tmpname); + free(ctx->tmpname); + ctx->tmpname = NULL; + return 0; + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_current; + int need_seek; + zip_source_args_seek_t *args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + + if (args == NULL) + return -1; + + need_seek = ctx->closep; + + switch (args->whence) { + case SEEK_SET: + new_current = args->offset; + break; + + case SEEK_END: + if (ctx->end == 0) { + LARGE_INTEGER zero; + LARGE_INTEGER new_offset; + + if (_zip_seek_win32(ctx->h, args->offset, SEEK_END, &ctx->error) < 0) { + return -1; + } + zero.QuadPart = 0; + if (!SetFilePointerEx(ctx->h, zero, &new_offset, FILE_CURRENT)) { + zip_error_set(&ctx->error, ZIP_ER_SEEK, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + new_current = new_offset.QuadPart; + need_seek = 0; + } + else { + new_current = (zip_int64_t)ctx->end + args->offset; + } + break; + case SEEK_CUR: + new_current = (zip_int64_t)ctx->current + args->offset; + break; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (new_current < 0 || (zip_uint64_t)new_current < ctx->start || (ctx->end != 0 && (zip_uint64_t)new_current > ctx->end)) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + ctx->current = (zip_uint64_t)new_current; + + if (need_seek) { + if (_zip_seek_win32_u(ctx->h, ctx->current, SEEK_SET, &ctx->error) < 0) { + return -1; + } + } + return 0; + } + + case ZIP_SOURCE_SEEK_WRITE: { + zip_source_args_seek_t *args; + + args = ZIP_SOURCE_GET_ARGS(zip_source_args_seek_t, data, len, &ctx->error); + if (args == NULL) { + return -1; + } + + if (_zip_seek_win32(ctx->hout, args->offset, args->whence, &ctx->error) < 0) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_STAT: { + if (len < sizeof(ctx->st)) + return -1; + + if (ctx->st.valid != 0) + memcpy(data, &ctx->st, sizeof(ctx->st)); + else { + DWORD win32err; + zip_stat_t *st; + HANDLE h; + int success; + + st = (zip_stat_t *)data; + + if (ctx->h != INVALID_HANDLE_VALUE) { + h = ctx->h; + } + else { + h = ctx->ops->op_open(ctx); + if (h == INVALID_HANDLE_VALUE) { + win32err = GetLastError(); + if (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND) { + zip_error_set(&ctx->error, ZIP_ER_READ, ENOENT); + return -1; + } + } + } + + success = _zip_stat_win32(h, st, ctx); + win32err = GetLastError(); + + /* We're done with the handle, so close it if we just opened it. */ + if (h != ctx->h) { + CloseHandle(h); + } + + if (success < 0) { + /* TODO: Is this the correct error to return in all cases? */ + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(win32err)); + return -1; + } + } + return sizeof(ctx->st); + } + + case ZIP_SOURCE_SUPPORTS: + return ctx->supports; + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->current; + + case ZIP_SOURCE_TELL_WRITE: { + LARGE_INTEGER zero; + LARGE_INTEGER offset; + + zero.QuadPart = 0; + if (!SetFilePointerEx(ctx->hout, zero, &offset, FILE_CURRENT)) { + zip_error_set(&ctx->error, ZIP_ER_TELL, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return offset.QuadPart; + } + + case ZIP_SOURCE_WRITE: { + DWORD ret; + if (!WriteFile(ctx->hout, data, (DWORD)len, &ret, NULL) || ret != len) { + zip_error_set(&ctx->error, ZIP_ER_WRITE, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return (zip_int64_t)ret; + } + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +static int +_win32_create_temp_file(_zip_source_win32_read_file_t *ctx) { + zip_uint32_t value; + /* + Windows has GetTempFileName(), but it closes the file after + creation, leaving it open to a horrible race condition. So + we reinvent the wheel. + */ + int i; + HANDLE th = INVALID_HANDLE_VALUE; + void *temp = NULL; + PSECURITY_DESCRIPTOR psd = NULL; + PSECURITY_ATTRIBUTES psa = NULL; + SECURITY_ATTRIBUTES sa; + SECURITY_INFORMATION si; + DWORD success; + PACL dacl = NULL; + + /* + Read the DACL from the original file, so we can copy it to the temp file. + If there is no original file, or if we can't read the DACL, we'll use the + default security descriptor. + */ + if (ctx->h != INVALID_HANDLE_VALUE && GetFileType(ctx->h) == FILE_TYPE_DISK) { + si = DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION; + success = GetSecurityInfo(ctx->h, SE_FILE_OBJECT, si, NULL, NULL, &dacl, NULL, &psd); + if (success == ERROR_SUCCESS) { + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.bInheritHandle = FALSE; + sa.lpSecurityDescriptor = psd; + psa = &sa; + } + } + + +#ifndef MS_UWP + value = GetTickCount(); +#else + value = (zip_uint32_t)GetTickCount64(); +#endif + + for (i = 0; i < 1024 && th == INVALID_HANDLE_VALUE; i++) { + th = ctx->ops->op_create_temp(ctx, &temp, value + i, psa); + if (th == INVALID_HANDLE_VALUE && GetLastError() != ERROR_FILE_EXISTS) + break; + } + + if (th == INVALID_HANDLE_VALUE) { + free(temp); + LocalFree(psd); + zip_error_set(&ctx->error, ZIP_ER_TMPOPEN, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + LocalFree(psd); + ctx->hout = th; + ctx->tmpname = temp; + + return 0; +} + + +static int +_zip_seek_win32_u(HANDLE h, zip_uint64_t offset, int whence, zip_error_t *error) { + if (offset > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_SEEK, EOVERFLOW); + return -1; + } + return _zip_seek_win32(h, (zip_int64_t)offset, whence, error); +} + + +static int +_zip_seek_win32(HANDLE h, zip_int64_t offset, int whence, zip_error_t *error) { + LARGE_INTEGER li; + DWORD method; + + switch (whence) { + case SEEK_SET: + method = FILE_BEGIN; + break; + case SEEK_END: + method = FILE_END; + break; + case SEEK_CUR: + method = FILE_CURRENT; + break; + default: + zip_error_set(error, ZIP_ER_SEEK, EINVAL); + return -1; + } + + li.QuadPart = (LONGLONG)offset; + if (!SetFilePointerEx(h, li, NULL, method)) { + zip_error_set(error, ZIP_ER_SEEK, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + return 0; +} + + +static int +_zip_win32_error_to_errno(DWORD win32err) { + /* + Note: This list isn't exhaustive, but should cover common cases. + */ + switch (win32err) { + case ERROR_INVALID_PARAMETER: + return EINVAL; + case ERROR_FILE_NOT_FOUND: + return ENOENT; + case ERROR_INVALID_HANDLE: + return EBADF; + case ERROR_ACCESS_DENIED: + return EACCES; + case ERROR_FILE_EXISTS: + return EEXIST; + case ERROR_TOO_MANY_OPEN_FILES: + return EMFILE; + case ERROR_DISK_FULL: + return ENOSPC; + default: + return 0; + } +} + + +static int +_zip_stat_win32(HANDLE h, zip_stat_t *st, _zip_source_win32_read_file_t *ctx) { + FILETIME mtimeft; + time_t mtime; + LARGE_INTEGER size; + int regularp; + + if (!GetFileTime(h, NULL, NULL, &mtimeft)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + if (_zip_filetime_to_time_t(mtimeft, &mtime) < 0) { + zip_error_set(&ctx->error, ZIP_ER_READ, ERANGE); + return -1; + } + + regularp = 0; + if (GetFileType(h) == FILE_TYPE_DISK) { + regularp = 1; + } + + if (!GetFileSizeEx(h, &size)) { + zip_error_set(&ctx->error, ZIP_ER_READ, _zip_win32_error_to_errno(GetLastError())); + return -1; + } + + zip_stat_init(st); + st->mtime = mtime; + st->valid |= ZIP_STAT_MTIME; + if (ctx->end != 0) { + st->size = ctx->end - ctx->start; + st->valid |= ZIP_STAT_SIZE; + } + else if (regularp) { + st->size = (zip_uint64_t)size.QuadPart; + st->valid |= ZIP_STAT_SIZE; + } + + return 0; +} + + +static int +_zip_filetime_to_time_t(FILETIME ft, time_t *t) { + /* + Inspired by http://stackoverflow.com/questions/6161776/convert-windows-filetime-to-second-in-unix-linux + */ + const zip_int64_t WINDOWS_TICK = 10000000LL; + const zip_int64_t SEC_TO_UNIX_EPOCH = 11644473600LL; + ULARGE_INTEGER li; + zip_int64_t secs; + time_t temp; + + li.LowPart = ft.dwLowDateTime; + li.HighPart = ft.dwHighDateTime; + secs = (li.QuadPart / WINDOWS_TICK - SEC_TO_UNIX_EPOCH); + + temp = (time_t)secs; + if (secs != (zip_int64_t)temp) + return -1; + + *t = temp; + return 0; +} diff --git a/third_party/libzip/lib/zip_source_win32utf8.c b/third_party/libzip/lib/zip_source_win32utf8.c new file mode 100644 index 0000000..4ad2bf0 --- /dev/null +++ b/third_party/libzip/lib/zip_source_win32utf8.c @@ -0,0 +1,77 @@ +/* + zip_source_win32utf8.c -- create data source from Windows file (UTF-8) + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" +#include "zipwin32.h" + + +ZIP_EXTERN zip_source_t * +zip_source_file(zip_t *za, const char *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_file_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_file_create(const char *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + int size; + wchar_t *wfname; + zip_source_t *source; + + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + /* Convert fname from UTF-8 to Windows-friendly UTF-16. */ + size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, fname, -1, NULL, 0); + if (size == 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if ((wfname = (wchar_t *)malloc(sizeof(wchar_t) * size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, fname, -1, wfname, size); + + source = zip_source_win32w_create(wfname, start, length, error); + + free(wfname); + return source; +} diff --git a/third_party/libzip/lib/zip_source_win32w.c b/third_party/libzip/lib/zip_source_win32w.c new file mode 100644 index 0000000..6a433fb --- /dev/null +++ b/third_party/libzip/lib/zip_source_win32w.c @@ -0,0 +1,144 @@ +/* + zip_source_win32w.c -- create data source from Windows file (UTF-16) + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" +#include "zipwin32.h" + +static void *_win32_strdup_w(const void *str); +static HANDLE _win32_open_w(_zip_source_win32_read_file_t *ctx); +static HANDLE _win32_create_temp_w(_zip_source_win32_read_file_t *ctx, void **temp, zip_uint32_t value, PSECURITY_ATTRIBUTES sa); +static int _win32_rename_temp_w(_zip_source_win32_read_file_t *ctx); +static int _win32_remove_w(const void *fname); + +// clang-format off +static _zip_source_win32_file_ops_t win32_ops_w = { + _win32_strdup_w, + _win32_open_w, + _win32_create_temp_w, + _win32_rename_temp_w, + _win32_remove_w +}; +// clang-format on + +ZIP_EXTERN zip_source_t * +zip_source_win32w(zip_t *za, const wchar_t *fname, zip_uint64_t start, zip_int64_t len) { + if (za == NULL) + return NULL; + + return zip_source_win32w_create(fname, start, len, &za->error); +} + + +ZIP_EXTERN zip_source_t * +zip_source_win32w_create(const wchar_t *fname, zip_uint64_t start, zip_int64_t length, zip_error_t *error) { + if (fname == NULL || length < -1) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + return _zip_source_win32_handle_or_name(fname, INVALID_HANDLE_VALUE, start, length, 1, NULL, &win32_ops_w, error); +} + + +static void * +_win32_strdup_w(const void *str) { + return _wcsdup((const wchar_t *)str); +} + + +static HANDLE +_win32_open_w(_zip_source_win32_read_file_t *ctx) { +#ifdef MS_UWP + CREATEFILE2_EXTENDED_PARAMETERS extParams = {0}; + extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; + extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; + extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; + extParams.dwSize = sizeof(extParams); + extParams.hTemplateFile = NULL; + extParams.lpSecurityAttributes = NULL; + + return CreateFile2(ctx->fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, &extParams); +#else + return CreateFileW(ctx->fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +#endif +} + + +static HANDLE +_win32_create_temp_w(_zip_source_win32_read_file_t *ctx, void **temp, zip_uint32_t value, PSECURITY_ATTRIBUTES sa) { + size_t len; + + len = wcslen((const wchar_t *)ctx->fname) + 10; + if (*temp == NULL) { + if ((*temp = malloc(sizeof(wchar_t) * len)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return INVALID_HANDLE_VALUE; + } + } + if (_snwprintf((wchar_t *)*temp, len, L"%s.%08x", (const wchar_t *)ctx->fname, value) != len - 1) { + return INVALID_HANDLE_VALUE; + } + +#ifdef MS_UWP + CREATEFILE2_EXTENDED_PARAMETERS extParams = {0}; + extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY; + extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; + extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; + extParams.dwSize = sizeof(extParams); + extParams.hTemplateFile = NULL; + extParams.lpSecurityAttributes = NULL; + + return CreateFile2((const wchar_t *)*temp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, CREATE_NEW, &extParams); +#else + return CreateFileW((const wchar_t *)*temp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY, NULL); +#endif +} + + +static int +_win32_rename_temp_w(_zip_source_win32_read_file_t *ctx) { + if (!MoveFileExW(ctx->tmpname, ctx->fname, MOVEFILE_REPLACE_EXISTING)) + return -1; + return 0; +} + + +static int +_win32_remove_w(const void *fname) { + DeleteFileW((const wchar_t *)fname); + return 0; +} diff --git a/third_party/libzip/lib/zip_source_window.c b/third_party/libzip/lib/zip_source_window.c new file mode 100644 index 0000000..d9e90bf --- /dev/null +++ b/third_party/libzip/lib/zip_source_window.c @@ -0,0 +1,283 @@ +/* + zip_source_window.c -- return part of lower source + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +struct window { + zip_uint64_t start; /* where in file we start reading */ + zip_uint64_t end; /* where in file we stop reading */ + + /* if not NULL, read file data for this file */ + zip_t *source_archive; + zip_uint64_t source_index; + + zip_uint64_t offset; /* offset in src for next read */ + + zip_stat_t stat; + zip_int8_t compression_flags; + zip_error_t error; + zip_int64_t supports; + bool needs_seek; +}; + +static zip_int64_t window_read(zip_source_t *, void *, void *, zip_uint64_t, zip_source_cmd_t); + + +zip_source_t * +zip_source_window(zip_t *za, zip_source_t *src, zip_uint64_t start, zip_uint64_t len) { + return _zip_source_window_new(src, start, len, NULL, 0, NULL, 0, &za->error); +} + + +zip_source_t * +_zip_source_window_new(zip_source_t *src, zip_uint64_t start, zip_uint64_t length, zip_stat_t *st, zip_int8_t compression_flags, zip_t *source_archive, zip_uint64_t source_index, zip_error_t *error) { + struct window *ctx; + + if (src == NULL || start + length < start || (source_archive == NULL && source_index != 0)) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = (struct window *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->start = start; + ctx->end = start + length; + zip_stat_init(&ctx->stat); + ctx->compression_flags = compression_flags; + ctx->source_archive = source_archive; + ctx->source_index = source_index; + zip_error_init(&ctx->error); + ctx->supports = (zip_source_supports(src) & ZIP_SOURCE_SUPPORTS_SEEKABLE) | (zip_source_make_command_bitmap(ZIP_SOURCE_GET_COMPRESSION_FLAGS, ZIP_SOURCE_SUPPORTS, ZIP_SOURCE_TELL, -1)); + ctx->needs_seek = (ctx->supports & ZIP_SOURCE_MAKE_COMMAND_BITMASK(ZIP_SOURCE_SEEK)) ? true : false; + + if (st) { + if (_zip_stat_merge(&ctx->stat, st, error) < 0) { + free(ctx); + return NULL; + } + } + + return zip_source_layered_create(src, window_read, ctx, error); +} + + +int +_zip_source_set_source_archive(zip_source_t *src, zip_t *za) { + src->source_archive = za; + return _zip_register_source(za, src); +} + + +/* called by zip_discard to avoid operating on file from closed archive */ +void +_zip_source_invalidate(zip_source_t *src) { + src->source_closed = 1; + + if (zip_error_code_zip(&src->error) == ZIP_ER_OK) { + zip_error_set(&src->error, ZIP_ER_ZIPCLOSED, 0); + } +} + + +static zip_int64_t +window_read(zip_source_t *src, void *_ctx, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct window *ctx; + zip_int64_t ret; + zip_uint64_t n, i; + + ctx = (struct window *)_ctx; + + switch (cmd) { + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + if (ctx->source_archive) { + zip_uint64_t offset; + + if ((offset = _zip_file_get_offset(ctx->source_archive, ctx->source_index, &ctx->error)) == 0) { + return -1; + } + if (ctx->end + offset < ctx->end) { + /* zip archive data claims end of data past zip64 limits */ + zip_error_set(&ctx->error, ZIP_ER_INCONS, 0); + return -1; + } + ctx->start += offset; + ctx->end += offset; + ctx->source_archive = NULL; + } + + if (!ctx->needs_seek) { + DEFINE_BYTE_ARRAY(b, BUFSIZE); + + if (!byte_array_init(b, BUFSIZE)) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + for (n = 0; n < ctx->start; n += (zip_uint64_t)ret) { + i = (ctx->start - n > BUFSIZE ? BUFSIZE : ctx->start - n); + if ((ret = zip_source_read(src, b, i)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + byte_array_fini(b); + return -1; + } + if (ret == 0) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + byte_array_fini(b); + return -1; + } + } + + byte_array_fini(b); + } + + ctx->offset = ctx->start; + return 0; + + case ZIP_SOURCE_READ: + if (len > ctx->end - ctx->offset) + len = ctx->end - ctx->offset; + + if (len == 0) + return 0; + + if (ctx->needs_seek) { + if (zip_source_seek(src, (zip_int64_t)ctx->offset, SEEK_SET) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + } + + if ((ret = zip_source_read(src, data, len)) < 0) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + + ctx->offset += (zip_uint64_t)ret; + + if (ret == 0) { + if (ctx->offset < ctx->end) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + } + return ret; + + case ZIP_SOURCE_SEEK: { + zip_int64_t new_offset = zip_source_seek_compute_offset(ctx->offset - ctx->start, ctx->end - ctx->start, data, len, &ctx->error); + + if (new_offset < 0) { + return -1; + } + + ctx->offset = (zip_uint64_t)new_offset + ctx->start; + return 0; + } + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + if (_zip_stat_merge(st, &ctx->stat, &ctx->error) < 0) { + return -1; + } + return 0; + } + + case ZIP_SOURCE_GET_COMPRESSION_FLAGS: + return ctx->compression_flags; + + case ZIP_SOURCE_SUPPORTS: + return ctx->supports; + + case ZIP_SOURCE_TELL: + return (zip_int64_t)(ctx->offset - ctx->start); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + + +void +_zip_deregister_source(zip_t *za, zip_source_t *src) { + unsigned int i; + + for (i = 0; i < za->nopen_source; i++) { + if (za->open_source[i] == src) { + za->open_source[i] = za->open_source[za->nopen_source - 1]; + za->nopen_source--; + break; + } + } +} + + +int +_zip_register_source(zip_t *za, zip_source_t *src) { + zip_source_t **open_source; + + if (za->nopen_source + 1 >= za->nopen_source_alloc) { + unsigned int n; + n = za->nopen_source_alloc + 10; + open_source = (zip_source_t **)realloc(za->open_source, n * sizeof(zip_source_t *)); + if (open_source == NULL) { + zip_error_set(&za->error, ZIP_ER_MEMORY, 0); + return -1; + } + za->nopen_source_alloc = n; + za->open_source = open_source; + } + + za->open_source[za->nopen_source++] = src; + + return 0; +} diff --git a/third_party/libzip/lib/zip_source_winzip_aes_decode.c b/third_party/libzip/lib/zip_source_winzip_aes_decode.c new file mode 100644 index 0000000..f1a05a8 --- /dev/null +++ b/third_party/libzip/lib/zip_source_winzip_aes_decode.c @@ -0,0 +1,265 @@ +/* + zip_source_winzip_aes_decode.c -- Winzip AES decryption routines + Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + +struct winzip_aes { + char *password; + zip_uint16_t encryption_method; + + zip_uint64_t data_length; + zip_uint64_t current_position; + + zip_winzip_aes_t *aes_ctx; + zip_error_t error; +}; + + +static int decrypt_header(zip_source_t *src, struct winzip_aes *ctx); +static void winzip_aes_free(struct winzip_aes *); +static zip_int64_t winzip_aes_decrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd); +static struct winzip_aes *winzip_aes_new(zip_uint16_t encryption_method, const char *password, zip_error_t *error); + + +zip_source_t * +zip_source_winzip_aes_decode(zip_t *za, zip_source_t *src, zip_uint16_t encryption_method, int flags, const char *password) { + zip_source_t *s2; + zip_stat_t st; + zip_uint64_t aux_length; + struct winzip_aes *ctx; + + if ((encryption_method != ZIP_EM_AES_128 && encryption_method != ZIP_EM_AES_192 && encryption_method != ZIP_EM_AES_256) || password == NULL || src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + if (flags & ZIP_CODEC_ENCODE) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + if (zip_source_stat(src, &st) != 0) { + _zip_error_set_from_source(&za->error, src); + return NULL; + } + + aux_length = WINZIP_AES_PASSWORD_VERIFY_LENGTH + SALT_LENGTH(encryption_method) + HMAC_LENGTH; + + if ((st.valid & ZIP_STAT_COMP_SIZE) == 0 || st.comp_size < aux_length) { + zip_error_set(&za->error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + + if ((ctx = winzip_aes_new(encryption_method, password, &za->error)) == NULL) { + return NULL; + } + + ctx->data_length = st.comp_size - aux_length; + + if ((s2 = zip_source_layered(za, src, winzip_aes_decrypt, ctx)) == NULL) { + winzip_aes_free(ctx); + return NULL; + } + + return s2; +} + + +static int +decrypt_header(zip_source_t *src, struct winzip_aes *ctx) { + zip_uint8_t header[WINZIP_AES_MAX_HEADER_LENGTH]; + zip_uint8_t password_verification[WINZIP_AES_PASSWORD_VERIFY_LENGTH]; + unsigned int headerlen; + zip_int64_t n; + + headerlen = WINZIP_AES_PASSWORD_VERIFY_LENGTH + SALT_LENGTH(ctx->encryption_method); + if ((n = zip_source_read(src, header, headerlen)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (n != headerlen) { + zip_error_set(&ctx->error, ZIP_ER_EOF, 0); + return -1; + } + + if ((ctx->aes_ctx = _zip_winzip_aes_new((zip_uint8_t *)ctx->password, strlen(ctx->password), header, ctx->encryption_method, password_verification, &ctx->error)) == NULL) { + return -1; + } + if (memcmp(password_verification, header + SALT_LENGTH(ctx->encryption_method), WINZIP_AES_PASSWORD_VERIFY_LENGTH) != 0) { + _zip_winzip_aes_free(ctx->aes_ctx); + ctx->aes_ctx = NULL; + zip_error_set(&ctx->error, ZIP_ER_WRONGPASSWD, 0); + return -1; + } + return 0; +} + + +static bool +verify_hmac(zip_source_t *src, struct winzip_aes *ctx) { + unsigned char computed[SHA1_LENGTH], from_file[HMAC_LENGTH]; + if (zip_source_read(src, from_file, HMAC_LENGTH) < HMAC_LENGTH) { + _zip_error_set_from_source(&ctx->error, src); + return false; + } + + if (!_zip_winzip_aes_finish(ctx->aes_ctx, computed)) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return false; + } + _zip_winzip_aes_free(ctx->aes_ctx); + ctx->aes_ctx = NULL; + + if (memcmp(from_file, computed, HMAC_LENGTH) != 0) { + zip_error_set(&ctx->error, ZIP_ER_CRC, 0); + return false; + } + + return true; +} + + +static zip_int64_t +winzip_aes_decrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd) { + struct winzip_aes *ctx; + zip_int64_t n; + + ctx = (struct winzip_aes *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + if (decrypt_header(src, ctx) < 0) { + return -1; + } + ctx->current_position = 0; + return 0; + + case ZIP_SOURCE_READ: + if (len > ctx->data_length - ctx->current_position) { + len = ctx->data_length - ctx->current_position; + } + + if (len == 0) { + if (!verify_hmac(src, ctx)) { + return -1; + } + return 0; + } + + if ((n = zip_source_read(src, data, len)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + ctx->current_position += (zip_uint64_t)n; + + if (!_zip_winzip_aes_decrypt(ctx->aes_ctx, (zip_uint8_t *)data, (zip_uint64_t)n)) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + return n; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + + st->encryption_method = ZIP_EM_NONE; + st->valid |= ZIP_STAT_ENCRYPTION_METHOD; + if (st->valid & ZIP_STAT_COMP_SIZE) { + st->comp_size -= 12 + SALT_LENGTH(ctx->encryption_method); + } + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, -1); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, len); + + case ZIP_SOURCE_FREE: + winzip_aes_free(ctx); + return 0; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } +} + + +static void +winzip_aes_free(struct winzip_aes *ctx) { + if (ctx == NULL) { + return; + } + + _zip_crypto_clear(ctx->password, strlen(ctx->password)); + free(ctx->password); + zip_error_fini(&ctx->error); + _zip_winzip_aes_free(ctx->aes_ctx); + free(ctx); +} + + +static struct winzip_aes * +winzip_aes_new(zip_uint16_t encryption_method, const char *password, zip_error_t *error) { + struct winzip_aes *ctx; + + if ((ctx = (struct winzip_aes *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->password = strdup(password)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + free(ctx); + return NULL; + } + + ctx->encryption_method = encryption_method; + ctx->aes_ctx = NULL; + + zip_error_init(&ctx->error); + + return ctx; +} diff --git a/third_party/libzip/lib/zip_source_winzip_aes_encode.c b/third_party/libzip/lib/zip_source_winzip_aes_encode.c new file mode 100644 index 0000000..c428c9a --- /dev/null +++ b/third_party/libzip/lib/zip_source_winzip_aes_encode.c @@ -0,0 +1,242 @@ +/* + zip_source_winzip_aes_encode.c -- Winzip AES encryption routines + Copyright (C) 2009-2019 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +struct winzip_aes { + char *password; + zip_uint16_t encryption_method; + + zip_uint8_t data[ZIP_MAX(WINZIP_AES_MAX_HEADER_LENGTH, SHA1_LENGTH)]; + zip_buffer_t *buffer; + + zip_winzip_aes_t *aes_ctx; + bool eof; + zip_error_t error; +}; + + +static int encrypt_header(zip_source_t *src, struct winzip_aes *ctx); +static void winzip_aes_free(struct winzip_aes *); +static zip_int64_t winzip_aes_encrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t len, zip_source_cmd_t cmd); +static struct winzip_aes *winzip_aes_new(zip_uint16_t encryption_method, const char *password, zip_error_t *error); + + +zip_source_t * +zip_source_winzip_aes_encode(zip_t *za, zip_source_t *src, zip_uint16_t encryption_method, int flags, const char *password) { + zip_source_t *s2; + struct winzip_aes *ctx; + + if ((encryption_method != ZIP_EM_AES_128 && encryption_method != ZIP_EM_AES_192 && encryption_method != ZIP_EM_AES_256) || password == NULL || src == NULL) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((ctx = winzip_aes_new(encryption_method, password, &za->error)) == NULL) { + return NULL; + } + + if ((s2 = zip_source_layered(za, src, winzip_aes_encrypt, ctx)) == NULL) { + winzip_aes_free(ctx); + return NULL; + } + + return s2; +} + + +static int +encrypt_header(zip_source_t *src, struct winzip_aes *ctx) { + zip_uint16_t salt_length = SALT_LENGTH(ctx->encryption_method); + if (!zip_random(ctx->data, salt_length)) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + return -1; + } + + if ((ctx->aes_ctx = _zip_winzip_aes_new((zip_uint8_t *)ctx->password, strlen(ctx->password), ctx->data, ctx->encryption_method, ctx->data + salt_length, &ctx->error)) == NULL) { + return -1; + } + + if ((ctx->buffer = _zip_buffer_new(ctx->data, salt_length + WINZIP_AES_PASSWORD_VERIFY_LENGTH)) == NULL) { + _zip_winzip_aes_free(ctx->aes_ctx); + ctx->aes_ctx = NULL; + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + return -1; + } + + return 0; +} + + +static zip_int64_t +winzip_aes_encrypt(zip_source_t *src, void *ud, void *data, zip_uint64_t length, zip_source_cmd_t cmd) { + struct winzip_aes *ctx; + zip_int64_t ret; + zip_uint64_t buffer_n; + + ctx = (struct winzip_aes *)ud; + + switch (cmd) { + case ZIP_SOURCE_OPEN: + ctx->eof = false; + if (encrypt_header(src, ctx) < 0) { + return -1; + } + return 0; + + case ZIP_SOURCE_READ: + buffer_n = 0; + + if (ctx->buffer) { + buffer_n = _zip_buffer_read(ctx->buffer, data, length); + + data = (zip_uint8_t *)data + buffer_n; + length -= buffer_n; + + if (_zip_buffer_eof(ctx->buffer)) { + _zip_buffer_free(ctx->buffer); + ctx->buffer = NULL; + } + } + + if (ctx->eof) { + return (zip_int64_t)buffer_n; + } + + if ((ret = zip_source_read(src, data, length)) < 0) { + _zip_error_set_from_source(&ctx->error, src); + return -1; + } + + if (!_zip_winzip_aes_encrypt(ctx->aes_ctx, data, (zip_uint64_t)ret)) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + /* TODO: return partial read? */ + return -1; + } + + if ((zip_uint64_t)ret < length) { + ctx->eof = true; + if (!_zip_winzip_aes_finish(ctx->aes_ctx, ctx->data)) { + zip_error_set(&ctx->error, ZIP_ER_INTERNAL, 0); + /* TODO: return partial read? */ + return -1; + } + _zip_winzip_aes_free(ctx->aes_ctx); + ctx->aes_ctx = NULL; + if ((ctx->buffer = _zip_buffer_new(ctx->data, HMAC_LENGTH)) == NULL) { + zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); + /* TODO: return partial read? */ + return -1; + } + buffer_n += _zip_buffer_read(ctx->buffer, data + ret, length - (zip_uint64_t)ret); + } + + return (zip_int64_t)(buffer_n + (zip_uint64_t)ret); + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st; + + st = (zip_stat_t *)data; + st->encryption_method = ctx->encryption_method; + st->valid |= ZIP_STAT_ENCRYPTION_METHOD; + if (st->valid & ZIP_STAT_COMP_SIZE) { + st->comp_size += 12 + SALT_LENGTH(ctx->encryption_method); + } + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, -1); + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, length); + + case ZIP_SOURCE_FREE: + winzip_aes_free(ctx); + return 0; + + default: + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } +} + + +static void +winzip_aes_free(struct winzip_aes *ctx) { + if (ctx == NULL) { + return; + } + + _zip_crypto_clear(ctx->password, strlen(ctx->password)); + free(ctx->password); + zip_error_fini(&ctx->error); + _zip_buffer_free(ctx->buffer); + _zip_winzip_aes_free(ctx->aes_ctx); + free(ctx); +} + + +static struct winzip_aes * +winzip_aes_new(zip_uint16_t encryption_method, const char *password, zip_error_t *error) { + struct winzip_aes *ctx; + + if ((ctx = (struct winzip_aes *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->password = strdup(password)) == NULL) { + free(ctx); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + ctx->encryption_method = encryption_method; + ctx->buffer = NULL; + ctx->aes_ctx = NULL; + + zip_error_init(&ctx->error); + + ctx->eof = false; + return ctx; +} diff --git a/third_party/libzip/lib/zip_source_write.c b/third_party/libzip/lib/zip_source_write.c new file mode 100644 index 0000000..9f494e0 --- /dev/null +++ b/third_party/libzip/lib/zip_source_write.c @@ -0,0 +1,46 @@ +/* + zip_source_write.c -- start a new file for writing + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN zip_int64_t +zip_source_write(zip_source_t *src, const void *data, zip_uint64_t length) { + if (!ZIP_SOURCE_IS_OPEN_WRITING(src) || length > ZIP_INT64_MAX) { + zip_error_set(&src->error, ZIP_ER_INVAL, 0); + return -1; + } + + return _zip_source_call(src, (void *)data, length, ZIP_SOURCE_WRITE); +} diff --git a/third_party/libzip/lib/zip_source_zip.c b/third_party/libzip/lib/zip_source_zip.c new file mode 100644 index 0000000..3fd90ab --- /dev/null +++ b/third_party/libzip/lib/zip_source_zip.c @@ -0,0 +1,57 @@ +/* + zip_source_zip.c -- create data source from zip file + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +ZIP_EXTERN zip_source_t * +zip_source_zip(zip_t *za, zip_t *srcza, zip_uint64_t srcidx, zip_flags_t flags, zip_uint64_t start, zip_int64_t len) { + if (len < -1) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len == -1) + len = 0; + + if (start == 0 && len == 0) + flags |= ZIP_FL_COMPRESSED; + else + flags &= ~ZIP_FL_COMPRESSED; + + return _zip_source_zip_new(za, srcza, srcidx, flags, start, (zip_uint64_t)len, NULL); +} diff --git a/third_party/libzip/lib/zip_source_zip_new.c b/third_party/libzip/lib/zip_source_zip_new.c new file mode 100644 index 0000000..ab78561 --- /dev/null +++ b/third_party/libzip/lib/zip_source_zip_new.c @@ -0,0 +1,175 @@ +/* + zip_source_zip_new.c -- prepare data structures for zip_fopen/zip_source_zip + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +zip_source_t * +_zip_source_zip_new(zip_t *za, zip_t *srcza, zip_uint64_t srcidx, zip_flags_t flags, zip_uint64_t start, zip_uint64_t len, const char *password) { + zip_source_t *src, *s2; + struct zip_stat st; + bool partial_data, needs_crc, needs_decrypt, needs_decompress; + + if (za == NULL) + return NULL; + + if (srcza == NULL || srcidx >= srcza->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((flags & ZIP_FL_UNCHANGED) == 0 && (ZIP_ENTRY_DATA_CHANGED(srcza->entry + srcidx) || srcza->entry[srcidx].deleted)) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return NULL; + } + + if (zip_stat_index(srcza, srcidx, flags | ZIP_FL_UNCHANGED, &st) < 0) { + zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); + return NULL; + } + + if (flags & ZIP_FL_ENCRYPTED) + flags |= ZIP_FL_COMPRESSED; + + if ((start > 0 || len > 0) && (flags & ZIP_FL_COMPRESSED)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + /* overflow or past end of file */ + if ((start > 0 || len > 0) && (start + len < start || start + len > st.size)) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return NULL; + } + + if (len == 0) { + len = st.size - start; + } + + partial_data = len < st.size; + needs_decrypt = ((flags & ZIP_FL_ENCRYPTED) == 0) && (st.encryption_method != ZIP_EM_NONE); + needs_decompress = ((flags & ZIP_FL_COMPRESSED) == 0) && (st.comp_method != ZIP_CM_STORE); + /* when reading the whole file, check for CRC errors */ + needs_crc = ((flags & ZIP_FL_COMPRESSED) == 0 || st.comp_method == ZIP_CM_STORE) && !partial_data; + + if (needs_decrypt) { + if (password == NULL) { + password = za->default_password; + } + if (password == NULL) { + zip_error_set(&za->error, ZIP_ER_NOPASSWD, 0); + return NULL; + } + } + + if (st.comp_size == 0) { + return zip_source_buffer(za, NULL, 0, 0); + } + + if (partial_data && !needs_decrypt && !needs_decompress) { + struct zip_stat st2; + + st2.size = len; + st2.comp_size = len; + st2.comp_method = ZIP_CM_STORE; + st2.mtime = st.mtime; + st2.valid = ZIP_STAT_SIZE | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_MTIME; + + if ((src = _zip_source_window_new(srcza->src, start, len, &st2, 0, srcza, srcidx, &za->error)) == NULL) { + return NULL; + } + } + else { + zip_dirent_t *de; + + if ((de = _zip_get_dirent(srcza, srcidx, flags, &za->error)) == NULL) { + return NULL; + } + if ((src = _zip_source_window_new(srcza->src, 0, st.comp_size, &st, (de->bitflags >> 1) & 3, srcza, srcidx, &za->error)) == NULL) { + return NULL; + } + } + + if (_zip_source_set_source_archive(src, srcza) < 0) { + zip_source_free(src); + return NULL; + } + + /* creating a layered source calls zip_keep() on the lower layer, so we free it */ + + if (needs_decrypt) { + zip_encryption_implementation enc_impl; + + if ((enc_impl = _zip_get_encryption_implementation(st.encryption_method, ZIP_CODEC_DECODE)) == NULL) { + zip_error_set(&za->error, ZIP_ER_ENCRNOTSUPP, 0); + return NULL; + } + + s2 = enc_impl(za, src, st.encryption_method, 0, password); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + if (needs_decompress) { + s2 = zip_source_decompress(za, src, st.comp_method); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + if (needs_crc) { + s2 = zip_source_crc(za, src, 1); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + + if (partial_data && (needs_decrypt || needs_decompress)) { + s2 = zip_source_window(za, src, start, len); + zip_source_free(src); + if (s2 == NULL) { + return NULL; + } + src = s2; + } + + return src; +} diff --git a/third_party/libzip/lib/zip_stat.c b/third_party/libzip/lib/zip_stat.c new file mode 100644 index 0000000..237d985 --- /dev/null +++ b/third_party/libzip/lib/zip_stat.c @@ -0,0 +1,46 @@ +/* + zip_stat.c -- get information about file by name + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_stat(zip_t *za, const char *fname, zip_flags_t flags, zip_stat_t *st) { + zip_int64_t idx; + + if ((idx = zip_name_locate(za, fname, flags)) < 0) + return -1; + + return zip_stat_index(za, (zip_uint64_t)idx, flags, st); +} diff --git a/third_party/libzip/lib/zip_stat_index.c b/third_party/libzip/lib/zip_stat_index.c new file mode 100644 index 0000000..d19e76a --- /dev/null +++ b/third_party/libzip/lib/zip_stat_index.c @@ -0,0 +1,73 @@ +/* + zip_stat_index.c -- get information about file by index + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN int +zip_stat_index(zip_t *za, zip_uint64_t index, zip_flags_t flags, zip_stat_t *st) { + const char *name; + zip_dirent_t *de; + + if ((de = _zip_get_dirent(za, index, flags, NULL)) == NULL) + return -1; + + if ((name = zip_get_name(za, index, flags)) == NULL) + return -1; + + + if ((flags & ZIP_FL_UNCHANGED) == 0 && ZIP_ENTRY_DATA_CHANGED(za->entry + index)) { + if (zip_source_stat(za->entry[index].source, st) < 0) { + zip_error_set(&za->error, ZIP_ER_CHANGED, 0); + return -1; + } + } + else { + zip_stat_init(st); + + st->crc = de->crc; + st->size = de->uncomp_size; + st->mtime = de->last_mod; + st->comp_size = de->comp_size; + st->comp_method = (zip_uint16_t)de->comp_method; + st->encryption_method = de->encryption_method; + st->valid = (de->crc_valid ? ZIP_STAT_CRC : 0) | ZIP_STAT_SIZE | ZIP_STAT_MTIME | ZIP_STAT_COMP_SIZE | ZIP_STAT_COMP_METHOD | ZIP_STAT_ENCRYPTION_METHOD; + } + + st->index = index; + st->name = name; + st->valid |= ZIP_STAT_INDEX | ZIP_STAT_NAME; + + return 0; +} diff --git a/third_party/libzip/lib/zip_stat_init.c b/third_party/libzip/lib/zip_stat_init.c new file mode 100644 index 0000000..46fa404 --- /dev/null +++ b/third_party/libzip/lib/zip_stat_init.c @@ -0,0 +1,83 @@ +/* + zip_stat_init.c -- initialize struct zip_stat. + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN void +zip_stat_init(zip_stat_t *st) { + st->valid = 0; + st->name = NULL; + st->index = ZIP_UINT64_MAX; + st->crc = 0; + st->mtime = (time_t)-1; + st->size = 0; + st->comp_size = 0; + st->comp_method = ZIP_CM_STORE; + st->encryption_method = ZIP_EM_NONE; +} + + +int +_zip_stat_merge(zip_stat_t *dst, const zip_stat_t *src, zip_error_t *error) { + /* name is not merged, since zip_stat_t doesn't own it, and src may not be valid as long as dst */ + if (src->valid & ZIP_STAT_INDEX) { + dst->index = src->index; + } + if (src->valid & ZIP_STAT_SIZE) { + dst->size = src->size; + } + if (src->valid & ZIP_STAT_COMP_SIZE) { + dst->comp_size = src->comp_size; + } + if (src->valid & ZIP_STAT_MTIME) { + dst->mtime = src->mtime; + } + if (src->valid & ZIP_STAT_CRC) { + dst->crc = src->crc; + } + if (src->valid & ZIP_STAT_COMP_METHOD) { + dst->comp_method = src->comp_method; + } + if (src->valid & ZIP_STAT_ENCRYPTION_METHOD) { + dst->encryption_method = src->encryption_method; + } + if (src->valid & ZIP_STAT_FLAGS) { + dst->flags = src->flags; + } + dst->valid |= src->valid; + + return 0; +} diff --git a/third_party/libzip/lib/zip_strerror.c b/third_party/libzip/lib/zip_strerror.c new file mode 100644 index 0000000..eb94198 --- /dev/null +++ b/third_party/libzip/lib/zip_strerror.c @@ -0,0 +1,41 @@ +/* + zip_sterror.c -- get string representation of zip error + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + + +ZIP_EXTERN const char * +zip_strerror(zip_t *za) { + return zip_error_strerror(&za->error); +} diff --git a/third_party/libzip/lib/zip_string.c b/third_party/libzip/lib/zip_string.c new file mode 100644 index 0000000..7e16a72 --- /dev/null +++ b/third_party/libzip/lib/zip_string.c @@ -0,0 +1,178 @@ +/* + zip_string.c -- string handling (with encoding) + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include + +#include "zipint.h" + + +zip_uint32_t +_zip_string_crc32(const zip_string_t *s) { + zip_uint32_t crc; + + crc = (zip_uint32_t)crc32(0L, Z_NULL, 0); + + if (s != NULL) + crc = (zip_uint32_t)crc32(crc, s->raw, s->length); + + return crc; +} + + +int +_zip_string_equal(const zip_string_t *a, const zip_string_t *b) { + if (a == NULL || b == NULL) + return a == b; + + if (a->length != b->length) + return 0; + + /* TODO: encoding */ + + return (memcmp(a->raw, b->raw, a->length) == 0); +} + + +void +_zip_string_free(zip_string_t *s) { + if (s == NULL) + return; + + free(s->raw); + free(s->converted); + free(s); +} + + +const zip_uint8_t * +_zip_string_get(zip_string_t *string, zip_uint32_t *lenp, zip_flags_t flags, zip_error_t *error) { + static const zip_uint8_t empty[1] = ""; + + if (string == NULL) { + if (lenp) + *lenp = 0; + return empty; + } + + if ((flags & ZIP_FL_ENC_RAW) == 0) { + /* start guessing */ + if (string->encoding == ZIP_ENCODING_UNKNOWN) + _zip_guess_encoding(string, ZIP_ENCODING_UNKNOWN); + + if (((flags & ZIP_FL_ENC_STRICT) && string->encoding != ZIP_ENCODING_ASCII && string->encoding != ZIP_ENCODING_UTF8_KNOWN) || (string->encoding == ZIP_ENCODING_CP437)) { + if (string->converted == NULL) { + if ((string->converted = _zip_cp437_to_utf8(string->raw, string->length, &string->converted_length, error)) == NULL) + return NULL; + } + if (lenp) + *lenp = string->converted_length; + return string->converted; + } + } + + if (lenp) + *lenp = string->length; + return string->raw; +} + + +zip_uint16_t +_zip_string_length(const zip_string_t *s) { + if (s == NULL) + return 0; + + return s->length; +} + + +zip_string_t * +_zip_string_new(const zip_uint8_t *raw, zip_uint16_t length, zip_flags_t flags, zip_error_t *error) { + zip_string_t *s; + zip_encoding_type_t expected_encoding; + + if (length == 0) + return NULL; + + switch (flags & ZIP_FL_ENCODING_ALL) { + case ZIP_FL_ENC_GUESS: + expected_encoding = ZIP_ENCODING_UNKNOWN; + break; + case ZIP_FL_ENC_UTF_8: + expected_encoding = ZIP_ENCODING_UTF8_KNOWN; + break; + case ZIP_FL_ENC_CP437: + expected_encoding = ZIP_ENCODING_CP437; + break; + default: + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + if ((s = (zip_string_t *)malloc(sizeof(*s))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((s->raw = (zip_uint8_t *)malloc((size_t)(length + 1))) == NULL) { + free(s); + return NULL; + } + + memcpy(s->raw, raw, length); + s->raw[length] = '\0'; + s->length = length; + s->encoding = ZIP_ENCODING_UNKNOWN; + s->converted = NULL; + s->converted_length = 0; + + if (expected_encoding != ZIP_ENCODING_UNKNOWN) { + if (_zip_guess_encoding(s, expected_encoding) == ZIP_ENCODING_ERROR) { + _zip_string_free(s); + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + } + + return s; +} + + +int +_zip_string_write(zip_t *za, const zip_string_t *s) { + if (s == NULL) + return 0; + + return _zip_write(za, s->raw, s->length); +} diff --git a/third_party/libzip/lib/zip_unchange.c b/third_party/libzip/lib/zip_unchange.c new file mode 100644 index 0000000..8285707 --- /dev/null +++ b/third_party/libzip/lib/zip_unchange.c @@ -0,0 +1,93 @@ +/* + zip_unchange.c -- undo changes to file in zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_unchange(zip_t *za, zip_uint64_t idx) { + return _zip_unchange(za, idx, 0); +} + + +int +_zip_unchange(zip_t *za, zip_uint64_t idx, int allow_duplicates) { + zip_int64_t i; + const char *orig_name, *changed_name; + + if (idx >= za->nentry) { + zip_error_set(&za->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (!allow_duplicates && za->entry[idx].changes && (za->entry[idx].changes->changed & ZIP_DIRENT_FILENAME)) { + if (za->entry[idx].orig != NULL) { + if ((orig_name = _zip_get_name(za, idx, ZIP_FL_UNCHANGED, &za->error)) == NULL) { + return -1; + } + + i = _zip_name_locate(za, orig_name, 0, NULL); + if (i >= 0 && (zip_uint64_t)i != idx) { + zip_error_set(&za->error, ZIP_ER_EXISTS, 0); + return -1; + } + } + else { + orig_name = NULL; + } + + if ((changed_name = _zip_get_name(za, idx, 0, &za->error)) == NULL) { + return -1; + } + + if (orig_name) { + if (_zip_hash_add(za->names, (const zip_uint8_t *)orig_name, idx, 0, &za->error) == false) { + return -1; + } + } + if (_zip_hash_delete(za->names, (const zip_uint8_t *)changed_name, &za->error) == false) { + _zip_hash_delete(za->names, (const zip_uint8_t *)orig_name, NULL); + return -1; + } + } + + _zip_dirent_free(za->entry[idx].changes); + za->entry[idx].changes = NULL; + + _zip_unchange_data(za->entry + idx); + + return 0; +} diff --git a/third_party/libzip/lib/zip_unchange_all.c b/third_party/libzip/lib/zip_unchange_all.c new file mode 100644 index 0000000..6a43358 --- /dev/null +++ b/third_party/libzip/lib/zip_unchange_all.c @@ -0,0 +1,56 @@ +/* + zip_unchange.c -- undo changes to all files in zip archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_unchange_all(zip_t *za) { + int ret; + zip_uint64_t i; + + if (!_zip_hash_revert(za->names, &za->error)) { + return -1; + } + + ret = 0; + for (i = 0; i < za->nentry; i++) + ret |= _zip_unchange(za, i, 1); + + ret |= zip_unchange_archive(za); + + return ret; +} diff --git a/third_party/libzip/lib/zip_unchange_archive.c b/third_party/libzip/lib/zip_unchange_archive.c new file mode 100644 index 0000000..404f1ed --- /dev/null +++ b/third_party/libzip/lib/zip_unchange_archive.c @@ -0,0 +1,51 @@ +/* + zip_unchange_archive.c -- undo global changes to ZIP archive + Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "zipint.h" + + +ZIP_EXTERN int +zip_unchange_archive(zip_t *za) { + if (za->comment_changed) { + _zip_string_free(za->comment_changes); + za->comment_changes = NULL; + za->comment_changed = 0; + } + + za->ch_flags = za->flags; + + return 0; +} diff --git a/third_party/libzip/lib/zip_unchange_data.c b/third_party/libzip/lib/zip_unchange_data.c new file mode 100644 index 0000000..f1df2bd --- /dev/null +++ b/third_party/libzip/lib/zip_unchange_data.c @@ -0,0 +1,53 @@ +/* + zip_unchange_data.c -- undo helper function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +void +_zip_unchange_data(zip_entry_t *ze) { + if (ze->source) { + zip_source_free(ze->source); + ze->source = NULL; + } + + if (ze->changes != NULL && (ze->changes->changed & ZIP_DIRENT_COMP_METHOD) && ze->changes->comp_method == ZIP_CM_REPLACED_DEFAULT) { + ze->changes->changed &= ~ZIP_DIRENT_COMP_METHOD; + if (ze->changes->changed == 0) { + _zip_dirent_free(ze->changes); + ze->changes = NULL; + } + } + + ze->deleted = 0; +} diff --git a/third_party/libzip/lib/zip_utf-8.c b/third_party/libzip/lib/zip_utf-8.c new file mode 100644 index 0000000..684eba5 --- /dev/null +++ b/third_party/libzip/lib/zip_utf-8.c @@ -0,0 +1,226 @@ +/* + zip_utf-8.c -- UTF-8 support functions for libzip + Copyright (C) 2011-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include + + +static const zip_uint16_t _cp437_to_unicode[256] = { + /* 0x00 - 0x0F */ + 0x0000, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, + + /* 0x10 - 0x1F */ + 0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8, 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC, + + /* 0x20 - 0x2F */ + 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, + + /* 0x30 - 0x3F */ + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, + + /* 0x40 - 0x4F */ + 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, + + /* 0x50 - 0x5F */ + 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, + + /* 0x60 - 0x6F */ + 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, + + /* 0x70 - 0x7F */ + 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302, + + /* 0x80 - 0x8F */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + + /* 0x90 - 0x9F */ + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + + /* 0xA0 - 0xAF */ + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + + /* 0xB0 - 0xBF */ + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + + /* 0xC0 - 0xCF */ + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + + /* 0xD0 - 0xDF */ + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + + /* 0xE0 - 0xEF */ + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + + /* 0xF0 - 0xFF */ + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0}; + +#define UTF_8_LEN_2_MASK 0xe0 +#define UTF_8_LEN_2_MATCH 0xc0 +#define UTF_8_LEN_3_MASK 0xf0 +#define UTF_8_LEN_3_MATCH 0xe0 +#define UTF_8_LEN_4_MASK 0xf8 +#define UTF_8_LEN_4_MATCH 0xf0 +#define UTF_8_CONTINUE_MASK 0xc0 +#define UTF_8_CONTINUE_MATCH 0x80 + + +zip_encoding_type_t +_zip_guess_encoding(zip_string_t *str, zip_encoding_type_t expected_encoding) { + zip_encoding_type_t enc; + const zip_uint8_t *name; + zip_uint32_t i, j, ulen; + + if (str == NULL) + return ZIP_ENCODING_ASCII; + + name = str->raw; + + if (str->encoding != ZIP_ENCODING_UNKNOWN) + enc = str->encoding; + else { + enc = ZIP_ENCODING_ASCII; + for (i = 0; i < str->length; i++) { + if ((name[i] > 31 && name[i] < 128) || name[i] == '\r' || name[i] == '\n' || name[i] == '\t') + continue; + + enc = ZIP_ENCODING_UTF8_GUESSED; + if ((name[i] & UTF_8_LEN_2_MASK) == UTF_8_LEN_2_MATCH) + ulen = 1; + else if ((name[i] & UTF_8_LEN_3_MASK) == UTF_8_LEN_3_MATCH) + ulen = 2; + else if ((name[i] & UTF_8_LEN_4_MASK) == UTF_8_LEN_4_MATCH) + ulen = 3; + else { + enc = ZIP_ENCODING_CP437; + break; + } + + if (i + ulen >= str->length) { + enc = ZIP_ENCODING_CP437; + break; + } + + for (j = 1; j <= ulen; j++) { + if ((name[i + j] & UTF_8_CONTINUE_MASK) != UTF_8_CONTINUE_MATCH) { + enc = ZIP_ENCODING_CP437; + goto done; + } + } + i += ulen; + } + } + +done: + str->encoding = enc; + + if (expected_encoding != ZIP_ENCODING_UNKNOWN) { + if (expected_encoding == ZIP_ENCODING_UTF8_KNOWN && enc == ZIP_ENCODING_UTF8_GUESSED) + str->encoding = enc = ZIP_ENCODING_UTF8_KNOWN; + + if (expected_encoding != enc && enc != ZIP_ENCODING_ASCII) + return ZIP_ENCODING_ERROR; + } + + return enc; +} + + +static zip_uint32_t +_zip_unicode_to_utf8_len(zip_uint32_t codepoint) { + if (codepoint < 0x0080) + return 1; + if (codepoint < 0x0800) + return 2; + if (codepoint < 0x10000) + return 3; + return 4; +} + + +static zip_uint32_t +_zip_unicode_to_utf8(zip_uint32_t codepoint, zip_uint8_t *buf) { + if (codepoint < 0x0080) { + buf[0] = codepoint & 0xff; + return 1; + } + if (codepoint < 0x0800) { + buf[0] = (zip_uint8_t)(UTF_8_LEN_2_MATCH | ((codepoint >> 6) & 0x1f)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 2; + } + if (codepoint < 0x10000) { + buf[0] = (zip_uint8_t)(UTF_8_LEN_3_MATCH | ((codepoint >> 12) & 0x0f)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f)); + buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 3; + } + buf[0] = (zip_uint8_t)(UTF_8_LEN_4_MATCH | ((codepoint >> 18) & 0x07)); + buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 12) & 0x3f)); + buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f)); + buf[3] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f)); + return 4; +} + + +zip_uint8_t * +_zip_cp437_to_utf8(const zip_uint8_t *const _cp437buf, zip_uint32_t len, zip_uint32_t *utf8_lenp, zip_error_t *error) { + zip_uint8_t *cp437buf = (zip_uint8_t *)_cp437buf; + zip_uint8_t *utf8buf; + zip_uint32_t buflen, i, offset; + + if (len == 0) { + if (utf8_lenp) + *utf8_lenp = 0; + return NULL; + } + + buflen = 1; + for (i = 0; i < len; i++) + buflen += _zip_unicode_to_utf8_len(_cp437_to_unicode[cp437buf[i]]); + + if ((utf8buf = (zip_uint8_t *)malloc(buflen)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + offset = 0; + for (i = 0; i < len; i++) + offset += _zip_unicode_to_utf8(_cp437_to_unicode[cp437buf[i]], utf8buf + offset); + + utf8buf[buflen - 1] = 0; + if (utf8_lenp) + *utf8_lenp = buflen - 1; + return utf8buf; +} diff --git a/third_party/libzip/lib/zip_winzip_aes.c b/third_party/libzip/lib/zip_winzip_aes.c new file mode 100644 index 0000000..03159d7 --- /dev/null +++ b/third_party/libzip/lib/zip_winzip_aes.c @@ -0,0 +1,163 @@ +/* + zip_winzip_aes.c -- Winzip AES de/encryption backend routines + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include "zip_crypto.h" + +#include +#include +#include + + +#define MAX_KEY_LENGTH 256 +#define PBKDF2_ITERATIONS 1000 + +struct _zip_winzip_aes { + _zip_crypto_aes_t *aes; + _zip_crypto_hmac_t *hmac; + zip_uint8_t counter[ZIP_CRYPTO_AES_BLOCK_LENGTH]; + zip_uint8_t pad[ZIP_CRYPTO_AES_BLOCK_LENGTH]; + int pad_offset; +}; + +static bool +aes_crypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length) { + zip_uint64_t i, j; + + for (i = 0; i < length; i++) { + if (ctx->pad_offset == AES_BLOCK_SIZE) { + for (j = 0; j < 8; j++) { + ctx->counter[j]++; + if (ctx->counter[j] != 0) { + break; + } + } + if (!_zip_crypto_aes_encrypt_block(ctx->aes, ctx->counter, ctx->pad)) { + return false; + } + ctx->pad_offset = 0; + } + data[i] ^= ctx->pad[ctx->pad_offset++]; + } + + return true; +} + + +zip_winzip_aes_t * +_zip_winzip_aes_new(const zip_uint8_t *password, zip_uint64_t password_length, const zip_uint8_t *salt, zip_uint16_t encryption_method, zip_uint8_t *password_verify, zip_error_t *error) { + zip_winzip_aes_t *ctx; + zip_uint8_t buffer[2 * (MAX_KEY_LENGTH / 8) + WINZIP_AES_PASSWORD_VERIFY_LENGTH]; + zip_uint16_t key_size = 0; /* in bits */ + zip_uint16_t key_length; /* in bytes */ + + switch (encryption_method) { + case ZIP_EM_AES_128: + key_size = 128; + break; + case ZIP_EM_AES_192: + key_size = 192; + break; + case ZIP_EM_AES_256: + key_size = 256; + break; + } + + if (key_size == 0 || salt == NULL || password == NULL || password_length == 0) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + + key_length = key_size / 8; + + if ((ctx = (zip_winzip_aes_t *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + memset(ctx->counter, 0, sizeof(ctx->counter)); + ctx->pad_offset = ZIP_CRYPTO_AES_BLOCK_LENGTH; + + if (!_zip_crypto_pbkdf2(password, password_length, salt, key_length / 2, PBKDF2_ITERATIONS, buffer, 2 * key_length + WINZIP_AES_PASSWORD_VERIFY_LENGTH)) { + free(ctx); + return NULL; + } + + if ((ctx->aes = _zip_crypto_aes_new(buffer, key_size, error)) == NULL) { + _zip_crypto_clear(ctx, sizeof(*ctx)); + free(ctx); + return NULL; + } + if ((ctx->hmac = _zip_crypto_hmac_new(buffer + key_length, key_length, error)) == NULL) { + _zip_crypto_aes_free(ctx->aes); + free(ctx); + return NULL; + } + + if (password_verify) { + memcpy(password_verify, buffer + (2 * key_size / 8), WINZIP_AES_PASSWORD_VERIFY_LENGTH); + } + + return ctx; +} + + +bool +_zip_winzip_aes_encrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length) { + return aes_crypt(ctx, data, length) && _zip_crypto_hmac(ctx->hmac, data, length); +} + + +bool +_zip_winzip_aes_decrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length) { + return _zip_crypto_hmac(ctx->hmac, data, length) && aes_crypt(ctx, data, length); +} + + +bool +_zip_winzip_aes_finish(zip_winzip_aes_t *ctx, zip_uint8_t *hmac) { + return _zip_crypto_hmac_output(ctx->hmac, hmac); +} + + +void +_zip_winzip_aes_free(zip_winzip_aes_t *ctx) { + if (ctx == NULL) { + return; + } + + _zip_crypto_aes_free(ctx->aes); + _zip_crypto_hmac_free(ctx->hmac); + free(ctx); +} diff --git a/third_party/libzip/lib/zipint.h b/third_party/libzip/lib/zipint.h new file mode 100644 index 0000000..093a1b2 --- /dev/null +++ b/third_party/libzip/lib/zipint.h @@ -0,0 +1,585 @@ +#ifndef _HAD_ZIPINT_H +#define _HAD_ZIPINT_H + +/* + zipint.h -- internal declarations. + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "compat.h" + +#ifdef ZIP_ALLOCATE_BUFFER +#include +#endif + +#include + +#ifndef _ZIP_COMPILING_DEPRECATED +#define ZIP_DISABLE_DEPRECATED +#endif + +#include "zip.h" + +#define CENTRAL_MAGIC "PK\1\2" +#define LOCAL_MAGIC "PK\3\4" +#define EOCD_MAGIC "PK\5\6" +#define DATADES_MAGIC "PK\7\10" +#define EOCD64LOC_MAGIC "PK\6\7" +#define EOCD64_MAGIC "PK\6\6" +#define CDENTRYSIZE 46u +#define LENTRYSIZE 30 +#define MAXCOMLEN 65536 +#define MAXEXTLEN 65536 +#define EOCDLEN 22 +#define EOCD64LOCLEN 20 +#define EOCD64LEN 56 +#define CDBUFSIZE (MAXCOMLEN + EOCDLEN + EOCD64LOCLEN) +#define BUFSIZE 8192 +#define EFZIP64SIZE 28 +#define EF_WINZIP_AES_SIZE 7 + +#define ZIP_CM_REPLACED_DEFAULT (-2) +#define ZIP_CM_WINZIP_AES 99 /* Winzip AES encrypted */ + +#define WINZIP_AES_PASSWORD_VERIFY_LENGTH 2 +#define WINZIP_AES_MAX_HEADER_LENGTH (16 + WINZIP_AES_PASSWORD_VERIFY_LENGTH) +#define AES_BLOCK_SIZE 16 +#define HMAC_LENGTH 10 +#define SHA1_LENGTH 20 +#define SALT_LENGTH(method) ((method) == ZIP_EM_AES_128 ? 8 : ((method) == ZIP_EM_AES_192 ? 12 : 16)) + +#define ZIP_CM_IS_DEFAULT(x) ((x) == ZIP_CM_DEFAULT || (x) == ZIP_CM_REPLACED_DEFAULT) +#define ZIP_CM_ACTUAL(x) ((zip_uint16_t)(ZIP_CM_IS_DEFAULT(x) ? ZIP_CM_DEFLATE : (x))) + +#define ZIP_EF_UTF_8_COMMENT 0x6375 +#define ZIP_EF_UTF_8_NAME 0x7075 +#define ZIP_EF_WINZIP_AES 0x9901 +#define ZIP_EF_ZIP64 0x0001 + +#define ZIP_EF_IS_INTERNAL(id) ((id) == ZIP_EF_UTF_8_COMMENT || (id) == ZIP_EF_UTF_8_NAME || (id) == ZIP_EF_WINZIP_AES || (id) == ZIP_EF_ZIP64) + +/* according to unzip-6.0's zipinfo.c, this corresponds to a regular file with rw permissions for everyone */ +#define ZIP_EXT_ATTRIB_DEFAULT (0100666u << 16) +/* according to unzip-6.0's zipinfo.c, this corresponds to a directory with rwx permissions for everyone */ +#define ZIP_EXT_ATTRIB_DEFAULT_DIR (0040777u << 16) + + +#define ZIP_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ZIP_MIN(a, b) ((a) < (b) ? (a) : (b)) + +/* This section contains API that won't materialize like this. It's + placed in the internal section, pending cleanup. */ + +/* flags for compression and encryption sources */ + +#define ZIP_CODEC_DECODE 0 /* decompress/decrypt (encode flag not set) */ +#define ZIP_CODEC_ENCODE 1 /* compress/encrypt */ + +typedef zip_source_t *(*zip_encryption_implementation)(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); + +zip_encryption_implementation _zip_get_encryption_implementation(zip_uint16_t method, int operation); + +// clang-format off +enum zip_compression_status { + ZIP_COMPRESSION_OK, + ZIP_COMPRESSION_END, + ZIP_COMPRESSION_ERROR, + ZIP_COMPRESSION_NEED_DATA +}; +// clang-format on +typedef enum zip_compression_status zip_compression_status_t; + +struct zip_compression_algorithm { + /* called once to create new context */ + void *(*allocate)(zip_uint16_t method, int compression_flags, zip_error_t *error); + /* called once to free context */ + void (*deallocate)(void *ctx); + + /* get compression specific general purpose bitflags */ + int (*compression_flags)(void *ctx); + + /* start processing */ + bool (*start)(void *ctx); + /* stop processing */ + bool (*end)(void *ctx); + + /* provide new input data, remains valid until next call to input or end */ + bool (*input)(void *ctx, zip_uint8_t *data, zip_uint64_t length); + + /* all input data has been provided */ + void (*end_of_input)(void *ctx); + + /* process input data, writing to data, which has room for length bytes, update length to number of bytes written */ + zip_compression_status_t (*process)(void *ctx, zip_uint8_t *data, zip_uint64_t *length); +}; +typedef struct zip_compression_algorithm zip_compression_algorithm_t; + +extern zip_compression_algorithm_t zip_algorithm_bzip2_compress; +extern zip_compression_algorithm_t zip_algorithm_bzip2_decompress; +extern zip_compression_algorithm_t zip_algorithm_deflate_compress; +extern zip_compression_algorithm_t zip_algorithm_deflate_decompress; + +bool zip_compression_method_supported(zip_int32_t method, bool compress); + +/* This API is not final yet, but we need it internally, so it's private for now. */ + +const zip_uint8_t *zip_get_extra_field_by_id(zip_t *, int, int, zip_uint16_t, int, zip_uint16_t *); + +/* This section contains API that is of limited use until support for + user-supplied compression/encryption implementation is finished. + Thus we will keep it private for now. */ + +typedef zip_int64_t (*zip_source_layered_callback)(zip_source_t *, void *, void *, zip_uint64_t, enum zip_source_cmd); +zip_source_t *zip_source_compress(zip_t *za, zip_source_t *src, zip_int32_t cm, int compression_flags); +zip_source_t *zip_source_crc(zip_t *, zip_source_t *, int); +zip_source_t *zip_source_decompress(zip_t *za, zip_source_t *src, zip_int32_t cm); +zip_source_t *zip_source_layered(zip_t *, zip_source_t *, zip_source_layered_callback, void *); +zip_source_t *zip_source_layered_create(zip_source_t *src, zip_source_layered_callback cb, void *ud, zip_error_t *error); +zip_source_t *zip_source_pkware(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +int zip_source_remove(zip_source_t *); +zip_int64_t zip_source_supports(zip_source_t *src); +zip_source_t *zip_source_window(zip_t *, zip_source_t *, zip_uint64_t, zip_uint64_t); +zip_source_t *zip_source_winzip_aes_decode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); +zip_source_t *zip_source_winzip_aes_encode(zip_t *, zip_source_t *, zip_uint16_t, int, const char *); + + +/* error source for layered sources */ + +enum zip_les { ZIP_LES_NONE, ZIP_LES_UPPER, ZIP_LES_LOWER, ZIP_LES_INVAL }; + +/* directory entry: general purpose bit flags */ + +#define ZIP_GPBF_ENCRYPTED 0x0001u /* is encrypted */ +#define ZIP_GPBF_DATA_DESCRIPTOR 0x0008u /* crc/size after file data */ +#define ZIP_GPBF_STRONG_ENCRYPTION 0x0040u /* uses strong encryption */ +#define ZIP_GPBF_ENCODING_UTF_8 0x0800u /* file name encoding is UTF-8 */ + + +/* extra fields */ +#define ZIP_EF_LOCAL ZIP_FL_LOCAL /* include in local header */ +#define ZIP_EF_CENTRAL ZIP_FL_CENTRAL /* include in central directory */ +#define ZIP_EF_BOTH (ZIP_EF_LOCAL | ZIP_EF_CENTRAL) /* include in both */ + +#define ZIP_FL_FORCE_ZIP64 1024 /* force zip64 extra field (_zip_dirent_write) */ + +#define ZIP_FL_ENCODING_ALL (ZIP_FL_ENC_GUESS | ZIP_FL_ENC_CP437 | ZIP_FL_ENC_UTF_8) + + +/* encoding type */ +enum zip_encoding_type { + ZIP_ENCODING_UNKNOWN, /* not yet analyzed */ + ZIP_ENCODING_ASCII, /* plain ASCII */ + ZIP_ENCODING_UTF8_KNOWN, /* is UTF-8 */ + ZIP_ENCODING_UTF8_GUESSED, /* possibly UTF-8 */ + ZIP_ENCODING_CP437, /* Code Page 437 */ + ZIP_ENCODING_ERROR /* should be UTF-8 but isn't */ +}; + +typedef enum zip_encoding_type zip_encoding_type_t; + +struct zip_hash; +struct zip_progress; + +typedef struct zip_cdir zip_cdir_t; +typedef struct zip_dirent zip_dirent_t; +typedef struct zip_entry zip_entry_t; +typedef struct zip_extra_field zip_extra_field_t; +typedef struct zip_string zip_string_t; +typedef struct zip_buffer zip_buffer_t; +typedef struct zip_hash zip_hash_t; +typedef struct zip_progress zip_progress_t; + +/* zip archive, part of API */ + +struct zip { + zip_source_t *src; /* data source for archive */ + unsigned int open_flags; /* flags passed to zip_open */ + zip_error_t error; /* error information */ + + unsigned int flags; /* archive global flags */ + unsigned int ch_flags; /* changed archive global flags */ + + char *default_password; /* password used when no other supplied */ + + zip_string_t *comment_orig; /* archive comment */ + zip_string_t *comment_changes; /* changed archive comment */ + bool comment_changed; /* whether archive comment was changed */ + + zip_uint64_t nentry; /* number of entries */ + zip_uint64_t nentry_alloc; /* number of entries allocated */ + zip_entry_t *entry; /* entries */ + + unsigned int nopen_source; /* number of open sources using archive */ + unsigned int nopen_source_alloc; /* number of sources allocated */ + zip_source_t **open_source; /* open sources using archive */ + + zip_hash_t *names; /* hash table for name lookup */ + + zip_progress_t *progress; /* progress callback for zip_close() */ +}; + +/* file in zip archive, part of API */ + +struct zip_file { + zip_t *za; /* zip archive containing this file */ + zip_error_t error; /* error information */ + bool eof; + zip_source_t *src; /* data source */ +}; + +/* zip archive directory entry (central or local) */ + +#define ZIP_DIRENT_COMP_METHOD 0x0001u +#define ZIP_DIRENT_FILENAME 0x0002u +#define ZIP_DIRENT_COMMENT 0x0004u +#define ZIP_DIRENT_EXTRA_FIELD 0x0008u +#define ZIP_DIRENT_ATTRIBUTES 0x0010u +#define ZIP_DIRENT_LAST_MOD 0x0020u +#define ZIP_DIRENT_ENCRYPTION_METHOD 0x0040u +#define ZIP_DIRENT_PASSWORD 0x0080u +#define ZIP_DIRENT_ALL ZIP_UINT32_MAX + +struct zip_dirent { + zip_uint32_t changed; + bool local_extra_fields_read; /* whether we already read in local header extra fields */ + bool cloned; /* whether this instance is cloned, and thus shares non-changed strings */ + + bool crc_valid; /* if CRC is valid (sometimes not for encrypted archives) */ + + zip_uint16_t version_madeby; /* (c) version of creator */ + zip_uint16_t version_needed; /* (cl) version needed to extract */ + zip_uint16_t bitflags; /* (cl) general purpose bit flag */ + zip_int32_t comp_method; /* (cl) compression method used (uint16 and ZIP_CM_DEFAULT (-1)) */ + time_t last_mod; /* (cl) time of last modification */ + zip_uint32_t crc; /* (cl) CRC-32 of uncompressed data */ + zip_uint64_t comp_size; /* (cl) size of compressed data */ + zip_uint64_t uncomp_size; /* (cl) size of uncompressed data */ + zip_string_t *filename; /* (cl) file name (NUL-terminated) */ + zip_extra_field_t *extra_fields; /* (cl) extra fields, parsed */ + zip_string_t *comment; /* (c) file comment */ + zip_uint32_t disk_number; /* (c) disk number start */ + zip_uint16_t int_attrib; /* (c) internal file attributes */ + zip_uint32_t ext_attrib; /* (c) external file attributes */ + zip_uint64_t offset; /* (c) offset of local header */ + + zip_uint16_t compression_level; /* level of compression to use (never valid in orig) */ + zip_uint16_t encryption_method; /* encryption method, computed from other fields */ + char *password; /* file specific encryption password */ +}; + +/* zip archive central directory */ + +struct zip_cdir { + zip_entry_t *entry; /* directory entries */ + zip_uint64_t nentry; /* number of entries */ + zip_uint64_t nentry_alloc; /* number of entries allocated */ + + zip_uint64_t size; /* size of central directory */ + zip_uint64_t offset; /* offset of central directory in file */ + zip_string_t *comment; /* zip archive comment */ + bool is_zip64; /* central directory in zip64 format */ +}; + +struct zip_extra_field { + zip_extra_field_t *next; + zip_flags_t flags; /* in local/central header */ + zip_uint16_t id; /* header id */ + zip_uint16_t size; /* data size */ + zip_uint8_t *data; +}; + +enum zip_source_write_state { + ZIP_SOURCE_WRITE_CLOSED, /* write is not in progress */ + ZIP_SOURCE_WRITE_OPEN, /* write is in progress */ + ZIP_SOURCE_WRITE_FAILED, /* commit failed, only rollback allowed */ + ZIP_SOURCE_WRITE_REMOVED /* file was removed */ +}; +typedef enum zip_source_write_state zip_source_write_state_t; + +struct zip_source { + zip_source_t *src; + union { + zip_source_callback f; + zip_source_layered_callback l; + } cb; + void *ud; + zip_error_t error; + zip_int64_t supports; /* supported commands */ + unsigned int open_count; /* number of times source was opened (directly or as lower layer) */ + zip_source_write_state_t write_state; /* whether source is open for writing */ + bool source_closed; /* set if source archive is closed */ + zip_t *source_archive; /* zip archive we're reading from, NULL if not from archive */ + unsigned int refcount; + bool eof; /* EOF reached */ + bool had_read_error; /* a previous ZIP_SOURCE_READ reported an error */ +}; + +#define ZIP_SOURCE_IS_OPEN_READING(src) ((src)->open_count > 0) +#define ZIP_SOURCE_IS_OPEN_WRITING(src) ((src)->write_state == ZIP_SOURCE_WRITE_OPEN) +#define ZIP_SOURCE_IS_LAYERED(src) ((src)->src != NULL) + +/* entry in zip archive directory */ + +struct zip_entry { + zip_dirent_t *orig; + zip_dirent_t *changes; + zip_source_t *source; + bool deleted; +}; + + +/* file or archive comment, or filename */ + +struct zip_string { + zip_uint8_t *raw; /* raw string */ + zip_uint16_t length; /* length of raw string */ + enum zip_encoding_type encoding; /* autorecognized encoding */ + zip_uint8_t *converted; /* autoconverted string */ + zip_uint32_t converted_length; /* length of converted */ +}; + + +/* byte array */ + +/* For performance, we usually keep 8k byte arrays on the stack. + However, there are (embedded) systems with a stack size of 12k; + for those, use malloc()/free() */ + +#ifdef ZIP_ALLOCATE_BUFFER +#define DEFINE_BYTE_ARRAY(buf, size) zip_uint8_t *buf +#define byte_array_init(buf, size) (((buf) = (zip_uint8_t *)malloc(size)) != NULL) +#define byte_array_fini(buf) (free(buf)) +#else +#define DEFINE_BYTE_ARRAY(buf, size) zip_uint8_t buf[size] +#define byte_array_init(buf, size) (1) +#define byte_array_fini(buf) ((void)0) +#endif + + +/* bounds checked access to memory buffer */ + +struct zip_buffer { + bool ok; + bool free_data; + + zip_uint8_t *data; + zip_uint64_t size; + zip_uint64_t offset; +}; + +/* which files to write in which order */ + +struct zip_filelist { + zip_uint64_t idx; + /* TODO const char *name; */ +}; + +typedef struct zip_filelist zip_filelist_t; + +struct _zip_winzip_aes; +typedef struct _zip_winzip_aes zip_winzip_aes_t; + +extern const char *const _zip_err_str[]; +extern const int _zip_nerr_str; +extern const int _zip_err_type[]; + +#define ZIP_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ZIP_MIN(a, b) ((a) < (b) ? (a) : (b)) + +#define ZIP_ENTRY_CHANGED(e, f) ((e)->changes && ((e)->changes->changed & (f))) +#define ZIP_ENTRY_DATA_CHANGED(x) ((x)->source != NULL) +#define ZIP_ENTRY_HAS_CHANGES(e) (ZIP_ENTRY_DATA_CHANGED(e) || (e)->deleted || ZIP_ENTRY_CHANGED((e), ZIP_DIRENT_ALL)) + +#define ZIP_IS_RDONLY(za) ((za)->ch_flags & ZIP_AFL_RDONLY) + + +#ifdef HAVE_EXPLICIT_MEMSET +#define _zip_crypto_clear(b, l) explicit_memset((b), 0, (l)) +#else +#ifdef HAVE_EXPLICIT_BZERO +#define _zip_crypto_clear(b, l) explicit_bzero((b), (l)) +#else +#include +#define _zip_crypto_clear(b, l) memset((b), 0, (l)) +#endif +#endif + + +zip_int64_t _zip_add_entry(zip_t *); + +zip_uint8_t *_zip_buffer_data(zip_buffer_t *buffer); +bool _zip_buffer_eof(zip_buffer_t *buffer); +void _zip_buffer_free(zip_buffer_t *buffer); +zip_uint8_t *_zip_buffer_get(zip_buffer_t *buffer, zip_uint64_t length); +zip_uint16_t _zip_buffer_get_16(zip_buffer_t *buffer); +zip_uint32_t _zip_buffer_get_32(zip_buffer_t *buffer); +zip_uint64_t _zip_buffer_get_64(zip_buffer_t *buffer); +zip_uint8_t _zip_buffer_get_8(zip_buffer_t *buffer); +zip_uint64_t _zip_buffer_left(zip_buffer_t *buffer); +zip_buffer_t *_zip_buffer_new(zip_uint8_t *data, zip_uint64_t size); +zip_buffer_t *_zip_buffer_new_from_source(zip_source_t *src, zip_uint64_t size, zip_uint8_t *buf, zip_error_t *error); +zip_uint64_t _zip_buffer_offset(zip_buffer_t *buffer); +bool _zip_buffer_ok(zip_buffer_t *buffer); +zip_uint8_t *_zip_buffer_peek(zip_buffer_t *buffer, zip_uint64_t length); +int _zip_buffer_put(zip_buffer_t *buffer, const void *src, size_t length); +int _zip_buffer_put_16(zip_buffer_t *buffer, zip_uint16_t i); +int _zip_buffer_put_32(zip_buffer_t *buffer, zip_uint32_t i); +int _zip_buffer_put_64(zip_buffer_t *buffer, zip_uint64_t i); +int _zip_buffer_put_8(zip_buffer_t *buffer, zip_uint8_t i); +zip_uint64_t _zip_buffer_read(zip_buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length); +int _zip_buffer_skip(zip_buffer_t *buffer, zip_uint64_t length); +int _zip_buffer_set_offset(zip_buffer_t *buffer, zip_uint64_t offset); +zip_uint64_t _zip_buffer_size(zip_buffer_t *buffer); + +int _zip_cdir_compute_crc(zip_t *, uLong *); +void _zip_cdir_free(zip_cdir_t *); +bool _zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error); +zip_cdir_t *_zip_cdir_new(zip_uint64_t, zip_error_t *); +zip_int64_t _zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors); +void _zip_deregister_source(zip_t *za, zip_source_t *src); + +zip_dirent_t *_zip_dirent_clone(const zip_dirent_t *); +void _zip_dirent_free(zip_dirent_t *); +void _zip_dirent_finalize(zip_dirent_t *); +void _zip_dirent_init(zip_dirent_t *); +bool _zip_dirent_needs_zip64(const zip_dirent_t *, zip_flags_t); +zip_dirent_t *_zip_dirent_new(void); +zip_int64_t _zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error); +void _zip_dirent_set_version_needed(zip_dirent_t *de, bool force_zip64); +zip_int32_t _zip_dirent_size(zip_source_t *src, zip_uint16_t, zip_error_t *); +int _zip_dirent_write(zip_t *za, zip_dirent_t *dirent, zip_flags_t flags); + +zip_extra_field_t *_zip_ef_clone(const zip_extra_field_t *, zip_error_t *); +zip_extra_field_t *_zip_ef_delete_by_id(zip_extra_field_t *, zip_uint16_t, zip_uint16_t, zip_flags_t); +void _zip_ef_free(zip_extra_field_t *); +const zip_uint8_t *_zip_ef_get_by_id(const zip_extra_field_t *, zip_uint16_t *, zip_uint16_t, zip_uint16_t, zip_flags_t, zip_error_t *); +zip_extra_field_t *_zip_ef_merge(zip_extra_field_t *, zip_extra_field_t *); +zip_extra_field_t *_zip_ef_new(zip_uint16_t, zip_uint16_t, const zip_uint8_t *, zip_flags_t); +bool _zip_ef_parse(const zip_uint8_t *, zip_uint16_t, zip_flags_t, zip_extra_field_t **, zip_error_t *); +zip_extra_field_t *_zip_ef_remove_internal(zip_extra_field_t *); +zip_uint16_t _zip_ef_size(const zip_extra_field_t *, zip_flags_t); +int _zip_ef_write(zip_t *za, const zip_extra_field_t *ef, zip_flags_t flags); + +void _zip_entry_finalize(zip_entry_t *); +void _zip_entry_init(zip_entry_t *); + +void _zip_error_clear(zip_error_t *); +void _zip_error_get(const zip_error_t *, int *, int *); + +void _zip_error_copy(zip_error_t *dst, const zip_error_t *src); +void _zip_error_set_from_source(zip_error_t *, zip_source_t *); + +const zip_uint8_t *_zip_extract_extra_field_by_id(zip_error_t *, zip_uint16_t, int, const zip_uint8_t *, zip_uint16_t, zip_uint16_t *); + +int _zip_file_extra_field_prepare_for_change(zip_t *, zip_uint64_t); +int _zip_file_fillbuf(void *, size_t, zip_file_t *); +zip_uint64_t _zip_file_get_end(const zip_t *za, zip_uint64_t index, zip_error_t *error); +zip_uint64_t _zip_file_get_offset(const zip_t *, zip_uint64_t, zip_error_t *); + +int _zip_filerange_crc(zip_source_t *src, zip_uint64_t offset, zip_uint64_t length, uLong *crcp, zip_error_t *error); + +zip_dirent_t *_zip_get_dirent(zip_t *, zip_uint64_t, zip_flags_t, zip_error_t *); + +enum zip_encoding_type _zip_guess_encoding(zip_string_t *, enum zip_encoding_type); +zip_uint8_t *_zip_cp437_to_utf8(const zip_uint8_t *const, zip_uint32_t, zip_uint32_t *, zip_error_t *); + +bool _zip_hash_add(zip_hash_t *hash, const zip_uint8_t *name, zip_uint64_t index, zip_flags_t flags, zip_error_t *error); +bool _zip_hash_delete(zip_hash_t *hash, const zip_uint8_t *key, zip_error_t *error); +void _zip_hash_free(zip_hash_t *hash); +zip_int64_t _zip_hash_lookup(zip_hash_t *hash, const zip_uint8_t *name, zip_flags_t flags, zip_error_t *error); +zip_hash_t *_zip_hash_new(zip_error_t *error); +bool _zip_hash_reserve_capacity(zip_hash_t *hash, zip_uint64_t capacity, zip_error_t *error); +bool _zip_hash_revert(zip_hash_t *hash, zip_error_t *error); + +zip_t *_zip_open(zip_source_t *, unsigned int, zip_error_t *); + +void _zip_progress_end(zip_progress_t *progress); +void _zip_progress_free(zip_progress_t *progress); +zip_progress_t *_zip_progress_new(zip_t *za, double precision, zip_progress_callback callback, void (*ud_free)(void *), void *ud); +void _zip_progress_start(zip_progress_t *progress); +void _zip_progress_subrange(zip_progress_t *progress, double start, double end); +void _zip_progress_update(zip_progress_t *progress, double value); + +ZIP_EXTERN bool zip_random(zip_uint8_t *buffer, zip_uint16_t length); + +int _zip_read(zip_source_t *src, zip_uint8_t *data, zip_uint64_t length, zip_error_t *error); +int _zip_read_at_offset(zip_source_t *src, zip_uint64_t offset, unsigned char *b, size_t length, zip_error_t *error); +zip_uint8_t *_zip_read_data(zip_buffer_t *buffer, zip_source_t *src, size_t length, bool nulp, zip_error_t *error); +int _zip_read_local_ef(zip_t *, zip_uint64_t); +zip_string_t *_zip_read_string(zip_buffer_t *buffer, zip_source_t *src, zip_uint16_t lenght, bool nulp, zip_error_t *error); +int _zip_register_source(zip_t *za, zip_source_t *src); + +void _zip_set_open_error(int *zep, const zip_error_t *err, int ze); + +zip_int64_t _zip_source_call(zip_source_t *src, void *data, zip_uint64_t length, zip_source_cmd_t command); +bool _zip_source_eof(zip_source_t *); +zip_source_t *_zip_source_file_or_p(const char *, FILE *, zip_uint64_t, zip_int64_t, const zip_stat_t *, zip_error_t *error); +zip_int8_t zip_source_get_compression_flags(zip_source_t *); +bool _zip_source_had_error(zip_source_t *); +void _zip_source_invalidate(zip_source_t *src); +zip_source_t *_zip_source_new(zip_error_t *error); +int _zip_source_set_source_archive(zip_source_t *, zip_t *); +zip_source_t *_zip_source_window_new(zip_source_t *src, zip_uint64_t start, zip_uint64_t length, zip_stat_t *st, zip_int8_t compression_flags, zip_t *source_archive, zip_uint64_t source_index, zip_error_t *error); +zip_source_t *_zip_source_zip_new(zip_t *, zip_t *, zip_uint64_t, zip_flags_t, zip_uint64_t, zip_uint64_t, const char *); + +int _zip_stat_merge(zip_stat_t *dst, const zip_stat_t *src, zip_error_t *error); +int _zip_string_equal(const zip_string_t *, const zip_string_t *); +void _zip_string_free(zip_string_t *); +zip_uint32_t _zip_string_crc32(const zip_string_t *); +const zip_uint8_t *_zip_string_get(zip_string_t *, zip_uint32_t *, zip_flags_t, zip_error_t *); +zip_uint16_t _zip_string_length(const zip_string_t *); +zip_string_t *_zip_string_new(const zip_uint8_t *, zip_uint16_t, zip_flags_t, zip_error_t *); +int _zip_string_write(zip_t *za, const zip_string_t *string); +bool _zip_winzip_aes_decrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length); +bool _zip_winzip_aes_encrypt(zip_winzip_aes_t *ctx, zip_uint8_t *data, zip_uint64_t length); +bool _zip_winzip_aes_finish(zip_winzip_aes_t *ctx, zip_uint8_t *hmac); +void _zip_winzip_aes_free(zip_winzip_aes_t *ctx); +zip_winzip_aes_t *_zip_winzip_aes_new(const zip_uint8_t *password, zip_uint64_t password_length, const zip_uint8_t *salt, zip_uint16_t key_size, zip_uint8_t *password_verify, zip_error_t *error); + +int _zip_changed(const zip_t *, zip_uint64_t *); +const char *_zip_get_name(zip_t *, zip_uint64_t, zip_flags_t, zip_error_t *); +int _zip_local_header_read(zip_t *, int); +void *_zip_memdup(const void *, size_t, zip_error_t *); +zip_int64_t _zip_name_locate(zip_t *, const char *, zip_flags_t, zip_error_t *); +zip_t *_zip_new(zip_error_t *); + +zip_int64_t _zip_file_replace(zip_t *, zip_uint64_t, const char *, zip_source_t *, zip_flags_t); +int _zip_set_name(zip_t *, zip_uint64_t, const char *, zip_flags_t); +void _zip_u2d_time(time_t, zip_uint16_t *, zip_uint16_t *); +int _zip_unchange(zip_t *, zip_uint64_t, int); +void _zip_unchange_data(zip_entry_t *); +int _zip_write(zip_t *za, const void *data, zip_uint64_t length); + +#endif /* zipint.h */ diff --git a/third_party/libzip/lib/zipwin32.h b/third_party/libzip/lib/zipwin32.h new file mode 100644 index 0000000..7d3ac76 --- /dev/null +++ b/third_party/libzip/lib/zipwin32.h @@ -0,0 +1,85 @@ +#ifndef _HAD_ZIPWIN32_H +#define _HAD_ZIPWIN32_H + +/* + zipwin32.h -- internal declarations for Windows. + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +/* 0x0501 => Windows XP; needs to be at least this value because of GetFileSizeEx */ +#if !defined(MS_UWP) && !defined(_WIN32_WINNT) +#define _WIN32_WINNT 0x0501 +#endif + +#include + +/* context for Win32 source */ + +struct _zip_source_win32_file_ops; + +struct _zip_source_win32_read_file { + zip_error_t error; /* last error information */ + zip_int64_t supports; + + /* operations */ + struct _zip_source_win32_file_ops *ops; + + /* reading */ + void *fname; /* name of file to read from - ANSI (char *) or Unicode (wchar_t *) */ + void *h; /* HANDLE for file to read from */ + int closep; /* whether to close f on ZIP_CMD_FREE */ + struct zip_stat st; /* stat information passed in */ + zip_uint64_t start; /* start offset of data to read */ + zip_uint64_t end; /* end offset of data to read, 0 for up to EOF */ + zip_uint64_t current; /* current offset */ + + /* writing */ + void *tmpname; /* name of temp file - ANSI (char *) or Unicode (wchar_t *) */ + void *hout; /* HANDLE for output file */ +}; + +typedef struct _zip_source_win32_read_file _zip_source_win32_read_file_t; + +/* internal operations for Win32 source */ + +struct _zip_source_win32_file_ops { + void *(*op_strdup)(const void *); + void *(*op_open)(_zip_source_win32_read_file_t *); + void *(*op_create_temp)(_zip_source_win32_read_file_t *, void **, zip_uint32_t, PSECURITY_ATTRIBUTES); + int (*op_rename_temp)(_zip_source_win32_read_file_t *); + int (*op_remove)(const void *); +}; + +typedef struct _zip_source_win32_file_ops _zip_source_win32_file_ops_t; + +zip_source_t *_zip_source_win32_handle_or_name(const void *, void *, zip_uint64_t, zip_int64_t, int, const zip_stat_t *, _zip_source_win32_file_ops_t *, zip_error_t *); + +#endif /* zipwin32.h */ diff --git a/third_party/libzip/libzip.pc.in b/third_party/libzip/libzip.pc.in new file mode 100644 index 0000000..c2565a8 --- /dev/null +++ b/third_party/libzip/libzip.pc.in @@ -0,0 +1,15 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +bindir=@bindir@ +libdir=@libdir@ +includedir=@includedir@ + +zipcmp=@bindir@/zipcmp + +Name: libzip +Description: library for handling zip archives +Version: @VERSION@ +Libs: @PKG_CONFIG_RPATH@ -L${libdir} -lzip +Libs.private: @LIBS@ +Cflags: -I${includedir} + diff --git a/third_party/libzip/man/CMakeLists.txt b/third_party/libzip/man/CMakeLists.txt new file mode 100644 index 0000000..5d7325a --- /dev/null +++ b/third_party/libzip/man/CMakeLists.txt @@ -0,0 +1,154 @@ +SET(MAN_PAGES + ZIP_SOURCE_GET_ARGS.3 + libzip.3 + zip_add.3 + zip_add_dir.3 + zip_close.3 + zip_delete.3 + zip_dir_add.3 + zip_discard.3 + zip_error_clear.3 + zip_error_code_system.3 + zip_error_code_zip.3 + zip_error_fini.3 + zip_error_get.3 + zip_error_get_sys_type.3 + zip_error_init.3 + zip_error_set.3 + zip_error_strerror.3 + zip_error_system_type.3 + zip_error_to_data.3 + zip_error_to_str.3 + zip_errors.3 + zip_fclose.3 + zip_fdopen.3 + zip_file_add.3 + zip_file_extra_field_delete.3 + zip_file_extra_field_get.3 + zip_file_extra_field_set.3 + zip_file_extra_fields_count.3 + zip_file_get_comment.3 + zip_file_get_error.3 + zip_file_get_external_attributes.3 + zip_file_rename.3 + zip_file_set_comment.3 + zip_file_set_encryption.3 + zip_file_set_external_attributes.3 + zip_file_set_mtime.3 + zip_file_strerror.3 + zip_fopen.3 + zip_fopen_encrypted.3 + zip_fread.3 + zip_fseek.3 + zip_ftell.3 + zip_get_archive_comment.3 + zip_get_archive_flag.3 + zip_get_error.3 + zip_get_file_comment.3 + zip_get_name.3 + zip_get_num_entries.3 + zip_get_num_files.3 + zip_libzip_version.3 + zip_name_locate.3 + zip_open.3 + zip_register_progress_callback.3 + zip_register_progress_callback_with_state.3 + zip_rename.3 + zip_set_archive_comment.3 + zip_set_archive_flag.3 + zip_set_default_password.3 + zip_set_file_comment.3 + zip_set_file_compression.3 + zip_source.3 + zip_source_begin_write.3 + zip_source_buffer.3 + zip_source_buffer_fragment.3 + zip_source_close.3 + zip_source_commit_write.3 + zip_source_error.3 + zip_source_file.3 + zip_source_filep.3 + zip_source_free.3 + zip_source_function.3 + zip_source_is_deleted.3 + zip_source_keep.3 + zip_source_make_command_bitmap.3 + zip_source_open.3 + zip_source_read.3 + zip_source_rollback_write.3 + zip_source_seek.3 + zip_source_seek_compute_offset.3 + zip_source_seek_write.3 + zip_source_stat.3 + zip_source_tell.3 + zip_source_tell_write.3 + zip_source_win32a.3 + zip_source_win32handle.3 + zip_source_win32w.3 + zip_source_write.3 + zip_source_zip.3 + zip_stat.3 + zip_stat_init.3 + zip_unchange.3 + zip_unchange_all.3 + zip_unchange_archive.3 + zipcmp.1 + zipmerge.1 + ziptool.1 +) + +FOREACH(MAN_PAGE ${MAN_PAGES}) + STRING(REGEX REPLACE "[1-9]$" "${DOCUMENTATION_FORMAT}" SOURCE_FILE ${MAN_PAGE}) + IF (DOCUMENTATION_FORMAT MATCHES "html") + INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${MAN_PAGE} DESTINATION ${CMAKE_INSTALL_DOCDIR} RENAME ${SOURCE_FILE}) + ELSE() + STRING(REGEX REPLACE ".*(.)$" "man\\1" SUBDIR ${MAN_PAGE}) + INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${MAN_PAGE} DESTINATION ${CMAKE_INSTALL_MANDIR}/${SUBDIR}) + ENDIF() + # CONFIGURE_FILE does not find out about updates to the sources, and it does not provide a target + #CONFIGURE_FILE(${SOURCE_FILE} ${MAN_PAGE} COPYONLY) + ADD_CUSTOM_COMMAND(OUTPUT ${MAN_PAGE} + DEPENDS ${SOURCE_FILE} + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE_FILE} ${CMAKE_CURRENT_BINARY_DIR}/${MAN_PAGE} + COMMENT "Preparing ${MAN_PAGE}" + ) + + STRING(REGEX REPLACE "[1-9]$" "html" HTML_FILE ${MAN_PAGE}) + STRING(REGEX REPLACE "[1-9]$" "man" MAN_FILE ${MAN_PAGE}) + STRING(REGEX REPLACE "[1-9]$" "mdoc" MDOC_FILE ${MAN_PAGE}) + + # html re-generation + ADD_CUSTOM_COMMAND(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/${HTML_FILE} + DEPENDS ${MDOC_FILE} + COMMAND ${CMAKE_COMMAND} -DIN=${MDOC_FILE} -DOUT=${HTML_FILE} -DDIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/update-html.cmake + ) + LIST(APPEND UPDATEHTML ${CMAKE_CURRENT_SOURCE_DIR}/${HTML_FILE}) + + # man re-generation + ADD_CUSTOM_COMMAND(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/${MAN_FILE} + DEPENDS ${MDOC_FILE} + COMMAND ${CMAKE_COMMAND} -DIN=${MDOC_FILE} -DOUT=${MAN_FILE} -DDIR=${CMAKE_CURRENT_SOURCE_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/update-man.cmake + ) + LIST(APPEND UPDATEMAN ${CMAKE_CURRENT_SOURCE_DIR}/${MAN_FILE}) +ENDFOREACH() +ADD_CUSTOM_TARGET(man ALL DEPENDS ${MAN_PAGES}) +ADD_CUSTOM_TARGET(update-man DEPENDS ${UPDATEMAN}) +ADD_CUSTOM_TARGET(update-html DEPENDS ${UPDATEHTML}) + +FILE(STRINGS links MANPAGE_LINKS) +FOREACH(LINKS_LINE ${MANPAGE_LINKS}) + IF(${LINKS_LINE} MATCHES "(.*) (.*)") + SET(SOURCE ${CMAKE_MATCH_1}) + SET(TARGET ${CMAKE_MATCH_2}) + IF (DOCUMENTATION_FORMAT MATCHES "html") + INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${SOURCE}.3 DESTINATION ${CMAKE_INSTALL_DOCDIR} RENAME ${TARGET}.html) + ELSE() + INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${SOURCE}.3 DESTINATION ${CMAKE_INSTALL_MANDIR}/man3 RENAME ${TARGET}.3) + ENDIF() + ENDIF() +ENDFOREACH() + +ADD_CUSTOM_TARGET(update_zip_errors + COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/make_zip_errors.sh ${CMAKE_SOURCE_DIR}/lib/zip.h ${CMAKE_CURRENT_SOURCE_DIR}/zip_errors.mdoc + DEPENDS ${CMAKE_SOURCE_DIR}/lib/zip.h ${CMAKE_CURRENT_SOURCE_DIR}/zip_errors.mdoc +) diff --git a/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.html b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.html new file mode 100644 index 0000000..66af70e --- /dev/null +++ b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.html @@ -0,0 +1,114 @@ + + + + + + + ZIP_SOURCE_GET_ARGS(3) + + + + + + + + +
ZIP_SOURCE_GET_ARGS(3)Library Functions ManualZIP_SOURCE_GET_ARGS(3)
+
+
+

+ZIP_SOURCE_GET_ARGS — +
validate and cast arguments to source callback
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

type * +
+ ZIP_SOURCE_GET_ARGS(type, + void *data, + zip_uint64_t len, + zip_error_t *error);

+
+
+

+The ZIP_SOURCE_GET_ARGS() macro casts + data to a pointer to type. +
+
+

+On success, ZIP_SOURCE_GET_ARGS() returns + data. In case of error, it returns + NULL and sets error. +
+
+

+ZIP_SOURCE_GET_ARGS() fails if: +
+
[]
+
len is less than the size of + type
+
+
+
+

+libzip(3), + zip_source_function(3) +
+
+

+ZIP_SOURCE_GET_ARGS() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.man b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.man new file mode 100644 index 0000000..0e23ebd --- /dev/null +++ b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.man @@ -0,0 +1,83 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" ZIP_SOURCE_GET_ARGS -- validate and cast arguments to source callback +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_GET_ARGS" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBZIP_SOURCE_GET_ARGS\fR +\- validate and cast arguments to source callback +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fItype *\fR +.br +.PD 0 +.HP 4n +\fBZIP_SOURCE_GET_ARGS\fR(\fItype\fR, \fIvoid\ *data\fR, \fIzip_uint64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The +\fBZIP_SOURCE_GET_ARGS\fR() +macro casts +\fIdata\fR +to a pointer to +\fItype\fR. +.SH "RETURN VALUES" +On success, +\fBZIP_SOURCE_GET_ARGS\fR() +returns +\fIdata\fR. +In case of error, it returns +\fRNULL\fR +and sets +\fIerror\fR. +.SH "ERRORS" +\fBZIP_SOURCE_GET_ARGS\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIlen\fR +is less than the size of +\fItype\fR +.SH "SEE ALSO" +libzip(3), +zip_source_function(3) +.SH "HISTORY" +\fBZIP_SOURCE_GET_ARGS\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.mdoc b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.mdoc new file mode 100644 index 0000000..2735964 --- /dev/null +++ b/third_party/libzip/man/ZIP_SOURCE_GET_ARGS.mdoc @@ -0,0 +1,79 @@ +.\" ZIP_SOURCE_GET_ARGS -- validate and cast arguments to source callback +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_GET_ARGS 3 +.Os +.Sh NAME +.Nm ZIP_SOURCE_GET_ARGS +.Nd validate and cast arguments to source callback +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft type * +.Fn ZIP_SOURCE_GET_ARGS "type" "void *data" "zip_uint64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The +.Fn ZIP_SOURCE_GET_ARGS +macro casts +.Ar data +to a pointer to +.Ar type . +.Sh RETURN VALUES +On success, +.Fn ZIP_SOURCE_GET_ARGS +returns +.Ar data . +In case of error, it returns +.Dv NULL +and sets +.Ar error . +.Sh ERRORS +.Fn ZIP_SOURCE_GET_ARGS +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar len +is less than the size of +.Ar type +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source_function 3 +.Sh HISTORY +.Fn ZIP_SOURCE_GET_ARGS +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/handle_links b/third_party/libzip/man/handle_links new file mode 100644 index 0000000..7c2ed37 --- /dev/null +++ b/third_party/libzip/man/handle_links @@ -0,0 +1,74 @@ +#!/usr/bin/env perl + +use strict; + +my $operation = shift @ARGV; + +if ($operation !~ m/^(install|uninstall)$/) { + print STDERR "$0: unknown operation $operation\n"; + exit(1); +} + +my %options = (); + +for my $arg (@ARGV) { + if ($arg =~ m/([^=]*)=(.*)/) { + $options{$1} = $2; + } + else { + print STDERR "$0: can't parse option [$arg]\n"; + exit(1); + } +} + +for my $option (qw(command directory extension file)) { + unless (defined($options{$option})) { + print STDERR "$0: required variable $option not provided\n"; + exit(1); + } +} + +my $fh; +unless (open $fh, '<', $options{file}) { + print STDERR "$0: can't open links file '$options{file}': $!"; + exit(1); +} + +my @cmd = split /\s+/, $options{command}; + +while (my $line = <$fh>) { + chomp $line; + my @args = split /\s+/, $line; + + process(@args); +} + +sub process { + my ($source, @destinations) = @_; + + my @args = (@cmd); + + if ($operation eq 'install') { + push @args, "$options{directory}/$source.$options{extension}"; + } + + for my $destination (@destinations) { + push @args, "$options{directory}/$destination.$options{extension}"; + run_command(@args); + pop @args; + } +} + +sub run_command { + print (join ' ', @_); + print "\n"; + + my $ret = system(@_); + + if ($ret != 0) { + print STDERR "$0: command failed: $?\n"; + exit(1); + } + + return 1; +} diff --git a/third_party/libzip/man/libzip.html b/third_party/libzip/man/libzip.html new file mode 100644 index 0000000..58f5d9b --- /dev/null +++ b/third_party/libzip/man/libzip.html @@ -0,0 +1,248 @@ + + + + + + + LIBZIP(3) + + + + + + + + +
LIBZIP(3)Library Functions ManualLIBZIP(3)
+
+
+

+libzip — +
library for manipulating zip archives
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +
+
+

+libzip is a library for reading, creating, and modifying + zip archives. +

The main design criteria for libzip + were:

+
    +
  • Do not create corrupt files, even in case of errors.
  • +
  • Do not delete data.
  • +
  • Be efficient.
  • +
+

For this reason, when modifying zip archives, + libzip writes to a temporary file and replaces the + original zip archive atomically.

+

Below there are two sections listing functions: one for how to + read from zip archives and one for how to create/modify them.

+
+
+

+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+
+

+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+

+ +
+
+
+

+ +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
September 29, 2018NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/libzip.man b/third_party/libzip/man/libzip.man new file mode 100644 index 0000000..19a5ca6 --- /dev/null +++ b/third_party/libzip/man/libzip.man @@ -0,0 +1,291 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" libzip.mdoc -- general overview of available functions +.\" Copyright (C) 2005-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "LIBZIP" "3" "September 29, 2018" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBlibzip\fR +\- library for manipulating zip archives +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.SH "DESCRIPTION" +\fBlibzip\fR +is a library for reading, creating, and modifying zip archives. +.PP +The main design criteria for +\fBlibzip\fR +were: +.PD 0 +.TP 4n +\fB\(bu\fR +Do not create corrupt files, even in case of errors. +.TP 4n +\fB\(bu\fR +Do not delete data. +.TP 4n +\fB\(bu\fR +Be efficient. +.PD +.PP +For this reason, when modifying zip archives, +\fBlibzip\fR +writes to a temporary file and replaces the original +zip archive atomically. +.PP +Below there are two sections listing functions: one for how to read +from zip archives and one for how to create/modify them. +.SH "READING ZIP ARCHIVES" +.SS "open archive" +.TP 4n +\fB\(bu\fR +zip_open(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_fdopen(3) +.PD +.SS "find files" +.TP 4n +\fB\(bu\fR +zip_name_locate(3) +.SS "read files" +.TP 4n +\fB\(bu\fR +zip_fopen(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_fopen_encrypted(3) +.TP 4n +\fB\(bu\fR +zip_fopen_index(3) +.TP 4n +\fB\(bu\fR +zip_fopen_index_encrypted(3) +.TP 4n +\fB\(bu\fR +zip_fread(3) +.TP 4n +\fB\(bu\fR +zip_fseek(3) +(uncompressed files only) +.TP 4n +\fB\(bu\fR +zip_ftell(3) +(uncompressed files only) +.TP 4n +\fB\(bu\fR +zip_fclose(3) +.PD +.SS "close archive" +.TP 4n +\fB\(bu\fR +zip_close(3) +.SS "miscellaneous" +.TP 4n +\fB\(bu\fR +zip_stat(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_file_get_comment(3) +.TP 4n +\fB\(bu\fR +zip_file_get_external_attributes(3) +.TP 4n +\fB\(bu\fR +zip_get_archive_comment(3) +.TP 4n +\fB\(bu\fR +zip_get_archive_flag(3) +.TP 4n +\fB\(bu\fR +zip_get_name(3) +.TP 4n +\fB\(bu\fR +zip_get_num_entries(3) +.TP 4n +\fB\(bu\fR +zip_set_default_password(3) +.PD +.SH "CREATING/MODIFYING ZIP ARCHIVES" +.SS "create/open archive" +.TP 4n +\fB\(bu\fR +zip_open(3) +.SS "add/change files and directories" +.TP 4n +\fB\(bu\fR +zip_dir_add(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_file_add(3) +.TP 4n +\fB\(bu\fR +zip_file_replace(3) +.TP 4n +\fB\(bu\fR +zip_file_set_comment(3) +.TP 4n +\fB\(bu\fR +zip_file_set_external_attributes(3) +.TP 4n +\fB\(bu\fR +zip_file_set_encryption(3) +.TP 4n +\fB\(bu\fR +zip_file_set_mtime(3) +.TP 4n +\fB\(bu\fR +zip_set_file_compression(3) +.TP 4n +\fB\(bu\fR +zip_source_buffer(3) +.TP 4n +\fB\(bu\fR +zip_source_file(3) +.TP 4n +\fB\(bu\fR +zip_source_filep(3) +.TP 4n +\fB\(bu\fR +zip_source_free(3) +.TP 4n +\fB\(bu\fR +zip_source_function(3) +.TP 4n +\fB\(bu\fR +zip_source_zip(3) +.PD +.SS "rename files" +.TP 4n +\fB\(bu\fR +zip_rename(3) +.SS "delete files" +.TP 4n +\fB\(bu\fR +zip_delete(3) +.SS "revert changes" +.TP 4n +\fB\(bu\fR +zip_unchange(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_unchange_all(3) +.TP 4n +\fB\(bu\fR +zip_unchange_archive(3) +.PD +.SS "read/modify extra fields" +.TP 4n +\fB\(bu\fR +zip_file_extra_field_by_id(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_file_extra_field_delete(3) +.TP 4n +\fB\(bu\fR +zip_file_extra_field_delete_by_id(3) +.TP 4n +\fB\(bu\fR +zip_file_extra_field_get(3) +.TP 4n +\fB\(bu\fR +zip_file_extra_field_set(3) +.TP 4n +\fB\(bu\fR +zip_file_extra_fields_count(3) +.TP 4n +\fB\(bu\fR +zip_file_extra_fields_count_by_id(3) +.PD +.SS "close archive (writing)" +.TP 4n +\fB\(bu\fR +zip_close(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_discard(3) +.PD +.SS "miscellaneous (writing)" +.TP 4n +\fB\(bu\fR +zip_libzip_version(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_register_progress_callback_with_state(3) +.TP 4n +\fB\(bu\fR +zip_set_archive_comment(3) +.TP 4n +\fB\(bu\fR +zip_set_archive_flag(3) +.TP 4n +\fB\(bu\fR +zip_source(3) +.PD +.SH "ERROR HANDLING" +.TP 4n +\fB\(bu\fR +zip_error_strerror(3) +.PD 0 +.TP 4n +\fB\(bu\fR +zip_strerror(3) +.TP 4n +\fB\(bu\fR +zip_file_strerror(3) +.TP 4n +\fB\(bu\fR +zip_get_error(3) +.TP 4n +\fB\(bu\fR +zip_error_init_with_code(3) +.TP 4n +\fB\(bu\fR +zip_error_system_type(3) +.TP 4n +\fB\(bu\fR +zip_errors(3) +.PD +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/libzip.mdoc b/third_party/libzip/man/libzip.mdoc new file mode 100644 index 0000000..8f16564 --- /dev/null +++ b/third_party/libzip/man/libzip.mdoc @@ -0,0 +1,237 @@ +.\" libzip.mdoc -- general overview of available functions +.\" Copyright (C) 2005-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd September 29, 2018 +.Dt LIBZIP 3 +.Os +.Sh NAME +.Nm libzip +.Nd library for manipulating zip archives +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Sh DESCRIPTION +.Nm +is a library for reading, creating, and modifying zip archives. +.Pp +The main design criteria for +.Nm +were: +.Bl -bullet -compact +.It +Do not create corrupt files, even in case of errors. +.It +Do not delete data. +.It +Be efficient. +.El +.Pp +For this reason, when modifying zip archives, +.Nm +writes to a temporary file and replaces the original +zip archive atomically. +.Pp +Below there are two sections listing functions: one for how to read +from zip archives and one for how to create/modify them. +.Sh READING ZIP ARCHIVES +.Ss open archive +.Bl -bullet -compact +.It +.Xr zip_open 3 +.It +.Xr zip_fdopen 3 +.El +.Ss find files +.Bl -bullet -compact +.It +.Xr zip_name_locate 3 +.El +.Ss read files +.Bl -bullet -compact +.It +.Xr zip_fopen 3 +.It +.Xr zip_fopen_encrypted 3 +.It +.Xr zip_fopen_index 3 +.It +.Xr zip_fopen_index_encrypted 3 +.It +.Xr zip_fread 3 +.It +.Xr zip_fseek 3 +(uncompressed files only) +.It +.Xr zip_ftell 3 +(uncompressed files only) +.It +.Xr zip_fclose 3 +.El +.Ss close archive +.Bl -bullet -compact +.It +.Xr zip_close 3 +.El +.Ss miscellaneous +.Bl -bullet -compact +.It +.Xr zip_stat 3 +.It +.Xr zip_file_get_comment 3 +.It +.Xr zip_file_get_external_attributes 3 +.It +.Xr zip_get_archive_comment 3 +.It +.Xr zip_get_archive_flag 3 +.It +.Xr zip_get_name 3 +.It +.Xr zip_get_num_entries 3 +.It +.Xr zip_set_default_password 3 +.El +.Sh CREATING/MODIFYING ZIP ARCHIVES +.Ss create/open archive +.Bl -bullet -compact +.It +.Xr zip_open 3 +.El +.Ss add/change files and directories +.Bl -bullet -compact +.It +.Xr zip_dir_add 3 +.It +.Xr zip_file_add 3 +.It +.Xr zip_file_replace 3 +.It +.Xr zip_file_set_comment 3 +.It +.Xr zip_file_set_external_attributes 3 +.It +.Xr zip_file_set_encryption 3 +.It +.Xr zip_file_set_mtime 3 +.It +.Xr zip_set_file_compression 3 +.It +.Xr zip_source_buffer 3 +.It +.Xr zip_source_file 3 +.It +.Xr zip_source_filep 3 +.It +.Xr zip_source_free 3 +.It +.Xr zip_source_function 3 +.It +.Xr zip_source_zip 3 +.El +.Ss rename files +.Bl -bullet -compact +.It +.Xr zip_rename 3 +.El +.Ss delete files +.Bl -bullet -compact +.It +.Xr zip_delete 3 +.El +.Ss revert changes +.Bl -bullet -compact +.It +.Xr zip_unchange 3 +.It +.Xr zip_unchange_all 3 +.It +.Xr zip_unchange_archive 3 +.El +.Ss read/modify extra fields +.Bl -bullet -compact +.It +.Xr zip_file_extra_field_by_id 3 +.It +.Xr zip_file_extra_field_delete 3 +.It +.Xr zip_file_extra_field_delete_by_id 3 +.It +.Xr zip_file_extra_field_get 3 +.It +.Xr zip_file_extra_field_set 3 +.It +.Xr zip_file_extra_fields_count 3 +.It +.Xr zip_file_extra_fields_count_by_id 3 +.El +.Ss close archive (writing) +.Bl -bullet -compact +.It +.Xr zip_close 3 +.It +.Xr zip_discard 3 +.El +.Ss miscellaneous (writing) +.Bl -bullet -compact +.It +.Xr zip_libzip_version 3 +.It +.Xr zip_register_progress_callback_with_state 3 +.It +.Xr zip_set_archive_comment 3 +.It +.Xr zip_set_archive_flag 3 +.It +.Xr zip_source 3 +.El +.Sh ERROR HANDLING +.Bl -bullet -compact +.It +.Xr zip_error_strerror 3 +.It +.Xr zip_strerror 3 +.It +.Xr zip_file_strerror 3 +.It +.Xr zip_get_error 3 +.It +.Xr zip_error_init_with_code 3 +.It +.Xr zip_error_system_type 3 +.It +.Xr zip_errors 3 +.El +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/links b/third_party/libzip/man/links new file mode 100644 index 0000000..7364474 --- /dev/null +++ b/third_party/libzip/man/links @@ -0,0 +1,22 @@ +zip_add zip_replace +zip_error_clear zip_file_error_clear +zip_error_get zip_file_error_get +zip_error_init zip_error_init_with_code +zip_file_add zip_file_replace +zip_file_extra_field_delete zip_file_extra_field_delete_by_id +zip_file_extra_field_get zip_file_extra_field_get_by_id +zip_file_extra_fields_count zip_file_extra_fields_count_by_id +zip_file_strerror zip_strerror +zip_fopen zip_fopen_index +zip_fopen_encrypted zip_fopen_index_encrypted +zip_open zip_open_from_source +zip_source_begin_write zip_source_begin_write_cloning +zip_source_buffer zip_source_buffer_create +zip_source_buffer_fragment zip_source_buffer_fragment_create +zip_source_file zip_source_file_create +zip_source_filep zip_source_filep_create +zip_source_function zip_source_function_create +zip_source_win32a zip_source_win32a_create +zip_source_win32handle zip_source_win32handle_create +zip_source_win32w zip_source_win32w_create +zip_stat zip_stat_index diff --git a/third_party/libzip/man/update-html.cmake b/third_party/libzip/man/update-html.cmake new file mode 100644 index 0000000..9e405b2 --- /dev/null +++ b/third_party/libzip/man/update-html.cmake @@ -0,0 +1,11 @@ +# expect variables IN, OUT, and DIR +EXECUTE_PROCESS(COMMAND mandoc -T html -Oman=%N.html,style=../nih-man.css ${DIR}/${IN} + OUTPUT_VARIABLE HTML) +SET(LINKBASE "http://pubs.opengroup.org/onlinepubs/9699919799/functions/") +STRING(REGEX REPLACE "()" "\\1${LINKBASE}\\2\\3" HTML "${HTML}") +STRING(REGEX REPLACE "${LINKBASE}(libzip|zip)" "\\1" HTML "${HTML}") +FILE(WRITE ${DIR}/${OUT}.new "${HTML}") +CONFIGURE_FILE(${DIR}/${OUT}.new ${DIR}/${OUT} COPYONLY) +FILE(REMOVE ${DIR}/${OUT}.new) + + diff --git a/third_party/libzip/man/update-man.cmake b/third_party/libzip/man/update-man.cmake new file mode 100644 index 0000000..4254711 --- /dev/null +++ b/third_party/libzip/man/update-man.cmake @@ -0,0 +1,7 @@ +# expect variables IN, OUT, and DIR +EXECUTE_PROCESS(COMMAND mandoc -T man ${DIR}/${IN} OUTPUT_VARIABLE MAN) +STRING(REGEX REPLACE "NetBSD [0-9.]*" "NiH" MAN "${MAN}") +FILE(WRITE ${DIR}/${OUT}.new "${MAN}") +CONFIGURE_FILE(${DIR}/${OUT}.new ${DIR}/${OUT} COPYONLY) +FILE(REMOVE ${DIR}/${OUT}.new) + diff --git a/third_party/libzip/man/zip_add.html b/third_party/libzip/man/zip_add.html new file mode 100644 index 0000000..c911ef3 --- /dev/null +++ b/third_party/libzip/man/zip_add.html @@ -0,0 +1,121 @@ + + + + + + + ZIP_ADD(3) + + + + + + + + +
ZIP_ADD(3)Library Functions ManualZIP_ADD(3)
+
+
+

+zip_add, zip_replace — +
add file to zip archive or replace file in zip archive (obsolete + interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_add(zip_t + *archive, const char + *name, zip_source_t + *source);

+

int +
+ zip_replace(zip_t + *archive, zip_uint64_t + index, zip_source_t + *source);

+
+
+

+The function zip_add() is the obsolete version of + zip_file_add(3). It is the same as + calling zip_file_add(3) with an + empty flags argument. Similarly, the + zip_replace() function is the obsolete version of + zip_file_replace(3). It is the + same as calling + zip_file_replace(3) with an + empty flags argument. +
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3) +
+
+

+zip_add() was added in libzip 0.6. In libzip 0.10 the + return type was changed from int to + zip_int64_t. It was deprecated in libzip 0.11, use + zip_file_add() instead. +

zip_replace() was added in libzip 0.6. In + libzip 0.10 the type of index was changed from + int to zip_uint64_t. It was + deprecated in libzip 0.11, use zip_file_replace() + instead.

+
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_add.man b/third_party/libzip/man/zip_add.man new file mode 100644 index 0000000..451645f --- /dev/null +++ b/third_party/libzip/man/zip_add.man @@ -0,0 +1,106 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_add.mdoc -- add files to zip archive +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ADD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_add\fR, +\fBzip_replace\fR +\- add file to zip archive or replace file in zip archive (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_add\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *name\fR, \fIzip_source_t\ *source\fR); +.PD +.PP +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_replace\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_add\fR() +is the obsolete version of +zip_file_add(3). +It is the same as calling +zip_file_add(3) +with an empty +\fIflags\fR +argument. +Similarly, the +\fBzip_replace\fR() +function is the obsolete version of +zip_file_replace(3). +It is the same as calling +zip_file_replace(3) +with an empty +\fIflags\fR +argument. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3) +.SH "HISTORY" +\fBzip_add\fR() +was added in libzip 0.6. +In libzip 0.10 the return type was changed from +\fIint\fR +to +\fIzip_int64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_file_add\fR() +instead. +.PP +\fBzip_replace\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_file_replace\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_add.mdoc b/third_party/libzip/man/zip_add.mdoc new file mode 100644 index 0000000..27c5319 --- /dev/null +++ b/third_party/libzip/man/zip_add.mdoc @@ -0,0 +1,96 @@ +.\" zip_add.mdoc -- add files to zip archive +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ADD 3 +.Os +.Sh NAME +.Nm zip_add , +.Nm zip_replace +.Nd add file to zip archive or replace file in zip archive (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_add "zip_t *archive" "const char *name" "zip_source_t *source" +.Ft int +.Fn zip_replace "zip_t *archive" "zip_uint64_t index" "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_add +is the obsolete version of +.Xr zip_file_add 3 . +It is the same as calling +.Xr zip_file_add 3 +with an empty +.Ar flags +argument. +Similarly, the +.Fn zip_replace +function is the obsolete version of +.Xr zip_file_replace 3 . +It is the same as calling +.Xr zip_file_replace 3 +with an empty +.Ar flags +argument. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 +.Sh HISTORY +.Fn zip_add +was added in libzip 0.6. +In libzip 0.10 the return type was changed from +.Vt int +to +.Vt zip_int64_t . +It was deprecated in libzip 0.11, use +.Fn zip_file_add +instead. +.Pp +.Fn zip_replace +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +It was deprecated in libzip 0.11, use +.Fn zip_file_replace +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_add_dir.html b/third_party/libzip/man/zip_add_dir.html new file mode 100644 index 0000000..f6d0086 --- /dev/null +++ b/third_party/libzip/man/zip_add_dir.html @@ -0,0 +1,102 @@ + + + + + + + ZIP_ADD_DIR(3) + + + + + + + + +
ZIP_ADD_DIR(3)Library Functions ManualZIP_ADD_DIR(3)
+
+
+

+zip_add_dir — +
add directory to zip archive (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_add_dir(zip_t + *archive, const char + *name);

+
+
+

+The function zip_add_dir() is the obsolete version of + zip_dir_add(3). It is the same as + calling zip_dir_add(3) with an empty + flags argument. +
+
+

+libzip(3), + zip_dir_add(3) +
+
+

+zip_add_dir() was added in libzip 0.8. In libzip 0.10 + the return type was changed from int to + zip_int64_t. It was deprecated in libzip 0.11, use + zip_dir_add() instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_add_dir.man b/third_party/libzip/man/zip_add_dir.man new file mode 100644 index 0000000..90f313d --- /dev/null +++ b/third_party/libzip/man/zip_add_dir.man @@ -0,0 +1,74 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_add_dir.mdoc -- add directory to zip archive +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ADD_DIR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_add_dir\fR +\- add directory to zip archive (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_add_dir\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *name\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_add_dir\fR() +is the obsolete version of +zip_dir_add(3). +It is the same as calling +zip_dir_add(3) +with an empty flags argument. +.SH "SEE ALSO" +libzip(3), +zip_dir_add(3) +.SH "HISTORY" +\fBzip_add_dir\fR() +was added in libzip 0.8. +In libzip 0.10 the return type was changed from +\fIint\fR +to +\fIzip_int64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_dir_add\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_add_dir.mdoc b/third_party/libzip/man/zip_add_dir.mdoc new file mode 100644 index 0000000..f28d1d5 --- /dev/null +++ b/third_party/libzip/man/zip_add_dir.mdoc @@ -0,0 +1,69 @@ +.\" zip_add_dir.mdoc -- add directory to zip archive +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ADD_DIR 3 +.Os +.Sh NAME +.Nm zip_add_dir +.Nd add directory to zip archive (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_add_dir "zip_t *archive" "const char *name" +.Sh DESCRIPTION +The function +.Fn zip_add_dir +is the obsolete version of +.Xr zip_dir_add 3 . +It is the same as calling +.Xr zip_dir_add 3 +with an empty flags argument. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_dir_add 3 +.Sh HISTORY +.Fn zip_add_dir +was added in libzip 0.8. +In libzip 0.10 the return type was changed from +.Vt int +to +.Vt zip_int64_t . +It was deprecated in libzip 0.11, use +.Fn zip_dir_add +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_close.html b/third_party/libzip/man/zip_close.html new file mode 100644 index 0000000..20d41b6 --- /dev/null +++ b/third_party/libzip/man/zip_close.html @@ -0,0 +1,146 @@ + + + + + + + ZIP_CLOSE(3) + + + + + + + + +
ZIP_CLOSE(3)Library Functions ManualZIP_CLOSE(3)
+
+
+

+zip_close — +
close zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_close(zip_t + *archive);

+
+
+

+The zip_close() function writes any changes made to + archive to disk. If archive + contains no files, the file is completely removed (no empty archive is + written). If successful, archive is freed. If writing + fails, zip_close() fails; + archive is left unchanged and must still be freed. +

To close and free a zip archive without saving changes, use + zip_discard(3).

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_close() will fail if: +
+
[]
+
Unexpected end-of-file found while reading from a file.
+
[]
+
The callback function of an added or replaced file returned an error but + failed to report which.
+
[]
+
The path argument is + NULL.
+
[]
+
Required memory could not be allocated.
+
[]
+
File is not a zip archive.
+
[]
+
A file read failed.
+
[]
+
A temporary file could not be renamed to its final name.
+
[]
+
A file seek failed.
+
[]
+
A temporary file could not be created.
+
[]
+
A file write failed.
+
[]
+
An error occurred while (de)compressing a stream with + zlib(3).
+
+Additionally, any errors returned by the callback function for added or replaced + files will be passed back. +
+
+

+libzip(3), + zip_discard(3), + zip_fdopen(3), + zip_get_error(3), + zip_open(3), + zip_register_progress_callback_with_state(3), + zip_strerror(3) +
+
+

+zip_close() was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_close.man b/third_party/libzip/man/zip_close.man new file mode 100644 index 0000000..69552b0 --- /dev/null +++ b/third_party/libzip/man/zip_close.man @@ -0,0 +1,136 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_close.mdoc -- close zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_CLOSE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_close\fR +\- close zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_close\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_close\fR() +function writes any changes made to +\fIarchive\fR +to disk. +If +\fIarchive\fR +contains no files, the file is completely removed (no empty archive is +written). +If successful, +\fIarchive\fR +is freed. +If writing fails, +\fBzip_close\fR() +fails; +\fIarchive\fR +is left unchanged and must still be freed. +.PP +To close and free a zip archive without saving changes, use +zip_discard(3). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_close\fR() +will fail if: +.TP 19n +[\fRZIP_ER_EOF\fR] +Unexpected end-of-file found while reading from a file. +.TP 19n +[\fRZIP_ER_INTERNAL\fR] +The callback function of an added or replaced file returned an +error but failed to report which. +.TP 19n +[\fRZIP_ER_INVAL\fR] +The +\fIpath\fR +argument is +\fRNULL\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOZIP\fR] +File is not a zip archive. +.TP 19n +[\fRZIP_ER_READ\fR] +A file read failed. +.TP 19n +[\fRZIP_ER_RENAME\fR] +A temporary file could not be renamed to its final name. +.TP 19n +[\fRZIP_ER_SEEK\fR] +A file seek failed. +.TP 19n +[\fRZIP_ER_TMPOPEN\fR] +A temporary file could not be created. +.TP 19n +[\fRZIP_ER_WRITE\fR] +A file write failed. +.TP 19n +[\fRZIP_ER_ZLIB\fR] +An error occurred while (de)compressing a stream with +zlib(3). +.PD 0 +.PP +Additionally, any errors returned by the callback function +for added or replaced files will be passed back. +.PD +.SH "SEE ALSO" +libzip(3), +zip_discard(3), +zip_fdopen(3), +zip_get_error(3), +zip_open(3), +zip_register_progress_callback_with_state(3), +zip_strerror(3) +.SH "HISTORY" +\fBzip_close\fR() +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_close.mdoc b/third_party/libzip/man/zip_close.mdoc new file mode 100644 index 0000000..d9327cb --- /dev/null +++ b/third_party/libzip/man/zip_close.mdoc @@ -0,0 +1,119 @@ +.\" zip_close.mdoc -- close zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_CLOSE 3 +.Os +.Sh NAME +.Nm zip_close +.Nd close zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_close "zip_t *archive" +.Sh DESCRIPTION +The +.Fn zip_close +function writes any changes made to +.Ar archive +to disk. +If +.Ar archive +contains no files, the file is completely removed (no empty archive is +written). +If successful, +.Ar archive +is freed. +If writing fails, +.Fn zip_close +fails; +.Ar archive +is left unchanged and must still be freed. +.Pp +To close and free a zip archive without saving changes, use +.Xr zip_discard 3 . +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_close +will fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_EOF +Unexpected end-of-file found while reading from a file. +.It Bq Er ZIP_ER_INTERNAL +The callback function of an added or replaced file returned an +error but failed to report which. +.It Bq Er ZIP_ER_INVAL +The +.Ar path +argument is +.Dv NULL . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOZIP +File is not a zip archive. +.It Bq Er ZIP_ER_READ +A file read failed. +.It Bq Er ZIP_ER_RENAME +A temporary file could not be renamed to its final name. +.It Bq Er ZIP_ER_SEEK +A file seek failed. +.It Bq Er ZIP_ER_TMPOPEN +A temporary file could not be created. +.It Bq Er ZIP_ER_WRITE +A file write failed. +.It Bq Er ZIP_ER_ZLIB +An error occurred while (de)compressing a stream with +.Xr zlib 3 . +.El +Additionally, any errors returned by the callback function +for added or replaced files will be passed back. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_discard 3 , +.Xr zip_fdopen 3 , +.Xr zip_get_error 3 , +.Xr zip_open 3 , +.Xr zip_register_progress_callback_with_state 3 , +.Xr zip_strerror 3 +.Sh HISTORY +.Fn zip_close +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_delete.html b/third_party/libzip/man/zip_delete.html new file mode 100644 index 0000000..d9f5cc3 --- /dev/null +++ b/third_party/libzip/man/zip_delete.html @@ -0,0 +1,114 @@ + + + + + + + ZIP_DELETE(3) + + + + + + + + +
ZIP_DELETE(3)Library Functions ManualZIP_DELETE(3)
+
+
+

+zip_delete — +
delete file from zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_delete(zip_t + *archive, zip_uint64_t + index);

+
+
+

+The file at position index in the zip archive + archive is marked as deleted. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_delete() fails if: +
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_unchange(3) +
+
+

+zip_delete() was added in libzip 0.6. In libzip 0.10 the + type of index was changed from int + to zip_uint64_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_delete.man b/third_party/libzip/man/zip_delete.man new file mode 100644 index 0000000..d607c1e --- /dev/null +++ b/third_party/libzip/man/zip_delete.man @@ -0,0 +1,84 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_delete.mdoc -- delete files from zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_DELETE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_delete\fR +\- delete file from zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_delete\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR); +.PD +.SH "DESCRIPTION" +The file at position +\fIindex\fR +in the zip archive +\fIarchive\fR +is marked as deleted. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_delete\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_unchange(3) +.SH "HISTORY" +\fBzip_delete\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_delete.mdoc b/third_party/libzip/man/zip_delete.mdoc new file mode 100644 index 0000000..dc8346e --- /dev/null +++ b/third_party/libzip/man/zip_delete.mdoc @@ -0,0 +1,80 @@ +.\" zip_delete.mdoc -- delete files from zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_DELETE 3 +.Os +.Sh NAME +.Nm zip_delete +.Nd delete file from zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_delete "zip_t *archive" "zip_uint64_t index" +.Sh DESCRIPTION +The file at position +.Ar index +in the zip archive +.Ar archive +is marked as deleted. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_delete +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_unchange 3 +.Sh HISTORY +.Fn zip_delete +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_dir_add.html b/third_party/libzip/man/zip_dir_add.html new file mode 100644 index 0000000..961c9df --- /dev/null +++ b/third_party/libzip/man/zip_dir_add.html @@ -0,0 +1,135 @@ + + + + + + + ZIP_DIR_ADD(3) + + + + + + + + +
ZIP_DIR_ADD(3)Library Functions ManualZIP_DIR_ADD(3)
+
+
+

+zip_dir_add — +
add directory to zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_dir_add(zip_t + *archive, const char + *name, zip_flags_t + flags);

+
+
+

+The function zip_dir_add() adds a directory to a zip + archive. The argument archive specifies the zip archive + to which the directory should be added. name is the + directory's name in the zip archive. The flags argument + can be any of: +
+
+
Guess encoding of name (default).
+
+
Interpret name as UTF-8.
+
+
Interpret name as code page 437 (CP-437).
+
+
+
+

+Upon successful completion, the index of the new entry in the archive is + returned. Otherwise, -1 is returned and the error code in + archive is set to indicate the error. +
+
+

+zip_dir_add() fails if: +
+
[]
+
There is already an entry called name in the + archive.
+
[]
+
archive or name are + NULL, or invalid UTF-8 encoded file names.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_add(3) +
+
+

+zip_dir_add() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+

+zip_dir_add() does not look in the file system, it just + creates one entry in the archive for the provided name. +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_dir_add.man b/third_party/libzip/man/zip_dir_add.man new file mode 100644 index 0000000..59e63a0 --- /dev/null +++ b/third_party/libzip/man/zip_dir_add.man @@ -0,0 +1,115 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_dir_add.mdoc -- add directory to zip archive +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_DIR_ADD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_dir_add\fR +\- add directory to zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_dir_add\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *name\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_dir_add\fR() +adds a directory to a zip archive. +The argument +\fIarchive\fR +specifies the zip archive to which the directory should be added. +\fIname\fR +is the directory's name in the zip archive. +The +\fIflags\fR +argument can be any of: +.TP 22n +\fRZIP_FL_ENC_GUESS\fR +Guess encoding of +\fIname\fR +(default). +.TP 22n +\fRZIP_FL_ENC_UTF_8\fR +Interpret +\fIname\fR +as UTF-8. +.TP 22n +\fRZIP_FL_ENC_CP437\fR +Interpret +\fIname\fR +as code page 437 (CP-437). +.SH "RETURN VALUES" +Upon successful completion, the index of the new entry in the archive +is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_dir_add\fR() +fails if: +.TP 19n +[\fRZIP_ER_EXISTS\fR] +There is already an entry called +\fIname\fR +in the archive. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIarchive\fR +or +\fIname\fR +are +\fRNULL\fR, +or invalid UTF-8 encoded file names. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3) +.SH "HISTORY" +\fBzip_dir_add\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> +.SH "CAVEATS" +\fBzip_dir_add\fR() +does not look in the file system, it just creates one entry in the +archive for the provided name. diff --git a/third_party/libzip/man/zip_dir_add.mdoc b/third_party/libzip/man/zip_dir_add.mdoc new file mode 100644 index 0000000..c075f83 --- /dev/null +++ b/third_party/libzip/man/zip_dir_add.mdoc @@ -0,0 +1,108 @@ +.\" zip_dir_add.mdoc -- add directory to zip archive +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_DIR_ADD 3 +.Os +.Sh NAME +.Nm zip_dir_add +.Nd add directory to zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_dir_add "zip_t *archive" "const char *name" "zip_flags_t flags" +.Sh DESCRIPTION +The function +.Fn zip_dir_add +adds a directory to a zip archive. +The argument +.Ar archive +specifies the zip archive to which the directory should be added. +.Ar name +is the directory's name in the zip archive. +The +.Ar flags +argument can be any of: +.Bl -tag -width XZIPXFLXENCXSTRICTXX +.It Dv ZIP_FL_ENC_GUESS +Guess encoding of +.Ar name +(default). +.It Dv ZIP_FL_ENC_UTF_8 +Interpret +.Ar name +as UTF-8. +.It Dv ZIP_FL_ENC_CP437 +Interpret +.Ar name +as code page 437 (CP-437). +.El +.Sh RETURN VALUES +Upon successful completion, the index of the new entry in the archive +is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_dir_add +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_EXISTS +There is already an entry called +.Ar name +in the archive. +.It Bq Er ZIP_ER_INVAL +.Ar archive +or +.Ar name +are +.Dv NULL , +or invalid UTF-8 encoded file names. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 +.Sh HISTORY +.Fn zip_dir_add +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at +.Sh CAVEATS +.Fn zip_dir_add +does not look in the file system, it just creates one entry in the +archive for the provided name. diff --git a/third_party/libzip/man/zip_discard.html b/third_party/libzip/man/zip_discard.html new file mode 100644 index 0000000..078dd77 --- /dev/null +++ b/third_party/libzip/man/zip_discard.html @@ -0,0 +1,97 @@ + + + + + + + ZIP_DISCARD(3) + + + + + + + + +
ZIP_DISCARD(3)Library Functions ManualZIP_DISCARD(3)
+
+
+

+zip_discard — +
close zip archive and discard changes
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_discard(zip_t + *archive);

+
+
+

+The zip_discard() function closes + archive and frees the memory allocated for it. Any + changes to the archive are not written to disk and discarded. +
+
+

+libzip(3), + zip_close(3) +
+
+

+zip_discard() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_discard.man b/third_party/libzip/man/zip_discard.man new file mode 100644 index 0000000..591f773 --- /dev/null +++ b/third_party/libzip/man/zip_discard.man @@ -0,0 +1,66 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_discard.mdoc -- close zip archive and discard changes +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_DISCARD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_discard\fR +\- close zip archive and discard changes +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_discard\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_discard\fR() +function closes +\fIarchive\fR +and frees the memory allocated for it. +Any changes to the archive are not written to disk and discarded. +.SH "SEE ALSO" +libzip(3), +zip_close(3) +.SH "HISTORY" +\fBzip_discard\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_discard.mdoc b/third_party/libzip/man/zip_discard.mdoc new file mode 100644 index 0000000..7404a48 --- /dev/null +++ b/third_party/libzip/man/zip_discard.mdoc @@ -0,0 +1,61 @@ +.\" zip_discard.mdoc -- close zip archive and discard changes +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_DISCARD 3 +.Os +.Sh NAME +.Nm zip_discard +.Nd close zip archive and discard changes +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_discard "zip_t *archive" +.Sh DESCRIPTION +The +.Fn zip_discard +function closes +.Ar archive +and frees the memory allocated for it. +Any changes to the archive are not written to disk and discarded. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_close 3 +.Sh HISTORY +.Fn zip_discard +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_clear.html b/third_party/libzip/man/zip_error_clear.html new file mode 100644 index 0000000..20ae860 --- /dev/null +++ b/third_party/libzip/man/zip_error_clear.html @@ -0,0 +1,104 @@ + + + + + + + ZIP_ERROR_CLEAR(3) + + + + + + + + +
ZIP_ERROR_CLEAR(3)Library Functions ManualZIP_ERROR_CLEAR(3)
+
+
+

+zip_error_clear, + zip_file_error_clear — +
clear error state for archive or file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_error_clear(zip_t + *archive);

+

void +
+ zip_file_error_clear(zip_file_t + *file);

+
+
+

+The zip_error_clear() function clears the error state + for the zip archive archive. +

The zip_file_error_clear() function does + the same for the zip file file.

+
+
+

+libzip(3), + zip_get_error(3) +
+
+

+zip_error_clear() and + zip_file_error_clear() were added in libzip 0.8. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_clear.man b/third_party/libzip/man/zip_error_clear.man new file mode 100644 index 0000000..fe92515 --- /dev/null +++ b/third_party/libzip/man/zip_error_clear.man @@ -0,0 +1,79 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_clear.mdoc -- clear error state for archive or file +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_CLEAR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_clear\fR, +\fBzip_file_error_clear\fR +\- clear error state for archive or file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_clear\fR(\fIzip_t\ *archive\fR); +.PD +.PP +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_file_error_clear\fR(\fIzip_file_t\ *file\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_clear\fR() +function clears the error state for the zip archive +\fIarchive\fR. +.PP +The +\fBzip_file_error_clear\fR() +function does the same for the zip file +\fIfile\fR. +.SH "SEE ALSO" +libzip(3), +zip_get_error(3) +.SH "HISTORY" +\fBzip_error_clear\fR() +and +\fBzip_file_error_clear\fR() +were added in libzip 0.8. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_clear.mdoc b/third_party/libzip/man/zip_error_clear.mdoc new file mode 100644 index 0000000..edac2c3 --- /dev/null +++ b/third_party/libzip/man/zip_error_clear.mdoc @@ -0,0 +1,69 @@ +.\" zip_error_clear.mdoc -- clear error state for archive or file +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_CLEAR 3 +.Os +.Sh NAME +.Nm zip_error_clear , +.Nm zip_file_error_clear +.Nd clear error state for archive or file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_error_clear "zip_t *archive" +.Ft void +.Fn zip_file_error_clear "zip_file_t *file" +.Sh DESCRIPTION +The +.Fn zip_error_clear +function clears the error state for the zip archive +.Ar archive . +.Pp +The +.Fn zip_file_error_clear +function does the same for the zip file +.Ar file . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_get_error 3 +.Sh HISTORY +.Fn zip_error_clear +and +.Fn zip_file_error_clear +were added in libzip 0.8. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_code_system.html b/third_party/libzip/man/zip_error_code_system.html new file mode 100644 index 0000000..0d622e3 --- /dev/null +++ b/third_party/libzip/man/zip_error_code_system.html @@ -0,0 +1,99 @@ + + + + + + + ZIP_ERROR_CODE_SYSTEM(3) + + + + + + + + +
ZIP_ERROR_CODE_SYSTEM(3)Library Functions ManualZIP_ERROR_CODE_SYSTEM(3)
+
+
+

+zip_error_code_system — +
get operating system error part of zip_error
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_error_code_system(const + zip_error_t *ze);

+
+
+

+The zip_error_code_system() function returns the system + specific part of the error from the zip_error error ze. + For finding out what system reported the error, use + zip_error_system_type(3). +
+
+

+libzip(3), + zip_error_code_zip(3), + zip_error_system_type(3) +
+
+

+zip_error_code_system() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_code_system.man b/third_party/libzip/man/zip_error_code_system.man new file mode 100644 index 0000000..4eb0cad --- /dev/null +++ b/third_party/libzip/man/zip_error_code_system.man @@ -0,0 +1,68 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_code_system.mdoc -- get system error part of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_CODE_SYSTEM" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_code_system\fR +\- get operating system error part of zip_error +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_error_code_system\fR(\fIconst\ zip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_code_system\fR() +function returns the system specific part of the error from the +zip_error error +\fIze\fR. +For finding out what system reported the error, use +zip_error_system_type(3). +.SH "SEE ALSO" +libzip(3), +zip_error_code_zip(3), +zip_error_system_type(3) +.SH "HISTORY" +\fBzip_error_code_system\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_code_system.mdoc b/third_party/libzip/man/zip_error_code_system.mdoc new file mode 100644 index 0000000..c87a206 --- /dev/null +++ b/third_party/libzip/man/zip_error_code_system.mdoc @@ -0,0 +1,63 @@ +.\" zip_error_code_system.mdoc -- get system error part of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_CODE_SYSTEM 3 +.Os +.Sh NAME +.Nm zip_error_code_system +.Nd get operating system error part of zip_error +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_error_code_system "const zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_error_code_system +function returns the system specific part of the error from the +zip_error error +.Ar ze . +For finding out what system reported the error, use +.Xr zip_error_system_type 3 . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_zip 3 , +.Xr zip_error_system_type 3 +.Sh HISTORY +.Fn zip_error_code_system +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_code_zip.html b/third_party/libzip/man/zip_error_code_zip.html new file mode 100644 index 0000000..7f7f852 --- /dev/null +++ b/third_party/libzip/man/zip_error_code_zip.html @@ -0,0 +1,96 @@ + + + + + + + ZIP_ERROR_CODE_ZIP(3) + + + + + + + + +
ZIP_ERROR_CODE_ZIP(3)Library Functions ManualZIP_ERROR_CODE_ZIP(3)
+
+
+

+zip_error_code_zip — +
get libzip error part of zip_error
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_error_code_zip(const + zip_error_t *ze);

+
+
+

+The zip_error_code_zip() function returns the libzip + specific part of the error from the zip_error error ze. +
+
+

+libzip(3), + zip_error_code_system(3) +
+
+

+zip_error_code_zip() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_code_zip.man b/third_party/libzip/man/zip_error_code_zip.man new file mode 100644 index 0000000..2a53981 --- /dev/null +++ b/third_party/libzip/man/zip_error_code_zip.man @@ -0,0 +1,65 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_code_zip.mdoc -- get libzip error part of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_CODE_ZIP" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_code_zip\fR +\- get libzip error part of zip_error +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_error_code_zip\fR(\fIconst\ zip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_code_zip\fR() +function returns the libzip specific part of the error from the +zip_error error +\fIze\fR. +.SH "SEE ALSO" +libzip(3), +zip_error_code_system(3) +.SH "HISTORY" +\fBzip_error_code_zip\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_code_zip.mdoc b/third_party/libzip/man/zip_error_code_zip.mdoc new file mode 100644 index 0000000..c68fff4 --- /dev/null +++ b/third_party/libzip/man/zip_error_code_zip.mdoc @@ -0,0 +1,60 @@ +.\" zip_error_code_zip.mdoc -- get libzip error part of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_CODE_ZIP 3 +.Os +.Sh NAME +.Nm zip_error_code_zip +.Nd get libzip error part of zip_error +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_error_code_zip "const zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_error_code_zip +function returns the libzip specific part of the error from the +zip_error error +.Ar ze . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_system 3 +.Sh HISTORY +.Fn zip_error_code_zip +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_fini.html b/third_party/libzip/man/zip_error_fini.html new file mode 100644 index 0000000..c752141 --- /dev/null +++ b/third_party/libzip/man/zip_error_fini.html @@ -0,0 +1,97 @@ + + + + + + + ZIP_ERROR_FINI(3) + + + + + + + + +
ZIP_ERROR_FINI(3)Library Functions ManualZIP_ERROR_FINI(3)
+
+
+

+zip_error_fini — +
clean up zip_error structure
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_error_fini(zip_error_t + *ze);

+
+
+

+The zip_error_fini() function cleans up and frees + internally allocated memory of the zip_error pointed to by + ze. +
+
+

+libzip(3), + zip_error_init(3) +
+
+

+zip_error_fini() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_fini.man b/third_party/libzip/man/zip_error_fini.man new file mode 100644 index 0000000..2e4a1ae --- /dev/null +++ b/third_party/libzip/man/zip_error_fini.man @@ -0,0 +1,65 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_fini.mdoc -- clean up zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_FINI" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_fini\fR +\- clean up zip_error structure +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_fini\fR(\fIzip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_fini\fR() +function cleans up and frees internally allocated memory of the +zip_error pointed to by +\fIze\fR. +.SH "SEE ALSO" +libzip(3), +zip_error_init(3) +.SH "HISTORY" +\fBzip_error_fini\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_fini.mdoc b/third_party/libzip/man/zip_error_fini.mdoc new file mode 100644 index 0000000..136db4c --- /dev/null +++ b/third_party/libzip/man/zip_error_fini.mdoc @@ -0,0 +1,60 @@ +.\" zip_error_fini.mdoc -- clean up zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_FINI 3 +.Os +.Sh NAME +.Nm zip_error_fini +.Nd clean up zip_error structure +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_error_fini "zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_error_fini +function cleans up and frees internally allocated memory of the +zip_error pointed to by +.Ar ze . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_init 3 +.Sh HISTORY +.Fn zip_error_fini +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_get.html b/third_party/libzip/man/zip_error_get.html new file mode 100644 index 0000000..91f15ce --- /dev/null +++ b/third_party/libzip/man/zip_error_get.html @@ -0,0 +1,150 @@ + + + + + + + ZIP_ERROR_GET(3) + + + + + + + + +
ZIP_ERROR_GET(3)Library Functions ManualZIP_ERROR_GET(3)
+
+
+

+zip_error_get, + zip_file_error_get — +
get error codes for archive or file (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_error_get(zip_t + *archive, int *zep, + int *sep);

+

void +
+ zip_file_error_get(zip_file_t + *file, int *zep, + int *sep);

+
+
+

+The functions zip_error_get() and + zip_file_error_get() are deprecated. Use + zip_error_code_system(3), + zip_error_code_zip(3), + zip_file_get_error(3), and + zip_get_error(3) instead. +

For zip_error_get(), replace

+
+
+int ze, se;
+zip_error_get(za, &ze, &se);
+
+
+with +
+
+int ze, se;
+zip_error_t *error = zip_get_error(za);
+ze = zip_error_code_zip(error);
+se = zip_error_code_system(error);
+
+
+For zip_file_error_get(), replace +
+
+int ze, se;
+zip_file_error_get(zf, &ze, &se);
+
+
+with +
+
+int ze, se;
+zip_error_t *error = zip_file_get_error(zf);
+ze = zip_error_code_zip(error);
+se = zip_error_code_system(error);
+
+
+
+
+

+libzip(3), + zip_error_code_system(3), + zip_error_code_zip(3), + zip_file_get_error(3), + zip_get_error(3) +
+
+

+zip_error_get() was added in libzip 0.6. It was + deprecated in libzip 1.0, use zip_get_error(), + zip_error_code_zip(), / + zip_error_code_system() instead. +

zip_file_error_get() was added in libzip + 0.6. It was deprecated in libzip 1.0, use + zip_file_get_error(), + zip_error_code_zip(), / + zip_error_code_system() instead.

+
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_get.man b/third_party/libzip/man/zip_error_get.man new file mode 100644 index 0000000..43e2c06 --- /dev/null +++ b/third_party/libzip/man/zip_error_get.man @@ -0,0 +1,139 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_get.mdoc -- get error codes for archive or file +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_GET" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_get\fR, +\fBzip_file_error_get\fR +\- get error codes for archive or file (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_get\fR(\fIzip_t\ *archive\fR, \fIint\ *zep\fR, \fIint\ *sep\fR); +.PD +.PP +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_file_error_get\fR(\fIzip_file_t\ *file\fR, \fIint\ *zep\fR, \fIint\ *sep\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_error_get\fR() +and +\fBzip_file_error_get\fR() +are deprecated. +Use +zip_error_code_system(3), +zip_error_code_zip(3), +zip_file_get_error(3), +and +zip_get_error(3) +instead. +.PP +For +\fBzip_error_get\fR(), +replace +.nf +.sp +.RS 6n +int ze, se; +zip_error_get(za, &ze, &se); +.RE +.fi +with +.nf +.sp +.RS 6n +int ze, se; +zip_error_t *error = zip_get_error(za); +ze = zip_error_code_zip(error); +se = zip_error_code_system(error); +.RE +.fi +For +\fBzip_file_error_get\fR(), +replace +.nf +.sp +.RS 6n +int ze, se; +zip_file_error_get(zf, &ze, &se); +.RE +.fi +with +.nf +.sp +.RS 6n +int ze, se; +zip_error_t *error = zip_file_get_error(zf); +ze = zip_error_code_zip(error); +se = zip_error_code_system(error); +.RE +.fi +.SH "SEE ALSO" +libzip(3), +zip_error_code_system(3), +zip_error_code_zip(3), +zip_file_get_error(3), +zip_get_error(3) +.SH "HISTORY" +\fBzip_error_get\fR() +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +\fBzip_get_error\fR(), +\fBzip_error_code_zip\fR(), +/ +\fBzip_error_code_system\fR() +instead. +.PP +\fBzip_file_error_get\fR() +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +\fBzip_file_get_error\fR(), +\fBzip_error_code_zip\fR(), +/ +\fBzip_error_code_system\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_get.mdoc b/third_party/libzip/man/zip_error_get.mdoc new file mode 100644 index 0000000..5271394 --- /dev/null +++ b/third_party/libzip/man/zip_error_get.mdoc @@ -0,0 +1,117 @@ +.\" zip_error_get.mdoc -- get error codes for archive or file +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_GET 3 +.Os +.Sh NAME +.Nm zip_error_get , +.Nm zip_file_error_get +.Nd get error codes for archive or file (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_error_get "zip_t *archive" "int *zep" "int *sep" +.Ft void +.Fn zip_file_error_get "zip_file_t *file" "int *zep" "int *sep" +.Sh DESCRIPTION +The functions +.Fn zip_error_get +and +.Fn zip_file_error_get +are deprecated. +Use +.Xr zip_error_code_system 3 , +.Xr zip_error_code_zip 3 , +.Xr zip_file_get_error 3 , +and +.Xr zip_get_error 3 +instead. +.Pp +For +.Fn zip_error_get , +replace +.Bd -literal -offset indent +int ze, se; +zip_error_get(za, &ze, &se); +.Ed +with +.Bd -literal -offset indent +int ze, se; +zip_error_t *error = zip_get_error(za); +ze = zip_error_code_zip(error); +se = zip_error_code_system(error); +.Ed +For +.Fn zip_file_error_get , +replace +.Bd -literal -offset indent +int ze, se; +zip_file_error_get(zf, &ze, &se); +.Ed +with +.Bd -literal -offset indent +int ze, se; +zip_error_t *error = zip_file_get_error(zf); +ze = zip_error_code_zip(error); +se = zip_error_code_system(error); +.Ed +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_system 3 , +.Xr zip_error_code_zip 3 , +.Xr zip_file_get_error 3 , +.Xr zip_get_error 3 +.Sh HISTORY +.Fn zip_error_get +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +.Fn zip_get_error , +.Fn zip_error_code_zip , +/ +.Fn zip_error_code_system +instead. +.Pp +.Fn zip_file_error_get +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +.Fn zip_file_get_error , +.Fn zip_error_code_zip , +/ +.Fn zip_error_code_system +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_get_sys_type.html b/third_party/libzip/man/zip_error_get_sys_type.html new file mode 100644 index 0000000..e85152c --- /dev/null +++ b/third_party/libzip/man/zip_error_get_sys_type.html @@ -0,0 +1,116 @@ + + + + + + + ZIP_ERROR_GET_SYS_TYPE(3) + + + + + + + + +
ZIP_ERROR_GET_SYS_TYPE(3)Library Functions ManualZIP_ERROR_GET_SYS_TYPE(3)
+
+
+

+zip_error_get_sys_type — +
get type of system error code (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_error_get_sys_type(int + ze);

+
+
+

+The function zip_error_get_sys_type() is deprecated; use + zip_error_init_with_code(3) + and + zip_error_system_type(3) + instead. +

Replace

+
+
+int i = zip_error_get_sys_type(ze);
+
+
+with +
+
+zip_error_t error;
+zip_error_init_with_code(&error, ze);
+int i = zip_error_system_type(&error);
+
+
+
+
+

+libzip(3), + zip_error_init_with_code(3), + zip_error_system_type(3) +
+
+

+zip_error_get_sys_type() was added in libzip 0.6. It was + deprecated in libzip 1.0, use zip_error_system_type() + instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_get_sys_type.man b/third_party/libzip/man/zip_error_get_sys_type.man new file mode 100644 index 0000000..753a94c --- /dev/null +++ b/third_party/libzip/man/zip_error_get_sys_type.man @@ -0,0 +1,88 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_get_sys_type.mdoc -- get type of error +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_GET_SYS_TYPE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_get_sys_type\fR +\- get type of system error code (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_error_get_sys_type\fR(\fIint\ ze\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_error_get_sys_type\fR() +is deprecated; use +zip_error_init_with_code(3) +and +zip_error_system_type(3) +instead. +.PP +Replace +.nf +.sp +.RS 6n +int i = zip_error_get_sys_type(ze); +.RE +.fi +with +.nf +.sp +.RS 6n +zip_error_t error; +zip_error_init_with_code(&error, ze); +int i = zip_error_system_type(&error); +.RE +.fi +.SH "SEE ALSO" +libzip(3), +zip_error_init_with_code(3), +zip_error_system_type(3) +.SH "HISTORY" +\fBzip_error_get_sys_type\fR() +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +\fBzip_error_system_type\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_get_sys_type.mdoc b/third_party/libzip/man/zip_error_get_sys_type.mdoc new file mode 100644 index 0000000..16d3af7 --- /dev/null +++ b/third_party/libzip/man/zip_error_get_sys_type.mdoc @@ -0,0 +1,77 @@ +.\" zip_error_get_sys_type.mdoc -- get type of error +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_GET_SYS_TYPE 3 +.Os +.Sh NAME +.Nm zip_error_get_sys_type +.Nd get type of system error code (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_error_get_sys_type "int ze" +.Sh DESCRIPTION +The function +.Fn zip_error_get_sys_type +is deprecated; use +.Xr zip_error_init_with_code 3 +and +.Xr zip_error_system_type 3 +instead. +.Pp +Replace +.Bd -literal -offset indent +int i = zip_error_get_sys_type(ze); +.Ed +with +.Bd -literal -offset indent +zip_error_t error; +zip_error_init_with_code(&error, ze); +int i = zip_error_system_type(&error); +.Ed +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_init_with_code 3 , +.Xr zip_error_system_type 3 +.Sh HISTORY +.Fn zip_error_get_sys_type +was added in libzip 0.6. +It was deprecated in libzip 1.0, use +.Fn zip_error_system_type +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_init.html b/third_party/libzip/man/zip_error_init.html new file mode 100644 index 0000000..24b671e --- /dev/null +++ b/third_party/libzip/man/zip_error_init.html @@ -0,0 +1,108 @@ + + + + + + + ZIP_ERROR_INIT(3) + + + + + + + + +
ZIP_ERROR_INIT(3)Library Functions ManualZIP_ERROR_INIT(3)
+
+
+

+zip_error_init, + zip_error_init_with_code — +
initialize zip_error structure
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_error_init(zip_error_t + *error);

+

void +
+ zip_error_init_with_code(zip_error_t + *error, int + ze);

+
+
+

+The zip_error_init() function initializes the zip_error + pointed to by error. *error must + be allocated before calling zip_error_init(). +

The zip_error_init_with_code() function + does the same, but additionally sets the zip error code to + ze and sets the system error code to the current + errno(3) value, if appropriate.

+
+
+

+libzip(3), + zip_error_fini(3) +
+
+

+zip_error_init() and + zip_error_init_with_code() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_init.man b/third_party/libzip/man/zip_error_init.man new file mode 100644 index 0000000..7623e98 --- /dev/null +++ b/third_party/libzip/man/zip_error_init.man @@ -0,0 +1,85 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_init.mdoc -- initialize zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_INIT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_init\fR, +\fBzip_error_init_with_code\fR +\- initialize zip_error structure +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_init\fR(\fIzip_error_t\ *error\fR); +.PD +.PP +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_init_with_code\fR(\fIzip_error_t\ *error\fR, \fIint\ ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_init\fR() +function initializes the zip_error pointed to by +\fIerror\fR. +\fI*error\fR +must be allocated before calling +\fBzip_error_init\fR(). +.PP +The +\fBzip_error_init_with_code\fR() +function does the same, but additionally sets the zip error code to +\fIze\fR +and sets the system error code to the current +errno(3) +value, if appropriate. +.SH "SEE ALSO" +libzip(3), +zip_error_fini(3) +.SH "HISTORY" +\fBzip_error_init\fR() +and +\fBzip_error_init_with_code\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_init.mdoc b/third_party/libzip/man/zip_error_init.mdoc new file mode 100644 index 0000000..b524303 --- /dev/null +++ b/third_party/libzip/man/zip_error_init.mdoc @@ -0,0 +1,76 @@ +.\" zip_error_init.mdoc -- initialize zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_INIT 3 +.Os +.Sh NAME +.Nm zip_error_init , +.Nm zip_error_init_with_code +.Nd initialize zip_error structure +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_error_init "zip_error_t *error" +.Ft void +.Fn zip_error_init_with_code "zip_error_t *error" "int ze" +.Sh DESCRIPTION +The +.Fn zip_error_init +function initializes the zip_error pointed to by +.Ar error . +.Ar *error +must be allocated before calling +.Fn zip_error_init . +.Pp +The +.Fn zip_error_init_with_code +function does the same, but additionally sets the zip error code to +.Ar ze +and sets the system error code to the current +.Xr errno 3 +value, if appropriate. +.\" TODO: describe when you would need to call this at all +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_fini 3 +.Sh HISTORY +.Fn zip_error_init +and +.Fn zip_error_init_with_code +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_set.html b/third_party/libzip/man/zip_error_set.html new file mode 100644 index 0000000..eba09b6 --- /dev/null +++ b/third_party/libzip/man/zip_error_set.html @@ -0,0 +1,101 @@ + + + + + + + ZIP_ERROR_SET(3) + + + + + + + + +
ZIP_ERROR_SET(3)Library Functions ManualZIP_ERROR_SET(3)
+
+
+

+zip_error_set — +
fill in zip_error structure
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_error_set(zip_error_t + *ze, int le, + int se);

+
+
+

+The zip_error_set() function sets the zip_error pointed + to by ze to the libzip error code + le and the system error code se. +

ze must be allocated and initialized with + zip_error_fini(3) before + calling zip_error(set).

+
+
+

+libzip(3), + zip_error_init(3) +
+
+

+zip_error_set() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_set.man b/third_party/libzip/man/zip_error_set.man new file mode 100644 index 0000000..250b97f --- /dev/null +++ b/third_party/libzip/man/zip_error_set.man @@ -0,0 +1,74 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_set.mdoc -- set zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_SET" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_set\fR +\- fill in zip_error structure +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_error_set\fR(\fIzip_error_t\ *ze\fR, \fIint\ le\fR, \fIint\ se\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_set\fR() +function sets the zip_error pointed to by +\fIze\fR +to the libzip error code +\fIle\fR +and the system error code +\fIse\fR. +.PP +\fIze\fR +must be allocated and initialized with +zip_error_fini(3) +before calling +\fBzip_error\fR(\fIset\fR). +.SH "SEE ALSO" +libzip(3), +zip_error_init(3) +.SH "HISTORY" +\fBzip_error_set\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_set.mdoc b/third_party/libzip/man/zip_error_set.mdoc new file mode 100644 index 0000000..f7cc446 --- /dev/null +++ b/third_party/libzip/man/zip_error_set.mdoc @@ -0,0 +1,69 @@ +.\" zip_error_set.mdoc -- set zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_SET 3 +.Os +.Sh NAME +.Nm zip_error_set +.Nd fill in zip_error structure +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_error_set "zip_error_t *ze" "int le" "int se" +.Sh DESCRIPTION +The +.Fn zip_error_set +function sets the zip_error pointed to by +.Ar ze +to the libzip error code +.Ar le +and the system error code +.Ar se . +.Pp +.Ar ze +must be allocated and initialized with +.Xr zip_error_fini 3 +before calling +.Fn zip_error set . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_init 3 +.Sh HISTORY +.Fn zip_error_set +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_strerror.html b/third_party/libzip/man/zip_error_strerror.html new file mode 100644 index 0000000..cba19f8 --- /dev/null +++ b/third_party/libzip/man/zip_error_strerror.html @@ -0,0 +1,101 @@ + + + + + + + ZIP_ERROR_STRERROR(3) + + + + + + + + +
ZIP_ERROR_STRERROR(3)Library Functions ManualZIP_ERROR_STRERROR(3)
+
+
+

+zip_error_strerror — +
create human-readable string for zip_error
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_error_strerror(zip_error_t + *ze);

+
+
+

+The zip_error_strerror() function returns an error + message string corresponding to ze like + strerror(3). This string will stay + valid until the next call to zip_error_strerror() or + until zip_error_fini(3) is + called. +
+
+

+libzip(3), + strerror(3), + zip_error_fini(3) +
+
+

+zip_error_strerror() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_strerror.man b/third_party/libzip/man/zip_error_strerror.man new file mode 100644 index 0000000..f1396ce --- /dev/null +++ b/third_party/libzip/man/zip_error_strerror.man @@ -0,0 +1,72 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_strerror.mdoc -- create human-readable version of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_STRERROR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_strerror\fR +\- create human-readable string for zip_error +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_error_strerror\fR(\fIzip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_strerror\fR() +function returns an error message string corresponding to +\fIze\fR +like +strerror(3). +This string will stay valid until the next call to +\fBzip_error_strerror\fR() +or until +zip_error_fini(3) +is called. +.SH "SEE ALSO" +libzip(3), +strerror(3), +zip_error_fini(3) +.SH "HISTORY" +\fBzip_error_strerror\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_strerror.mdoc b/third_party/libzip/man/zip_error_strerror.mdoc new file mode 100644 index 0000000..8d44c99 --- /dev/null +++ b/third_party/libzip/man/zip_error_strerror.mdoc @@ -0,0 +1,67 @@ +.\" zip_error_strerror.mdoc -- create human-readable version of zip_error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_STRERROR 3 +.Os +.Sh NAME +.Nm zip_error_strerror +.Nd create human-readable string for zip_error +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_error_strerror "zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_error_strerror +function returns an error message string corresponding to +.Ar ze +like +.Xr strerror 3 . +This string will stay valid until the next call to +.Fn zip_error_strerror +or until +.Xr zip_error_fini 3 +is called. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr strerror 3 , +.Xr zip_error_fini 3 +.Sh HISTORY +.Fn zip_error_strerror +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_system_type.html b/third_party/libzip/man/zip_error_system_type.html new file mode 100644 index 0000000..0a6308e --- /dev/null +++ b/third_party/libzip/man/zip_error_system_type.html @@ -0,0 +1,107 @@ + + + + + + + ZIP_ERROR_SYSTEM_TYPE(3) + + + + + + + + +
ZIP_ERROR_SYSTEM_TYPE(3)Library Functions ManualZIP_ERROR_SYSTEM_TYPE(3)
+
+
+

+zip_error_system_type — +
return type of system error
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_error_system_type(const + zip_error_t *ze);

+
+
+

+The zip_error_system_type() function returns the type of + the system specific part for the zip_error ze. + Currently, the following system types are defined: +
+
+
System specific part of ze is unused.
+
+
System specific part of ze is an + errno(2).
+
+
System specific part of ze is a + zlib(3) error.
+
+
+
+

+libzip(3), + zip_error_code_system(3) +
+
+

+zip_error_system_type() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_system_type.man b/third_party/libzip/man/zip_error_system_type.man new file mode 100644 index 0000000..0d55f4a --- /dev/null +++ b/third_party/libzip/man/zip_error_system_type.man @@ -0,0 +1,83 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_system_type.mdoc -- return system type for error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_SYSTEM_TYPE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_system_type\fR +\- return type of system error +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_error_system_type\fR(\fIconst\ zip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_error_system_type\fR() +function returns the type of the system specific part for the zip_error +\fIze\fR. +Currently, the following system types are defined: +.TP 13n +\fRZIP_ET_NONE\fR +System specific part of +\fIze\fR +is unused. +.TP 13n +\fRZIP_ET_SYS\fR +System specific part of +\fIze\fR +is an +errno(2). +.TP 13n +\fRZIP_ET_ZLIB\fR +System specific part of +\fIze\fR +is a +zlib(3) +error. +.SH "SEE ALSO" +libzip(3), +zip_error_code_system(3) +.SH "HISTORY" +\fBzip_error_system_type\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_system_type.mdoc b/third_party/libzip/man/zip_error_system_type.mdoc new file mode 100644 index 0000000..f9fbfce --- /dev/null +++ b/third_party/libzip/man/zip_error_system_type.mdoc @@ -0,0 +1,77 @@ +.\" zip_error_system_type.mdoc -- return system type for error +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_SYSTEM_TYPE 3 +.Os +.Sh NAME +.Nm zip_error_system_type +.Nd return type of system error +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_error_system_type "const zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_error_system_type +function returns the type of the system specific part for the zip_error +.Ar ze . +Currently, the following system types are defined: +.Bl -tag -width ZIP_ET_NONE +.It Dv ZIP_ET_NONE +System specific part of +.Ar ze +is unused. +.It Dv ZIP_ET_SYS +System specific part of +.Ar ze +is an +.Xr errno 2 . +.It Dv ZIP_ET_ZLIB +System specific part of +.Ar ze +is a +.Xr zlib 3 +error. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_system 3 +.Sh HISTORY +.Fn zip_error_system_type +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_to_data.html b/third_party/libzip/man/zip_error_to_data.html new file mode 100644 index 0000000..9f3ab16 --- /dev/null +++ b/third_party/libzip/man/zip_error_to_data.html @@ -0,0 +1,108 @@ + + + + + + + ZIP_ERROR_TO_DATA(3) + + + + + + + + +
ZIP_ERROR_TO_DATA(3)Library Functions ManualZIP_ERROR_TO_DATA(3)
+
+
+

+zip_error_to_data — +
convert zip_error to return value suitable for + ZIP_SOURCE_ERROR
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_error_to_data(const + zip_error_t *ze, void + *data, zip_uint64_t + len);

+
+
+

+zip_error_to_data() function converts the zip_error + ze into data suitable as return value for + ZIP_SOURCE_ERROR. The data is written into the buffer + data of size len. If the buffer is + not large enough to hold 2 ints, an error is returned. +
+
+

+zip_error_to_data() returns 2*(sizeof int) on success, + and -1 on error. +
+
+

+libzip(3), + zip_source_function(3) +
+
+

+zip_error_to_data() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_to_data.man b/third_party/libzip/man/zip_error_to_data.man new file mode 100644 index 0000000..f655129 --- /dev/null +++ b/third_party/libzip/man/zip_error_to_data.man @@ -0,0 +1,74 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_to_data.mdoc -- create error data for ZIP_SOURCE_ERROR +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_TO_DATA" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_to_data\fR +\- convert zip_error to return value suitable for ZIP_SOURCE_ERROR +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_error_to_data\fR(\fIconst\ zip_error_t\ *ze\fR, \fIvoid\ *data\fR, \fIzip_uint64_t\ len\fR); +.PD +.SH "DESCRIPTION" +\fBzip_error_to_data\fR() +function converts the zip_error +\fIze\fR +into data suitable as return value for +\fRZIP_SOURCE_ERROR\fR. +The data is written into the buffer +\fIdata\fR +of size +\fIlen\fR. +If the buffer is not large enough to hold 2 ints, an error is +returned. +.SH "RETURN VALUES" +\fBzip_error_to_data\fR() +returns 2*(sizeof int) on success, and \-1 on error. +.SH "SEE ALSO" +libzip(3), +zip_source_function(3) +.SH "HISTORY" +\fBzip_error_to_data\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_to_data.mdoc b/third_party/libzip/man/zip_error_to_data.mdoc new file mode 100644 index 0000000..e7ba170 --- /dev/null +++ b/third_party/libzip/man/zip_error_to_data.mdoc @@ -0,0 +1,69 @@ +.\" zip_error_to_data.mdoc -- create error data for ZIP_SOURCE_ERROR +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_TO_DATA 3 +.Os +.Sh NAME +.Nm zip_error_to_data +.Nd convert zip_error to return value suitable for ZIP_SOURCE_ERROR +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_error_to_data "const zip_error_t *ze" "void *data" "zip_uint64_t len" +.Sh DESCRIPTION +.Fn zip_error_to_data +function converts the zip_error +.Ar ze +into data suitable as return value for +.Dv ZIP_SOURCE_ERROR . +The data is written into the buffer +.Ar data +of size +.Ar len . +If the buffer is not large enough to hold 2 ints, an error is +returned. +.Sh RETURN VALUES +.Fn zip_error_to_data +returns 2*(sizeof int) on success, and \-1 on error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source_function 3 +.Sh HISTORY +.Fn zip_error_to_data +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_error_to_str.html b/third_party/libzip/man/zip_error_to_str.html new file mode 100644 index 0000000..1319139 --- /dev/null +++ b/third_party/libzip/man/zip_error_to_str.html @@ -0,0 +1,124 @@ + + + + + + + ZIP_ERROR_TO_STR(3) + + + + + + + + +
ZIP_ERROR_TO_STR(3)Library Functions ManualZIP_ERROR_TO_STR(3)
+
+
+

+zip_error_to_str — +
get string representation of zip error (obsolete + interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_error_to_str(char + *buf, zip_uint64_t + len, int ze, + int se);

+
+
+

+The function zip_error_to_str() is deprecated; use + zip_error_init_with_code(3) + and zip_error_strerror(3) + instead. +

Replace

+
+
+char buf[BUFSIZE];
+zip_error_to_str(buf, sizeof(buf), ze, se);
+printf("%s", buf);
+
+
+with +
+
+zip_error_t error;
+zip_error_init_with_code(&error, ze);
+printf("%s", zip_error_strerror(&error));
+zip_error_fini(&error);
+
+
+
+
+

+libzip(3), + zip_error_init_with_code(3), + zip_error_strerror(3) +
+
+

+zip_error_to_str() was added in libzip 0.6. In libzip + 0.10 the type of len was changed from + size_t to zip_uint64_t. It was + deprecated in libzip 1.0, use + zip_error_init_with_code() and + zip_error_strerror() instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_error_to_str.man b/third_party/libzip/man/zip_error_to_str.man new file mode 100644 index 0000000..0db434a --- /dev/null +++ b/third_party/libzip/man/zip_error_to_str.man @@ -0,0 +1,99 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_error_to_str.mdoc -- get string representation of zip error code +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_ERROR_TO_STR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_error_to_str\fR +\- get string representation of zip error (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_error_to_str\fR(\fIchar\ *buf\fR, \fIzip_uint64_t\ len\fR, \fIint\ ze\fR, \fIint\ se\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_error_to_str\fR() +is deprecated; use +zip_error_init_with_code(3) +and +zip_error_strerror(3) +instead. +.PP +Replace +.nf +.sp +.RS 6n +char buf[BUFSIZE]; +zip_error_to_str(buf, sizeof(buf), ze, se); +printf("%s", buf); +.RE +.fi +with +.nf +.sp +.RS 6n +zip_error_t error; +zip_error_init_with_code(&error, ze); +printf("%s", zip_error_strerror(&error)); +zip_error_fini(&error); +.RE +.fi +.SH "SEE ALSO" +libzip(3), +zip_error_init_with_code(3), +zip_error_strerror(3) +.SH "HISTORY" +\fBzip_error_to_str\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIlen\fR +was changed from +\fIsize_t\fR +to +\fIzip_uint64_t\fR. +It was deprecated in libzip 1.0, use +\fBzip_error_init_with_code\fR() +and +\fBzip_error_strerror\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_error_to_str.mdoc b/third_party/libzip/man/zip_error_to_str.mdoc new file mode 100644 index 0000000..7054d3e --- /dev/null +++ b/third_party/libzip/man/zip_error_to_str.mdoc @@ -0,0 +1,88 @@ +.\" zip_error_to_str.mdoc -- get string representation of zip error code +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERROR_TO_STR 3 +.Os +.Sh NAME +.Nm zip_error_to_str +.Nd get string representation of zip error (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_error_to_str "char *buf" "zip_uint64_t len" "int ze" "int se" +.Sh DESCRIPTION +The function +.Fn zip_error_to_str +is deprecated; use +.Xr zip_error_init_with_code 3 +and +.Xr zip_error_strerror 3 +instead. +.Pp +Replace +.Bd -literal -offset indent +char buf[BUFSIZE]; +zip_error_to_str(buf, sizeof(buf), ze, se); +printf("%s", buf); +.Ed +with +.Bd -literal -offset indent +zip_error_t error; +zip_error_init_with_code(&error, ze); +printf("%s", zip_error_strerror(&error)); +zip_error_fini(&error); +.Ed +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_init_with_code 3 , +.Xr zip_error_strerror 3 +.Sh HISTORY +.Fn zip_error_to_str +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar len +was changed from +.Vt size_t +to +.Vt zip_uint64_t . +It was deprecated in libzip 1.0, use +.Fn zip_error_init_with_code +and +.Fn zip_error_strerror +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_errors.html b/third_party/libzip/man/zip_errors.html new file mode 100644 index 0000000..f9eef5f --- /dev/null +++ b/third_party/libzip/man/zip_errors.html @@ -0,0 +1,150 @@ + + + + + + + ZIP_ERRORS(3) + + + + + + + + +
ZIP_ERRORS(3)Library Functions ManualZIP_ERRORS(3)
+
+
+

+zip_errors — +
list of all libzip error codes
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +
+
+

+The following error codes are used by libzip: +
+
[ZIP_ER_CHANGED]
+
Entry has been changed.
+
[ZIP_ER_CLOSE]
+
Closing zip archive failed.
+
[ZIP_ER_COMPNOTSUPP]
+
Compression method not supported.
+
[ZIP_ER_COMPRESSED_DATA]
+
Compressed data invalid.
+
[ZIP_ER_CRC]
+
CRC error.
+
[ZIP_ER_DELETED]
+
Entry has been deleted.
+
[ZIP_ER_ENCRNOTSUPP]
+
Encryption method not supported.
+
[ZIP_ER_EOF]
+
Premature end of file.
+
[ZIP_ER_EXISTS]
+
File already exists.
+
[ZIP_ER_INCONS]
+
Zip archive inconsistent.
+
[ZIP_ER_INTERNAL]
+
Internal error.
+
[ZIP_ER_INUSE]
+
Resource still in use.
+
[ZIP_ER_INVAL]
+
Invalid argument.
+
[ZIP_ER_MEMORY]
+
Malloc failure.
+
[ZIP_ER_MULTIDISK]
+
Multi-disk zip archives not supported.
+
[ZIP_ER_NOENT]
+
No such file.
+
[ZIP_ER_NOPASSWD]
+
No password provided.
+
[ZIP_ER_NOZIP]
+
Not a zip archive.
+
[ZIP_ER_OK]
+
No error.
+
[ZIP_ER_OPEN]
+
Can't open file.
+
[ZIP_ER_OPNOTSUPP]
+
Operation not supported.
+
[ZIP_ER_RDONLY]
+
Read-only archive.
+
[ZIP_ER_READ]
+
Read error.
+
[ZIP_ER_REMOVE]
+
Can't remove file.
+
[ZIP_ER_RENAME]
+
Renaming temporary file failed.
+
[ZIP_ER_SEEK]
+
Seek error.
+
[ZIP_ER_TELL]
+
Tell error.
+
[ZIP_ER_TMPOPEN]
+
Failure to create temporary file.
+
[ZIP_ER_WRITE]
+
Write error.
+
[ZIP_ER_WRONGPASSWD]
+
Wrong password provided.
+
[ZIP_ER_ZIPCLOSED]
+
Containing zip archive was closed.
+
[ZIP_ER_ZLIB]
+
Zlib error.
+
+
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_errors.man b/third_party/libzip/man/zip_errors.man new file mode 100644 index 0000000..63c3947 --- /dev/null +++ b/third_party/libzip/man/zip_errors.man @@ -0,0 +1,147 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_errors.mdoc -- list of all libzip error codes +.\" Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS BE LIABLE FOR ANY +.\" DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +.\" GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +.\" IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +.\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +.\" +.\" This file was generated automatically by ./make_zip_errors.sh +.\" from ./../lib/zip.h; make changes there. +.\" +.TH "ZIP_ERRORS" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_errors\fR +\- list of all libzip error codes +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.SH "DESCRIPTION" +The following error codes are used by libzip: +.TP 26n +[\fRZIP_ER_CHANGED\fR] +Entry has been changed. +.TP 26n +[\fRZIP_ER_CLOSE\fR] +Closing zip archive failed. +.TP 26n +[\fRZIP_ER_COMPNOTSUPP\fR] +Compression method not supported. +.TP 26n +[\fRZIP_ER_COMPRESSED_DATA\fR] +Compressed data invalid. +.TP 26n +[\fRZIP_ER_CRC\fR] +CRC error. +.TP 26n +[\fRZIP_ER_DELETED\fR] +Entry has been deleted. +.TP 26n +[\fRZIP_ER_ENCRNOTSUPP\fR] +Encryption method not supported. +.TP 26n +[\fRZIP_ER_EOF\fR] +Premature end of file. +.TP 26n +[\fRZIP_ER_EXISTS\fR] +File already exists. +.TP 26n +[\fRZIP_ER_INCONS\fR] +Zip archive inconsistent. +.TP 26n +[\fRZIP_ER_INTERNAL\fR] +Internal error. +.TP 26n +[\fRZIP_ER_INUSE\fR] +Resource still in use. +.TP 26n +[\fRZIP_ER_INVAL\fR] +Invalid argument. +.TP 26n +[\fRZIP_ER_MEMORY\fR] +Malloc failure. +.TP 26n +[\fRZIP_ER_MULTIDISK\fR] +Multi-disk zip archives not supported. +.TP 26n +[\fRZIP_ER_NOENT\fR] +No such file. +.TP 26n +[\fRZIP_ER_NOPASSWD\fR] +No password provided. +.TP 26n +[\fRZIP_ER_NOZIP\fR] +Not a zip archive. +.TP 26n +[\fRZIP_ER_OK\fR] +No error. +.TP 26n +[\fRZIP_ER_OPEN\fR] +Can't open file. +.TP 26n +[\fRZIP_ER_OPNOTSUPP\fR] +Operation not supported. +.TP 26n +[\fRZIP_ER_RDONLY\fR] +Read-only archive. +.TP 26n +[\fRZIP_ER_READ\fR] +Read error. +.TP 26n +[\fRZIP_ER_REMOVE\fR] +Can't remove file. +.TP 26n +[\fRZIP_ER_RENAME\fR] +Renaming temporary file failed. +.TP 26n +[\fRZIP_ER_SEEK\fR] +Seek error. +.TP 26n +[\fRZIP_ER_TELL\fR] +Tell error. +.TP 26n +[\fRZIP_ER_TMPOPEN\fR] +Failure to create temporary file. +.TP 26n +[\fRZIP_ER_WRITE\fR] +Write error. +.TP 26n +[\fRZIP_ER_WRONGPASSWD\fR] +Wrong password provided. +.TP 26n +[\fRZIP_ER_ZIPCLOSED\fR] +Containing zip archive was closed. +.TP 26n +[\fRZIP_ER_ZLIB\fR] +Zlib error. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_errors.mdoc b/third_party/libzip/man/zip_errors.mdoc new file mode 100644 index 0000000..9f6357f --- /dev/null +++ b/third_party/libzip/man/zip_errors.mdoc @@ -0,0 +1,117 @@ +.\" zip_errors.mdoc -- list of all libzip error codes +.\" Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS BE LIABLE FOR ANY +.\" DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +.\" GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +.\" IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +.\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +.\" +.\" This file was generated automatically by ./make_zip_errors.sh +.\" from ./../lib/zip.h; make changes there. +.\" +.Dd December 18, 2017 +.Dt ZIP_ERRORS 3 +.Os +.Sh NAME +.Nm zip_errors +.Nd list of all libzip error codes +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Sh DESCRIPTION +The following error codes are used by libzip: +.Bl -tag -width XZIP_ER_COMPRESSED_DATAX +.It Bq Er ZIP_ER_CHANGED +Entry has been changed. +.It Bq Er ZIP_ER_CLOSE +Closing zip archive failed. +.It Bq Er ZIP_ER_COMPNOTSUPP +Compression method not supported. +.It Bq Er ZIP_ER_COMPRESSED_DATA +Compressed data invalid. +.It Bq Er ZIP_ER_CRC +CRC error. +.It Bq Er ZIP_ER_DELETED +Entry has been deleted. +.It Bq Er ZIP_ER_ENCRNOTSUPP +Encryption method not supported. +.It Bq Er ZIP_ER_EOF +Premature end of file. +.It Bq Er ZIP_ER_EXISTS +File already exists. +.It Bq Er ZIP_ER_INCONS +Zip archive inconsistent. +.It Bq Er ZIP_ER_INTERNAL +Internal error. +.It Bq Er ZIP_ER_INUSE +Resource still in use. +.It Bq Er ZIP_ER_INVAL +Invalid argument. +.It Bq Er ZIP_ER_MEMORY +Malloc failure. +.It Bq Er ZIP_ER_MULTIDISK +Multi-disk zip archives not supported. +.It Bq Er ZIP_ER_NOENT +No such file. +.It Bq Er ZIP_ER_NOPASSWD +No password provided. +.It Bq Er ZIP_ER_NOZIP +Not a zip archive. +.It Bq Er ZIP_ER_OK +No error. +.It Bq Er ZIP_ER_OPEN +Can't open file. +.It Bq Er ZIP_ER_OPNOTSUPP +Operation not supported. +.It Bq Er ZIP_ER_RDONLY +Read-only archive. +.It Bq Er ZIP_ER_READ +Read error. +.It Bq Er ZIP_ER_REMOVE +Can't remove file. +.It Bq Er ZIP_ER_RENAME +Renaming temporary file failed. +.It Bq Er ZIP_ER_SEEK +Seek error. +.It Bq Er ZIP_ER_TELL +Tell error. +.It Bq Er ZIP_ER_TMPOPEN +Failure to create temporary file. +.It Bq Er ZIP_ER_WRITE +Write error. +.It Bq Er ZIP_ER_WRONGPASSWD +Wrong password provided. +.It Bq Er ZIP_ER_ZIPCLOSED +Containing zip archive was closed. +.It Bq Er ZIP_ER_ZLIB +Zlib error. +.El +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fclose.html b/third_party/libzip/man/zip_fclose.html new file mode 100644 index 0000000..c19b2ca --- /dev/null +++ b/third_party/libzip/man/zip_fclose.html @@ -0,0 +1,103 @@ + + + + + + + ZIP_FCLOSE(3) + + + + + + + + +
ZIP_FCLOSE(3)Library Functions ManualZIP_FCLOSE(3)
+
+
+

+zip_fclose — +
close file in zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_fclose(zip_file_t + *file);

+
+
+

+The zip_fclose() function closes + file and frees the memory allocated for it. +
+
+

+Upon successful completion 0 is returned. Otherwise, the error code is returned. +
+
+

+libzip(3), + zip_fopen(3), + zip_fread(3), + zip_fseek(3) +
+
+

+zip_fclose() was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fclose.man b/third_party/libzip/man/zip_fclose.man new file mode 100644 index 0000000..977a7b7 --- /dev/null +++ b/third_party/libzip/man/zip_fclose.man @@ -0,0 +1,70 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fclose.mdoc -- close file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FCLOSE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fclose\fR +\- close file in zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_fclose\fR(\fIzip_file_t\ *file\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_fclose\fR() +function closes +\fIfile\fR +and frees the memory allocated for it. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, the error code is returned. +.SH "SEE ALSO" +libzip(3), +zip_fopen(3), +zip_fread(3), +zip_fseek(3) +.SH "HISTORY" +\fBzip_fclose\fR() +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fclose.mdoc b/third_party/libzip/man/zip_fclose.mdoc new file mode 100644 index 0000000..0bbeee7 --- /dev/null +++ b/third_party/libzip/man/zip_fclose.mdoc @@ -0,0 +1,65 @@ +.\" zip_fclose.mdoc -- close file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FCLOSE 3 +.Os +.Sh NAME +.Nm zip_fclose +.Nd close file in zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_fclose "zip_file_t *file" +.Sh DESCRIPTION +The +.Fn zip_fclose +function closes +.Ar file +and frees the memory allocated for it. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, the error code is returned. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fopen 3 , +.Xr zip_fread 3 , +.Xr zip_fseek 3 +.Sh HISTORY +.Fn zip_fclose +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fdopen.html b/third_party/libzip/man/zip_fdopen.html new file mode 100644 index 0000000..d34f1e6 --- /dev/null +++ b/third_party/libzip/man/zip_fdopen.html @@ -0,0 +1,154 @@ + + + + + + + ZIP_FDOPEN(3) + + + + + + + + +
ZIP_FDOPEN(3)Library Functions ManualZIP_FDOPEN(3)
+
+
+

+zip_fdopen — +
open zip archive using open file descriptor
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_t * +
+ zip_fdopen(int + fd, int flags, + int *errorp);

+
+
+

+The zip archive specified by the open file descriptor fd + is opened and a pointer to a struct zip, used to + manipulate the archive, is returned. In contrast to + zip_open(3), using + zip_fdopen the archive can only be opened in read-only + mode. The fd argument may not be used any longer after + calling zip_fdopen. The flags + are specified by or'ing the + following values, or 0 for none of them. +
+
+
+
Perform additional stricter consistency checks on the archive, and error + if they fail.
+
+
+

If an error occurs and errorp is + non-NULL, it will be set to + the corresponding error code.

+
+
+

+Upon successful completion zip_fdopen() returns a + struct zip pointer, and fd should + not be used any longer, nor passed to + close(2). Otherwise, + NULL is returned and *errorp is + set to indicate the error. In the error case, fd remains + unchanged. +
+
+

+The file specified by fd is prepared for use by + libzip(3) unless: +
+
[]
+
Inconsistencies were found in the file specified by + path. This error is often caused by specifying + ZIP_CHECKCONS but can also happen without it.
+
[]
+
The flags argument is invalid. Not all + zip_open(3) flags are allowed for + zip_fdopen, see + DESCRIPTION.
+
[]
+
Required memory could not be allocated.
+
[]
+
The file specified by fd is not a zip archive.
+
[]
+
The file specified by fd could not be prepared for + use by libzip(3).
+
[]
+
A read error occurred; see errno for details.
+
[]
+
The file specified by fd does not allow seeks.
+
+
+
+

+libzip(3), + zip_close(3), + zip_error_strerror(3), + zip_open(3) +
+
+

+zip_fdopen() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fdopen.man b/third_party/libzip/man/zip_fdopen.man new file mode 100644 index 0000000..e07f926 --- /dev/null +++ b/third_party/libzip/man/zip_fdopen.man @@ -0,0 +1,158 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fdopen.mdoc -- open zip archive using existing file descriptor +.\" Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FDOPEN" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fdopen\fR +\- open zip archive using open file descriptor +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_fdopen\fR(\fIint\ fd\fR, \fIint\ flags\fR, \fIint\ *errorp\fR); +.PD +.SH "DESCRIPTION" +The zip archive specified by the open file descriptor +\fIfd\fR +is opened and a pointer to a +\fIstruct zip\fR, +used to manipulate the archive, is returned. +In contrast to +zip_open(3), +using +\fBzip_fdopen\fR +the archive can only be opened in read-only mode. +The +\fIfd\fR +argument may not be used any longer after calling +\fBzip_fdopen\fR. +The +\fIflags\fR +are specified by +\fIor\fR'ing +the following values, or 0 for none of them. +.RS 6n +.TP 15n +\fRZIP_CHECKCONS\fR +Perform additional stricter consistency checks on the archive, and +error if they fail. +.RE +.PP +If an error occurs and +\fIerrorp\fR +is +non-\fRNULL\fR, +it will be set to the corresponding error code. +.SH "RETURN VALUES" +Upon successful completion +\fBzip_fdopen\fR() +returns a +\fIstruct zip\fR +pointer, and +\fIfd\fR +should not be used any longer, nor passed to +close(2). +Otherwise, +\fRNULL\fR +is returned and +\fI*errorp\fR +is set to indicate the error. +In the error case, +\fIfd\fR +remains unchanged. +.SH "ERRORS" +The file specified by +\fIfd\fR +is prepared for use by +libzip(3) +unless: +.TP 19n +[\fRZIP_ER_INCONS\fR] +Inconsistencies were found in the file specified by +\fIpath\fR. +This error is often caused by specifying +\fRZIP_CHECKCONS\fR +but can also happen without it. +.TP 19n +[\fRZIP_ER_INVAL\fR] +The +\fIflags\fR +argument is invalid. +Not all +zip_open(3) +flags are allowed for +\fBzip_fdopen\fR, +see +\fIDESCRIPTION\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOZIP\fR] +The file specified by +\fIfd\fR +is not a zip archive. +.TP 19n +[\fRZIP_ER_OPEN\fR] +The file specified by +\fIfd\fR +could not be prepared for use by +libzip(3). +.TP 19n +[\fRZIP_ER_READ\fR] +A read error occurred; see +\fIerrno\fR +for details. +.TP 19n +[\fRZIP_ER_SEEK\fR] +The file specified by +\fIfd\fR +does not allow seeks. +.SH "SEE ALSO" +libzip(3), +zip_close(3), +zip_error_strerror(3), +zip_open(3) +.SH "HISTORY" +\fBzip_fdopen\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fdopen.mdoc b/third_party/libzip/man/zip_fdopen.mdoc new file mode 100644 index 0000000..44b5055 --- /dev/null +++ b/third_party/libzip/man/zip_fdopen.mdoc @@ -0,0 +1,147 @@ +.\" zip_fdopen.mdoc -- open zip archive using existing file descriptor +.\" Copyright (C) 2009-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FDOPEN 3 +.Os +.Sh NAME +.Nm zip_fdopen +.Nd open zip archive using open file descriptor +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_t * +.Fn zip_fdopen "int fd" "int flags" "int *errorp" +.Sh DESCRIPTION +The zip archive specified by the open file descriptor +.Ar fd +is opened and a pointer to a +.Ft struct zip , +used to manipulate the archive, is returned. +In contrast to +.Xr zip_open 3 , +using +.Nm zip_fdopen +the archive can only be opened in read-only mode. +The +.Ar fd +argument may not be used any longer after calling +.Nm zip_fdopen . +The +.Fa flags +are specified by +.Em or Ns No 'ing +the following values, or 0 for none of them. +.Bl -tag -offset indent -width ZIP_CHECKCONS +.It Dv ZIP_CHECKCONS +Perform additional stricter consistency checks on the archive, and +error if they fail. +.El +.Pp +If an error occurs and +.Ar errorp +is +.No non- Ns Dv NULL , +it will be set to the corresponding error code. +.Sh RETURN VALUES +Upon successful completion +.Fn zip_fdopen +returns a +.Ft struct zip +pointer, and +.Ar fd +should not be used any longer, nor passed to +.Xr close 2 . +Otherwise, +.Dv NULL +is returned and +.Ar *errorp +is set to indicate the error. +In the error case, +.Ar fd +remains unchanged. +.Sh ERRORS +The file specified by +.Ar fd +is prepared for use by +.Xr libzip 3 +unless: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INCONS +Inconsistencies were found in the file specified by +.Ar path . +This error is often caused by specifying +.Dv ZIP_CHECKCONS +but can also happen without it. +.It Bq Er ZIP_ER_INVAL +The +.Ar flags +argument is invalid. +Not all +.Xr zip_open 3 +flags are allowed for +.Nm zip_fdopen , +see +.Sx DESCRIPTION . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOZIP +The file specified by +.Ar fd +is not a zip archive. +.It Bq Er ZIP_ER_OPEN +The file specified by +.Ar fd +could not be prepared for use by +.Xr libzip 3 . +.It Bq Er ZIP_ER_READ +A read error occurred; see +.Va errno +for details. +.It Bq Er ZIP_ER_SEEK +The file specified by +.Ar fd +does not allow seeks. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_close 3 , +.Xr zip_error_strerror 3 , +.Xr zip_open 3 +.Sh HISTORY +.Fn zip_fdopen +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_add.html b/third_party/libzip/man/zip_file_add.html new file mode 100644 index 0000000..99274c9 --- /dev/null +++ b/third_party/libzip/man/zip_file_add.html @@ -0,0 +1,177 @@ + + + + + + + ZIP_FILE_ADD(3) + + + + + + + + +
ZIP_FILE_ADD(3)Library Functions ManualZIP_FILE_ADD(3)
+
+
+

+zip_file_add, zip_file_replace + — +
add file to zip archive or replace file in zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_file_add(zip_t + *archive, const char + *name, zip_source_t + *source, zip_flags_t + flags);

+

int +
+ zip_file_replace(zip_t + *archive, zip_uint64_t + index, zip_source_t + *source, zip_flags_t + flags);

+
+
+

+The function zip_file_add() adds a file to a zip + archive, while zip_file_replace() replaces an existing + file in a zip archive. The argument archive specifies + the zip archive to which the file should be added. name + is the file's name in the zip archive (for + zip_file_add()), while index + specifies which file should be replaced (for + zip_file_replace()). The flags + argument can be any combination of ZIP_FL_OVERWRITE + with one of ZIP_FL_ENC_*: +
+
+
Overwrite any existing file of the same name. For + zip_file_add only.
+
+
Guess encoding of name (default).
+
+
Interpret name as UTF-8.
+
+
Interpret name as code page 437 (CP-437).
+
+The data is obtained from the source argument, see + zip_source(3). +

NOTE: + zip_source_free(3) should not + be called on a source after it was used successfully + in a zip_file_add or + zip_file_replace call.

+
+
+

+Upon successful completion, zip_file_add() returns the + index of the new file in the archive, and + zip_file_replace() returns 0. Otherwise, -1 is + returned and the error code in archive is set to + indicate the error. +
+
+

+
+
+zip_source_t *s;
+const char *buf="teststring";
+
+if ((s=zip_source_buffer(archive, buf, sizeof(buf), 0)) == NULL ||
+    zip_file_add(archive, name, s, ZIP_FL_ENC_UTF_8) < 0) {
+    zip_source_free(s);
+    printf("error adding file: %s\n", zip_strerror(archive));
+}
+
+
+
+
+

+zip_file_add() and + zip_file_replace() fail if: +
+
[]
+
There is already a file called name in the archive. + (Only applies to zip_file_add(), and only if + ZIP_FL_OVERWRITE is not provided).
+
[]
+
source or name are + NULL, or index is + invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Archive was opened in read-only mode.
+
+
+
+

+libzip(3), + zip_source(3) +
+
+

+zip_file_add() and + zip_file_replace() were added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_add.man b/third_party/libzip/man/zip_file_add.man new file mode 100644 index 0000000..10c0050 --- /dev/null +++ b/third_party/libzip/man/zip_file_add.man @@ -0,0 +1,182 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_add.mdoc -- add files to zip archive +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_ADD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_add\fR, +\fBzip_file_replace\fR +\- add file to zip archive or replace file in zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_file_add\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *name\fR, \fIzip_source_t\ *source\fR, \fIzip_flags_t\ flags\fR); +.PD +.PP +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_replace\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_source_t\ *source\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_file_add\fR() +adds a file to a zip archive, while +\fBzip_file_replace\fR() +replaces an existing file in a zip archive. +The argument +\fIarchive\fR +specifies the zip archive to which the file should be added. +\fIname\fR +is the file's name in the zip archive (for +\fBzip_file_add\fR()), +while +\fIindex\fR +specifies which file should be replaced (for +\fBzip_file_replace\fR()). +The +\fIflags\fR +argument can be any combination of +\fRZIP_FL_OVERWRITE\fR +with one of +\fRZIP_FL_ENC_*\fR: +.TP 22n +\fRZIP_FL_OVERWRITE\fR +Overwrite any existing file of the same name. +For +\fBzip_file_add\fR +only. +.TP 22n +\fRZIP_FL_ENC_GUESS\fR +Guess encoding of +\fIname\fR +(default). +.TP 22n +\fRZIP_FL_ENC_UTF_8\fR +Interpret +\fIname\fR +as UTF-8. +.TP 22n +\fRZIP_FL_ENC_CP437\fR +Interpret +\fIname\fR +as code page 437 (CP-437). +.PD 0 +.PP +The data is obtained from the +\fIsource\fR +argument, see +zip_source(3). +.PD +.PP +\fINOTE\fR: +zip_source_free(3) +should not be called on a +\fIsource\fR +after it was used successfully in a +\fBzip_file_add\fR +or +\fBzip_file_replace\fR +call. +.SH "RETURN VALUES" +Upon successful completion, +\fBzip_file_add\fR() +returns the index of the new file in the archive, and +\fBzip_file_replace\fR() +returns 0. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "EXAMPLES" +.nf +.RS 6n +zip_source_t *s; +const char *buf="teststring"; + +if ((s=zip_source_buffer(archive, buf, sizeof(buf), 0)) == NULL || + zip_file_add(archive, name, s, ZIP_FL_ENC_UTF_8) < 0) { + zip_source_free(s); + printf("error adding file: %s\en", zip_strerror(archive)); +} +.RE +.fi +.SH "ERRORS" +\fBzip_file_add\fR() +and +\fBzip_file_replace\fR() +fail if: +.TP 19n +[\fRZIP_ER_EXISTS\fR] +There is already a file called +\fIname\fR +in the archive. +(Only applies to +\fBzip_file_add\fR(), +and only if +\fRZIP_FL_OVERWRITE\fR +is not provided). +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIsource\fR +or +\fIname\fR +are +\fRNULL\fR, +or +\fIindex\fR +is invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +Archive was opened in read-only mode. +.SH "SEE ALSO" +libzip(3), +zip_source(3) +.SH "HISTORY" +\fBzip_file_add\fR() +and +\fBzip_file_replace\fR() +were added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_add.mdoc b/third_party/libzip/man/zip_file_add.mdoc new file mode 100644 index 0000000..9939ddd --- /dev/null +++ b/third_party/libzip/man/zip_file_add.mdoc @@ -0,0 +1,163 @@ +.\" zip_file_add.mdoc -- add files to zip archive +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_ADD 3 +.Os +.Sh NAME +.Nm zip_file_add , +.Nm zip_file_replace +.Nd add file to zip archive or replace file in zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_file_add "zip_t *archive" "const char *name" "zip_source_t *source" "zip_flags_t flags" +.Ft int +.Fn zip_file_replace "zip_t *archive" "zip_uint64_t index" "zip_source_t *source" "zip_flags_t flags" +.Sh DESCRIPTION +The function +.Fn zip_file_add +adds a file to a zip archive, while +.Fn zip_file_replace +replaces an existing file in a zip archive. +The argument +.Ar archive +specifies the zip archive to which the file should be added. +.Ar name +is the file's name in the zip archive (for +.Fn zip_file_add ) , +while +.Ar index +specifies which file should be replaced (for +.Fn zip_file_replace ) . +The +.Ar flags +argument can be any combination of +.Dv ZIP_FL_OVERWRITE +with one of +.Dv ZIP_FL_ENC_* : +.Bl -tag -width XZIPXFLXENCXSTRICTXX +.It Dv ZIP_FL_OVERWRITE +Overwrite any existing file of the same name. +For +.Nm zip_file_add +only. +.It Dv ZIP_FL_ENC_GUESS +Guess encoding of +.Ar name +(default). +.It Dv ZIP_FL_ENC_UTF_8 +Interpret +.Ar name +as UTF-8. +.It Dv ZIP_FL_ENC_CP437 +Interpret +.Ar name +as code page 437 (CP-437). +.El +The data is obtained from the +.Ar source +argument, see +.Xr zip_source 3 . +.Pp +.Em NOTE : +.Xr zip_source_free 3 +should not be called on a +.Ar source +after it was used successfully in a +.Nm zip_file_add +or +.Nm zip_file_replace +call. +.Sh RETURN VALUES +Upon successful completion, +.Fn zip_file_add +returns the index of the new file in the archive, and +.Fn zip_file_replace +returns 0. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh EXAMPLES +.Bd -literal -offset indent +zip_source_t *s; +const char *buf="teststring"; + +if ((s=zip_source_buffer(archive, buf, sizeof(buf), 0)) == NULL || + zip_file_add(archive, name, s, ZIP_FL_ENC_UTF_8) < 0) { + zip_source_free(s); + printf("error adding file: %s\en", zip_strerror(archive)); +} +.Ed +.Sh ERRORS +.Fn zip_file_add +and +.Fn zip_file_replace +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_EXISTS +There is already a file called +.Ar name +in the archive. +(Only applies to +.Fn zip_file_add , +and only if +.Dv ZIP_FL_OVERWRITE +is not provided). +.It Bq Er ZIP_ER_INVAL +.Ar source +or +.Ar name +are +.Dv NULL , +or +.Ar index +is invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_RDONLY +Archive was opened in read-only mode. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_file_add +and +.Fn zip_file_replace +were added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_extra_field_delete.html b/third_party/libzip/man/zip_file_extra_field_delete.html new file mode 100644 index 0000000..7457e16 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_delete.html @@ -0,0 +1,159 @@ + + + + + + + ZIP_FILE_EXTRA_FIELD_DELETE(3) + + + + + + + + +
ZIP_FILE_EXTRA_FIELD_DELETE(3)Library Functions ManualZIP_FILE_EXTRA_FIELD_DELETE(3)
+
+
+

+zip_file_extra_field_delete, + zip_file_extra_field_delete_by_id — +
delete extra field for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_extra_field_delete(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_index, + zip_flags_t flags);

+

int +
+ zip_file_extra_field_delete_by_id(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_id, + zip_uint16_t + extra_field_index, + zip_flags_t flags);

+
+
+

+The zip_file_extra_field_delete() function deletes the + extra field with index extra_field_index for the file at + position index in the zip archive. +

If extra_field_index is + ZIP_EXTRA_FIELD_ALL, then all extra fields will be + deleted.

+

The following flags are supported:

+
+
+
+
Delete extra fields from the archive's central directory.
+
+
Delete extra fields from the local file headers.
+
+
+

The zip_file_extra_field_delete_by_id() + function deletes the extra field with ID (two-byte signature) + extra_field_id and index + extra_field_index (in other words, the + extra_field_index'th extra + field with ID extra_field_id) The other arguments are + the same as for zip_file_extra_field_delete() + (ZIP_EXTRA_FIELD_ALL will delete all extra fields of + the specified ID).

+

Please note that due to the library design, the index of an extra + field may be different between central directory and local file headers. For + this reason, it is not allowed to specify both + ZIP_FL_CENTRAL and + ZIP_FL_LOCAL in flags, except + when deleting all extra fields (i.e., + extra_field_index being + ZIP_EXTRA_FIELD_ALL).

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_file_extra_field_delete() and + zip_file_extra_field_delete_by_id() fail if: +
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_file_extra_field_get(3), + zip_file_extra_field_set(3), + zip_file_extra_fields_count(3) +
+
+

+zip_file_extra_field_delete() and + zip_file_extra_field_delete_by_id() were added in + libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_extra_field_delete.man b/third_party/libzip/man/zip_file_extra_field_delete.man new file mode 100644 index 0000000..ccc5071 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_delete.man @@ -0,0 +1,141 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_extra_field_delete.mdoc -- delete extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_EXTRA_FIELD_DELETE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_extra_field_delete\fR, +\fBzip_file_extra_field_delete_by_id\fR +\- delete extra field for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_field_delete\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_index\fR, \fIzip_flags_t\ flags\fR); +.PD +.PP +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_field_delete_by_id\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_id\fR, \fIzip_uint16_t\ extra_field_index\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_extra_field_delete\fR() +function deletes the extra field with index +\fIextra_field_index\fR +for the file at position +\fIindex\fR +in the zip archive. +.PP +If +\fIextra_field_index\fR +is +\fRZIP_EXTRA_FIELD_ALL\fR, +then all extra fields will be deleted. +.PP +The following +\fIflags\fR +are supported: +.RS 6n +.TP 18n +\fRZIP_FL_CENTRAL\fR +Delete extra fields from the archive's central directory. +.TP 18n +\fRZIP_FL_LOCAL\fR +Delete extra fields from the local file headers. +.RE +.PP +The +\fBzip_file_extra_field_delete_by_id\fR() +function deletes the extra field with ID (two-byte signature) +\fIextra_field_id\fR +and index +\fIextra_field_index\fR +(in other words, the +\fIextra_field_index\fR'th +extra field with ID +\fIextra_field_id\fR) +The other arguments are the same as for +\fBzip_file_extra_field_delete\fR() +(\fRZIP_EXTRA_FIELD_ALL\fR +will delete all extra fields of the specified ID). +.PP +Please note that due to the library design, the index of an extra +field may be different between central directory and local file +headers. +For this reason, it is not allowed to specify both +\fRZIP_FL_CENTRAL\fR +and +\fRZIP_FL_LOCAL\fR +in +\fIflags\fR, +except when deleting all extra fields (i.e., +\fIextra_field_index\fR +being +\fRZIP_EXTRA_FIELD_ALL\fR). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_extra_field_delete\fR() +and +\fBzip_file_extra_field_delete_by_id\fR() +fail if: +.TP 19n +[\fRZIP_ER_NOENT\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_file_extra_field_get(3), +zip_file_extra_field_set(3), +zip_file_extra_fields_count(3) +.SH "HISTORY" +\fBzip_file_extra_field_delete\fR() +and +\fBzip_file_extra_field_delete_by_id\fR() +were added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_extra_field_delete.mdoc b/third_party/libzip/man/zip_file_extra_field_delete.mdoc new file mode 100644 index 0000000..005e747 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_delete.mdoc @@ -0,0 +1,130 @@ +.\" zip_file_extra_field_delete.mdoc -- delete extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_EXTRA_FIELD_DELETE 3 +.Os +.Sh NAME +.Nm zip_file_extra_field_delete , +.Nm zip_file_extra_field_delete_by_id +.Nd delete extra field for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_extra_field_delete "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_index" "zip_flags_t flags" +.Ft int +.Fn zip_file_extra_field_delete_by_id "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_id" "zip_uint16_t extra_field_index" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_extra_field_delete +function deletes the extra field with index +.Ar extra_field_index +for the file at position +.Ar index +in the zip archive. +.Pp +If +.Ar extra_field_index +is +.Dv ZIP_EXTRA_FIELD_ALL , +then all extra fields will be deleted. +.Pp +The following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_CENTRALXX -offset indent +.It Dv ZIP_FL_CENTRAL +Delete extra fields from the archive's central directory. +.It Dv ZIP_FL_LOCAL +Delete extra fields from the local file headers. +.El +.Pp +The +.Fn zip_file_extra_field_delete_by_id +function deletes the extra field with ID (two-byte signature) +.Ar extra_field_id +and index +.Ar extra_field_index +(in other words, the +.Ar extra_field_index Ns No 'th +extra field with ID +.Ar extra_field_id ) +The other arguments are the same as for +.Fn zip_file_extra_field_delete +.Dv ( ZIP_EXTRA_FIELD_ALL +will delete all extra fields of the specified ID). +.Pp +Please note that due to the library design, the index of an extra +field may be different between central directory and local file +headers. +For this reason, it is not allowed to specify both +.Dv ZIP_FL_CENTRAL +and +.Dv ZIP_FL_LOCAL +in +.Ar flags , +except when deleting all extra fields (i.e., +.Ar extra_field_index +being +.Dv ZIP_EXTRA_FIELD_ALL ) . +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_extra_field_delete +and +.Fn zip_file_extra_field_delete_by_id +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_NOENT +.Ar index +is not a valid file index in +.Ar archive . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_extra_field_get 3 , +.Xr zip_file_extra_field_set 3 , +.Xr zip_file_extra_fields_count 3 +.Sh HISTORY +.Fn zip_file_extra_field_delete +and +.Fn zip_file_extra_field_delete_by_id +were added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_extra_field_get.html b/third_party/libzip/man/zip_file_extra_field_get.html new file mode 100644 index 0000000..2f1a942 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_get.html @@ -0,0 +1,176 @@ + + + + + + + ZIP_FILE_EXTRA_FIELD_GET(3) + + + + + + + + +
ZIP_FILE_EXTRA_FIELD_GET(3)Library Functions ManualZIP_FILE_EXTRA_FIELD_GET(3)
+
+
+

+zip_file_extra_field_get, + zip_file_extra_field_get_by_id — +
get extra field for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const zip_uint8_t * +
+ zip_file_extra_field_get(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_index, + zip_uint16_t *idp, + zip_uint16_t *lenp, + zip_flags_t flags);

+

const zip_uint8_t * +
+ zip_file_extra_field_get_by_id(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_id, + zip_uint16_t + extra_field_index, + zip_uint16_t *lenp, + zip_flags_t flags);

+
+
+

+The zip_file_extra_field_get() function returns the + extra field with index extra_field_index for the file at + position index in the zip archive. This pointer should + not be modified or free(3)'d, and becomes + invalid when archive is closed. If + idp is not NULL, the integer to + which it points will be set to the ID (two-byte signature) of the selected + extra field. If lenp is not + NULL, the integer to which it points will be set to + the length of the extra field. Generally speaking, lenp + and idp should be passed since only the extra field data + is returned (i.e., neither the ID nor the length, if the + idp and lenp arguments are not + provided). +

The following flags are supported:

+
+
+
+
Return extra fields from the archive's central directory.
+
+
Return extra fields from the local file headers.
+
+
Return the original unchanged extra fields, ignoring any changes + made.
+
+
+

The zip_file_extra_field_get_by_id() + function returns the extra field with ID (two-byte signature) + extra_field_id and index + extra_field_index (in other words, the + extra_field_index'th extra + field with ID extra_field_id) The other arguments are + the same as for zip_file_extra_field_get().

+
+
+

+Upon successful completion, a pointer to an extra field is returned, or + NULL if there is no extra field with that + extra_field_index for the file with index + index. In case of an error, NULL + is returned and the error code in archive is set to + indicate the error. +
+
+

+zip_file_extra_field_get() and + zip_file_extra_field_get_by_id() fail if: +
+
[]
+
index is not a valid file index in + archive, or extra_field_index + is not a valid extra file index (for ID + extra_field_id).
+
+
+
+

+libzip(3), + zip_file_extra_field_delete(3), + zip_file_extra_field_set(3), + zip_file_extra_fields_count(3) +
+
+

+zip_file_extra_field_get() and + zip_file_extra_field_get_by_id() were added in libzip + 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+

+Please note that the extra field IDs 0x0001 (ZIP64 extension), 0x6375 (Infozip + UTF-8 comment), and 0x7075 (Infozip UTF-8 file name) can not be read using + zip_file_extra_field_get() since they are used by + libzip(3) internally. +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_extra_field_get.man b/third_party/libzip/man/zip_file_extra_field_get.man new file mode 100644 index 0000000..39c5428 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_get.man @@ -0,0 +1,169 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_extra_field_get.mdoc -- get extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_EXTRA_FIELD_GET" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_extra_field_get\fR, +\fBzip_file_extra_field_get_by_id\fR +\- get extra field for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst zip_uint8_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_field_get\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_index\fR, \fIzip_uint16_t\ *idp\fR, \fIzip_uint16_t\ *lenp\fR, \fIzip_flags_t\ flags\fR); +.PD +.PP +\fIconst zip_uint8_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_field_get_by_id\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_id\fR, \fIzip_uint16_t\ extra_field_index\fR, \fIzip_uint16_t\ *lenp\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_extra_field_get\fR() +function returns the extra field with index +\fIextra_field_index\fR +for the file at position +\fIindex\fR +in the zip archive. +This pointer should not be modified or +free(3)'d, +and becomes invalid when +\fIarchive\fR +is closed. +If +\fIidp\fR +is not +\fRNULL\fR, +the integer to which it points will be set to the ID (two-byte +signature) of the selected extra field. +If +\fIlenp\fR +is not +\fRNULL\fR, +the integer to which it points will be set to the length of the +extra field. +Generally speaking, +\fIlenp\fR +and +\fIidp\fR +should be passed since only the extra field data is returned (i.e., +neither the ID nor the length, if the +\fIidp\fR +and +\fIlenp\fR +arguments are not provided). +.PP +The following +\fIflags\fR +are supported: +.RS 6n +.TP 20n +\fRZIP_FL_CENTRAL\fR +Return extra fields from the archive's central directory. +.TP 20n +\fRZIP_FL_LOCAL\fR +Return extra fields from the local file headers. +.TP 20n +\fRZIP_FL_UNCHANGED\fR +Return the original unchanged extra fields, ignoring any changes made. +.RE +.PP +The +\fBzip_file_extra_field_get_by_id\fR() +function returns the extra field with ID (two-byte signature) +\fIextra_field_id\fR +and index +\fIextra_field_index\fR +(in other words, the +\fIextra_field_index\fR'th +extra field with ID +\fIextra_field_id\fR) +The other arguments are the same as for +\fBzip_file_extra_field_get\fR(). +.SH "RETURN VALUES" +Upon successful completion, a pointer to an extra field is returned, +or +\fRNULL\fR +if there is no extra field with that +\fIextra_field_index\fR +for the file with index +\fIindex\fR. +In case of an error, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_extra_field_get\fR() +and +\fBzip_file_extra_field_get_by_id\fR() +fail if: +.TP 19n +[\fRZIP_ER_NOENT\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +or +\fIextra_field_index\fR +is not a valid extra file index (for ID +\fIextra_field_id\fR). +.SH "SEE ALSO" +libzip(3), +zip_file_extra_field_delete(3), +zip_file_extra_field_set(3), +zip_file_extra_fields_count(3) +.SH "HISTORY" +\fBzip_file_extra_field_get\fR() +and +\fBzip_file_extra_field_get_by_id\fR() +were added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> +.SH "CAVEATS" +Please note that the extra field IDs 0x0001 (ZIP64 extension), +0x6375 (Infozip UTF-8 comment), and +0x7075 (Infozip UTF-8 file name) can not be read using +\fBzip_file_extra_field_get\fR() +since they are used by +libzip(3) +internally. diff --git a/third_party/libzip/man/zip_file_extra_field_get.mdoc b/third_party/libzip/man/zip_file_extra_field_get.mdoc new file mode 100644 index 0000000..72b2c87 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_get.mdoc @@ -0,0 +1,157 @@ +.\" zip_file_extra_field_get.mdoc -- get extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_EXTRA_FIELD_GET 3 +.Os +.Sh NAME +.Nm zip_file_extra_field_get , +.Nm zip_file_extra_field_get_by_id +.Nd get extra field for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const zip_uint8_t * +.Fn zip_file_extra_field_get "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_index" "zip_uint16_t *idp" "zip_uint16_t *lenp" "zip_flags_t flags" +.Ft const zip_uint8_t * +.Fn zip_file_extra_field_get_by_id "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_id" "zip_uint16_t extra_field_index" "zip_uint16_t *lenp" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_extra_field_get +function returns the extra field with index +.Ar extra_field_index +for the file at position +.Ar index +in the zip archive. +This pointer should not be modified or +.Xr free 3 Ap d , +and becomes invalid when +.Ar archive +is closed. +If +.Ar idp +is not +.Dv NULL , +the integer to which it points will be set to the ID (two-byte +signature) of the selected extra field. +If +.Ar lenp +is not +.Dv NULL , +the integer to which it points will be set to the length of the +extra field. +Generally speaking, +.Ar lenp +and +.Ar idp +should be passed since only the extra field data is returned (i.e., +neither the ID nor the length, if the +.Ar idp +and +.Ar lenp +arguments are not provided). +.Pp +The following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_UNCHANGEDXX -offset indent +.It Dv ZIP_FL_CENTRAL +Return extra fields from the archive's central directory. +.It Dv ZIP_FL_LOCAL +Return extra fields from the local file headers. +.It Dv ZIP_FL_UNCHANGED +Return the original unchanged extra fields, ignoring any changes made. +.El +.Pp +The +.Fn zip_file_extra_field_get_by_id +function returns the extra field with ID (two-byte signature) +.Ar extra_field_id +and index +.Ar extra_field_index +(in other words, the +.Ar extra_field_index Ns No 'th +extra field with ID +.Ar extra_field_id ) +The other arguments are the same as for +.Fn zip_file_extra_field_get . +.Sh RETURN VALUES +Upon successful completion, a pointer to an extra field is returned, +or +.Dv NULL +if there is no extra field with that +.Ar extra_field_index +for the file with index +.Ar index . +In case of an error, +.Dv NULL +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_extra_field_get +and +.Fn zip_file_extra_field_get_by_id +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_NOENT +.Ar index +is not a valid file index in +.Ar archive , +or +.Ar extra_field_index +is not a valid extra file index (for ID +.Ar extra_field_id ) . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_extra_field_delete 3 , +.Xr zip_file_extra_field_set 3 , +.Xr zip_file_extra_fields_count 3 +.Sh HISTORY +.Fn zip_file_extra_field_get +and +.Fn zip_file_extra_field_get_by_id +were added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at +.Sh CAVEATS +Please note that the extra field IDs 0x0001 (ZIP64 extension), +0x6375 (Infozip UTF-8 comment), and +0x7075 (Infozip UTF-8 file name) can not be read using +.Fn zip_file_extra_field_get +since they are used by +.Xr libzip 3 +internally. diff --git a/third_party/libzip/man/zip_file_extra_field_set.html b/third_party/libzip/man/zip_file_extra_field_set.html new file mode 100644 index 0000000..8f78da5 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_set.html @@ -0,0 +1,148 @@ + + + + + + + ZIP_FILE_EXTRA_FIELD_SET(3) + + + + + + + + +
ZIP_FILE_EXTRA_FIELD_SET(3)Library Functions ManualZIP_FILE_EXTRA_FIELD_SET(3)
+
+
+

+zip_file_extra_field_set — +
set extra field for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_extra_field_set(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_id, + zip_uint16_t + extra_field_index, const + zip_uint8_t *extra_field_data, + zip_uint16_t len, + zip_flags_t flags);

+
+
+

+The zip_file_extra_field_set() function sets the extra + field with ID (two-byte signature) extra_field_id and + index extra_field_index for the file at position + index in the zip archive. The extra field's data will be + set to extra_field_data and length + len. If a new entry shall be appended, set + extra_field_index to + ZIP_EXTRA_FIELD_NEW. +

At least one of the following flags must be + set:

+
+
+
+
Set extra field in the archive's central directory.
+
+
Set extra field in the local file headers.
+
+
+

Please note that the extra field IDs 0x0001 (ZIP64 extension), + 0x6375 (Infozip UTF-8 comment), and 0x7075 (Infozip UTF-8 file name) can not + be set using zip_file_extra_field_set() since they + are set by libzip(3) automatically when + needed.

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_file_extra_field_set() fails if: +
+
[]
+
The extra field size is too large (ID and length need 4 bytes; the maximum + length of all extra fields for one file combined is 65536 bytes). This + error also occurs if extra_field_index is too + large.
+
[]
+
Required memory could not be allocated.
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_file_extra_field_delete(3), + zip_file_extra_field_get(3), + zip_file_extra_fields_count(3) +
+
+

+zip_file_extra_field_set() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_extra_field_set.man b/third_party/libzip/man/zip_file_extra_field_set.man new file mode 100644 index 0000000..3db94fe --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_set.man @@ -0,0 +1,123 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_extra_field_set.mdoc -- set extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_EXTRA_FIELD_SET" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_extra_field_set\fR +\- set extra field for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_field_set\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_id\fR, \fIzip_uint16_t\ extra_field_index\fR, \fIconst\ zip_uint8_t\ *extra_field_data\fR, \fIzip_uint16_t\ len\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_extra_field_set\fR() +function sets the extra field with ID (two-byte signature) +\fIextra_field_id\fR +and index +\fIextra_field_index\fR +for the file at position +\fIindex\fR +in the zip archive. +The extra field's data will be set to +\fIextra_field_data\fR +and length +\fIlen\fR. +If a new entry shall be appended, set +\fIextra_field_index\fR +to +\fRZIP_EXTRA_FIELD_NEW\fR. +.PP +At least one of the following +\fIflags\fR +must be set: +.RS 6n +.TP 18n +\fRZIP_FL_CENTRAL\fR +Set extra field in the archive's central directory. +.TP 18n +\fRZIP_FL_LOCAL\fR +Set extra field in the local file headers. +.RE +.PP +Please note that the extra field IDs 0x0001 (ZIP64 extension), +0x6375 (Infozip UTF-8 comment), and +0x7075 (Infozip UTF-8 file name) can not be set using +\fBzip_file_extra_field_set\fR() +since they are set by +libzip(3) +automatically when needed. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_extra_field_set\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +The extra field size is too large (ID and length need 4 bytes; the +maximum length of all extra fields for one file combined is 65536 +bytes). +This error also occurs if +\fIextra_field_index\fR +is too large. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOENT\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_file_extra_field_delete(3), +zip_file_extra_field_get(3), +zip_file_extra_fields_count(3) +.SH "HISTORY" +\fBzip_file_extra_field_set\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_extra_field_set.mdoc b/third_party/libzip/man/zip_file_extra_field_set.mdoc new file mode 100644 index 0000000..3e6abc1 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_field_set.mdoc @@ -0,0 +1,115 @@ +.\" zip_file_extra_field_set.mdoc -- set extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_EXTRA_FIELD_SET 3 +.Os +.Sh NAME +.Nm zip_file_extra_field_set +.Nd set extra field for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_extra_field_set "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_id" "zip_uint16_t extra_field_index" "const zip_uint8_t *extra_field_data" "zip_uint16_t len" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_extra_field_set +function sets the extra field with ID (two-byte signature) +.Ar extra_field_id +and index +.Ar extra_field_index +for the file at position +.Ar index +in the zip archive. +The extra field's data will be set to +.Ar extra_field_data +and length +.Ar len . +If a new entry shall be appended, set +.Ar extra_field_index +to +.Dv ZIP_EXTRA_FIELD_NEW . +.Pp +At least one of the following +.Ar flags +must be set: +.Bl -tag -width ZIP_FL_CENTRALXX -offset indent +.It Dv ZIP_FL_CENTRAL +Set extra field in the archive's central directory. +.It Dv ZIP_FL_LOCAL +Set extra field in the local file headers. +.El +.Pp +Please note that the extra field IDs 0x0001 (ZIP64 extension), +0x6375 (Infozip UTF-8 comment), and +0x7075 (Infozip UTF-8 file name) can not be set using +.Fn zip_file_extra_field_set +since they are set by +.Xr libzip 3 +automatically when needed. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_extra_field_set +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +The extra field size is too large (ID and length need 4 bytes; the +maximum length of all extra fields for one file combined is 65536 +bytes). +This error also occurs if +.Ar extra_field_index +is too large. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOENT +.Ar index +is not a valid file index in +.Ar archive . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_extra_field_delete 3 , +.Xr zip_file_extra_field_get 3 , +.Xr zip_file_extra_fields_count 3 +.Sh HISTORY +.Fn zip_file_extra_field_set +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_extra_fields_count.html b/third_party/libzip/man/zip_file_extra_fields_count.html new file mode 100644 index 0000000..ad968da --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_fields_count.html @@ -0,0 +1,149 @@ + + + + + + + ZIP_FILE_EXTRA_FIELDS_COUNT(3) + + + + + + + + +
ZIP_FILE_EXTRA_FIELDS_COUNT(3)Library Functions ManualZIP_FILE_EXTRA_FIELDS_COUNT(3)
+
+
+

+zip_file_extra_fields_count, + zip_file_extra_fields_count_by_id — +
count extra fields for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int16_t +
+ zip_file_extra_fields_count(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags);

+

zip_int16_t +
+ zip_file_extra_fields_count_by_id(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + extra_field_id, + zip_flags_t flags);

+
+
+

+The zip_file_extra_fields_count() function counts the + extra fields for the file at position index in the zip + archive. +

The following flags are supported:

+
+
+
+
Count extra fields from the archive's central directory.
+
+
Count extra fields from the local file headers.
+
+
Count the original unchanged extra fields, ignoring any changes made.
+
+
+

The zip_file_extra_fields_count_by_id() + function counts the extra fields with ID (two-byte signature) + extra_field_id. The other arguments are the same as + for zip_file_extra_fields_count().

+

Extra fields that are the same in the central directory and the + local file header are merged into one. Therefore, the counts with + ZIP_FL_CENTRAL and + ZIP_FL_LOCAL do not need to add up to the same value + as when given ZIP_FL_CENTRAL|ZIP_FL_LOCAL at the + same time.

+
+
+

+Upon successful completion, the requested number of extra fields is returned. + Otherwise, -1 is returned and the error code in archive + is set to indicate the error. +
+
+

+zip_file_extra_fields_count() and + zip_file_extra_fields_count_by_id() fail if: +
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_file_extra_field_delete(3), + zip_file_extra_field_get(3), + zip_file_extra_field_set(3) +
+
+

+zip_file_extra_fields_count() and + zip_file_extra_fields_count_by_id() were added in + libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_extra_fields_count.man b/third_party/libzip/man/zip_file_extra_fields_count.man new file mode 100644 index 0000000..35a85e1 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_fields_count.man @@ -0,0 +1,124 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_extra_fields_count.mdoc -- count extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_EXTRA_FIELDS_COUNT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_extra_fields_count\fR, +\fBzip_file_extra_fields_count_by_id\fR +\- count extra fields for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int16_t\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_fields_count\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR); +.PD +.PP +\fIzip_int16_t\fR +.br +.PD 0 +.HP 4n +\fBzip_file_extra_fields_count_by_id\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ extra_field_id\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_extra_fields_count\fR() +function counts the extra fields for the file at position +\fIindex\fR +in the zip archive. +.PP +The following +\fIflags\fR +are supported: +.RS 6n +.TP 18n +\fRZIP_FL_CENTRAL\fR +Count extra fields from the archive's central directory. +.TP 18n +\fRZIP_FL_LOCAL\fR +Count extra fields from the local file headers. +.TP 18n +\fRZIP_FL_UNCHANGED\fR +Count the original unchanged extra fields, ignoring any changes made. +.RE +.PP +The +\fBzip_file_extra_fields_count_by_id\fR() +function counts the extra fields with ID (two-byte signature) +\fIextra_field_id\fR. +The other arguments are the same as for +\fBzip_file_extra_fields_count\fR(). +.PP +Extra fields that are the same in the central directory and the local file +header are merged into one. +Therefore, the counts with +\fRZIP_FL_CENTRAL\fR +and +\fRZIP_FL_LOCAL\fR +do not need to add up to the same value as when given +\fRZIP_FL_CENTRAL|ZIP_FL_LOCAL\fR +at the same time. +.SH "RETURN VALUES" +Upon successful completion, the requested number of extra fields is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_extra_fields_count\fR() +and +\fBzip_file_extra_fields_count_by_id\fR() +fail if: +.TP 19n +[\fRZIP_ER_NOENT\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_file_extra_field_delete(3), +zip_file_extra_field_get(3), +zip_file_extra_field_set(3) +.SH "HISTORY" +\fBzip_file_extra_fields_count\fR() +and +\fBzip_file_extra_fields_count_by_id\fR() +were added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_extra_fields_count.mdoc b/third_party/libzip/man/zip_file_extra_fields_count.mdoc new file mode 100644 index 0000000..47bb9a3 --- /dev/null +++ b/third_party/libzip/man/zip_file_extra_fields_count.mdoc @@ -0,0 +1,113 @@ +.\" zip_file_extra_fields_count.mdoc -- count extra field for file in zip +.\" Copyright (C) 2012-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_EXTRA_FIELDS_COUNT 3 +.Os +.Sh NAME +.Nm zip_file_extra_fields_count , +.Nm zip_file_extra_fields_count_by_id +.Nd count extra fields for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int16_t +.Fn zip_file_extra_fields_count "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" +.Ft zip_int16_t +.Fn zip_file_extra_fields_count_by_id "zip_t *archive" "zip_uint64_t index" "zip_uint16_t extra_field_id" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_extra_fields_count +function counts the extra fields for the file at position +.Ar index +in the zip archive. +.Pp +The following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_CENTRALXX -offset indent +.It Dv ZIP_FL_CENTRAL +Count extra fields from the archive's central directory. +.It Dv ZIP_FL_LOCAL +Count extra fields from the local file headers. +.It Dv ZIP_FL_UNCHANGED +Count the original unchanged extra fields, ignoring any changes made. +.El +.Pp +The +.Fn zip_file_extra_fields_count_by_id +function counts the extra fields with ID (two-byte signature) +.Ar extra_field_id . +The other arguments are the same as for +.Fn zip_file_extra_fields_count . +.Pp +Extra fields that are the same in the central directory and the local file +header are merged into one. +Therefore, the counts with +.Dv ZIP_FL_CENTRAL +and +.Dv ZIP_FL_LOCAL +do not need to add up to the same value as when given +.Dv ZIP_FL_CENTRAL|ZIP_FL_LOCAL +at the same time. +.Sh RETURN VALUES +Upon successful completion, the requested number of extra fields is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_extra_fields_count +and +.Fn zip_file_extra_fields_count_by_id +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_NOENT +.Ar index +is not a valid file index in +.Ar archive . +.\" TODO: _zip_read_local_ef errors +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_extra_field_delete 3 , +.Xr zip_file_extra_field_get 3 , +.Xr zip_file_extra_field_set 3 +.Sh HISTORY +.Fn zip_file_extra_fields_count +and +.Fn zip_file_extra_fields_count_by_id +were added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_get_comment.html b/third_party/libzip/man/zip_file_get_comment.html new file mode 100644 index 0000000..3471489 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_comment.html @@ -0,0 +1,142 @@ + + + + + + + ZIP_FILE_GET_COMMENT(3) + + + + + + + + +
ZIP_FILE_GET_COMMENT(3)Library Functions ManualZIP_FILE_GET_COMMENT(3)
+
+
+

+zip_file_get_comment — +
get comment for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_file_get_comment(zip_t + *archive, zip_uint64_t + index, zip_uint32_t + *lenp, zip_flags_t + flags);

+
+
+

+The zip_file_get_comment() function returns the comment + for the file at position index in the zip archive. The + name is in UTF-8 encoding unless ZIP_FL_ENC_RAW was + specified (see below). This pointer should not be modified or + free(3)'d, and becomes invalid when + archive is closed. If lenp is not + NULL, the integer to which it points will be set to + the length of the comment. If flags is set to + ZIP_FL_UNCHANGED, the original unchanged comment is + returned. +

Additionally, the following flags are + supported:

+
+
+
+
Return the unmodified comment as it is in the ZIP archive.
+
+
(Default.) Guess the encoding of the comment in the ZIP archive and + convert it to UTF-8, if necessary.
+
+
Follow the ZIP specification for file names and extend it to file + comments, expecting them to be encoded in CP-437 in the ZIP archive + (except if it is a UTF-8 comment from the special extra field). Convert it + to UTF-8.
+
+
+Note: ASCII is a subset of both CP-437 and UTF-8. +
+
+

+Upon successful completion, a pointer to the comment is returned, or + NULL if there is no comment. In case of an error, + NULL is returned and the error code in + archive is set to indicate the error. +
+
+

+zip_file_get_comment() fails if: +
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_file_set_comment(3), + zip_get_archive_comment(3) +
+
+

+zip_file_get_comment() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_get_comment.man b/third_party/libzip/man/zip_file_get_comment.man new file mode 100644 index 0000000..248f4f6 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_comment.man @@ -0,0 +1,125 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_get_comment.mdoc -- get comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_GET_COMMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_get_comment\fR +\- get comment for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_file_get_comment\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint32_t\ *lenp\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_get_comment\fR() +function returns the comment for the file at position +\fIindex\fR +in the zip archive. +The name is in UTF-8 encoding unless +\fRZIP_FL_ENC_RAW\fR +was specified (see below). +This pointer should not be modified or +free(3)'d, +and becomes invalid when +\fIarchive\fR +is closed. +If +\fIlenp\fR +is not +\fRNULL\fR, +the integer to which it points will be set to the length of the +comment. +If +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original unchanged comment is returned. +.PP +Additionally, the following +\fIflags\fR +are supported: +.RS 6n +.TP 21n +\fRZIP_FL_ENC_RAW\fR +Return the unmodified comment as it is in the ZIP archive. +.TP 21n +\fRZIP_FL_ENC_GUESS\fR +(Default.) +Guess the encoding of the comment in the ZIP archive and convert it +to UTF-8, if necessary. +.TP 21n +\fRZIP_FL_ENC_STRICT\fR +Follow the ZIP specification for file names and extend it to file +comments, expecting them to be encoded in CP-437 in the ZIP archive +(except if it is a UTF-8 comment from the special extra field). +Convert it to UTF-8. +.RE +\fINote\fR: +ASCII is a subset of both CP-437 and UTF-8. +.SH "RETURN VALUES" +Upon successful completion, a pointer to the comment is returned, +or +\fRNULL\fR +if there is no comment. +In case of an error, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_get_comment\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_file_set_comment(3), +zip_get_archive_comment(3) +.SH "HISTORY" +\fBzip_file_get_comment\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_get_comment.mdoc b/third_party/libzip/man/zip_file_get_comment.mdoc new file mode 100644 index 0000000..7243282 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_comment.mdoc @@ -0,0 +1,118 @@ +.\" zip_file_get_comment.mdoc -- get comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_GET_COMMENT 3 +.Os +.Sh NAME +.Nm zip_file_get_comment +.Nd get comment for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_file_get_comment "zip_t *archive" "zip_uint64_t index" "zip_uint32_t *lenp" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_get_comment +function returns the comment for the file at position +.Ar index +in the zip archive. +The name is in UTF-8 encoding unless +.Dv ZIP_FL_ENC_RAW +was specified (see below). +This pointer should not be modified or +.Xr free 3 Ap d , +and becomes invalid when +.Ar archive +is closed. +If +.Ar lenp +is not +.Dv NULL , +the integer to which it points will be set to the length of the +comment. +If +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original unchanged comment is returned. +.Pp +Additionally, the following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_ENC_STRICTXX -offset indent +.It Dv ZIP_FL_ENC_RAW +Return the unmodified comment as it is in the ZIP archive. +.It Dv ZIP_FL_ENC_GUESS +(Default.) +Guess the encoding of the comment in the ZIP archive and convert it +to UTF-8, if necessary. +.It Dv ZIP_FL_ENC_STRICT +Follow the ZIP specification for file names and extend it to file +comments, expecting them to be encoded in CP-437 in the ZIP archive +(except if it is a UTF-8 comment from the special extra field). +Convert it to UTF-8. +.El +.Em Note : +ASCII is a subset of both CP-437 and UTF-8. +.Sh RETURN VALUES +Upon successful completion, a pointer to the comment is returned, +or +.Dv NULL +if there is no comment. +In case of an error, +.Dv NULL +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_get_comment +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_set_comment 3 , +.Xr zip_get_archive_comment 3 +.Sh HISTORY +.Fn zip_file_get_comment +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_get_error.html b/third_party/libzip/man/zip_file_get_error.html new file mode 100644 index 0000000..0f89e39 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_error.html @@ -0,0 +1,95 @@ + + + + + + + ZIP_FILE_GET_ERROR(3) + + + + + + + + +
ZIP_FILE_GET_ERROR(3)Library Functions ManualZIP_FILE_GET_ERROR(3)
+
+
+

+zip_file_get_error — +
extract zip_error from zip_file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_error_t * +
+ zip_file_get_error(zip_file_t + *zf);

+
+
+

+zip_file_get_error() function returns the zip_error + associated with the zip_file zf. +
+
+

+libzip(3) +
+
+

+zip_file_get_error() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_get_error.man b/third_party/libzip/man/zip_file_get_error.man new file mode 100644 index 0000000..d364ac0 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_error.man @@ -0,0 +1,62 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_get_error.mdoc -- extract zip_error from zip_file +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_GET_ERROR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_get_error\fR +\- extract zip_error from zip_file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_error_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_file_get_error\fR(\fIzip_file_t\ *zf\fR); +.PD +.SH "DESCRIPTION" +\fBzip_file_get_error\fR() +function returns the zip_error associated with the zip_file +\fIzf\fR. +.SH "SEE ALSO" +libzip(3) +.SH "HISTORY" +\fBzip_file_get_error\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_get_error.mdoc b/third_party/libzip/man/zip_file_get_error.mdoc new file mode 100644 index 0000000..56628a1 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_error.mdoc @@ -0,0 +1,57 @@ +.\" zip_file_get_error.mdoc -- extract zip_error from zip_file +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_GET_ERROR 3 +.Os +.Sh NAME +.Nm zip_file_get_error +.Nd extract zip_error from zip_file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_error_t * +.Fn zip_file_get_error "zip_file_t *zf" +.Sh DESCRIPTION +.Fn zip_file_get_error +function returns the zip_error associated with the zip_file +.Ar zf . +.Sh SEE ALSO +.Xr libzip 3 +.Sh HISTORY +.Fn zip_file_get_error +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_get_external_attributes.html b/third_party/libzip/man/zip_file_get_external_attributes.html new file mode 100644 index 0000000..937b0d0 --- /dev/null +++ b/third_party/libzip/man/zip_file_get_external_attributes.html @@ -0,0 +1,176 @@ + + + + + + + ZIP_FILE_GET_EXTERNAL_ATTRIBUTES(3) + + + + + + + + +
ZIP_FILE_GET_EXTERNAL_ATTRIBUTES(3)Library Functions ManualZIP_FILE_GET_EXTERNAL_ATTRIBUTES(3)
+
+
+

+zip_file_get_external_attributes — +
get external attributes for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_get_external_attributes(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags, zip_uint8_t + *opsys, zip_uint32_t + *attributes);

+
+
+

+The zip_file_get_external_attributes() function returns + the operating system and external attributes for the file at position + index in the zip archive. The external attributes + usually contain the operating system-specific file permissions. If + flags is set to + ZIP_FL_UNCHANGED, the original unchanged values are + returned. If opsys or attributes + are NULL, they are not filled in. +

The following operating systems are defined by the zip + specification:

+ +

The defines above follow the PKWARE Inc. Appnote; please note that + the InfoZIP Appnote has a slightly different mapping.

+
+
+

+Upon successful completion, 0 is returned. In case of an error, + -1 is returned and the error code in + archive is set to indicate the error. +
+
+

+The following code can be used to expand attributes if the + operating system is ZIP_OPSYS_DOS. +
+
+#include <sys/stat.h>
+
+#define FA_RDONLY       0x01            // FILE_ATTRIBUTE_READONLY
+#define FA_DIREC        0x10            // FILE_ATTRIBUTE_DIRECTORY
+
+static mode_t
+_zip_dos_attr2mode(zip_uint32_t attr)
+{
+   mode_t m = S_IRUSR | S_IRGRP | S_IROTH;
+   if (0 == (attr & FA_RDONLY))
+      m |= S_IWUSR | S_IWGRP | S_IWOTH;
+
+   if (attr & FA_DIREC)
+      m = (S_IFDIR | (m & ~S_IFMT)) | S_IXUSR | S_IXGRP | S_IXOTH;
+
+   return m;
+}
+
+
+
+
+

+zip_file_get_external_attributes() fails if: +
+
[]
+
index is not a valid file index in + archive.
+
+
+
+

+libzip(3), + zip_file_set_external_attributes(3) +
+
+

+zip_file_get_external_attributes() was added in libzip + 0.11.2. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_get_external_attributes.man b/third_party/libzip/man/zip_file_get_external_attributes.man new file mode 100644 index 0000000..acd3fbb --- /dev/null +++ b/third_party/libzip/man/zip_file_get_external_attributes.man @@ -0,0 +1,174 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_get_external_attributes.mdoc -- get external attributes for file in zip +.\" Copyright (C) 2013-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_GET_EXTERNAL_ATTRIBUTES" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_get_external_attributes\fR +\- get external attributes for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_get_external_attributes\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR, \fIzip_uint8_t\ *opsys\fR, \fIzip_uint32_t\ *attributes\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_get_external_attributes\fR() +function returns the operating system and external attributes for the +file at position +\fIindex\fR +in the zip archive. +The external attributes usually contain the operating system-specific +file permissions. +If +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original unchanged values are returned. +If +\fIopsys\fR +or +\fIattributes\fR +are +\fRNULL\fR, +they are not filled in. +.PP +The following operating systems are defined by the zip specification: +.RS 6n +.PD 0 +.PP +\fRZIP_OPSYS_ACORN_RISC\fR +.PP +\fRZIP_OPSYS_ALTERNATE_MVS\fR +.PP +\fRZIP_OPSYS_AMIGA\fR +.PP +\fRZIP_OPSYS_ATARI_ST\fR +.PP +\fRZIP_OPSYS_BEOS\fR +.PP +\fRZIP_OPSYS_CPM\fR +.PP +\fRZIP_OPSYS_DOS\fR +.PP +\fRZIP_OPSYS_MACINTOSH\fR +.PP +\fRZIP_OPSYS_MVS\fR +.PP +\fRZIP_OPSYS_OPENVMS\fR +.PP +\fRZIP_OPSYS_OS_2\fR +.PP +\fRZIP_OPSYS_OS_400\fR +.PP +\fRZIP_OPSYS_OS_X\fR +.PP +\fRZIP_OPSYS_TANDEM\fR +.PP +\fRZIP_OPSYS_UNIX\fR +.PP +\fRZIP_OPSYS_VFAT\fR +.PP +\fRZIP_OPSYS_VM_CMS\fR +.PP +\fRZIP_OPSYS_VSE\fR +.PP +\fRZIP_OPSYS_WINDOWS_NTFS\fR +(uncommon, use +\fRZIP_OPSYS_DOS\fR +instead) +.PP +\fRZIP_OPSYS_Z_SYSTEM\fR +.RE +.PD +.PP +The defines above follow the PKWARE Inc. Appnote; please note that +the InfoZIP Appnote has a slightly different mapping. +.SH "RETURN VALUES" +Upon successful completion, 0 is returned. +In case of an error, +\fR\-1\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "EXAMPLES" +The following code can be used to expand +\fIattributes\fR +if the operating system is +\fRZIP_OPSYS_DOS\fR. +.nf +.sp +.RS 0n +#include + +#define FA_RDONLY 0x01 // FILE_ATTRIBUTE_READONLY +#define FA_DIREC 0x10 // FILE_ATTRIBUTE_DIRECTORY + +static mode_t +_zip_dos_attr2mode(zip_uint32_t attr) +{ + mode_t m = S_IRUSR | S_IRGRP | S_IROTH; + if (0 == (attr & FA_RDONLY)) + m |= S_IWUSR | S_IWGRP | S_IWOTH; + + if (attr & FA_DIREC) + m = (S_IFDIR | (m & ~S_IFMT)) | S_IXUSR | S_IXGRP | S_IXOTH; + + return m; +} +.RE +.fi +.SH "ERRORS" +\fBzip_file_get_external_attributes\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_file_set_external_attributes(3) +.SH "HISTORY" +\fBzip_file_get_external_attributes\fR() +was added in libzip 0.11.2. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_get_external_attributes.mdoc b/third_party/libzip/man/zip_file_get_external_attributes.mdoc new file mode 100644 index 0000000..5b3cdcc --- /dev/null +++ b/third_party/libzip/man/zip_file_get_external_attributes.mdoc @@ -0,0 +1,165 @@ +.\" zip_file_get_external_attributes.mdoc -- get external attributes for file in zip +.\" Copyright (C) 2013-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_GET_EXTERNAL_ATTRIBUTES 3 +.Os +.Sh NAME +.Nm zip_file_get_external_attributes +.Nd get external attributes for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_get_external_attributes "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" "zip_uint8_t *opsys" "zip_uint32_t *attributes" +.Sh DESCRIPTION +The +.Fn zip_file_get_external_attributes +function returns the operating system and external attributes for the +file at position +.Ar index +in the zip archive. +The external attributes usually contain the operating system-specific +file permissions. +If +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original unchanged values are returned. +If +.Ar opsys +or +.Ar attributes +are +.Dv NULL , +they are not filled in. +.Pp +The following operating systems are defined by the zip specification: +.Bl -item -compact -offset indent +.It +.Dv ZIP_OPSYS_ACORN_RISC +.It +.Dv ZIP_OPSYS_ALTERNATE_MVS +.It +.Dv ZIP_OPSYS_AMIGA +.It +.Dv ZIP_OPSYS_ATARI_ST +.It +.Dv ZIP_OPSYS_BEOS +.It +.Dv ZIP_OPSYS_CPM +.It +.Dv ZIP_OPSYS_DOS +.It +.Dv ZIP_OPSYS_MACINTOSH +.It +.Dv ZIP_OPSYS_MVS +.It +.Dv ZIP_OPSYS_OPENVMS +.It +.Dv ZIP_OPSYS_OS_2 +.It +.Dv ZIP_OPSYS_OS_400 +.It +.Dv ZIP_OPSYS_OS_X +.It +.Dv ZIP_OPSYS_TANDEM +.It +.Dv ZIP_OPSYS_UNIX +.It +.Dv ZIP_OPSYS_VFAT +.It +.Dv ZIP_OPSYS_VM_CMS +.It +.Dv ZIP_OPSYS_VSE +.It +.Dv ZIP_OPSYS_WINDOWS_NTFS +(uncommon, use +.Dv ZIP_OPSYS_DOS +instead) +.It +.Dv ZIP_OPSYS_Z_SYSTEM +.El +.Pp +The defines above follow the PKWARE Inc. Appnote; please note that +the InfoZIP Appnote has a slightly different mapping. +.Sh RETURN VALUES +Upon successful completion, 0 is returned. +In case of an error, +.Dv \-1 +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh EXAMPLES +The following code can be used to expand +.Ar attributes +if the operating system is +.Dv ZIP_OPSYS_DOS . +.Bd -literal +#include + +#define FA_RDONLY 0x01 // FILE_ATTRIBUTE_READONLY +#define FA_DIREC 0x10 // FILE_ATTRIBUTE_DIRECTORY + +static mode_t +_zip_dos_attr2mode(zip_uint32_t attr) +{ + mode_t m = S_IRUSR | S_IRGRP | S_IROTH; + if (0 == (attr & FA_RDONLY)) + m |= S_IWUSR | S_IWGRP | S_IWOTH; + + if (attr & FA_DIREC) + m = (S_IFDIR | (m & ~S_IFMT)) | S_IXUSR | S_IXGRP | S_IXOTH; + + return m; +} +.Ed +.Sh ERRORS +.Fn zip_file_get_external_attributes +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_set_external_attributes 3 +.Sh HISTORY +.Fn zip_file_get_external_attributes +was added in libzip 0.11.2. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_rename.html b/third_party/libzip/man/zip_file_rename.html new file mode 100644 index 0000000..b15e352 --- /dev/null +++ b/third_party/libzip/man/zip_file_rename.html @@ -0,0 +1,131 @@ + + + + + + + ZIP_FILE_RENAME(3) + + + + + + + + +
ZIP_FILE_RENAME(3)Library Functions ManualZIP_FILE_RENAME(3)
+
+
+

+zip_file_rename — +
rename file in zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_rename(zip_t + *archive, zip_uint64_t + index, const char + *name, zip_flags_t + flags);

+
+
+

+The file at position index in the zip archive + archive is renamed to name. The + flags argument can be any of: +
+
+
Guess encoding of name (default).
+
+
Interpret name as UTF-8.
+
+
Interpret name as code page 437 (CP-437).
+
+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_file_rename() fails if: +
+
[]
+
The file to be renamed has been deleted from the archive.
+
[]
+
There is already a file called name in the + archive.
+
[]
+
index is not a valid file index in + archive, name is + NULL, the empty string, or not a valid UTF-8 + encoded string. Also a file cannot be renamed to a directory or vice + versa. Directories are denoted by a trailing slash.
+
+
+
+

+libzip(3), + zip_unchange(3) +
+
+

+zip_file_rename() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_rename.man b/third_party/libzip/man/zip_file_rename.man new file mode 100644 index 0000000..45cee19 --- /dev/null +++ b/third_party/libzip/man/zip_file_rename.man @@ -0,0 +1,110 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_rename.mdoc -- rename file in zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_RENAME" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_rename\fR +\- rename file in zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_rename\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIconst\ char\ *name\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The file at position +\fIindex\fR +in the zip archive +\fIarchive\fR +is renamed to +\fIname\fR. +The +\fIflags\fR +argument can be any of: +.TP 22n +\fRZIP_FL_ENC_GUESS\fR +Guess encoding of +\fIname\fR +(default). +.TP 22n +\fRZIP_FL_ENC_UTF_8\fR +Interpret +\fIname\fR +as UTF-8. +.TP 22n +\fRZIP_FL_ENC_CP437\fR +Interpret +\fIname\fR +as code page 437 (CP-437). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_rename\fR() +fails if: +.TP 19n +[\fRZIP_ER_DELETED\fR] +The file to be renamed has been deleted from the archive. +.TP 19n +[\fRZIP_ER_EXISTS\fR] +There is already a file called +\fIname\fR +in the archive. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +\fIname is\fR +\fRNULL\fR, +the empty string, or not a valid UTF-8 encoded string. +Also a file cannot be renamed to a directory or vice versa. +Directories are denoted by a trailing slash. +.SH "SEE ALSO" +libzip(3), +zip_unchange(3) +.SH "HISTORY" +\fBzip_file_rename\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_rename.mdoc b/third_party/libzip/man/zip_file_rename.mdoc new file mode 100644 index 0000000..017e26e --- /dev/null +++ b/third_party/libzip/man/zip_file_rename.mdoc @@ -0,0 +1,103 @@ +.\" zip_file_rename.mdoc -- rename file in zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_RENAME 3 +.Os +.Sh NAME +.Nm zip_file_rename +.Nd rename file in zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_rename "zip_t *archive" "zip_uint64_t index" "const char *name" "zip_flags_t flags" +.Sh DESCRIPTION +The file at position +.Ar index +in the zip archive +.Ar archive +is renamed to +.Ar name . +The +.Ar flags +argument can be any of: +.Bl -tag -width XZIPXFLXENCXSTRICTXX +.It Dv ZIP_FL_ENC_GUESS +Guess encoding of +.Ar name +(default). +.It Dv ZIP_FL_ENC_UTF_8 +Interpret +.Ar name +as UTF-8. +.It Dv ZIP_FL_ENC_CP437 +Interpret +.Ar name +as code page 437 (CP-437). +.El +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_rename +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_DELETED +The file to be renamed has been deleted from the archive. +.It Bq Er ZIP_ER_EXISTS +There is already a file called +.Ar name +in the archive. +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive , +.Ar name is +.Dv NULL , +the empty string, or not a valid UTF-8 encoded string. +Also a file cannot be renamed to a directory or vice versa. +Directories are denoted by a trailing slash. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_unchange 3 +.Sh HISTORY +.Fn zip_file_rename +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_set_comment.html b/third_party/libzip/man/zip_file_set_comment.html new file mode 100644 index 0000000..e567e3b --- /dev/null +++ b/third_party/libzip/man/zip_file_set_comment.html @@ -0,0 +1,136 @@ + + + + + + + ZIP_FILE_SET_COMMENT(3) + + + + + + + + +
ZIP_FILE_SET_COMMENT(3)Library Functions ManualZIP_FILE_SET_COMMENT(3)
+
+
+

+zip_file_set_comment — +
set comment for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_set_comment(zip_t + *archive, zip_uint64_t + index, const char + *comment, zip_uint16_t + len, zip_flags_t + flags);

+
+
+

+The zip_file_set_comment() function sets the comment for + the file at position index in the zip archive to + comment of length len. If + comment is NULL and + len is 0, the file comment will be removed. The + flags argument can be any of: +
+
+
Guess encoding of comment (default).
+
+
Interpret comment as UTF-8.
+
+
Interpret comment as code page 437 (CP-437).
+
+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_file_set_comment() fails if: +
+
[]
+
index is not a valid file index in + archive, or len is less than 0 + or longer than the maximum comment length in a zip file (65535), or + comment is not a valid UTF-8 encoded string.
+
[]
+
Required memory could not be allocated.
+
[]
+
The archive was opened in read-only mode.
+
+
+
+

+libzip(3), + zip_file_get_comment(3), + zip_get_archive_comment(3), + zip_set_archive_comment(3) +
+
+

+zip_file_set_comment() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_set_comment.man b/third_party/libzip/man/zip_file_set_comment.man new file mode 100644 index 0000000..b1425ca --- /dev/null +++ b/third_party/libzip/man/zip_file_set_comment.man @@ -0,0 +1,122 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_set_comment.mdoc -- set comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_SET_COMMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_set_comment\fR +\- set comment for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_set_comment\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIconst\ char\ *comment\fR, \fIzip_uint16_t\ len\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_set_comment\fR() +function sets the comment for the file at position +\fIindex\fR +in the zip archive to +\fIcomment\fR +of length +\fIlen\fR. +If +\fIcomment\fR +is +\fRNULL\fR +and +\fIlen\fR +is 0, the file comment will be removed. +The +\fIflags\fR +argument can be any of: +.TP 22n +\fRZIP_FL_ENC_GUESS\fR +Guess encoding of +\fIcomment\fR +(default). +.TP 22n +\fRZIP_FL_ENC_UTF_8\fR +Interpret +\fIcomment\fR +as UTF-8. +.TP 22n +\fRZIP_FL_ENC_CP437\fR +Interpret +\fIcomment\fR +as code page 437 (CP-437). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_set_comment\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +or +\fIlen\fR +is less than 0 or longer than the maximum comment length in a zip file +(65535), or +\fIcomment\fR +is not a valid UTF-8 encoded string. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +The +\fIarchive\fR +was opened in read-only mode. +.SH "SEE ALSO" +libzip(3), +zip_file_get_comment(3), +zip_get_archive_comment(3), +zip_set_archive_comment(3) +.SH "HISTORY" +\fBzip_file_set_comment\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_set_comment.mdoc b/third_party/libzip/man/zip_file_set_comment.mdoc new file mode 100644 index 0000000..1e596cf --- /dev/null +++ b/third_party/libzip/man/zip_file_set_comment.mdoc @@ -0,0 +1,115 @@ +.\" zip_file_set_comment.mdoc -- set comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_SET_COMMENT 3 +.Os +.Sh NAME +.Nm zip_file_set_comment +.Nd set comment for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_set_comment "zip_t *archive" "zip_uint64_t index" "const char *comment" "zip_uint16_t len" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_set_comment +function sets the comment for the file at position +.Ar index +in the zip archive to +.Ar comment +of length +.Ar len . +If +.Ar comment +is +.Dv NULL +and +.Ar len +is 0, the file comment will be removed. +The +.Ar flags +argument can be any of: +.Bl -tag -width XZIPXFLXENCXSTRICTXX +.It Dv ZIP_FL_ENC_GUESS +Guess encoding of +.Ar comment +(default). +.It Dv ZIP_FL_ENC_UTF_8 +Interpret +.Ar comment +as UTF-8. +.It Dv ZIP_FL_ENC_CP437 +Interpret +.Ar comment +as code page 437 (CP-437). +.El +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_set_comment +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive , +or +.Ar len +is less than 0 or longer than the maximum comment length in a zip file +(65535), or +.Ar comment +is not a valid UTF-8 encoded string. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_RDONLY +The +.Ar archive +was opened in read-only mode. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_get_comment 3 , +.Xr zip_get_archive_comment 3 , +.Xr zip_set_archive_comment 3 +.Sh HISTORY +.Fn zip_file_set_comment +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_set_encryption.html b/third_party/libzip/man/zip_file_set_encryption.html new file mode 100644 index 0000000..ea5c280 --- /dev/null +++ b/third_party/libzip/man/zip_file_set_encryption.html @@ -0,0 +1,144 @@ + + + + + + + ZIP_FILE_SET_ENCRYPTION(3) + + + + + + + + +
ZIP_FILE_SET_ENCRYPTION(3)Library Functions ManualZIP_FILE_SET_ENCRYPTION(3)
+
+
+

+zip_file_set_encryption — +
set encryption method for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_set_encryption(zip_t + *archive, zip_uint64_t + index, zip_uint16_t + method, const char + *password);

+
+
+

+The zip_file_set_encryption() function sets the + encryption method for the file at position index in the + zip archive to method using the password + password. The method is the same + as returned by zip_stat(3). For the + method argument, currently only the following values are + supported: +
+
+
No encryption.
+
+
Winzip AES-128 encryption.
+
+
Winzip AES-192 encryption.
+
+
Winzip AES-256 encryption.
+
+

If password is NULL, + the default password provided by + zip_set_default_password(3) + is used.

+

The current encryption method for a file in a zip archive can be + determined using zip_stat(3).

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_file_set_encryption() fails if: +
+
[]
+
Unsupported compression method requested.
+
[]
+
index is not a valid file index in + archive, or the argument combination is + invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Read-only zip file, no changes allowed.
+
+
+
+

+libzip(3), + zip_set_default_password(3), + zip_stat(3) +
+
+

+zip_file_set_encryption() was added in libzip 1.2.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_set_encryption.man b/third_party/libzip/man/zip_file_set_encryption.man new file mode 100644 index 0000000..d82e28e --- /dev/null +++ b/third_party/libzip/man/zip_file_set_encryption.man @@ -0,0 +1,123 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_set_encryption.mdoc -- set encryption method for file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_SET_ENCRYPTION" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_set_encryption\fR +\- set encryption method for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_set_encryption\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_uint16_t\ method\fR, \fIconst\ char\ *password\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_set_encryption\fR() +function sets the encryption method for the file at position +\fIindex\fR +in the zip archive to +\fImethod\fR +using the password +\fIpassword\fR. +The +\fImethod\fR +is the same as returned by +zip_stat(3). +For the +\fImethod\fR +argument, currently only the following values are supported: +.TP 19n +\fRZIP_EM_NONE\fR +No encryption. +.TP 19n +\fRZIP_EM_AES_128\fR +Winzip AES-128 encryption. +.TP 19n +\fRZIP_EM_AES_192\fR +Winzip AES-192 encryption. +.TP 19n +\fRZIP_EM_AES_256\fR +Winzip AES-256 encryption. +.PP +If +\fIpassword\fR +is +\fRNULL\fR, +the default password provided by +zip_set_default_password(3) +is used. +.PP +The current encryption method for a file in a zip archive can be +determined using +zip_stat(3). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_set_encryption\fR() +fails if: +.TP 19n +[\fRZIP_ER_ENCRNOTSUPP\fR] +Unsupported compression method requested. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +or the argument combination is invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +Read-only zip file, no changes allowed. +.SH "SEE ALSO" +libzip(3), +zip_set_default_password(3), +zip_stat(3) +.SH "HISTORY" +\fBzip_file_set_encryption\fR() +was added in libzip 1.2.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_set_encryption.mdoc b/third_party/libzip/man/zip_file_set_encryption.mdoc new file mode 100644 index 0000000..a09c42a --- /dev/null +++ b/third_party/libzip/man/zip_file_set_encryption.mdoc @@ -0,0 +1,114 @@ +.\" zip_file_set_encryption.mdoc -- set encryption method for file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_SET_ENCRYPTION 3 +.Os +.Sh NAME +.Nm zip_file_set_encryption +.Nd set encryption method for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_set_encryption "zip_t *archive" "zip_uint64_t index" "zip_uint16_t method" "const char *password" +.Sh DESCRIPTION +The +.Fn zip_file_set_encryption +function sets the encryption method for the file at position +.Ar index +in the zip archive to +.Ar method +using the password +.Ar password . +The +.Ar method +is the same as returned by +.Xr zip_stat 3 . +For the +.Ar method +argument, currently only the following values are supported: +.Bl -tag -width ZIP_CM_DEFLATE_XX +.It Dv ZIP_EM_NONE +No encryption. +.It Dv ZIP_EM_AES_128 +Winzip AES-128 encryption. +.It Dv ZIP_EM_AES_192 +Winzip AES-192 encryption. +.It Dv ZIP_EM_AES_256 +Winzip AES-256 encryption. +.El +.Pp +If +.Ar password +is +.Dv NULL , +the default password provided by +.Xr zip_set_default_password 3 +is used. +.Pp +The current encryption method for a file in a zip archive can be +determined using +.Xr zip_stat 3 . +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_set_encryption +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_ENCRNOTSUPP +Unsupported compression method requested. +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive , +or the argument combination is invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_RDONLY +Read-only zip file, no changes allowed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_set_default_password 3 , +.Xr zip_stat 3 +.Sh HISTORY +.Fn zip_file_set_encryption +was added in libzip 1.2.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_set_external_attributes.html b/third_party/libzip/man/zip_file_set_external_attributes.html new file mode 100644 index 0000000..5892f0a --- /dev/null +++ b/third_party/libzip/man/zip_file_set_external_attributes.html @@ -0,0 +1,125 @@ + + + + + + + ZIP_FILE_SET_EXTERNAL_ATTRIBUTES(3) + + + + + + + + +
ZIP_FILE_SET_EXTERNAL_ATTRIBUTES(3)Library Functions ManualZIP_FILE_SET_EXTERNAL_ATTRIBUTES(3)
+
+
+

+zip_file_set_external_attributes — +
set external attributes for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_set_external_attributes(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags, zip_uint8_t + opsys, zip_uint32_t + attributes);

+
+
+

+The zip_file_set_external_attributes() function sets the + operating system and external attributes for the file at position + index in the zip archive. Currently, no + flags are supported. +

For a list of known opsys values, see + zip_file_get_external_attributes(3).

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_file_set_external_attributes() fails if: +
+
[]
+
index is not a valid file index in + archive.
+
[]
+
Required memory could not be allocated.
+
[]
+
The archive was opened in read-only mode.
+
+
+
+

+libzip(3), + zip_file_get_external_attributes(3) +
+
+

+zip_file_set_external_attributes() was added in libzip + 0.11.2. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_set_external_attributes.man b/third_party/libzip/man/zip_file_set_external_attributes.man new file mode 100644 index 0000000..76c375e --- /dev/null +++ b/third_party/libzip/man/zip_file_set_external_attributes.man @@ -0,0 +1,95 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_set_external_attributes.mdoc -- set external attributes for file in zip +.\" Copyright (C) 2013-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_SET_EXTERNAL_ATTRIBUTES" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_set_external_attributes\fR +\- set external attributes for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_set_external_attributes\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR, \fIzip_uint8_t\ opsys\fR, \fIzip_uint32_t\ attributes\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_set_external_attributes\fR() +function sets the operating system and external attributes for the +file at position +\fIindex\fR +in the zip archive. +Currently, no +\fIflags\fR +are supported. +.PP +For a list of known +\fIopsys\fR +values, see +zip_file_get_external_attributes(3). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_set_external_attributes\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +The +\fIarchive\fR +was opened in read-only mode. +.SH "SEE ALSO" +libzip(3), +zip_file_get_external_attributes(3) +.SH "HISTORY" +\fBzip_file_set_external_attributes\fR() +was added in libzip 0.11.2. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_set_external_attributes.mdoc b/third_party/libzip/man/zip_file_set_external_attributes.mdoc new file mode 100644 index 0000000..d7fa082 --- /dev/null +++ b/third_party/libzip/man/zip_file_set_external_attributes.mdoc @@ -0,0 +1,89 @@ +.\" zip_file_set_external_attributes.mdoc -- set external attributes for file in zip +.\" Copyright (C) 2013-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_SET_EXTERNAL_ATTRIBUTES 3 +.Os +.Sh NAME +.Nm zip_file_set_external_attributes +.Nd set external attributes for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_set_external_attributes "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" "zip_uint8_t opsys" "zip_uint32_t attributes" +.Sh DESCRIPTION +The +.Fn zip_file_set_external_attributes +function sets the operating system and external attributes for the +file at position +.Ar index +in the zip archive. +Currently, no +.Ar flags +are supported. +.Pp +For a list of known +.Ar opsys +values, see +.Xr zip_file_get_external_attributes 3 . +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_set_external_attributes +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_RDONLY +The +.Ar archive +was opened in read-only mode. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_get_external_attributes 3 +.Sh HISTORY +.Fn zip_file_set_external_attributes +was added in libzip 0.11.2. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_set_mtime.html b/third_party/libzip/man/zip_file_set_mtime.html new file mode 100644 index 0000000..e56948f --- /dev/null +++ b/third_party/libzip/man/zip_file_set_mtime.html @@ -0,0 +1,121 @@ + + + + + + + ZIP_FILE_SET_MTIME(3) + + + + + + + + +
ZIP_FILE_SET_MTIME(3)Library Functions ManualZIP_FILE_SET_MTIME(3)
+
+
+

+zip_file_set_mtime — +
set last modification time (mtime) for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_file_set_mtime(zip_t + *archive, zip_uint64_t + index, time_t + mtime, zip_flags_t + flags);

+
+
+

+The zip_file_set_mtime() function sets the last + modification time (mtime) for the file at position index + in the zip archive to mtime. Currently, no support for + any flags is implemented. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_file_set_mtime() fails if: +
+
[]
+
index is not a valid file index in + archive.
+
[]
+
Required memory could not be allocated.
+
[]
+
The archive was opened in read-only mode.
+
+
+
+

+libzip(3), + zip_stat(3) +
+
+

+zip_file_set_mtime() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_set_mtime.man b/third_party/libzip/man/zip_file_set_mtime.man new file mode 100644 index 0000000..aa2e52f --- /dev/null +++ b/third_party/libzip/man/zip_file_set_mtime.man @@ -0,0 +1,91 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_set_mtime.mdoc -- set mtime for file in zip +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_SET_MTIME" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_set_mtime\fR +\- set last modification time (mtime) for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_file_set_mtime\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fItime_t\ mtime\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_file_set_mtime\fR() +function sets the last modification time (mtime) for the file at +position +\fIindex\fR +in the zip archive to +\fImtime\fR. +Currently, no support for any +\fIflags\fR +is implemented. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_file_set_mtime\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +The +\fIarchive\fR +was opened in read-only mode. +.SH "SEE ALSO" +libzip(3), +zip_stat(3) +.SH "HISTORY" +\fBzip_file_set_mtime\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_set_mtime.mdoc b/third_party/libzip/man/zip_file_set_mtime.mdoc new file mode 100644 index 0000000..32057b5 --- /dev/null +++ b/third_party/libzip/man/zip_file_set_mtime.mdoc @@ -0,0 +1,85 @@ +.\" zip_file_set_mtime.mdoc -- set mtime for file in zip +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_SET_MTIME 3 +.Os +.Sh NAME +.Nm zip_file_set_mtime +.Nd set last modification time (mtime) for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_file_set_mtime "zip_t *archive" "zip_uint64_t index" "time_t mtime" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_file_set_mtime +function sets the last modification time (mtime) for the file at +position +.Ar index +in the zip archive to +.Ar mtime . +Currently, no support for any +.Ar flags +is implemented. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_file_set_mtime +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_RDONLY +The +.Ar archive +was opened in read-only mode. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_stat 3 +.Sh HISTORY +.Fn zip_file_set_mtime +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_file_strerror.html b/third_party/libzip/man/zip_file_strerror.html new file mode 100644 index 0000000..8e19642 --- /dev/null +++ b/third_party/libzip/man/zip_file_strerror.html @@ -0,0 +1,115 @@ + + + + + + + ZIP_FILE_STRERROR(3) + + + + + + + + +
ZIP_FILE_STRERROR(3)Library Functions ManualZIP_FILE_STRERROR(3)
+
+
+

+zip_file_strerror, zip_strerror + — +
get string representation for a zip error
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_file_strerror(zip_file_t + *file);

+

const char * +
+ zip_strerror(zip_t + *archive);

+
+
+

+The zip_strerror() function returns a string describing + the last error for the zip archive archive, while the + zip_file_strerror() function does the same for a zip + file file (one file in an archive). The returned string + must not be modified or freed, and becomes invalid when + archive or file, respectively, is + closed or on the next call to zip_strerror() or + zip_file_strerror(), respectively, for the same + archive. +
+
+

+zip_file_strerror() and + zip_strerror() return a pointer to the error string. +
+
+

+libzip(3), + zip_error_strerror(3) +
+
+

+zip_file_strerror() and + zip_strerror() were added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_file_strerror.man b/third_party/libzip/man/zip_file_strerror.man new file mode 100644 index 0000000..a8cee3a --- /dev/null +++ b/third_party/libzip/man/zip_file_strerror.man @@ -0,0 +1,95 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_file_strerror.mdoc -- get string representation for a zip error +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FILE_STRERROR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_file_strerror\fR, +\fBzip_strerror\fR +\- get string representation for a zip error +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_file_strerror\fR(\fIzip_file_t\ *file\fR); +.PD +.PP +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_strerror\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_strerror\fR() +function returns a string describing the last error for the zip archive +\fIarchive\fR, +while the +\fBzip_file_strerror\fR() +function does the same for a zip file +\fIfile\fR +(one file in an archive). +The returned string must not be modified or freed, and becomes invalid when +\fIarchive\fR +or +\fIfile\fR, +respectively, +is closed or on the next call to +\fBzip_strerror\fR() +or +\fBzip_file_strerror\fR(), +respectively, +for the same archive. +.SH "RETURN VALUES" +\fBzip_file_strerror\fR() +and +\fBzip_strerror\fR() +return a pointer to the error string. +.SH "SEE ALSO" +libzip(3), +zip_error_strerror(3) +.SH "HISTORY" +\fBzip_file_strerror\fR() +and +\fBzip_strerror\fR() +were added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_file_strerror.mdoc b/third_party/libzip/man/zip_file_strerror.mdoc new file mode 100644 index 0000000..1f16b9b --- /dev/null +++ b/third_party/libzip/man/zip_file_strerror.mdoc @@ -0,0 +1,85 @@ +.\" zip_file_strerror.mdoc -- get string representation for a zip error +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FILE_STRERROR 3 +.Os +.Sh NAME +.Nm zip_file_strerror , +.Nm zip_strerror +.Nd get string representation for a zip error +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_file_strerror "zip_file_t *file" +.Ft const char * +.Fn zip_strerror "zip_t *archive" +.Sh DESCRIPTION +The +.Fn zip_strerror +function returns a string describing the last error for the zip archive +.Ar archive , +while the +.Fn zip_file_strerror +function does the same for a zip file +.Ar file +(one file in an archive). +The returned string must not be modified or freed, and becomes invalid when +.Ar archive +or +.Ar file , +respectively, +is closed or on the next call to +.Fn zip_strerror +or +.Fn zip_file_strerror , +respectively, +for the same archive. +.Sh RETURN VALUES +.Fn zip_file_strerror +and +.Fn zip_strerror +return a pointer to the error string. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_strerror 3 +.Sh HISTORY +.Fn zip_file_strerror +and +.Fn zip_strerror +were added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fopen.html b/third_party/libzip/man/zip_fopen.html new file mode 100644 index 0000000..5367fae --- /dev/null +++ b/third_party/libzip/man/zip_fopen.html @@ -0,0 +1,171 @@ + + + + + + + ZIP_FOPEN(3) + + + + + + + + +
ZIP_FOPEN(3)Library Functions ManualZIP_FOPEN(3)
+
+
+

+zip_fopen, zip_fopen_index + — +
open file in zip archive for reading
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_file_t * +
+ zip_fopen(zip_t + *archive, const char + *fname, zip_flags_t + flags);

+

zip_file_t * +
+ zip_fopen_index(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags);

+
+
+

+The zip_fopen() function opens the file name + fname in archive. The + flags argument specifies how the name lookup should be + done, according to the values are described in + zip_name_locate(3). Also, the + following values may be or'ed to it. +
+
+
+
Read the compressed data. Otherwise the data is uncompressed by + zip_fread().
+
+
Read the original data from the zip archive, ignoring any changes made to + the file.
+
+
+

The zip_fopen_index() function opens the + file at position index.

+

If encrypted data is encountered, the functions call + zip_fopen_encrypted(3) or + zip_fopen_index_encrypted(3) + respectively, using the default password set with + zip_set_default_password(3).

+
+
+

+Upon successful completion, a struct zip_file pointer is + returned. Otherwise, NULL is returned and the error + code in archive is set to indicate the error. +
+
+

+
+
[]
+
The file data has been changed.
+
[]
+
The compression method used is not supported.
+
[]
+
The encryption method used is not supported.
+
[]
+
Required memory could not be allocated.
+
[]
+
The file is encrypted, but no password has been provided.
+
[]
+
A file read error occurred.
+
[]
+
A file seek error occurred.
+
[]
+
The provided password does not match the password used for encryption. + Note that some incorrect passwords are not detected by the check done by + zip_fopen().
+
[]
+
Initializing the zlib stream failed.
+
+

The function zip_fopen() may also fail and + set zip_err for any of the errors specified for the + routine + zip_name_locate(3).

+

The function zip_fopen_index() may also + fail with ZIP_ER_INVAL if + index is invalid.

+
+
+

+libzip(3), + zip_fclose(3), + zip_fread(3), + zip_fseek(3), + zip_get_num_entries(3), + zip_name_locate(3), + zip_set_default_password(3) +
+
+

+zip_fopen() and + zip_fopen_index() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fopen.man b/third_party/libzip/man/zip_fopen.man new file mode 100644 index 0000000..95e0100 --- /dev/null +++ b/third_party/libzip/man/zip_fopen.man @@ -0,0 +1,166 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fopen.mdoc -- open file in zip archive for reading +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FOPEN" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fopen\fR, +\fBzip_fopen_index\fR +\- open file in zip archive for reading +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_file_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_fopen\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_flags_t\ flags\fR); +.PD +.PP +\fIzip_file_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_fopen_index\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_fopen\fR() +function opens the file name +\fIfname\fR +in +\fIarchive\fR. +The +\fIflags\fR +argument specifies how the name lookup should be done, according to +the values are described in +zip_name_locate(3). +Also, the following values may be +\fIor\fR'ed +to it. +.RS 6n +.TP 19n +\fRZIP_FL_COMPRESSED\fR +Read the compressed data. +Otherwise the data is uncompressed by +\fBzip_fread\fR(). +.TP 19n +\fRZIP_FL_UNCHANGED\fR +Read the original data from the zip archive, ignoring any changes made +to the file. +.RE +.PP +The +\fBzip_fopen_index\fR() +function opens the file at position +\fIindex\fR. +.PP +If encrypted data is encountered, the functions call +zip_fopen_encrypted(3) +or +zip_fopen_index_encrypted(3) +respectively, using the default password set with +zip_set_default_password(3). +.SH "RETURN VALUES" +Upon successful completion, a +\fIstruct zip_file\fR +pointer is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +.TP 19n +[\fRZIP_ER_CHANGED\fR] +The file data has been changed. +.TP 19n +[\fRZIP_ER_COMPNOTSUPP\fR] +The compression method used is not supported. +.TP 19n +[\fRZIP_ER_ENCRNOTSUPP\fR] +The encryption method used is not supported. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOPASSWD\fR] +The file is encrypted, but no password has been provided. +.TP 19n +[\fRZIP_ER_READ\fR] +A file read error occurred. +.TP 19n +[\fRZIP_ER_SEEK\fR] +A file seek error occurred. +.TP 19n +[\fRZIP_ER_WRONGPASSWD\fR] +The provided password does not match the password used for encryption. +Note that some incorrect passwords are not detected by the check done by +\fBzip_fopen\fR(). +.TP 19n +[\fRZIP_ER_ZLIB\fR] +Initializing the zlib stream failed. +.PP +The function +\fBzip_fopen\fR() +may also fail and set +\fIzip_err\fR +for any of the errors specified for the routine +zip_name_locate(3). +.PP +The function +\fBzip_fopen_index\fR() +may also fail with +\fRZIP_ER_INVAL\fR +if +\fIindex\fR +is invalid. +.SH "SEE ALSO" +libzip(3), +zip_fclose(3), +zip_fread(3), +zip_fseek(3), +zip_get_num_entries(3), +zip_name_locate(3), +zip_set_default_password(3) +.SH "HISTORY" +\fBzip_fopen\fR() +and +\fBzip_fopen_index\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fopen.mdoc b/third_party/libzip/man/zip_fopen.mdoc new file mode 100644 index 0000000..fb54f87 --- /dev/null +++ b/third_party/libzip/man/zip_fopen.mdoc @@ -0,0 +1,147 @@ +.\" zip_fopen.mdoc -- open file in zip archive for reading +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FOPEN 3 +.Os +.Sh NAME +.Nm zip_fopen , +.Nm zip_fopen_index +.Nd open file in zip archive for reading +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_file_t * +.Fn zip_fopen "zip_t *archive" "const char *fname" "zip_flags_t flags" +.Ft zip_file_t * +.Fn zip_fopen_index "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_fopen +function opens the file name +.Ar fname +in +.Ar archive . +The +.Ar flags +argument specifies how the name lookup should be done, according to +the values are described in +.Xr zip_name_locate 3 . +Also, the following values may be +.Em or Ns No 'ed +to it. +.Bl -tag -offset indent -width ZIP_FL_COMPRESSED +.It Dv ZIP_FL_COMPRESSED +Read the compressed data. +Otherwise the data is uncompressed by +.Fn zip_fread . +.It Dv ZIP_FL_UNCHANGED +Read the original data from the zip archive, ignoring any changes made +to the file. +.El +.Pp +The +.Fn zip_fopen_index +function opens the file at position +.Ar index . +.Pp +If encrypted data is encountered, the functions call +.Xr zip_fopen_encrypted 3 +or +.Xr zip_fopen_index_encrypted 3 +respectively, using the default password set with +.Xr zip_set_default_password 3 . +.Sh RETURN VALUES +Upon successful completion, a +.Ft struct zip_file +pointer is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Bl -tag -width Er +.It Bq Er ZIP_ER_CHANGED +The file data has been changed. +.It Bq Er ZIP_ER_COMPNOTSUPP +The compression method used is not supported. +.It Bq Er ZIP_ER_ENCRNOTSUPP +The encryption method used is not supported. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOPASSWD +The file is encrypted, but no password has been provided. +.It Bq Er ZIP_ER_READ +A file read error occurred. +.It Bq Er ZIP_ER_SEEK +A file seek error occurred. +.It Bq Er ZIP_ER_WRONGPASSWD +The provided password does not match the password used for encryption. +Note that some incorrect passwords are not detected by the check done by +.Fn zip_fopen . +.It Bq Er ZIP_ER_ZLIB +Initializing the zlib stream failed. +.El +.Pp +The function +.Fn zip_fopen +may also fail and set +.Va zip_err +for any of the errors specified for the routine +.Xr zip_name_locate 3 . +.Pp +The function +.Fn zip_fopen_index +may also fail with +.Er ZIP_ER_INVAL +if +.Ar index +is invalid. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fclose 3 , +.Xr zip_fread 3 , +.Xr zip_fseek 3 , +.Xr zip_get_num_entries 3 , +.Xr zip_name_locate 3 , +.Xr zip_set_default_password 3 +.Sh HISTORY +.Fn zip_fopen +and +.Fn zip_fopen_index +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fopen_encrypted.html b/third_party/libzip/man/zip_fopen_encrypted.html new file mode 100644 index 0000000..51af5a9 --- /dev/null +++ b/third_party/libzip/man/zip_fopen_encrypted.html @@ -0,0 +1,144 @@ + + + + + + + ZIP_FOPEN_ENCRYPTED(3) + + + + + + + + +
ZIP_FOPEN_ENCRYPTED(3)Library Functions ManualZIP_FOPEN_ENCRYPTED(3)
+
+
+

+zip_fopen_encrypted, + zip_fopen_index_encrypted — +
open encrypted file in zip archive for reading
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_file_t * +
+ zip_fopen_encrypted(zip_t + *archive, const char + *fname, zip_flags_t + flags, const char + *password);

+

zip_file_t * +
+ zip_fopen_index_encrypted(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags, const char + *password);

+
+
+

+The zip_fopen_encrypted() function opens the encrypted + file name fname in archive using + the password given in the password argument. The + flags argument are the same as for + zip_fopen(3). +

The zip_fopen_index_encrypted() function + opens the file at position index, see + zip_fopen_index(3). These + functions are called automatically by + zip_fopen(3); you only need to call + them if you want to specify a non-default password (see + zip_set_default_password(3)).

+
+
+

+Upon successful completion, a struct zip_file pointer is + returned. Otherwise, NULL is returned and the error + code in archive is set to indicate the error. +
+
+

+
+
[]
+
No password was provided.
+
+

The function zip_fopen_encrypted() may + also fail and set zip_err for any of the errors + specified for the routine + zip_fopen(3).

+

The function zip_fopen_index_encrypted() + may also fail and set zip_err for any of the errors + specified for the routine + zip_fopen_index(3).

+
+
+

+libzip(3), + zip_fclose(3), + zip_fopen(3), + zip_fread(3), + zip_get_num_entries(3), + zip_name_locate(3) +
+
+

+zip_fopen_encrypted() and + zip_fopen_index_encrypted() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fopen_encrypted.man b/third_party/libzip/man/zip_fopen_encrypted.man new file mode 100644 index 0000000..872a3c8 --- /dev/null +++ b/third_party/libzip/man/zip_fopen_encrypted.man @@ -0,0 +1,126 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fopen_encrypted.mdoc -- open encrypted file in zip archive for reading +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FOPEN_ENCRYPTED" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fopen_encrypted\fR, +\fBzip_fopen_index_encrypted\fR +\- open encrypted file in zip archive for reading +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_file_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_fopen_encrypted\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_flags_t\ flags\fR, \fIconst\ char\ *password\fR); +.PD +.PP +\fIzip_file_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_fopen_index_encrypted\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR, \fIconst\ char\ *password\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_fopen_encrypted\fR() +function opens the encrypted file name +\fIfname\fR +in +\fIarchive\fR +using the password given in the +\fIpassword\fR +argument. +The +\fIflags\fR +argument are the same as for +zip_fopen(3). +.PP +The +\fBzip_fopen_index_encrypted\fR() +function opens the file at position +\fIindex\fR, +see +zip_fopen_index(3). +These functions are called automatically by +zip_fopen(3); +you only need to call them if you want to specify a non-default password +(see +zip_set_default_password(3)). +.SH "RETURN VALUES" +Upon successful completion, a +\fIstruct zip_file\fR +pointer is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +.TP 22n +[\fRZIP_ER_NOPASSWD\fR] +No password was provided. +.PP +The function +\fBzip_fopen_encrypted\fR() +may also fail and set +\fIzip_err\fR +for any of the errors specified for the routine +zip_fopen(3). +.PP +The function +\fBzip_fopen_index_encrypted\fR() +may also fail and set +\fIzip_err\fR +for any of the errors specified for the routine +zip_fopen_index(3). +.SH "SEE ALSO" +libzip(3), +zip_fclose(3), +zip_fopen(3), +zip_fread(3), +zip_get_num_entries(3), +zip_name_locate(3) +.SH "HISTORY" +\fBzip_fopen_encrypted\fR() +and +\fBzip_fopen_index_encrypted\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fopen_encrypted.mdoc b/third_party/libzip/man/zip_fopen_encrypted.mdoc new file mode 100644 index 0000000..fb159ce --- /dev/null +++ b/third_party/libzip/man/zip_fopen_encrypted.mdoc @@ -0,0 +1,117 @@ +.\" zip_fopen_encrypted.mdoc -- open encrypted file in zip archive for reading +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FOPEN_ENCRYPTED 3 +.Os +.Sh NAME +.Nm zip_fopen_encrypted , +.Nm zip_fopen_index_encrypted +.Nd open encrypted file in zip archive for reading +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_file_t * +.Fn zip_fopen_encrypted "zip_t *archive" "const char *fname" "zip_flags_t flags" "const char *password" +.Ft zip_file_t * +.Fn zip_fopen_index_encrypted "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" "const char *password" +.Sh DESCRIPTION +The +.Fn zip_fopen_encrypted +function opens the encrypted file name +.Ar fname +in +.Ar archive +using the password given in the +.Ar password +argument. +The +.Ar flags +argument are the same as for +.Xr zip_fopen 3 . +.Pp +The +.Fn zip_fopen_index_encrypted +function opens the file at position +.Ar index , +see +.Xr zip_fopen_index 3 . +These functions are called automatically by +.Xr zip_fopen 3 ; +you only need to call them if you want to specify a non-default password +(see +.Xr zip_set_default_password 3 ) . +.Sh RETURN VALUES +Upon successful completion, a +.Ft struct zip_file +pointer is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Bl -tag -width ZIP_ER_ENCRNOTSUPPXX +.It Bq Er ZIP_ER_NOPASSWD +No password was provided. +.El +.Pp +The function +.Fn zip_fopen_encrypted +may also fail and set +.Va zip_err +for any of the errors specified for the routine +.Xr zip_fopen 3 . +.Pp +The function +.Fn zip_fopen_index_encrypted +may also fail and set +.Va zip_err +for any of the errors specified for the routine +.Xr zip_fopen_index 3 . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fclose 3 , +.Xr zip_fopen 3 , +.Xr zip_fread 3 , +.Xr zip_get_num_entries 3 , +.Xr zip_name_locate 3 +.Sh HISTORY +.Fn zip_fopen_encrypted +and +.Fn zip_fopen_index_encrypted +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fread.html b/third_party/libzip/man/zip_fread.html new file mode 100644 index 0000000..d6f5b16 --- /dev/null +++ b/third_party/libzip/man/zip_fread.html @@ -0,0 +1,110 @@ + + + + + + + ZIP_FREAD(3) + + + + + + + + +
ZIP_FREAD(3)Library Functions ManualZIP_FREAD(3)
+
+
+

+zip_fread — +
read from file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_fread(zip_file_t + *file, void *buf, + zip_uint64_t nbytes);

+
+
+

+The zip_fread() function reads at most + nbytes bytes from file into + buf. +
+
+

+If successful, the number of bytes actually read is returned. Otherwise, -1 is + returned. +
+
+

+libzip(3), + zip_fclose(3), + zip_fopen(3), + zip_fseek(3) +
+
+

+zip_fread() was added in libzip 0.6. In libzip 0.10 the + return type was changed from ssize_t to + zip_int64_t. In libzip 0.10 the type of + nbytes was changed from size_t to + zip_uint64_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fread.man b/third_party/libzip/man/zip_fread.man new file mode 100644 index 0000000..d0eb517 --- /dev/null +++ b/third_party/libzip/man/zip_fread.man @@ -0,0 +1,83 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fread.mdoc -- read from file +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FREAD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fread\fR +\- read from file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_fread\fR(\fIzip_file_t\ *file\fR, \fIvoid\ *buf\fR, \fIzip_uint64_t\ nbytes\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_fread\fR() +function reads at most +\fInbytes\fR +bytes from +\fIfile\fR +into +\fIbuf\fR. +.SH "RETURN VALUES" +If successful, the number of bytes actually read is returned. +Otherwise, \-1 is returned. +.SH "SEE ALSO" +libzip(3), +zip_fclose(3), +zip_fopen(3), +zip_fseek(3) +.SH "HISTORY" +\fBzip_fread\fR() +was added in libzip 0.6. +In libzip 0.10 the return type was changed from +\fIssize_t\fR +to +\fIzip_int64_t\fR. +In libzip 0.10 the type of +\fInbytes\fR +was changed from +\fIsize_t\fR +to +\fIzip_uint64_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fread.mdoc b/third_party/libzip/man/zip_fread.mdoc new file mode 100644 index 0000000..4d3e8d6 --- /dev/null +++ b/third_party/libzip/man/zip_fread.mdoc @@ -0,0 +1,78 @@ +.\" zip_fread.mdoc -- read from file +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FREAD 3 +.Os +.Sh NAME +.Nm zip_fread +.Nd read from file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_fread "zip_file_t *file" "void *buf" "zip_uint64_t nbytes" +.Sh DESCRIPTION +The +.Fn zip_fread +function reads at most +.Ar nbytes +bytes from +.Ar file +into +.Ar buf . +.Sh RETURN VALUES +If successful, the number of bytes actually read is returned. +Otherwise, \-1 is returned. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fclose 3 , +.Xr zip_fopen 3 , +.Xr zip_fseek 3 +.Sh HISTORY +.Fn zip_fread +was added in libzip 0.6. +In libzip 0.10 the return type was changed from +.Vt ssize_t +to +.Vt zip_int64_t . +In libzip 0.10 the type of +.Ar nbytes +was changed from +.Vt size_t +to +.Vt zip_uint64_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_fseek.html b/third_party/libzip/man/zip_fseek.html new file mode 100644 index 0000000..7fb7f20 --- /dev/null +++ b/third_party/libzip/man/zip_fseek.html @@ -0,0 +1,110 @@ + + + + + + + ZIP_FSEEK(3) + + + + + + + + +
ZIP_FSEEK(3)Library Functions ManualZIP_FSEEK(3)
+
+
+

+zip_fseek — +
seek in file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int8_t +
+ zip_fseek(zip_file_t + *file, zip_int64_t + offset, int + whence);

+
+
+

+The zip_fseek() function seeks to the specified + offset relative to whence, just + like fseek(3). +

zip_fseek only works on uncompressed + (stored) data. When called on compressed data it will return an error.

+
+
+

+If successful, zip_fseek returns 0. Otherwise, -1 is + returned. +
+
+

+libzip(3), + zip_fclose(3), + zip_fopen(3), + zip_fread(3), + zip_ftell(3) +
+
+

+zip_fseek() was added in libzip 1.2.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_fseek.man b/third_party/libzip/man/zip_fseek.man new file mode 100644 index 0000000..d69e0e6 --- /dev/null +++ b/third_party/libzip/man/zip_fseek.man @@ -0,0 +1,80 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_fseek.mdoc -- seek in file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FSEEK" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_fseek\fR +\- seek in file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int8_t\fR +.br +.PD 0 +.HP 4n +\fBzip_fseek\fR(\fIzip_file_t\ *file\fR, \fIzip_int64_t\ offset\fR, \fIint\ whence\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_fseek\fR() +function seeks to the specified +\fIoffset\fR +relative to +\fIwhence\fR, +just like +fseek(3). +.PP +\fBzip_fseek\fR +only works on uncompressed (stored) data. +When called on compressed data it will return an error. +.SH "RETURN VALUES" +If successful, +\fBzip_fseek\fR +returns 0. +Otherwise, \-1 is returned. +.SH "SEE ALSO" +libzip(3), +zip_fclose(3), +zip_fopen(3), +zip_fread(3), +zip_ftell(3) +.SH "HISTORY" +\fBzip_fseek\fR() +was added in libzip 1.2.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_fseek.mdoc b/third_party/libzip/man/zip_fseek.mdoc new file mode 100644 index 0000000..756ca27 --- /dev/null +++ b/third_party/libzip/man/zip_fseek.mdoc @@ -0,0 +1,75 @@ +.\" zip_fseek.mdoc -- seek in file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FSEEK 3 +.Os +.Sh NAME +.Nm zip_fseek +.Nd seek in file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int8_t +.Fn zip_fseek "zip_file_t *file" "zip_int64_t offset" "int whence" +.Sh DESCRIPTION +The +.Fn zip_fseek +function seeks to the specified +.Ar offset +relative to +.Ar whence , +just like +.Xr fseek 3 . +.Pp +.Nm +only works on uncompressed (stored) data. +When called on compressed data it will return an error. +.Sh RETURN VALUES +If successful, +.Nm +returns 0. +Otherwise, \-1 is returned. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fclose 3 , +.Xr zip_fopen 3 , +.Xr zip_fread 3 , +.Xr zip_ftell 3 +.Sh HISTORY +.Fn zip_fseek +was added in libzip 1.2.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_ftell.html b/third_party/libzip/man/zip_ftell.html new file mode 100644 index 0000000..d38061a --- /dev/null +++ b/third_party/libzip/man/zip_ftell.html @@ -0,0 +1,107 @@ + + + + + + + ZIP_FTELL(3) + + + + + + + + +
ZIP_FTELL(3)Library Functions ManualZIP_FTELL(3)
+
+
+

+zip_ftell — +
tell position in file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_ftell(zip_file_t + *file);

+
+
+

+The zip_ftell() function reports the current offset in + the file. +

zip_ftell only works on uncompressed + (stored) data. When called on compressed data it will return an error.

+
+
+

+If successful, zip_ftell returns the current file + position. Otherwise, -1 is returned. +
+
+

+libzip(3), + zip_fclose(3), + zip_fopen(3), + zip_fread(3), + zip_fseek(3) +
+
+

+zip_ftell() was added in libzip 1.2.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_ftell.man b/third_party/libzip/man/zip_ftell.man new file mode 100644 index 0000000..9f87de8 --- /dev/null +++ b/third_party/libzip/man/zip_ftell.man @@ -0,0 +1,75 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_ftell.mdoc -- tell position in file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_FTELL" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_ftell\fR +\- tell position in file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_ftell\fR(\fIzip_file_t\ *file\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_ftell\fR() +function reports the current offset in the file. +.PP +\fBzip_ftell\fR +only works on uncompressed (stored) data. +When called on compressed data it will return an error. +.SH "RETURN VALUES" +If successful, +\fBzip_ftell\fR +returns the current file position. +Otherwise, \-1 is returned. +.SH "SEE ALSO" +libzip(3), +zip_fclose(3), +zip_fopen(3), +zip_fread(3), +zip_fseek(3) +.SH "HISTORY" +\fBzip_ftell\fR() +was added in libzip 1.2.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_ftell.mdoc b/third_party/libzip/man/zip_ftell.mdoc new file mode 100644 index 0000000..2638d5d --- /dev/null +++ b/third_party/libzip/man/zip_ftell.mdoc @@ -0,0 +1,70 @@ +.\" zip_ftell.mdoc -- tell position in file +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_FTELL 3 +.Os +.Sh NAME +.Nm zip_ftell +.Nd tell position in file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_ftell "zip_file_t *file" +.Sh DESCRIPTION +The +.Fn zip_ftell +function reports the current offset in the file. +.Pp +.Nm +only works on uncompressed (stored) data. +When called on compressed data it will return an error. +.Sh RETURN VALUES +If successful, +.Nm +returns the current file position. +Otherwise, \-1 is returned. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fclose 3 , +.Xr zip_fopen 3 , +.Xr zip_fread 3 , +.Xr zip_fseek 3 +.Sh HISTORY +.Fn zip_ftell +was added in libzip 1.2.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_archive_comment.html b/third_party/libzip/man/zip_get_archive_comment.html new file mode 100644 index 0000000..e2b8e32 --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_comment.html @@ -0,0 +1,130 @@ + + + + + + + ZIP_GET_ARCHIVE_COMMENT(3) + + + + + + + + +
ZIP_GET_ARCHIVE_COMMENT(3)Library Functions ManualZIP_GET_ARCHIVE_COMMENT(3)
+
+
+

+zip_get_archive_comment — +
get zip archive comment
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_get_archive_comment(zip_t + *archive, int + *lenp, zip_flags_t + flags);

+
+
+

+The zip_get_archive_comment() function returns the + comment for the entire zip archive. The return value is in UTF-8 encoding + unless ZIP_FL_ENC_RAW was specified (see below). This + pointer should not be modified or + free(3)'d, and becomes invalid when + archive is closed. If lenp is not + NULL, the integer to which it points will be set to + the length of the comment. If flags is set to + ZIP_FL_UNCHANGED, the original unchanged comment is + returned. +

Additionally, the following flags are + supported:

+
+
+
+
Return the unmodified archive comment as it is in the ZIP archive.
+
+
(Default.) Guess the encoding of the archive comment in the ZIP archive + and convert it to UTF-8, if necessary.
+
+
Follow the ZIP specification for file names and extend it to the archive + comment, thus also expecting it in CP-437 encoding. Convert it to + UTF-8.
+
+
+Note: ASCII is a subset of both CP-437 and UTF-8. +
+
+

+Upon successful completion, a pointer to the comment is returned, or + NULL if there is no comment. +
+
+

+libzip(3), + zip_file_get_comment(3) +
+
+

+zip_get_archive_comment() was added in libzip 0.7. In + libzip 0.11 the type of flags was changed from + int to zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
July 22, 2018NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_archive_comment.man b/third_party/libzip/man/zip_get_archive_comment.man new file mode 100644 index 0000000..8cdfa30 --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_comment.man @@ -0,0 +1,114 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_archive_comment.mdoc -- get zip archive comment +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_ARCHIVE_COMMENT" "3" "July 22, 2018" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_archive_comment\fR +\- get zip archive comment +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_get_archive_comment\fR(\fIzip_t\ *archive\fR, \fIint\ *lenp\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_archive_comment\fR() +function returns the comment for the entire zip archive. +The return value is in UTF-8 encoding unless +\fRZIP_FL_ENC_RAW\fR +was specified (see below). +This pointer should not be modified or +free(3)'d, +and becomes invalid when +\fIarchive\fR +is closed. +If +\fIlenp\fR +is not +\fRNULL\fR, +the integer to which it points will be set to the length of the +comment. +If +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original unchanged comment is returned. +.PP +Additionally, the following +\fIflags\fR +are supported: +.RS 6n +.TP 21n +\fRZIP_FL_ENC_RAW\fR +Return the unmodified archive comment as it is in the ZIP archive. +.TP 21n +\fRZIP_FL_ENC_GUESS\fR +(Default.) +Guess the encoding of the archive comment in the ZIP archive and convert it +to UTF-8, if necessary. +.TP 21n +\fRZIP_FL_ENC_STRICT\fR +Follow the ZIP specification for file names and extend it to the +archive comment, thus also expecting it in CP-437 encoding. +Convert it to UTF-8. +.RE +\fINote\fR: +ASCII is a subset of both CP-437 and UTF-8. +.SH "RETURN VALUES" +Upon successful completion, a pointer to the comment is returned, +or +\fRNULL\fR +if there is no comment. +.SH "SEE ALSO" +libzip(3), +zip_file_get_comment(3) +.SH "HISTORY" +\fBzip_get_archive_comment\fR() +was added in libzip 0.7. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_archive_comment.mdoc b/third_party/libzip/man/zip_get_archive_comment.mdoc new file mode 100644 index 0000000..ce9a01b --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_comment.mdoc @@ -0,0 +1,111 @@ +.\" zip_get_archive_comment.mdoc -- get zip archive comment +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd July 22, 2018 +.Dt ZIP_GET_ARCHIVE_COMMENT 3 +.Os +.Sh NAME +.Nm zip_get_archive_comment +.Nd get zip archive comment +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_get_archive_comment "zip_t *archive" "int *lenp" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_get_archive_comment +function returns the comment for the entire zip archive. +The return value is in UTF-8 encoding unless +.Dv ZIP_FL_ENC_RAW +was specified (see below). +This pointer should not be modified or +.Xr free 3 Ap d , +and becomes invalid when +.Ar archive +is closed. +If +.Ar lenp +is not +.Dv NULL , +the integer to which it points will be set to the length of the +comment. +If +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original unchanged comment is returned. +.Pp +Additionally, the following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_ENC_STRICTXX -offset indent +.It Dv ZIP_FL_ENC_RAW +Return the unmodified archive comment as it is in the ZIP archive. +.It Dv ZIP_FL_ENC_GUESS +(Default.) +Guess the encoding of the archive comment in the ZIP archive and convert it +to UTF-8, if necessary. +.It Dv ZIP_FL_ENC_STRICT +Follow the ZIP specification for file names and extend it to the +archive comment, thus also expecting it in CP-437 encoding. +Convert it to UTF-8. +.El +.Em Note : +ASCII is a subset of both CP-437 and UTF-8. +.Sh RETURN VALUES +Upon successful completion, a pointer to the comment is returned, +or +.Dv NULL +if there is no comment. +.\" In case of an error, +.\" .Dv NULL +.\" is returned and the error code in +.\" .Ar archive +.\" is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_get_comment 3 +.Sh HISTORY +.Fn zip_get_archive_comment +was added in libzip 0.7. +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_archive_flag.html b/third_party/libzip/man/zip_get_archive_flag.html new file mode 100644 index 0000000..1299aca --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_flag.html @@ -0,0 +1,118 @@ + + + + + + + ZIP_GET_ARCHIVE_FLAG(3) + + + + + + + + +
ZIP_GET_ARCHIVE_FLAG(3)Library Functions ManualZIP_GET_ARCHIVE_FLAG(3)
+
+
+

+zip_get_archive_flag — +
get status flags for zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_get_archive_flag(zip_t + *archive, zip_flags_t + flag, zip_flags_t + flags);

+
+
+

+The zip_get_archive_flag() function returns if the flag + flag is set for the archive + archive. The archive flags might have been changed with + zip_set_archive_flag(); if flags + is set to ZIP_FL_UNCHANGED, the original unchanged + flags are tested. +

Supported flags are:

+
+
+
The archive is read-only.
+
+
+
+

+zip_get_archive_flag() returns 1 if + flag is set for archive, 0 if not, + and -1 if an error occurred. +
+
+

+libzip(3), + zip_set_archive_flag(3) +
+
+

+zip_get_archive_flag() was added in libzip 0.9. In + libzip 0.11 the type of flag was changed from + int to zip_flags_t m and the type + of flags was changed from int to + zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_archive_flag.man b/third_party/libzip/man/zip_get_archive_flag.man new file mode 100644 index 0000000..4f9d08b --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_flag.man @@ -0,0 +1,98 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_archive_flag.mdoc -- get comment for file in zip +.\" Copyright (C) 2008-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_ARCHIVE_FLAG" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_archive_flag\fR +\- get status flags for zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_get_archive_flag\fR(\fIzip_t\ *archive\fR, \fIzip_flags_t\ flag\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_archive_flag\fR() +function returns if the flag +\fIflag\fR +is set for the archive +\fIarchive\fR. +The archive flags might have been changed with +\fBzip_set_archive_flag\fR(); +if +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original unchanged flags are tested. +.PP +Supported flags are: +.TP 20n +\fRZIP_AFL_RDONLY\fR +The archive is read-only. +.SH "RETURN VALUES" +\fBzip_get_archive_flag\fR() +returns 1 if +\fIflag\fR +is set for +\fIarchive\fR, +0 if not, +and \-1 if an error occurred. +.SH "SEE ALSO" +libzip(3), +zip_set_archive_flag(3) +.SH "HISTORY" +\fBzip_get_archive_flag\fR() +was added in libzip 0.9. +In libzip 0.11 the type of +\fIflag\fR +was changed from +\fIint\fR +to +\fIzip_flags_t m\fR +and the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_archive_flag.mdoc b/third_party/libzip/man/zip_get_archive_flag.mdoc new file mode 100644 index 0000000..baf6b05 --- /dev/null +++ b/third_party/libzip/man/zip_get_archive_flag.mdoc @@ -0,0 +1,94 @@ +.\" zip_get_archive_flag.mdoc -- get comment for file in zip +.\" Copyright (C) 2008-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_ARCHIVE_FLAG 3 +.Os +.Sh NAME +.Nm zip_get_archive_flag +.Nd get status flags for zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_get_archive_flag "zip_t *archive" "zip_flags_t flag" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_get_archive_flag +function returns if the flag +.Ar flag +is set for the archive +.Ar archive . +The archive flags might have been changed with +.Fn zip_set_archive_flag ; +if +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original unchanged flags are tested. +.Pp +Supported flags are: +.Bl -tag -width XZIPXAFLXRDONLYXXX +.It Dv ZIP_AFL_RDONLY +The archive is read-only. +.El +.Sh RETURN VALUES +.Fn zip_get_archive_flag +returns 1 if +.Ar flag +is set for +.Ar archive , +0 if not, +and \-1 if an error occurred. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_set_archive_flag 3 +.Sh HISTORY +.Fn zip_get_archive_flag +was added in libzip 0.9. +In libzip 0.11 the type of +.Ar flag +was changed from +.Vt int +to +.Vt zip_flags_t m +and the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_error.html b/third_party/libzip/man/zip_get_error.html new file mode 100644 index 0000000..f7f50e1 --- /dev/null +++ b/third_party/libzip/man/zip_get_error.html @@ -0,0 +1,97 @@ + + + + + + + ZIP_GET_ERROR(3) + + + + + + + + +
ZIP_GET_ERROR(3)Library Functions ManualZIP_GET_ERROR(3)
+
+
+

+zip_get_error — +
get zip error for archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_error_t * +
+ zip_get_error(zip_t + *archive);

+
+
+

+The zip_get_error() function returns the zip error for + the zip archive archive. +
+
+

+libzip(3), + zip_error_code_system(3), + zip_error_code_zip(3) +
+
+

+zip_get_error() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_error.man b/third_party/libzip/man/zip_get_error.man new file mode 100644 index 0000000..9cddbc2 --- /dev/null +++ b/third_party/libzip/man/zip_get_error.man @@ -0,0 +1,65 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_error.mdoc -- get zip_error for archive +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_ERROR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_error\fR +\- get zip error for archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_error_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_get_error\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_error\fR() +function returns the zip error for the zip archive +\fIarchive\fR. +.SH "SEE ALSO" +libzip(3), +zip_error_code_system(3), +zip_error_code_zip(3) +.SH "HISTORY" +\fBzip_get_error\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_error.mdoc b/third_party/libzip/man/zip_get_error.mdoc new file mode 100644 index 0000000..8ce2ea5 --- /dev/null +++ b/third_party/libzip/man/zip_get_error.mdoc @@ -0,0 +1,60 @@ +.\" zip_get_error.mdoc -- get zip_error for archive +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_ERROR 3 +.Os +.Sh NAME +.Nm zip_get_error +.Nd get zip error for archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_error_t * +.Fn zip_get_error "zip_t *archive" +.Sh DESCRIPTION +The +.Fn zip_get_error +function returns the zip error for the zip archive +.Ar archive . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_system 3 , +.Xr zip_error_code_zip 3 +.Sh HISTORY +.Fn zip_get_error +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_file_comment.html b/third_party/libzip/man/zip_get_file_comment.html new file mode 100644 index 0000000..7242ee4 --- /dev/null +++ b/third_party/libzip/man/zip_get_file_comment.html @@ -0,0 +1,105 @@ + + + + + + + ZIP_GET_FILE_COMMENT(3) + + + + + + + + +
ZIP_GET_FILE_COMMENT(3)Library Functions ManualZIP_GET_FILE_COMMENT(3)
+
+
+

+zip_get_file_comment — +
get comment for file in zip (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_get_file_comment(zip_t + *archive, zip_uint64_t + index, int *lenp, + int flags);

+
+
+

+The zip_get_file_comment() function is the obsolete + version of + zip_file_get_comment(3). + The only differences are the types of the lenp and + flags arguments. +
+
+

+libzip(3), + zip_file_get_comment(3) +
+
+

+zip_get_file_comment() was added in libzip 0.7. In + libzip 0.10 the type of index was changed from + int to zip_uint64_t. It was + deprecated in libzip 0.11, use zip_file_get_comment() + instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_file_comment.man b/third_party/libzip/man/zip_get_file_comment.man new file mode 100644 index 0000000..011871d --- /dev/null +++ b/third_party/libzip/man/zip_get_file_comment.man @@ -0,0 +1,78 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_file_comment.mdoc -- get comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_FILE_COMMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_file_comment\fR +\- get comment for file in zip (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_get_file_comment\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIint\ *lenp\fR, \fIint\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_file_comment\fR() +function is the obsolete version of +zip_file_get_comment(3). +The only differences are the types of the +\fIlenp\fR +and +\fIflags\fR +arguments. +.SH "SEE ALSO" +libzip(3), +zip_file_get_comment(3) +.SH "HISTORY" +\fBzip_get_file_comment\fR() +was added in libzip 0.7. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_file_get_comment\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_file_comment.mdoc b/third_party/libzip/man/zip_get_file_comment.mdoc new file mode 100644 index 0000000..a22159e --- /dev/null +++ b/third_party/libzip/man/zip_get_file_comment.mdoc @@ -0,0 +1,73 @@ +.\" zip_get_file_comment.mdoc -- get comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_FILE_COMMENT 3 +.Os +.Sh NAME +.Nm zip_get_file_comment +.Nd get comment for file in zip (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_get_file_comment "zip_t *archive" "zip_uint64_t index" "int *lenp" "int flags" +.Sh DESCRIPTION +The +.Fn zip_get_file_comment +function is the obsolete version of +.Xr zip_file_get_comment 3 . +The only differences are the types of the +.Ar lenp +and +.Ar flags +arguments. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_get_comment 3 +.Sh HISTORY +.Fn zip_get_file_comment +was added in libzip 0.7. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +It was deprecated in libzip 0.11, use +.Fn zip_file_get_comment +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_name.html b/third_party/libzip/man/zip_get_name.html new file mode 100644 index 0000000..e68dbbc --- /dev/null +++ b/third_party/libzip/man/zip_get_name.html @@ -0,0 +1,146 @@ + + + + + + + ZIP_GET_NAME(3) + + + + + + + + +
ZIP_GET_NAME(3)Library Functions ManualZIP_GET_NAME(3)
+
+
+

+zip_get_name — +
get name of file by index
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

const char * +
+ zip_get_name(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags);

+
+
+

+The zip_get_name() function returns the name of the file + at position index in archive. The + name is in UTF-8 encoding unless ZIP_FL_ENC_RAW was + specified (see below). +

If flags is set to + ZIP_FL_UNCHANGED, the original unchanged filename is + returned. The returned string must not be modified or freed, and becomes + invalid when archive is closed.

+

Additionally, the following flags are + supported:

+
+
+
+
Return the unmodified names as it is in the ZIP archive.
+
+
(Default.) Guess the encoding of the name in the ZIP archive and convert + it to UTF-8, if necessary.
+
+
Follow the ZIP specification and expect CP-437 encoded names in the ZIP + archive (except if they are explicitly marked as UTF-8). Convert it to + UTF-8.
+
+
+Note: ASCII is a subset of both CP-437 and UTF-8. +
+
+

+Upon successful completion, a pointer to the name is returned. Otherwise, + NULL and the error code in + archive is set to indicate the error. +
+
+

+zip_get_name() fails if: +
+
[]
+
index refers to a file that has been deleted (see + zip_delete(3)).
+
[]
+
index is not a valid file index in + archive, or index points to an + added file and ZIP_FL_UNCHANGED is set.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_name_locate(3) +
+
+

+zip_get_name() was added in libzip 0.6. In libzip 0.10 + the type of index was changed from + int to zip_uint64_t. In libzip + 0.11 the type of flags was changed from + int to zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_name.man b/third_party/libzip/man/zip_get_name.man new file mode 100644 index 0000000..a83ca8e --- /dev/null +++ b/third_party/libzip/man/zip_get_name.man @@ -0,0 +1,140 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_name.mdoc -- get name of file by index +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_NAME" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_name\fR +\- get name of file by index +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_get_name\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_name\fR() +function returns the name of the file at position +\fIindex\fR +in +\fIarchive\fR. +The name is in UTF-8 encoding unless +\fRZIP_FL_ENC_RAW\fR +was specified (see below). +.PP +If +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original unchanged filename is returned. +The returned string must not be modified or freed, and becomes invalid when +\fIarchive\fR +is closed. +.PP +Additionally, the following +\fIflags\fR +are supported: +.RS 6n +.TP 21n +\fRZIP_FL_ENC_RAW\fR +Return the unmodified names as it is in the ZIP archive. +.TP 21n +\fRZIP_FL_ENC_GUESS\fR +(Default.) +Guess the encoding of the name in the ZIP archive and convert it +to UTF-8, if necessary. +.TP 21n +\fRZIP_FL_ENC_STRICT\fR +Follow the ZIP specification and expect CP-437 encoded names in +the ZIP archive (except if they are explicitly marked as UTF-8). +Convert it to UTF-8. +.RE +\fINote\fR: +ASCII is a subset of both CP-437 and UTF-8. +.SH "RETURN VALUES" +Upon successful completion, a pointer to the name is returned. +Otherwise, +\fRNULL\fR +and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_get_name\fR() +fails if: +.TP 19n +[\fRZIP_ER_DELETED\fR] +\fIindex\fR +refers to a file that has been deleted +(see +zip_delete(3)). +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +or +\fIindex\fR +points to an added file and +\fRZIP_FL_UNCHANGED\fR +is set. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_name_locate(3) +.SH "HISTORY" +\fBzip_get_name\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_name.mdoc b/third_party/libzip/man/zip_get_name.mdoc new file mode 100644 index 0000000..27084f4 --- /dev/null +++ b/third_party/libzip/man/zip_get_name.mdoc @@ -0,0 +1,131 @@ +.\" zip_get_name.mdoc -- get name of file by index +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_NAME 3 +.Os +.Sh NAME +.Nm zip_get_name +.Nd get name of file by index +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_get_name "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_get_name +function returns the name of the file at position +.Ar index +in +.Ar archive . +The name is in UTF-8 encoding unless +.Dv ZIP_FL_ENC_RAW +was specified (see below). +.Pp +If +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original unchanged filename is returned. +The returned string must not be modified or freed, and becomes invalid when +.Ar archive +is closed. +.Pp +Additionally, the following +.Ar flags +are supported: +.Bl -tag -width ZIP_FL_ENC_STRICTXX -offset indent +.It Dv ZIP_FL_ENC_RAW +Return the unmodified names as it is in the ZIP archive. +.It Dv ZIP_FL_ENC_GUESS +(Default.) +Guess the encoding of the name in the ZIP archive and convert it +to UTF-8, if necessary. +.It Dv ZIP_FL_ENC_STRICT +Follow the ZIP specification and expect CP-437 encoded names in +the ZIP archive (except if they are explicitly marked as UTF-8). +Convert it to UTF-8. +.El +.Em Note : +ASCII is a subset of both CP-437 and UTF-8. +.Sh RETURN VALUES +Upon successful completion, a pointer to the name is returned. +Otherwise, +.Dv NULL +and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_get_name +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_DELETED +.Ar index +refers to a file that has been deleted +(see +.Xr zip_delete 3 ) . +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive , +or +.Ar index +points to an added file and +.Dv ZIP_FL_UNCHANGED +is set. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_name_locate 3 +.Sh HISTORY +.Fn zip_get_name +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_num_entries.html b/third_party/libzip/man/zip_get_num_entries.html new file mode 100644 index 0000000..a81a1ab --- /dev/null +++ b/third_party/libzip/man/zip_get_num_entries.html @@ -0,0 +1,111 @@ + + + + + + + ZIP_GET_NUM_ENTRIES(3) + + + + + + + + +
ZIP_GET_NUM_ENTRIES(3)Library Functions ManualZIP_GET_NUM_ENTRIES(3)
+
+
+

+zip_get_num_entries — +
get number of files in archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_get_num_entries(zip_t + *archive, zip_flags_t + flags);

+
+
+

+The zip_get_num_entries() function returns the number of + files in archive. If flags is set + to ZIP_FL_UNCHANGED, the original number of entries is + returned. +
+
+

+zip_get_num_entries() returns the number of files in the + zip archive, or -1 if archive is + NULL. +
+
+

+libzip(3), + zip_fopen_index(3), + zip_stat_index(3) +
+
+

+zip_get_num_entries() was added in libzip 0.10. In + libzip 0.11 the return type was changed from + zip_uint64_t to zip_int64_t. In + libzip 0.11 the type of flags was changed from + int to zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_num_entries.man b/third_party/libzip/man/zip_get_num_entries.man new file mode 100644 index 0000000..f33f6ec --- /dev/null +++ b/third_party/libzip/man/zip_get_num_entries.man @@ -0,0 +1,87 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_num_entries.mdoc -- get number of files in archive +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_NUM_ENTRIES" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_num_entries\fR +\- get number of files in archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_get_num_entries\fR(\fIzip_t\ *archive\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_get_num_entries\fR() +function returns the number of files in +\fIarchive\fR. +If +\fIflags\fR +is set to +\fRZIP_FL_UNCHANGED\fR, +the original number of entries is returned. +.SH "RETURN VALUES" +\fBzip_get_num_entries\fR() +returns the number of files in the zip archive, +or \-1 if +\fIarchive\fR +is +\fRNULL\fR. +.SH "SEE ALSO" +libzip(3), +zip_fopen_index(3), +zip_stat_index(3) +.SH "HISTORY" +\fBzip_get_num_entries\fR() +was added in libzip 0.10. +In libzip 0.11 the return type was changed from +\fIzip_uint64_t\fR +to +\fIzip_int64_t\fR. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_num_entries.mdoc b/third_party/libzip/man/zip_get_num_entries.mdoc new file mode 100644 index 0000000..bfc7005 --- /dev/null +++ b/third_party/libzip/man/zip_get_num_entries.mdoc @@ -0,0 +1,82 @@ +.\" zip_get_num_entries.mdoc -- get number of files in archive +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_NUM_ENTRIES 3 +.Os +.Sh NAME +.Nm zip_get_num_entries +.Nd get number of files in archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_get_num_entries "zip_t *archive" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_get_num_entries +function returns the number of files in +.Ar archive . +If +.Ar flags +is set to +.Dv ZIP_FL_UNCHANGED , +the original number of entries is returned. +.Sh RETURN VALUES +.Fn zip_get_num_entries +returns the number of files in the zip archive, +or \-1 if +.Ar archive +is +.Dv NULL . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fopen_index 3 , +.Xr zip_stat_index 3 +.Sh HISTORY +.Fn zip_get_num_entries +was added in libzip 0.10. +In libzip 0.11 the return type was changed from +.Vt zip_uint64_t +to +.Vt zip_int64_t . +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_get_num_files.html b/third_party/libzip/man/zip_get_num_files.html new file mode 100644 index 0000000..82b8a85 --- /dev/null +++ b/third_party/libzip/man/zip_get_num_files.html @@ -0,0 +1,110 @@ + + + + + + + ZIP_GET_NUM_FILES(3) + + + + + + + + +
ZIP_GET_NUM_FILES(3)Library Functions ManualZIP_GET_NUM_FILES(3)
+
+
+

+zip_get_num_files — +
get number of files in archive (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_get_num_files(zip_t + *archive);

+
+
+

+This function is deprecated. Use + zip_get_num_entries(3) + instead. +

The zip_get_num_files() function returns + the number of files in archive.

+
+
+

+zip_get_num_files() returns the number of files in the + zip archive, or -1 if archive is + NULL. +
+
+

+libzip(3), + zip_fopen_index(3), + zip_stat_index(3) +
+
+

+zip_get_num_files() was added in libzip 0.6. It was + deprecated in libzip 0.11, use + zip_get_num_entries(instead) + instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_get_num_files.man b/third_party/libzip/man/zip_get_num_files.man new file mode 100644 index 0000000..0760eed --- /dev/null +++ b/third_party/libzip/man/zip_get_num_files.man @@ -0,0 +1,80 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_get_num_files.mdoc -- get number of files in archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_GET_NUM_FILES" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_get_num_files\fR +\- get number of files in archive (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_get_num_files\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +\fIThis function is deprecated\fR. +\fIUse\fR +zip_get_num_entries(3) +\fIinstead\fR. +.PP +The +\fBzip_get_num_files\fR() +function returns the number of files in +\fIarchive\fR. +.SH "RETURN VALUES" +\fBzip_get_num_files\fR() +returns the number of files in the zip archive, +or \-1 if +\fIarchive\fR +is +\fRNULL\fR. +.SH "SEE ALSO" +libzip(3), +zip_fopen_index(3), +zip_stat_index(3) +.SH "HISTORY" +\fBzip_get_num_files\fR() +was added in libzip 0.6. +It was deprecated in libzip 0.11, use +\fBzip_get_num_entries\fR(\fIinstead\fR) +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_get_num_files.mdoc b/third_party/libzip/man/zip_get_num_files.mdoc new file mode 100644 index 0000000..30ebbc3 --- /dev/null +++ b/third_party/libzip/man/zip_get_num_files.mdoc @@ -0,0 +1,75 @@ +.\" zip_get_num_files.mdoc -- get number of files in archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_GET_NUM_FILES 3 +.Os +.Sh NAME +.Nm zip_get_num_files +.Nd get number of files in archive (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_get_num_files "zip_t *archive" +.Sh DESCRIPTION +.Em This function is deprecated . +.Em Use +.Xr zip_get_num_entries 3 +.Em instead . +.Pp +The +.Fn zip_get_num_files +function returns the number of files in +.Ar archive . +.Sh RETURN VALUES +.Fn zip_get_num_files +returns the number of files in the zip archive, +or \-1 if +.Ar archive +is +.Dv NULL . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fopen_index 3 , +.Xr zip_stat_index 3 +.Sh HISTORY +.Fn zip_get_num_files +was added in libzip 0.6. +It was deprecated in libzip 0.11, use +.Fn zip_get_num_entries instead +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_libzip_version.html b/third_party/libzip/man/zip_libzip_version.html new file mode 100644 index 0000000..ed1b794 --- /dev/null +++ b/third_party/libzip/man/zip_libzip_version.html @@ -0,0 +1,88 @@ + + + + + + + ZIP_LIBZIP_VERSION(3) + + + + + + + + +
ZIP_LIBZIP_VERSION(3)Library Functions ManualZIP_LIBZIP_VERSION(3)
+
+

+zip_libzip_version — +
return run-time version of library
+

+libzip (-lzip) +

+#include + <zip.h> +
+const char * +
+zip_libzip_version(void); +

+zip_libzip_version returns the version number + of the library as string in the format + “$MAJOR.$MINOR.$MICRO$SUFFIX” where + $MAJOR is the major version, + $MINOR the minor, + $MICRO the micro, and + $SUFFIX a suffix that's only set for + development versions. +

+libzip(3) +

+zip_libzip_version() was added in libzip + 1.3.1. +

+Dieter Baron + <dillo@nih.at> + and Thomas Klausner + <tk@giga.or.at>
+ + + + + +
December 18, 2017NetBSD 8.99.27
+ + diff --git a/third_party/libzip/man/zip_libzip_version.man b/third_party/libzip/man/zip_libzip_version.man new file mode 100644 index 0000000..3b2bcee --- /dev/null +++ b/third_party/libzip/man/zip_libzip_version.man @@ -0,0 +1,71 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_libzip_version.mdoc -- return run-time version of library +.\" Copyright (C) 2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_LIBZIP_VERSION" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_libzip_version\fR +\- return run-time version of library +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIconst char *\fR +.br +.PD 0 +.HP 4n +\fBzip_libzip_version\fR(\fIvoid\fR); +.PD +.SH "DESCRIPTION" +\fBzip_libzip_version\fR +returns the version number of the library as string in the format +\(lq$MAJOR.$MINOR.$MICRO$SUFFIX\(rq +where +\fI$MAJOR\fR +is the major version, +\fI$MINOR\fR +the minor, +\fI$MICRO\fR +the micro, and +\fI$SUFFIX\fR +a suffix that's only set for development versions. +.SH "SEE ALSO" +libzip(3) +.SH "HISTORY" +\fBzip_libzip_version\fR() +was added in libzip 1.3.1. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_libzip_version.mdoc b/third_party/libzip/man/zip_libzip_version.mdoc new file mode 100644 index 0000000..8973736 --- /dev/null +++ b/third_party/libzip/man/zip_libzip_version.mdoc @@ -0,0 +1,66 @@ +.\" zip_libzip_version.mdoc -- return run-time version of library +.\" Copyright (C) 2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_LIBZIP_VERSION 3 +.Os +.Sh NAME +.Nm zip_libzip_version +.Nd return run-time version of library +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft const char * +.Fn zip_libzip_version void +.Sh DESCRIPTION +.Nm +returns the version number of the library as string in the format +.Dq $MAJOR.$MINOR.$MICRO$SUFFIX +where +.Ar $MAJOR +is the major version, +.Ar $MINOR +the minor, +.Ar $MICRO +the micro, and +.Ar $SUFFIX +a suffix that's only set for development versions. +.Sh SEE ALSO +.Xr libzip 3 +.Sh HISTORY +.Fn zip_libzip_version +was added in libzip 1.3.1. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_name_locate.html b/third_party/libzip/man/zip_name_locate.html new file mode 100644 index 0000000..6648724 --- /dev/null +++ b/third_party/libzip/man/zip_name_locate.html @@ -0,0 +1,148 @@ + + + + + + + ZIP_NAME_LOCATE(3) + + + + + + + + +
ZIP_NAME_LOCATE(3)Library Functions ManualZIP_NAME_LOCATE(3)
+
+
+

+zip_name_locate — +
get index of file by name
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_name_locate(zip_t + *archive, const char + *fname, zip_flags_t + flags);

+
+
+

+The zip_name_locate() function returns the index of the + file named fname in archive. If + archive does not contain a file with that name, -1 is + returned. The flags are specified by + or'ing the following values, or 0 + for none of them. +
+
+
+
Ignore case distinctions. (Will only work well if the file names are + ASCII.) With this flag, zip_name_locate() will be + slow for archives with many files.
+
+
Ignore directory part of file name in archive. With this flag, + zip_name_locate() will be slow for archives with + many files.
+
+
Compare against the unmodified names as it is in the ZIP archive.
+
+
(Default.) Guess the encoding of the name in the ZIP archive and convert + it to UTF-8, if necessary, before comparing.
+
+
Follow the ZIP specification and expect CP-437 encoded names in the ZIP + archive (except if they are explicitly marked as UTF-8). Convert it to + UTF-8 before comparing.
+
+
+Note: ASCII is a subset of both CP-437 and UTF-8. +
+
+

+zip_name_locate() returns the index of the file named + fname or -1, if archive does not + contain an entry of that name. +
+
+

+zip_name_locate() fails if: +
+
[]
+
One of the arguments is invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
No entry of the name fname is found in the + archive.
+
+
+
+

+libzip(3), + zip_get_name(3) +
+
+

+zip_name_locate() was added in libzip 0.6. In libzip + 0.11 the return type was changed from int to + zip_int64_t. In libzip 0.11 the type of + flags was changed from int to + zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_name_locate.man b/third_party/libzip/man/zip_name_locate.man new file mode 100644 index 0000000..c8acfae --- /dev/null +++ b/third_party/libzip/man/zip_name_locate.man @@ -0,0 +1,136 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_name_locate.mdoc -- get index of file by name +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_NAME_LOCATE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_name_locate\fR +\- get index of file by name +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_name_locate\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_flags_t\ flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_name_locate\fR() +function returns the index of the file named +\fIfname\fR +in +\fIarchive\fR. +If +\fIarchive\fR +does not contain a file with that name, \-1 is returned. +The +\fIflags\fR +are specified by +\fIor\fR'ing +the following values, or 0 for none of them. +.RS 6n +.TP 15n +\fRZIP_FL_NOCASE\fR +Ignore case distinctions. +(Will only work well if the file names are ASCII.) +With this flag, +\fBzip_name_locate\fR() +will be slow for archives with many files. +.TP 15n +\fRZIP_FL_NODIR\fR +Ignore directory part of file name in archive. +With this flag, +\fBzip_name_locate\fR() +will be slow for archives with many files. +.TP 15n +\fRZIP_FL_ENC_RAW\fR +.br +Compare against the unmodified names as it is in the ZIP archive. +.TP 15n +\fRZIP_FL_ENC_GUESS\fR +(Default.) +Guess the encoding of the name in the ZIP archive and convert it +to UTF-8, if necessary, before comparing. +.TP 15n +\fRZIP_FL_ENC_STRICT\fR +Follow the ZIP specification and expect CP-437 encoded names in +the ZIP archive (except if they are explicitly marked as UTF-8). +Convert it to UTF-8 before comparing. +.RE +\fINote\fR: +ASCII is a subset of both CP-437 and UTF-8. +.SH "RETURN VALUES" +\fBzip_name_locate\fR() +returns the index of the file named +\fIfname\fR +or \-1, if +\fIarchive\fR +does not contain an entry of that name. +.SH "ERRORS" +\fBzip_name_locate\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +One of the arguments is invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOENT\fR] +No entry of the name +\fIfname\fR +is found in the archive. +.SH "SEE ALSO" +libzip(3), +zip_get_name(3) +.SH "HISTORY" +\fBzip_name_locate\fR() +was added in libzip 0.6. +In libzip 0.11 the return type was changed from +\fIint\fR +to +\fIzip_int64_t\fR. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_name_locate.mdoc b/third_party/libzip/man/zip_name_locate.mdoc new file mode 100644 index 0000000..d16402d --- /dev/null +++ b/third_party/libzip/man/zip_name_locate.mdoc @@ -0,0 +1,124 @@ +.\" zip_name_locate.mdoc -- get index of file by name +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_NAME_LOCATE 3 +.Os +.Sh NAME +.Nm zip_name_locate +.Nd get index of file by name +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_name_locate "zip_t *archive" "const char *fname" "zip_flags_t flags" +.Sh DESCRIPTION +The +.Fn zip_name_locate +function returns the index of the file named +.Ar fname +in +.Ar archive . +If +.Ar archive +does not contain a file with that name, \-1 is returned. +The +.Fa flags +are specified by +.Em or Ns No 'ing +the following values, or 0 for none of them. +.Bl -tag -offset indent -width ZIP_FL_NOCASE +.It Dv ZIP_FL_NOCASE +Ignore case distinctions. +(Will only work well if the file names are ASCII.) +With this flag, +.Fn zip_name_locate +will be slow for archives with many files. +.It Dv ZIP_FL_NODIR +Ignore directory part of file name in archive. +With this flag, +.Fn zip_name_locate +will be slow for archives with many files. +.It Dv ZIP_FL_ENC_RAW +Compare against the unmodified names as it is in the ZIP archive. +.It Dv ZIP_FL_ENC_GUESS +(Default.) +Guess the encoding of the name in the ZIP archive and convert it +to UTF-8, if necessary, before comparing. +.It Dv ZIP_FL_ENC_STRICT +Follow the ZIP specification and expect CP-437 encoded names in +the ZIP archive (except if they are explicitly marked as UTF-8). +Convert it to UTF-8 before comparing. +.El +.Em Note : +ASCII is a subset of both CP-437 and UTF-8. +.Sh RETURN VALUES +.Fn zip_name_locate +returns the index of the file named +.Ar fname +or \-1, if +.Ar archive +does not contain an entry of that name. +.Sh ERRORS +.Fn zip_name_locate +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +One of the arguments is invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOENT +No entry of the name +.Ar fname +is found in the archive. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_get_name 3 +.Sh HISTORY +.Fn zip_name_locate +was added in libzip 0.6. +In libzip 0.11 the return type was changed from +.Vt int +to +.Vt zip_int64_t . +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_open.html b/third_party/libzip/man/zip_open.html new file mode 100644 index 0000000..6be3f05 --- /dev/null +++ b/third_party/libzip/man/zip_open.html @@ -0,0 +1,176 @@ + + + + + + + ZIP_OPEN(3) + + + + + + + + +
ZIP_OPEN(3)Library Functions ManualZIP_OPEN(3)
+
+
+

+zip_open, zip_open_from_source + — +
open zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_t * +
+ zip_open(const + char *path, int + flags, int + *errorp);

+

zip_t * +
+ zip_open_from_source(zip_source_t + *zs, int flags, + zip_error_t *ze);

+
+
+

+The zip_open() function opens the zip archive specified + by path and returns a pointer to a + struct zip, used to manipulate the archive. The + flags are specified by + or'ing the following values, or 0 + for none of them. +
+
+
+
Perform additional stricter consistency checks on the archive, and error + if they fail.
+
+
Create the archive if it does not exist.
+
+
Error if archive already exists.
+
+
If archive exists, ignore its current contents. In other words, handle it + the same way as an empty archive.
+
+
Open archive in read-only mode.
+
+
+

If an error occurs and errorp is + non-NULL, it will be set to the corresponding error + code.

+

The zip_open_from_source() function opens + a zip archive encapsulated by the zip_source zs using + the provided flags. In case of error, the zip_error + ze is filled in.

+
+
+

+Upon successful completion zip_open() and + zip_open_from_source() return a struct + zip pointer. Otherwise, NULL is returned and + zip_open() sets *errorp to + indicate the error, while + zip_open_from(source) sets + ze to indicate the error. +
+
+

+The archive specified by path is opened unless: +
+
[]
+
The file specified by path exists and + ZIP_EXCL is set.
+
[]
+
Inconsistencies were found in the file specified by + path. This error is often caused by specifying + ZIP_CHECKCONS but can also happen without it.
+
[]
+
The path argument is + NULL.
+
[]
+
Required memory could not be allocated.
+
[]
+
The file specified by path does not exist and + ZIP_CREATE is not set.
+
[]
+
The file specified by path is not a zip + archive.
+
[]
+
The file specified by path could not be opened.
+
[]
+
A read error occurred; see errno for details.
+
[]
+
The file specified by path does not allow + seeks.
+
+
+
+

+libzip(3), + zip_close(3), + zip_error_strerror(3), + zip_fdopen(3) +
+
+

+zip_open() and + zip_open_from_source() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_open.man b/third_party/libzip/man/zip_open.man new file mode 100644 index 0000000..c822395 --- /dev/null +++ b/third_party/libzip/man/zip_open.man @@ -0,0 +1,192 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_open.mdoc -- open zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_OPEN" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_open\fR, +\fBzip_open_from_source\fR +\- open zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_open\fR(\fIconst\ char\ *path\fR, \fIint\ flags\fR, \fIint\ *errorp\fR); +.PD +.PP +\fIzip_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_open_from_source\fR(\fIzip_source_t\ *zs\fR, \fIint\ flags\fR, \fIzip_error_t\ *ze\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_open\fR() +function opens the zip archive specified by +\fIpath\fR +and returns a pointer to a +\fIstruct zip\fR, +used to manipulate the archive. +The +\fIflags\fR +are specified by +\fIor\fR'ing +the following values, or 0 for none of them. +.RS 6n +.TP 15n +\fRZIP_CHECKCONS\fR +Perform additional stricter consistency checks on the archive, and +error if they fail. +.TP 15n +\fRZIP_CREATE\fR +Create the archive if it does not exist. +.TP 15n +\fRZIP_EXCL\fR +Error if archive already exists. +.TP 15n +\fRZIP_TRUNCATE\fR +If archive exists, ignore its current contents. +In other words, handle it the same way as an empty archive. +.TP 15n +\fRZIP_RDONLY\fR +Open archive in read-only mode. +.RE +.PP +If an error occurs and +\fIerrorp\fR +is +non-\fRNULL\fR, +it will be set to the corresponding error code. +.PP +The +\fBzip_open_from_source\fR() +function opens a zip archive encapsulated by the zip_source +\fIzs\fR +using the provided +\fIflags\fR. +In case of error, the zip_error +\fIze\fR +is filled in. +.SH "RETURN VALUES" +Upon successful completion +\fBzip_open\fR() +and +\fBzip_open_from_source\fR() +return a +\fIstruct zip\fR +pointer. +Otherwise, +\fRNULL\fR +is returned and +\fBzip_open\fR() +sets +\fI*errorp\fR +to indicate the error, while +\fBzip_open_from\fR(\fIsource\fR) +sets +\fIze\fR +to indicate the error. +.SH "ERRORS" +The archive specified by +\fIpath\fR +is opened unless: +.TP 19n +[\fRZIP_ER_EXISTS\fR] +The file specified by +\fIpath\fR +exists and +\fRZIP_EXCL\fR +is set. +.TP 19n +[\fRZIP_ER_INCONS\fR] +Inconsistencies were found in the file specified by +\fIpath\fR. +This error is often caused by specifying +\fRZIP_CHECKCONS\fR +but can also happen without it. +.TP 19n +[\fRZIP_ER_INVAL\fR] +The +\fIpath\fR +argument is +\fRNULL\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_NOENT\fR] +The file specified by +\fIpath\fR +does not exist and +\fRZIP_CREATE\fR +is not set. +.TP 19n +[\fRZIP_ER_NOZIP\fR] +The file specified by +\fIpath\fR +is not a zip archive. +.TP 19n +[\fRZIP_ER_OPEN\fR] +The file specified by +\fIpath\fR +could not be opened. +.TP 19n +[\fRZIP_ER_READ\fR] +A read error occurred; see +\fIerrno\fR +for details. +.TP 19n +[\fRZIP_ER_SEEK\fR] +The file specified by +\fIpath\fR +does not allow seeks. +.SH "SEE ALSO" +libzip(3), +zip_close(3), +zip_error_strerror(3), +zip_fdopen(3) +.SH "HISTORY" +\fBzip_open\fR() +and +\fBzip_open_from_source\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_open.mdoc b/third_party/libzip/man/zip_open.mdoc new file mode 100644 index 0000000..49d036c --- /dev/null +++ b/third_party/libzip/man/zip_open.mdoc @@ -0,0 +1,170 @@ +.\" zip_open.mdoc -- open zip archive +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_OPEN 3 +.Os +.Sh NAME +.Nm zip_open , +.Nm zip_open_from_source +.Nd open zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_t * +.Fn zip_open "const char *path" "int flags" "int *errorp" +.Ft zip_t * +.Fn zip_open_from_source "zip_source_t *zs" "int flags" "zip_error_t *ze" +.Sh DESCRIPTION +The +.Fn zip_open +function opens the zip archive specified by +.Ar path +and returns a pointer to a +.Ft struct zip , +used to manipulate the archive. +The +.Fa flags +are specified by +.Em or Ns No 'ing +the following values, or 0 for none of them. +.Bl -tag -offset indent -width ZIP_CHECKCONS +.It Dv ZIP_CHECKCONS +Perform additional stricter consistency checks on the archive, and +error if they fail. +.It Dv ZIP_CREATE +Create the archive if it does not exist. +.It Dv ZIP_EXCL +Error if archive already exists. +.It Dv ZIP_TRUNCATE +If archive exists, ignore its current contents. +In other words, handle it the same way as an empty archive. +.It Dv ZIP_RDONLY +Open archive in read-only mode. +.El +.Pp +If an error occurs and +.Ar errorp +is +.Pf non- Dv NULL , +it will be set to the corresponding error code. +.Pp +The +.Fn zip_open_from_source +function opens a zip archive encapsulated by the zip_source +.Fa zs +using the provided +.Fa flags . +In case of error, the zip_error +.Fa ze +is filled in. +.Sh RETURN VALUES +Upon successful completion +.Fn zip_open +and +.Fn zip_open_from_source +return a +.Ft struct zip +pointer. +Otherwise, +.Dv NULL +is returned and +.Fn zip_open +sets +.Ar *errorp +to indicate the error, while +.Fn zip_open_from source +sets +.Ar ze +to indicate the error. +.Sh ERRORS +The archive specified by +.Ar path +is opened unless: +.Bl -tag -width Er +.It Bq Er ZIP_ER_EXISTS +The file specified by +.Ar path +exists and +.Dv ZIP_EXCL +is set. +.It Bq Er ZIP_ER_INCONS +Inconsistencies were found in the file specified by +.Ar path . +This error is often caused by specifying +.Dv ZIP_CHECKCONS +but can also happen without it. +.It Bq Er ZIP_ER_INVAL +The +.Ar path +argument is +.Dv NULL . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_NOENT +The file specified by +.Ar path +does not exist and +.Dv ZIP_CREATE +is not set. +.It Bq Er ZIP_ER_NOZIP +The file specified by +.Ar path +is not a zip archive. +.It Bq Er ZIP_ER_OPEN +The file specified by +.Ar path +could not be opened. +.It Bq Er ZIP_ER_READ +A read error occurred; see +.Va errno +for details. +.It Bq Er ZIP_ER_SEEK +The file specified by +.Ar path +does not allow seeks. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_close 3 , +.Xr zip_error_strerror 3 , +.Xr zip_fdopen 3 +.Sh HISTORY +.Fn zip_open +and +.Fn zip_open_from_source +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_register_progress_callback.html b/third_party/libzip/man/zip_register_progress_callback.html new file mode 100644 index 0000000..59ce4a2 --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback.html @@ -0,0 +1,111 @@ + + + + + + + ZIP_REGISTER_PROGRESS_CALLBACK(3) + + + + + + + + +
ZIP_REGISTER_PROGRESS_CALLBACK(3)Library Functions ManualZIP_REGISTER_PROGRESS_CALLBACK(3)
+
+
+

+zip_register_progress_callback — +
provide updates during zip_close (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

typedef void + (*zip_progress_callback_t)(double);

+

void +
+ zip_register_progress_callback(zip_t + *archive, + zip_progress_callback_t + progress_callback);

+
+
+

+The function zip_register_progress_callback() is the + obsolete version of + zip_register_progress_callback_with_state(3). +

The zip_register_progress_callback() + function registers a callback function + progress_callback for the zip archive + archive. This function is called during + zip_close(3) after every zip archive + entry that's completely written to disk. The value is a + double in the range from 0.0 to 1.0. This can be used + to provide progress indicators for user interfaces.

+
+
+

+libzip(3), + zip_close(3) +
+
+

+zip_register_progress_callback() was added in libzip + 1.2.0. It was deprecated in libzip 1.3.0, use + zip_register_progress_callback_with_state() instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_register_progress_callback.man b/third_party/libzip/man/zip_register_progress_callback.man new file mode 100644 index 0000000..3d0e5b9 --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback.man @@ -0,0 +1,83 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_register_progress_callback.mdoc -- provide updates during zip_close +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_REGISTER_PROGRESS_CALLBACK" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_register_progress_callback\fR +\- provide updates during zip_close (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fItypedef void (*zip_progress_callback_t)(double);\fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_register_progress_callback\fR(\fIzip_t\ *archive\fR, \fIzip_progress_callback_t\ progress_callback\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_register_progress_callback\fR() +is the obsolete version of +zip_register_progress_callback_with_state(3). +.PP +The +\fBzip_register_progress_callback\fR() +function registers a callback function +\fIprogress_callback\fR +for the zip archive +\fIarchive\fR. +This function is called during +zip_close(3) +after every zip archive entry that's completely written to disk. +The value is a +\fIdouble\fR +in the range from 0.0 to 1.0. +This can be used to provide progress indicators for user interfaces. +.SH "SEE ALSO" +libzip(3), +zip_close(3) +.SH "HISTORY" +\fBzip_register_progress_callback\fR() +was added in libzip 1.2.0. +It was deprecated in libzip 1.3.0, use +\fBzip_register_progress_callback_with_state\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_register_progress_callback.mdoc b/third_party/libzip/man/zip_register_progress_callback.mdoc new file mode 100644 index 0000000..9fd0cd0 --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback.mdoc @@ -0,0 +1,77 @@ +.\" zip_register_progress_callback.mdoc -- provide updates during zip_close +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_REGISTER_PROGRESS_CALLBACK 3 +.Os +.Sh NAME +.Nm zip_register_progress_callback +.Nd provide updates during zip_close (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Vt typedef void (*zip_progress_callback_t)(double); +.Ft void +.Fn zip_register_progress_callback "zip_t *archive" "zip_progress_callback_t progress_callback" +.Sh DESCRIPTION +The function +.Fn zip_register_progress_callback +is the obsolete version of +.Xr zip_register_progress_callback_with_state 3 . +.Pp +The +.Fn zip_register_progress_callback +function registers a callback function +.Ar progress_callback +for the zip archive +.Ar archive . +This function is called during +.Xr zip_close 3 +after every zip archive entry that's completely written to disk. +The value is a +.Vt double +in the range from 0.0 to 1.0. +This can be used to provide progress indicators for user interfaces. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_close 3 +.Sh HISTORY +.Fn zip_register_progress_callback +was added in libzip 1.2.0. +It was deprecated in libzip 1.3.0, use +.Fn zip_register_progress_callback_with_state +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_register_progress_callback_with_state.html b/third_party/libzip/man/zip_register_progress_callback_with_state.html new file mode 100644 index 0000000..f6a0932 --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback_with_state.html @@ -0,0 +1,111 @@ + + + + + + + ZIP_REGISTER_PROGRESS_CALLBACK_WITH_STATE(3) + + + + + + + + +
ZIP_REGISTER_PROGRESS_CALLBACK_WITH_STATE(3)Library Functions ManualZIP_REGISTER_PROGRESS_CALLBACK_WITH_STATE(3)
+
+

+zip_register_progress_callback_with_state + — +
provide updates during zip_close
+

+libzip (-lzip) +

+#include + <zip.h> +
+typedef void (*zip_progress_callback)(zip_t *, + double, void *); +
+void +
+zip_register_progress_callback_with_state(zip_t + *archive, double + precision, + zip_progress_callback + callback, void + (*ud_free)(void *), + void *ud); +

+The + zip_register_progress_callback_with_state() + function registers a callback function + callback for the zip archive + archive. The + precision argument is a double in the range + from 0.00 to 1.0 that defines the smallest change for which the callback + should be called (to avoid too frequent calls). The + ud_free function is called during cleanup for + deleting the userdata supplied in ud. +
+The callback function is called during + zip_close(3) in regular + intervals (after every zip archive entry that's completely written to disk, + and while writing data for entries) with zip archive + archive, the current progression state as a + double, and the user-provided user-data + ud as arguments. The progression state is a + double in the range from 0.0 to 1.0. This can + be used to provide progress indicators for user interfaces. +

+libzip(3), + zip_close(3) +

+zip_register_progress_callback_with_state() + was added in libzip 1.3.0. +

+Dieter Baron + <dillo@nih.at> + and Thomas Klausner + <tk@giga.or.at>
+ + + + + +
December 18, 2017NetBSD 8.99.27
+ + diff --git a/third_party/libzip/man/zip_register_progress_callback_with_state.man b/third_party/libzip/man/zip_register_progress_callback_with_state.man new file mode 100644 index 0000000..f24905b --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback_with_state.man @@ -0,0 +1,92 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_register_progress_callback_with_state.mdoc -- provide updates during zip_close +.\" Copyright (C) 2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_REGISTER_PROGRESS_CALLBACK_WITH_STATE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_register_progress_callback_with_state\fR +\- provide updates during zip_close +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fItypedef void (*zip_progress_callback)(zip_t *, double, void *);\fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_register_progress_callback_with_state\fR(\fIzip_t\ *archive\fR, \fIdouble\ precision\fR, \fIzip_progress_callback\ callback\fR, \fIvoid\ (*ud_free)(void\ *)\fR, \fIvoid\ *ud\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_register_progress_callback_with_state\fR() +function registers a callback function +\fIcallback\fR +for the zip archive +\fIarchive\fR. +The +\fIprecision\fR +argument is a double in the range from 0.00 to 1.0 that defines the +smallest change for which the callback should be called (to avoid too +frequent calls). +The +\fIud_free\fR +function is called during cleanup for deleting the userdata supplied in +\fIud\fR. +.PP +The callback function is called during +zip_close(3) +in regular intervals (after every zip archive entry that's completely +written to disk, and while writing data for entries) with zip archive +\fIarchive\fR, +the current progression state as a +\fIdouble\fR, +and the user-provided user-data +\fIud\fR +as arguments. +The progression state is a +\fIdouble\fR +in the range from 0.0 to 1.0. +This can be used to provide progress indicators for user interfaces. +.SH "SEE ALSO" +libzip(3), +zip_close(3) +.SH "HISTORY" +\fBzip_register_progress_callback_with_state\fR() +was added in libzip 1.3.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_register_progress_callback_with_state.mdoc b/third_party/libzip/man/zip_register_progress_callback_with_state.mdoc new file mode 100644 index 0000000..7eea3d6 --- /dev/null +++ b/third_party/libzip/man/zip_register_progress_callback_with_state.mdoc @@ -0,0 +1,86 @@ +.\" zip_register_progress_callback_with_state.mdoc -- provide updates during zip_close +.\" Copyright (C) 2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_REGISTER_PROGRESS_CALLBACK_WITH_STATE 3 +.Os +.Sh NAME +.Nm zip_register_progress_callback_with_state +.Nd provide updates during zip_close +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Vt typedef void (*zip_progress_callback)(zip_t *, double, void *); +.Ft void +.Fn zip_register_progress_callback_with_state "zip_t *archive" "double precision" "zip_progress_callback callback" "void (*ud_free)(void *)" "void *ud" +.Sh DESCRIPTION +The +.Fn zip_register_progress_callback_with_state +function registers a callback function +.Ar callback +for the zip archive +.Ar archive . +The +.Ar precision +argument is a double in the range from 0.00 to 1.0 that defines the +smallest change for which the callback should be called (to avoid too +frequent calls). +The +.Ar ud_free +function is called during cleanup for deleting the userdata supplied in +.Ar ud . +.Pp +The callback function is called during +.Xr zip_close 3 +in regular intervals (after every zip archive entry that's completely +written to disk, and while writing data for entries) with zip archive +.Ar archive , +the current progression state as a +.Vt double , +and the user-provided user-data +.Ar ud +as arguments. +The progression state is a +.Vt double +in the range from 0.0 to 1.0. +This can be used to provide progress indicators for user interfaces. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_close 3 +.Sh HISTORY +.Fn zip_register_progress_callback_with_state +was added in libzip 1.3.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_rename.html b/third_party/libzip/man/zip_rename.html new file mode 100644 index 0000000..6d4d2f6 --- /dev/null +++ b/third_party/libzip/man/zip_rename.html @@ -0,0 +1,104 @@ + + + + + + + ZIP_RENAME(3) + + + + + + + + +
ZIP_RENAME(3)Library Functions ManualZIP_RENAME(3)
+
+
+

+zip_rename — +
rename file in zip archive (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_rename(zip_t + *archive, zip_uint64_t + index, const char + *name);

+
+
+

+zip_rename() is the obsolete version of + zip_file_rename(3). It is the + same as calling + zip_file_rename(3) with an empty + flags argument. +
+
+

+libzip(3), + zip_file_rename(3) +
+
+

+zip_rename() was added in libzip 0.6. In libzip 0.10 the + type of index was changed from int + to zip_uint64_t. It was deprecated in libzip 0.11, use + zip_file_rename() instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_rename.man b/third_party/libzip/man/zip_rename.man new file mode 100644 index 0000000..ea8b8c0 --- /dev/null +++ b/third_party/libzip/man/zip_rename.man @@ -0,0 +1,75 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_rename.mdoc -- rename file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_RENAME" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_rename\fR +\- rename file in zip archive (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_rename\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIconst\ char\ *name\fR); +.PD +.SH "DESCRIPTION" +\fBzip_rename\fR() +is the obsolete version of +zip_file_rename(3). +It is the same as calling +zip_file_rename(3) +with an empty flags argument. +.SH "SEE ALSO" +libzip(3), +zip_file_rename(3) +.SH "HISTORY" +\fBzip_rename\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_file_rename\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_rename.mdoc b/third_party/libzip/man/zip_rename.mdoc new file mode 100644 index 0000000..ce3a748 --- /dev/null +++ b/third_party/libzip/man/zip_rename.mdoc @@ -0,0 +1,70 @@ +.\" zip_rename.mdoc -- rename file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_RENAME 3 +.Os +.Sh NAME +.Nm zip_rename +.Nd rename file in zip archive (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_rename "zip_t *archive" "zip_uint64_t index" "const char *name" +.Sh DESCRIPTION +.Fn zip_rename +is the obsolete version of +.Xr zip_file_rename 3 . +It is the same as calling +.Xr zip_file_rename 3 +with an empty flags argument. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_rename 3 +.Sh HISTORY +.Fn zip_rename +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +It was deprecated in libzip 0.11, use +.Fn zip_file_rename +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_set_archive_comment.html b/third_party/libzip/man/zip_set_archive_comment.html new file mode 100644 index 0000000..13c92cf --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_comment.html @@ -0,0 +1,124 @@ + + + + + + + ZIP_SET_ARCHIVE_COMMENT(3) + + + + + + + + +
ZIP_SET_ARCHIVE_COMMENT(3)Library Functions ManualZIP_SET_ARCHIVE_COMMENT(3)
+
+
+

+zip_set_archive_comment — +
set zip archive comment
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_set_archive_comment(zip_t + *archive, const char + *comment, zip_uint16_t + len);

+
+
+

+The zip_set_archive_comment() function sets the comment + for the entire zip archive. If comment is + NULL and len is 0, the archive + comment will be removed. comment must be encoded in + ASCII or UTF-8. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_set_archive_comment() fails if: +
+
[]
+
len is less than 0 or longer than the maximum + comment length in a zip file (65535), or comment is + not a valid UTF-8 encoded string.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_get_comment(3), + zip_file_set_comment(3), + zip_get_archive_comment(3) +
+
+

+zip_set_archive_comment() was added in libzip 0.7. In + libzip 0.11 the type of len was changed from + int to zip_uint16_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_set_archive_comment.man b/third_party/libzip/man/zip_set_archive_comment.man new file mode 100644 index 0000000..d50ec71 --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_comment.man @@ -0,0 +1,98 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_set_archive_comment.mdoc -- set zip archive comment +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SET_ARCHIVE_COMMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_set_archive_comment\fR +\- set zip archive comment +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_set_archive_comment\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *comment\fR, \fIzip_uint16_t\ len\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_set_archive_comment\fR() +function sets the comment for the entire zip archive. +If +\fIcomment\fR +is +\fRNULL\fR +and +\fIlen\fR +is 0, the archive comment will be removed. +\fIcomment\fR +must be encoded in ASCII or UTF-8. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_set_archive_comment\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIlen\fR +is less than 0 or longer than the maximum comment length in a zip file +(65535), or +\fIcomment\fR +is not a valid UTF-8 encoded string. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_get_comment(3), +zip_file_set_comment(3), +zip_get_archive_comment(3) +.SH "HISTORY" +\fBzip_set_archive_comment\fR() +was added in libzip 0.7. +In libzip 0.11 the type of +\fIlen\fR +was changed from +\fIint\fR +to +\fIzip_uint16_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_set_archive_comment.mdoc b/third_party/libzip/man/zip_set_archive_comment.mdoc new file mode 100644 index 0000000..3d90b0b --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_comment.mdoc @@ -0,0 +1,93 @@ +.\" zip_set_archive_comment.mdoc -- set zip archive comment +.\" Copyright (C) 2006-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SET_ARCHIVE_COMMENT 3 +.Os +.Sh NAME +.Nm zip_set_archive_comment +.Nd set zip archive comment +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_set_archive_comment "zip_t *archive" "const char *comment" "zip_uint16_t len" +.Sh DESCRIPTION +The +.Fn zip_set_archive_comment +function sets the comment for the entire zip archive. +If +.Ar comment +is +.Dv NULL +and +.Ar len +is 0, the archive comment will be removed. +.Ar comment +must be encoded in ASCII or UTF-8. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_set_archive_comment +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar len +is less than 0 or longer than the maximum comment length in a zip file +(65535), or +.Ar comment +is not a valid UTF-8 encoded string. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_get_comment 3 , +.Xr zip_file_set_comment 3 , +.Xr zip_get_archive_comment 3 +.Sh HISTORY +.Fn zip_set_archive_comment +was added in libzip 0.7. +In libzip 0.11 the type of +.Ar len +was changed from +.Vt int +to +.Vt zip_uint16_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_set_archive_flag.html b/third_party/libzip/man/zip_set_archive_flag.html new file mode 100644 index 0000000..0de64b6 --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_flag.html @@ -0,0 +1,107 @@ + + + + + + + ZIP_SET_ARCHIVE_FLAG(3) + + + + + + + + +
ZIP_SET_ARCHIVE_FLAG(3)Library Functions ManualZIP_SET_ARCHIVE_FLAG(3)
+
+
+

+zip_set_archive_flag — +
set zip archive flag
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_set_archive_flag(zip_t + *archive, zip_flags_t + flag, int + value);

+
+
+

+The zip_set_archive_flag() function sets the flag + flag for the archive archive to + the value value. +

Currently there are no supported flags.

+
+
+

+Upon successful completion 0 is returned, and -1 if an error occurred. +
+
+

+libzip(3), + zip_get_archive_flag(3) +
+
+

+zip_set_archive_flag() was added in libzip 0.9. In + libzip 0.11 the type of flag was changed from + int to zip_flags_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_set_archive_flag.man b/third_party/libzip/man/zip_set_archive_flag.man new file mode 100644 index 0000000..0cacf4c --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_flag.man @@ -0,0 +1,79 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_set_archive_flag.mdoc -- set zip archive flag +.\" Copyright (C) 2008-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SET_ARCHIVE_FLAG" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_set_archive_flag\fR +\- set zip archive flag +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_set_archive_flag\fR(\fIzip_t\ *archive\fR, \fIzip_flags_t\ flag\fR, \fIint\ value\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_set_archive_flag\fR() +function sets the flag +\fIflag\fR +for the archive +\fIarchive\fR +to the value +\fIvalue\fR. +.PP +Currently there are no supported flags. +.SH "RETURN VALUES" +Upon successful completion 0 is returned, and \-1 if an error +occurred. +.SH "SEE ALSO" +libzip(3), +zip_get_archive_flag(3) +.SH "HISTORY" +\fBzip_set_archive_flag\fR() +was added in libzip 0.9. +In libzip 0.11 the type of +\fIflag\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_set_archive_flag.mdoc b/third_party/libzip/man/zip_set_archive_flag.mdoc new file mode 100644 index 0000000..116a340 --- /dev/null +++ b/third_party/libzip/man/zip_set_archive_flag.mdoc @@ -0,0 +1,74 @@ +.\" zip_set_archive_flag.mdoc -- set zip archive flag +.\" Copyright (C) 2008-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SET_ARCHIVE_FLAG 3 +.Os +.Sh NAME +.Nm zip_set_archive_flag +.Nd set zip archive flag +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_set_archive_flag "zip_t *archive" "zip_flags_t flag" "int value" +.Sh DESCRIPTION +The +.Fn zip_set_archive_flag +function sets the flag +.Ar flag +for the archive +.Ar archive +to the value +.Ar value . +.Pp +Currently there are no supported flags. +.Sh RETURN VALUES +Upon successful completion 0 is returned, and \-1 if an error +occurred. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_get_archive_flag 3 +.Sh HISTORY +.Fn zip_set_archive_flag +was added in libzip 0.9. +In libzip 0.11 the type of +.Ar flag +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_set_default_password.html b/third_party/libzip/man/zip_set_default_password.html new file mode 100644 index 0000000..ff4135a --- /dev/null +++ b/third_party/libzip/man/zip_set_default_password.html @@ -0,0 +1,119 @@ + + + + + + + ZIP_SET_DEFAULT_PASSWORD(3) + + + + + + + + +
ZIP_SET_DEFAULT_PASSWORD(3)Library Functions ManualZIP_SET_DEFAULT_PASSWORD(3)
+
+
+

+zip_set_default_password — +
set default password for encrypted files in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_set_default_password(zip_t + *archive, const char + *password);

+
+
+

+The zip_set_default_password() function sets the default + password used when accessing encrypted files. If + password is NULL, the default + password is unset. +

If you prefer a different password for single files, use + zip_fopen_encrypted(3) + instead of zip_fopen(3). Usually, + however, the same password is used for every file in an zip archive.

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_set_default_password() fails if: +
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_fopen(3), + zip_fopen_encrypted(3) +
+
+

+zip_set_default_password() was added in libzip 0.10. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_set_default_password.man b/third_party/libzip/man/zip_set_default_password.man new file mode 100644 index 0000000..7104bb3 --- /dev/null +++ b/third_party/libzip/man/zip_set_default_password.man @@ -0,0 +1,87 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_set_default_password.mdoc -- set default password for zip +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SET_DEFAULT_PASSWORD" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_set_default_password\fR +\- set default password for encrypted files in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_set_default_password\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *password\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_set_default_password\fR() +function sets the default password used when accessing encrypted files. +If +\fIpassword\fR +is +\fRNULL\fR, +the default password is unset. +.PP +If you prefer a different password for single files, use +zip_fopen_encrypted(3) +instead of +zip_fopen(3). +Usually, however, the same password is used for every file in an +zip archive. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_set_default_password\fR() +fails if: +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_fopen(3), +zip_fopen_encrypted(3) +.SH "HISTORY" +\fBzip_set_default_password\fR() +was added in libzip 0.10. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_set_default_password.mdoc b/third_party/libzip/man/zip_set_default_password.mdoc new file mode 100644 index 0000000..792176c --- /dev/null +++ b/third_party/libzip/man/zip_set_default_password.mdoc @@ -0,0 +1,83 @@ +.\" zip_set_default_password.mdoc -- set default password for zip +.\" Copyright (C) 2011-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SET_DEFAULT_PASSWORD 3 +.Os +.Sh NAME +.Nm zip_set_default_password +.Nd set default password for encrypted files in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_set_default_password "zip_t *archive" "const char *password" +.Sh DESCRIPTION +The +.Fn zip_set_default_password +function sets the default password used when accessing encrypted files. +If +.Ar password +is +.Dv NULL , +the default password is unset. +.Pp +If you prefer a different password for single files, use +.Xr zip_fopen_encrypted 3 +instead of +.Xr zip_fopen 3 . +Usually, however, the same password is used for every file in an +zip archive. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_set_default_password +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_fopen 3 , +.Xr zip_fopen_encrypted 3 +.Sh HISTORY +.Fn zip_set_default_password +was added in libzip 0.10. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_set_file_comment.html b/third_party/libzip/man/zip_set_file_comment.html new file mode 100644 index 0000000..ee7591a --- /dev/null +++ b/third_party/libzip/man/zip_set_file_comment.html @@ -0,0 +1,109 @@ + + + + + + + ZIP_SET_FILE_COMMENT(3) + + + + + + + + +
ZIP_SET_FILE_COMMENT(3)Library Functions ManualZIP_SET_FILE_COMMENT(3)
+
+
+

+zip_set_file_comment — +
set comment for file in zip (obsolete interface)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_set_file_comment(zip_t + *archive, zip_uint64_t + index, const char + *comment, int + len);

+
+
+

+The zip_set_file_comment() function is the obsolete + version of + zip_file_set_comment(3). + The only differences are the type of the len argument + and the additional flags argument. + zip_set_file_comment() is the same as calling + zip_file_set_comment(3) + with an empty flags argument. +
+
+

+libzip(3), + zip_file_set_comment(3) +
+
+

+zip_set_file_comment() was added in libzip 0.7. In + libzip 0.10 the type of index was changed from + int to zip_uint64_t. It was + deprecated in libzip 0.11, use zip_file_set_comment() + instead. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_set_file_comment.man b/third_party/libzip/man/zip_set_file_comment.man new file mode 100644 index 0000000..2ba8a7c --- /dev/null +++ b/third_party/libzip/man/zip_set_file_comment.man @@ -0,0 +1,84 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_set_file_comment.mdoc -- set comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SET_FILE_COMMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_set_file_comment\fR +\- set comment for file in zip (obsolete interface) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_set_file_comment\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIconst\ char\ *comment\fR, \fIint\ len\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_set_file_comment\fR() +function is the obsolete version of +zip_file_set_comment(3). +The only differences are the type of the +\fIlen\fR +argument and the additional +\fIflags\fR +argument. +\fBzip_set_file_comment\fR() +is the same as calling +zip_file_set_comment(3) +with an empty +\fIflags\fR +argument. +.SH "SEE ALSO" +libzip(3), +zip_file_set_comment(3) +.SH "HISTORY" +\fBzip_set_file_comment\fR() +was added in libzip 0.7. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +It was deprecated in libzip 0.11, use +\fBzip_file_set_comment\fR() +instead. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_set_file_comment.mdoc b/third_party/libzip/man/zip_set_file_comment.mdoc new file mode 100644 index 0000000..f6e2b37 --- /dev/null +++ b/third_party/libzip/man/zip_set_file_comment.mdoc @@ -0,0 +1,79 @@ +.\" zip_set_file_comment.mdoc -- set comment for file in zip +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SET_FILE_COMMENT 3 +.Os +.Sh NAME +.Nm zip_set_file_comment +.Nd set comment for file in zip (obsolete interface) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_set_file_comment "zip_t *archive" "zip_uint64_t index" "const char *comment" "int len" +.Sh DESCRIPTION +The +.Fn zip_set_file_comment +function is the obsolete version of +.Xr zip_file_set_comment 3 . +The only differences are the type of the +.Ar len +argument and the additional +.Ar flags +argument. +.Fn zip_set_file_comment +is the same as calling +.Xr zip_file_set_comment 3 +with an empty +.Ar flags +argument. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_set_comment 3 +.Sh HISTORY +.Fn zip_set_file_comment +was added in libzip 0.7. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +It was deprecated in libzip 0.11, use +.Fn zip_file_set_comment +instead. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_set_file_compression.html b/third_party/libzip/man/zip_set_file_compression.html new file mode 100644 index 0000000..07d8e03 --- /dev/null +++ b/third_party/libzip/man/zip_set_file_compression.html @@ -0,0 +1,148 @@ + + + + + + + ZIP_SET_FILE_COMPRESSION(3) + + + + + + + + +
ZIP_SET_FILE_COMPRESSION(3)Library Functions ManualZIP_SET_FILE_COMPRESSION(3)
+
+
+

+zip_set_file_compression — +
set compression method for file in zip
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_set_file_compression(zip_t + *archive, zip_uint64_t + index, zip_int32_t + comp, zip_uint32_t + comp_flags);

+
+
+

+The zip_set_file_compression() function sets the + compression method for the file at position index in the + zip archive to comp with the compression method specific + comp_flags. The comp is the same + as returned by zip_stat(3). For the + comp argument, currently only the following values are + supported: +
+
+
default compression; currently the same as + ZIP_CM_DEFLATE, but flags + are ignored.
+
+
Store the file uncompressed.
+
+
Compress the file using the bzip2(1) + algorithm.
+
+
Deflate the file with the zlib(3) + algorithm and default options.
+
+

NOTE: Only the deflate and store methods can be + assumed to be universally supported.

+

The comp_flags argument defines the + compression level, 1 being fastest compression and 9 highest. Allowed values + are 0 (which uses the default compression for the algorithm) and 1-9, other + values are undefined. Further compression method specific flags might be + added over time.

+

The current compression method for a file in a zip archive can be + determined using zip_stat(3).

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+zip_set_file_compression() fails if: +
+
[]
+
Unsupported compression method requested.
+
[]
+
index is not a valid file index in + archive, or the argument combination is + invalid.
+
[]
+
Read-only zip file, no changes allowed.
+
+
+
+

+libzip(3), + zip_stat(3) +
+
+

+zip_set_file_compression() was added in libzip 0.11. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_set_file_compression.man b/third_party/libzip/man/zip_set_file_compression.man new file mode 100644 index 0000000..759309b --- /dev/null +++ b/third_party/libzip/man/zip_set_file_compression.man @@ -0,0 +1,131 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_set_file_compression.mdoc -- set compression method and its flags +.\" Copyright (C) 2012-2019 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SET_FILE_COMPRESSION" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_set_file_compression\fR +\- set compression method for file in zip +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_set_file_compression\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_int32_t\ comp\fR, \fIzip_uint32_t\ comp_flags\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_set_file_compression\fR() +function sets the compression method for the file at position +\fIindex\fR +in the zip archive to +\fIcomp\fR +with the compression method specific +\fIcomp_flags\fR. +The +\fIcomp\fR +is the same as returned by +zip_stat(3). +For the +\fIcomp\fR +argument, currently only the following values are supported: +.TP 19n +\fRZIP_CM_DEFAULT\fR +default compression; currently the same as +\fRZIP_CM_DEFLATE\fR, +but +\fIflags\fR +are ignored. +.TP 19n +\fRZIP_CM_STORE\fR +Store the file uncompressed. +.TP 19n +\fRZIP_CM_BZIP2\fR +Compress the file using the +bzip2(1) +algorithm. +.TP 19n +\fRZIP_CM_DEFLATE\fR +Deflate the file with the +zlib(3) +algorithm and default options. +.PP +\fINOTE\fR: +Only the deflate and store methods can be assumed to be universally +supported. +.PP +The +\fIcomp_flags\fR +argument defines the compression level, 1 being fastest compression +and 9 highest. +Allowed values are 0 (which uses the default compression for the +algorithm) and 1-9, other values are undefined. +Further compression method specific flags might be added over time. +.PP +The current compression method for a file in a zip archive can be +determined using +zip_stat(3). +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_set_file_compression\fR() +fails if: +.TP 19n +[\fRZIP_ER_COMPNOTSUPP\fR] +Unsupported compression method requested. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIarchive\fR, +or the argument combination is invalid. +.TP 19n +[\fRZIP_ER_RDONLY\fR] +Read-only zip file, no changes allowed. +.SH "SEE ALSO" +libzip(3), +zip_stat(3) +.SH "HISTORY" +\fBzip_set_file_compression\fR() +was added in libzip 0.11. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_set_file_compression.mdoc b/third_party/libzip/man/zip_set_file_compression.mdoc new file mode 100644 index 0000000..3d3b5f4 --- /dev/null +++ b/third_party/libzip/man/zip_set_file_compression.mdoc @@ -0,0 +1,123 @@ +.\" zip_set_file_compression.mdoc -- set compression method and its flags +.\" Copyright (C) 2012-2019 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP files. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SET_FILE_COMPRESSION 3 +.Os +.Sh NAME +.Nm zip_set_file_compression +.Nd set compression method for file in zip +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_set_file_compression "zip_t *archive" "zip_uint64_t index" "zip_int32_t comp" "zip_uint32_t comp_flags" +.Sh DESCRIPTION +The +.Fn zip_set_file_compression +function sets the compression method for the file at position +.Ar index +in the zip archive to +.Ar comp +with the compression method specific +.Ar comp_flags . +The +.Ar comp +is the same as returned by +.Xr zip_stat 3 . +For the +.Ar comp +argument, currently only the following values are supported: +.Bl -tag -width ZIP_CM_DEFLATE_XX +.It Dv ZIP_CM_DEFAULT +default compression; currently the same as +.Dv ZIP_CM_DEFLATE , +but +.Ar flags +are ignored. +.It Dv ZIP_CM_STORE +Store the file uncompressed. +.It Dv ZIP_CM_BZIP2 +Compress the file using the +.Xr bzip2 1 +algorithm. +.It Dv ZIP_CM_DEFLATE +Deflate the file with the +.Xr zlib 3 +algorithm and default options. +.El +.Pp +.Em NOTE : +Only the deflate and store methods can be assumed to be universally +supported. +.Pp +The +.Ar comp_flags +argument defines the compression level, 1 being fastest compression +and 9 highest. +Allowed values are 0 (which uses the default compression for the +algorithm) and 1-9, other values are undefined. +Further compression method specific flags might be added over time. +.Pp +The current compression method for a file in a zip archive can be +determined using +.Xr zip_stat 3 . +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_set_file_compression +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_COMPNOTSUPP +Unsupported compression method requested. +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar archive , +or the argument combination is invalid. +.It Bq Er ZIP_ER_RDONLY +Read-only zip file, no changes allowed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_stat 3 +.Sh HISTORY +.Fn zip_set_file_compression +was added in libzip 0.11. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source.html b/third_party/libzip/man/zip_source.html new file mode 100644 index 0000000..762d892 --- /dev/null +++ b/third_party/libzip/man/zip_source.html @@ -0,0 +1,117 @@ + + + + + + + ZIP_SOURCE(3) + + + + + + + + +
ZIP_SOURCE(3)Library Functions ManualZIP_SOURCE(3)
+
+
+

+zip_source — +
zip data source structure
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t *zs;

+
+
+

+A struct zip_source is a data source used by + libzip(3) for adding or replacing file + contents for a file in a zip archive. If the source supports seeking, it can + also be used to open zip archives from. It is created by calling one of + zip_source_buffer(3), + zip_source_buffer_create(3), + zip_source_file(3), + zip_source_file_create(3), + zip_source_filep(3), + zip_source_filep_create(3), + zip_source_function(3), + zip_source_function_create(3), + or zip_source_zip(3). + zip_source_t is reference counted, and created with a + reference count of 1. + zip_open_from_source(3), + zip_file_add(3), and + zip_file_replace(3) will + decrement the reference count of the zip_source_t when + they are done using it, so + zip_source_free(3) only needs to + be called when these functions return an error. Use + zip_source_keep(3) to increase + the reference count, for example if you need the source after + zip_close(3). +
+
+

+libzip(3), + zip_source_buffer(3), + zip_source_file(3), + zip_source_filep(3), + zip_source_free(3), + zip_source_function(3), + zip_source_zip(3) +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source.man b/third_party/libzip/man/zip_source.man new file mode 100644 index 0000000..856401e --- /dev/null +++ b/third_party/libzip/man/zip_source.man @@ -0,0 +1,89 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source.mdoc -- description of zip data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source\fR +\- zip data source structure +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *zs\fR; +.SH "DESCRIPTION" +A +\fIstruct zip_source\fR +is a data source used by +libzip(3) +for adding or replacing file contents for a file in a zip archive. +If the source supports seeking, it can also be used to open zip archives from. +It is created by calling one of +zip_source_buffer(3), +zip_source_buffer_create(3), +zip_source_file(3), +zip_source_file_create(3), +zip_source_filep(3), +zip_source_filep_create(3), +zip_source_function(3), +zip_source_function_create(3), +or +zip_source_zip(3). +\fIzip_source_t\fR +is reference counted, and created with a reference count of 1. +zip_open_from_source(3), +zip_file_add(3), +and +zip_file_replace(3) +will decrement the reference count of the +\fIzip_source_t\fR +when they are done using it, so +zip_source_free(3) +only needs to be called when these functions return an error. +Use +zip_source_keep(3) +to increase the reference count, for example if you need the source after +zip_close(3). +.SH "SEE ALSO" +libzip(3), +zip_source_buffer(3), +zip_source_file(3), +zip_source_filep(3), +zip_source_free(3), +zip_source_function(3), +zip_source_zip(3) +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source.mdoc b/third_party/libzip/man/zip_source.mdoc new file mode 100644 index 0000000..0795bd8 --- /dev/null +++ b/third_party/libzip/man/zip_source.mdoc @@ -0,0 +1,88 @@ +.\" zip_source.mdoc -- description of zip data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE 3 +.Os +.Sh NAME +.Nm zip_source +.Nd zip data source structure +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Vt zip_source_t *zs ; +.Sh DESCRIPTION +A +.Vt struct zip_source +is a data source used by +.Xr libzip 3 +for adding or replacing file contents for a file in a zip archive. +If the source supports seeking, it can also be used to open zip archives from. +It is created by calling one of +.Xr zip_source_buffer 3 , +.Xr zip_source_buffer_create 3 , +.Xr zip_source_file 3 , +.Xr zip_source_file_create 3 , +.Xr zip_source_filep 3 , +.Xr zip_source_filep_create 3 , +.Xr zip_source_function 3 , +.Xr zip_source_function_create 3 , +or +.Xr zip_source_zip 3 . +.Vt zip_source_t +is reference counted, and created with a reference count of 1. +.Xr zip_open_from_source 3 , +.Xr zip_file_add 3 , +and +.Xr zip_file_replace 3 +will decrement the reference count of the +.Vt zip_source_t +when they are done using it, so +.Xr zip_source_free 3 +only needs to be called when these functions return an error. +Use +.Xr zip_source_keep 3 +to increase the reference count, for example if you need the source after +.Xr zip_close 3 . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source_buffer 3 , +.Xr zip_source_file 3 , +.Xr zip_source_filep 3 , +.Xr zip_source_free 3 , +.Xr zip_source_function 3 , +.Xr zip_source_zip 3 +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_begin_write.html b/third_party/libzip/man/zip_source_begin_write.html new file mode 100644 index 0000000..a5d1d9c --- /dev/null +++ b/third_party/libzip/man/zip_source_begin_write.html @@ -0,0 +1,123 @@ + + + + + + + ZIP_SOURCE_BEGIN_WRITE(3) + + + + + + + + +
ZIP_SOURCE_BEGIN_WRITE(3)Library Functions ManualZIP_SOURCE_BEGIN_WRITE(3)
+
+
+

+zip_source_begin_write, + zip_source_begin_write_cloning — +
prepare zip source for writing
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_begin_write(zip_source_t + *source);

+

int +
+ zip_source_begin_write_cloning(zip_source_t + *source, zip_uint64_t + offset);

+
+
+

+The functions zip_source_begin_write() and + zip_source_begin_write_cloning() prepare + source for writing. Usually this involves creating + temporary files or allocating buffers. +

zip_source_begin_write_cloning() preserves + the first offset bytes of the original file. This is + done efficiently, and writes to source won't overwrite + the original data until zip_commit_write() is + called.

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_commit_write(3), + zip_source_rollback_write(3), + zip_source_seek_write(3), + zip_source_tell_write(3), + zip_source_write(3) +
+
+

+zip_source_begin_write() was added in libzip 1.0. +

zip_source_begin_write_cloning() was added + in libzip 1.4.0.

+
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_begin_write.man b/third_party/libzip/man/zip_source_begin_write.man new file mode 100644 index 0000000..a0a21c5 --- /dev/null +++ b/third_party/libzip/man/zip_source_begin_write.man @@ -0,0 +1,99 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_begin_write.mdoc -- prepare zip source for writing +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_BEGIN_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_begin_write\fR, +\fBzip_source_begin_write_cloning\fR +\- prepare zip source for writing +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_begin_write\fR(\fIzip_source_t\ *source\fR); +.PD +.PP +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_begin_write_cloning\fR(\fIzip_source_t\ *source\fR, \fIzip_uint64_t\ offset\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_begin_write\fR() +and +\fBzip_source_begin_write_cloning\fR() +prepare +\fIsource\fR +for writing. +Usually this involves creating temporary files or allocating buffers. +.PP +\fBzip_source_begin_write_cloning\fR() +preserves the first +\fIoffset\fR +bytes of the original file. +This is done efficiently, and writes to +\fIsource\fR +won't overwrite the original data until +\fBzip_commit_write\fR() +is called. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_commit_write(3), +zip_source_rollback_write(3), +zip_source_seek_write(3), +zip_source_tell_write(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_begin_write\fR() +was added in libzip 1.0. +.PP +\fBzip_source_begin_write_cloning\fR() +was added in libzip 1.4.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_begin_write.mdoc b/third_party/libzip/man/zip_source_begin_write.mdoc new file mode 100644 index 0000000..bef77e2 --- /dev/null +++ b/third_party/libzip/man/zip_source_begin_write.mdoc @@ -0,0 +1,89 @@ +.\" zip_source_begin_write.mdoc -- prepare zip source for writing +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_BEGIN_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_begin_write , +.Nm zip_source_begin_write_cloning +.Nd prepare zip source for writing +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_begin_write "zip_source_t *source" +.Ft int +.Fn zip_source_begin_write_cloning "zip_source_t *source" "zip_uint64_t offset" +.Sh DESCRIPTION +The functions +.Fn zip_source_begin_write +and +.Fn zip_source_begin_write_cloning +prepare +.Fa source +for writing. +Usually this involves creating temporary files or allocating buffers. +.Pp +.Fn zip_source_begin_write_cloning +preserves the first +.Ar offset +bytes of the original file. +This is done efficiently, and writes to +.Ar source +won't overwrite the original data until +.Fn zip_commit_write +is called. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_commit_write 3 , +.Xr zip_source_rollback_write 3 , +.Xr zip_source_seek_write 3 , +.Xr zip_source_tell_write 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_begin_write +was added in libzip 1.0. +.Pp +.Fn zip_source_begin_write_cloning +was added in libzip 1.4.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_buffer.html b/third_party/libzip/man/zip_source_buffer.html new file mode 100644 index 0000000..4e8a3a6 --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer.html @@ -0,0 +1,135 @@ + + + + + + + ZIP_SOURCE_BUFFER(3) + + + + + + + + +
ZIP_SOURCE_BUFFER(3)Library Functions ManualZIP_SOURCE_BUFFER(3)
+
+
+

+zip_source_buffer, + zip_source_buffer_create — +
create zip data source from buffer
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_buffer(zip_t + *archive, const void + *data, zip_uint64_t + len, int + freep);

+

zip_source_t * +
+ zip_source_buffer_create(const + void *data, zip_uint64_t + len, int freep, + zip_error_t *error);

+
+
+

+The functions zip_source_buffer() and + zip_source_buffer_create() create a zip source from + the buffer data of size len. If + freep is non-zero, the buffer will be freed when it is + no longer needed. data must remain valid for the + lifetime of the created source. +

The source can be used to open a zip archive from.

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_buffer() and + zip_source_buffer_create() fail if: +
+
[]
+
len is greater than zero and + data is NULL.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_open_from_source(3), + zip_source(3) +
+
+

+zip_source_buffer() and + zip_source_buffer_create() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_buffer.man b/third_party/libzip/man/zip_source_buffer.man new file mode 100644 index 0000000..5e29096 --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer.man @@ -0,0 +1,112 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_buffer.mdoc -- create zip data source from buffer +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_BUFFER" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_buffer\fR, +\fBzip_source_buffer_create\fR +\- create zip data source from buffer +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_buffer\fR(\fIzip_t\ *archive\fR, \fIconst\ void\ *data\fR, \fIzip_uint64_t\ len\fR, \fIint\ freep\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_buffer_create\fR(\fIconst\ void\ *data\fR, \fIzip_uint64_t\ len\fR, \fIint\ freep\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_buffer\fR() +and +\fBzip_source_buffer_create\fR() +create a zip source from the buffer +\fIdata\fR +of size +\fIlen\fR. +If +\fIfreep\fR +is non-zero, the buffer will be freed when it is no longer needed. +\fIdata\fR +must remain valid for the lifetime of the created source. +.PP +The source can be used to open a zip archive from. +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_buffer\fR() +and +\fBzip_source_buffer_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIlen\fR +is greater than zero and +\fIdata\fR +is +\fRNULL\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_open_from_source(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_buffer\fR() +and +\fBzip_source_buffer_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_buffer.mdoc b/third_party/libzip/man/zip_source_buffer.mdoc new file mode 100644 index 0000000..a08927e --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer.mdoc @@ -0,0 +1,102 @@ +.\" zip_source_buffer.mdoc -- create zip data source from buffer +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_BUFFER 3 +.Os +.Sh NAME +.Nm zip_source_buffer , +.Nm zip_source_buffer_create +.Nd create zip data source from buffer +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_buffer "zip_t *archive" "const void *data" "zip_uint64_t len" "int freep" +.Ft zip_source_t * +.Fn zip_source_buffer_create "const void *data" "zip_uint64_t len" "int freep" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_buffer +and +.Fn zip_source_buffer_create +create a zip source from the buffer +.Ar data +of size +.Ar len . +If +.Ar freep +is non-zero, the buffer will be freed when it is no longer needed. +.Ar data +must remain valid for the lifetime of the created source. +.Pp +The source can be used to open a zip archive from. +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_buffer +and +.Fn zip_source_buffer_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar len +is greater than zero and +.Ar data +is +.Dv NULL . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_open_from_source 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_buffer +and +.Fn zip_source_buffer_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_buffer_fragment.html b/third_party/libzip/man/zip_source_buffer_fragment.html new file mode 100644 index 0000000..0c3a670 --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer_fragment.html @@ -0,0 +1,150 @@ + + + + + + + ZIP_SOURCE_BUFFER_FRAGMENT(3) + + + + + + + + +
ZIP_SOURCE_BUFFER_FRAGMENT(3)Library Functions ManualZIP_SOURCE_BUFFER_FRAGMENT(3)
+
+
+

+zip_source_buffer_fragment, + zip_source_buffer_fragment_create — +
create zip data source from multiple buffer
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_buffer_fragment(zip_t + *archive, + zip_buffer_fragment_t + *fragments, zip_uint64_t + nfragments, int + freep);

+

zip_source_t * +
+ zip_source_buffer_fragment_create(zip_buffer_fragment_t + *fragments, zip_uint64_t + nfragments, int + freep, zip_error_t + *error);

+
+
+

+The functions zip_source_buffer_fragment() and + zip_source_buffer_fragment_create() create a zip + source from the data in fragments. + nfragments specifies the number of fragments. If + freep is non-zero, the data will be freed when it is no + longer needed. +
+
+struct zip_stat {
+    zip_uint8_t *data;    /* pointer to the actual data */
+    zip_uint64_t length;  /* length of this fragment */
+};
+
+
+

The data fragments point to must remain + valid for the lifetime of the created source. + fragments itself can be discarded once the source is + created.

+

The source can be used to open a zip archive from.

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_buffer() and + zip_source_buffer_create() fail if: +
+
[]
+
nfragments is greater than zero and + fragments is NULL.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_open_from_source(3), + zip_source(3) +
+
+

+zip_source_buffer_fragment() and + zip_source_buffer_fragment_create() were added in + libzip 1.4.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_buffer_fragment.man b/third_party/libzip/man/zip_source_buffer_fragment.man new file mode 100644 index 0000000..7c8ebbc --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer_fragment.man @@ -0,0 +1,125 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_buffer_fragment.mdoc -- create zip data source from multiple buffers +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_BUFFER_FRAGMENT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_buffer_fragment\fR, +\fBzip_source_buffer_fragment_create\fR +\- create zip data source from multiple buffer +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_buffer_fragment\fR(\fIzip_t\ *archive\fR, \fIzip_buffer_fragment_t\ *fragments\fR, \fIzip_uint64_t\ nfragments\fR, \fIint\ freep\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_buffer_fragment_create\fR(\fIzip_buffer_fragment_t\ *fragments\fR, \fIzip_uint64_t\ nfragments\fR, \fIint\ freep\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_buffer_fragment\fR() +and +\fBzip_source_buffer_fragment_create\fR() +create a zip source from the data in +\fIfragments\fR. +\fInfragments\fR +specifies the number of fragments. +If +\fIfreep\fR +is non-zero, the data will be freed when it is no longer needed. +.nf +.sp +.RS 0n +struct zip_stat { + zip_uint8_t *data; /* pointer to the actual data */ + zip_uint64_t length; /* length of this fragment */ +}; +.RE +.fi +.PP +The data +\fIfragments\fR +point to must remain valid for the lifetime of the created source. +\fIfragments\fR +itself can be discarded once the source is created. +.PP +The source can be used to open a zip archive from. +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_buffer\fR() +and +\fBzip_source_buffer_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fInfragments\fR +is greater than zero and +\fIfragments\fR +is +\fRNULL\fR. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_open_from_source(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_buffer_fragment\fR() +and +\fBzip_source_buffer_fragment_create\fR() +were added in libzip 1.4.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_buffer_fragment.mdoc b/third_party/libzip/man/zip_source_buffer_fragment.mdoc new file mode 100644 index 0000000..e39eba0 --- /dev/null +++ b/third_party/libzip/man/zip_source_buffer_fragment.mdoc @@ -0,0 +1,112 @@ +.\" zip_source_buffer_fragment.mdoc -- create zip data source from multiple buffers +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_BUFFER_FRAGMENT 3 +.Os +.Sh NAME +.Nm zip_source_buffer_fragment , +.Nm zip_source_buffer_fragment_create +.Nd create zip data source from multiple buffer +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_buffer_fragment "zip_t *archive" "zip_buffer_fragment_t *fragments" "zip_uint64_t nfragments" "int freep" +.Ft zip_source_t * +.Fn zip_source_buffer_fragment_create "zip_buffer_fragment_t *fragments" "zip_uint64_t nfragments" "int freep" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_buffer_fragment +and +.Fn zip_source_buffer_fragment_create +create a zip source from the data in +.Ar fragments . +.Ar nfragments +specifies the number of fragments. +If +.Ar freep +is non-zero, the data will be freed when it is no longer needed. +.Bd -literal +struct zip_stat { + zip_uint8_t *data; /* pointer to the actual data */ + zip_uint64_t length; /* length of this fragment */ +}; +.Ed +.Pp +The data +.Ar fragments +point to must remain valid for the lifetime of the created source. +.Ar fragments +itself can be discarded once the source is created. +.Pp +The source can be used to open a zip archive from. +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_buffer +and +.Fn zip_source_buffer_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar nfragments +is greater than zero and +.Ar fragments +is +.Dv NULL . +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_open_from_source 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_buffer_fragment +and +.Fn zip_source_buffer_fragment_create +were added in libzip 1.4.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_close.html b/third_party/libzip/man/zip_source_close.html new file mode 100644 index 0000000..c3bf7bf --- /dev/null +++ b/third_party/libzip/man/zip_source_close.html @@ -0,0 +1,105 @@ + + + + + + + ZIP_SOURCE_CLOSE(3) + + + + + + + + +
ZIP_SOURCE_CLOSE(3)Library Functions ManualZIP_SOURCE_CLOSE(3)
+
+
+

+zip_source_close — +
open zip_source (which was open for reading)
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_close(zip_source_t + *source);

+
+
+

+The function zip_source_close() closes + source, indicating that no more data will be read. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_free(3), + zip_source_open(3) +
+
+

+zip_source_close() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_close.man b/third_party/libzip/man/zip_source_close.man new file mode 100644 index 0000000..283e93b --- /dev/null +++ b/third_party/libzip/man/zip_source_close.man @@ -0,0 +1,72 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_close.mdoc -- close zip source (open for reading) +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_CLOSE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_close\fR +\- open zip_source (which was open for reading) +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_close\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_close\fR() +closes +\fIsource\fR, +indicating that no more data will be read. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_free(3), +zip_source_open(3) +.SH "HISTORY" +\fBzip_source_close\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_close.mdoc b/third_party/libzip/man/zip_source_close.mdoc new file mode 100644 index 0000000..4220861 --- /dev/null +++ b/third_party/libzip/man/zip_source_close.mdoc @@ -0,0 +1,67 @@ +.\" zip_source_close.mdoc -- close zip source (open for reading) +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_CLOSE 3 +.Os +.Sh NAME +.Nm zip_source_close +.Nd open zip_source (which was open for reading) +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_close "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_close +closes +.Fa source , +indicating that no more data will be read. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_free 3 , +.Xr zip_source_open 3 +.Sh HISTORY +.Fn zip_source_close +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_commit_write.html b/third_party/libzip/man/zip_source_commit_write.html new file mode 100644 index 0000000..2c3ebb1 --- /dev/null +++ b/third_party/libzip/man/zip_source_commit_write.html @@ -0,0 +1,109 @@ + + + + + + + ZIP_SOURCE_COMMIT_WRITE(3) + + + + + + + + +
ZIP_SOURCE_COMMIT_WRITE(3)Library Functions ManualZIP_SOURCE_COMMIT_WRITE(3)
+
+
+

+zip_source_commit_write — +
finalize changes to zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_commit_write(zip_source_t + *source);

+
+
+

+The function zip_source_commit_write() finishes writing + data to source and replaces the original with the newly + written data. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_rollback_write(3), + zip_source_seek_write(3), + zip_source_tell_write(3), + zip_source_write(3) +
+
+

+zip_source_commit_write() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_commit_write.man b/third_party/libzip/man/zip_source_commit_write.man new file mode 100644 index 0000000..2df6abb --- /dev/null +++ b/third_party/libzip/man/zip_source_commit_write.man @@ -0,0 +1,75 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_commit_write.mdoc -- finalize changes to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_COMMIT_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_commit_write\fR +\- finalize changes to zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_commit_write\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_commit_write\fR() +finishes writing data to +\fIsource\fR +and replaces the original with the newly written data. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_rollback_write(3), +zip_source_seek_write(3), +zip_source_tell_write(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_commit_write\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_commit_write.mdoc b/third_party/libzip/man/zip_source_commit_write.mdoc new file mode 100644 index 0000000..69c4f1b --- /dev/null +++ b/third_party/libzip/man/zip_source_commit_write.mdoc @@ -0,0 +1,70 @@ +.\" zip_source_commit_write.mdoc -- finalize changes to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_COMMIT_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_commit_write +.Nd finalize changes to zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_commit_write "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_commit_write +finishes writing data to +.Fa source +and replaces the original with the newly written data. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_rollback_write 3 , +.Xr zip_source_seek_write 3 , +.Xr zip_source_tell_write 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_commit_write +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_error.html b/third_party/libzip/man/zip_source_error.html new file mode 100644 index 0000000..16b982a --- /dev/null +++ b/third_party/libzip/man/zip_source_error.html @@ -0,0 +1,97 @@ + + + + + + + ZIP_SOURCE_ERROR(3) + + + + + + + + +
ZIP_SOURCE_ERROR(3)Library Functions ManualZIP_SOURCE_ERROR(3)
+
+
+

+zip_source_error — +
get zip error for data source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_error_t * +
+ zip_source_error(zip_source_t + *source);

+
+
+

+The zip_source_error() function returns the zip error + for the data source source. +
+
+

+libzip(3), + zip_error_code_system(3), + zip_error_code_zip(3) +
+
+

+zip_source_error() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_error.man b/third_party/libzip/man/zip_source_error.man new file mode 100644 index 0000000..62e7544 --- /dev/null +++ b/third_party/libzip/man/zip_source_error.man @@ -0,0 +1,65 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_error.mdoc -- get zip_error for data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_ERROR" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_error\fR +\- get zip error for data source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_error_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_error\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_source_error\fR() +function returns the zip error for the data source +\fIsource\fR. +.SH "SEE ALSO" +libzip(3), +zip_error_code_system(3), +zip_error_code_zip(3) +.SH "HISTORY" +\fBzip_source_error\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_error.mdoc b/third_party/libzip/man/zip_source_error.mdoc new file mode 100644 index 0000000..af098d1 --- /dev/null +++ b/third_party/libzip/man/zip_source_error.mdoc @@ -0,0 +1,60 @@ +.\" zip_source_error.mdoc -- get zip_error for data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_ERROR 3 +.Os +.Sh NAME +.Nm zip_source_error +.Nd get zip error for data source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_error_t * +.Fn zip_source_error "zip_source_t *source" +.Sh DESCRIPTION +The +.Fn zip_source_error +function returns the zip error for the data source +.Ar source . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_error_code_system 3 , +.Xr zip_error_code_zip 3 +.Sh HISTORY +.Fn zip_source_error +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_file.html b/third_party/libzip/man/zip_source_file.html new file mode 100644 index 0000000..11ec0da --- /dev/null +++ b/third_party/libzip/man/zip_source_file.html @@ -0,0 +1,141 @@ + + + + + + + ZIP_SOURCE_FILE(3) + + + + + + + + +
ZIP_SOURCE_FILE(3)Library Functions ManualZIP_SOURCE_FILE(3)
+
+
+

+zip_source_file, + zip_source_file_create — +
create data source from a file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_file(zip_t + *archive, const char + *fname, zip_uint64_t + start, zip_int64_t + len);

+

zip_source_t * +
+ zip_source_file_create(const + char *fname, zip_uint64_t + start, zip_int64_t + len, zip_error_t + *error);

+
+
+

+The functions zip_source_file() and + zip_source_file_create() create a zip source from a + file. They open fname and read len + bytes from offset start from it. If + len is 0 or -1, the whole file (starting from + start) is used. +

If the file supports seek, the source can be used to open a zip + archive from.

+

The file is opened and read when the data from the source is used, + usually by zip_close() or + zip_open_from_source().

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_file() and + zip_source_file_create() fail if: +
+
[]
+
fname, start, or + len are invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Opening fname failed.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3) +
+
+

+zip_source_file() and + zip_source_file_create() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_file.man b/third_party/libzip/man/zip_source_file.man new file mode 100644 index 0000000..ab719a1 --- /dev/null +++ b/third_party/libzip/man/zip_source_file.man @@ -0,0 +1,125 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_file.mdoc -- create data source from a file +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_FILE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_file\fR, +\fBzip_source_file_create\fR +\- create data source from a file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_file\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_file_create\fR(\fIconst\ char\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_file\fR() +and +\fBzip_source_file_create\fR() +create a zip source from a file. +They open +\fIfname\fR +and read +\fIlen\fR +bytes from offset +\fIstart\fR +from it. +If +\fIlen\fR +is 0 or \-1, the whole file (starting from +\fIstart\fR) +is used. +.PP +If the file supports seek, the source can be used to open a zip archive from. +.PP +The file is opened and read when the data from the source is used, usually by +\fBzip_close\fR() +or +\fBzip_open_from_source\fR(). +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_file\fR() +and +\fBzip_source_file_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIfname\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_OPEN\fR] +Opening +\fIfname\fR +failed. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_file\fR() +and +\fBzip_source_file_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_file.mdoc b/third_party/libzip/man/zip_source_file.mdoc new file mode 100644 index 0000000..90304dd --- /dev/null +++ b/third_party/libzip/man/zip_source_file.mdoc @@ -0,0 +1,114 @@ +.\" zip_source_file.mdoc -- create data source from a file +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_FILE 3 +.Os +.Sh NAME +.Nm zip_source_file , +.Nm zip_source_file_create +.Nd create data source from a file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_file "zip_t *archive" "const char *fname" "zip_uint64_t start" "zip_int64_t len" +.Ft zip_source_t * +.Fn zip_source_file_create "const char *fname" "zip_uint64_t start" "zip_int64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_file +and +.Fn zip_source_file_create +create a zip source from a file. +They open +.Ar fname +and read +.Ar len +bytes from offset +.Ar start +from it. +If +.Ar len +is 0 or \-1, the whole file (starting from +.Ar start ) +is used. +.Pp +If the file supports seek, the source can be used to open a zip archive from. +.Pp +The file is opened and read when the data from the source is used, usually by +.Fn zip_close +or +.Fn zip_open_from_source . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_file +and +.Fn zip_source_file_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar fname , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_OPEN +Opening +.Ar fname +failed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_file +and +.Fn zip_source_file_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_filep.html b/third_party/libzip/man/zip_source_filep.html new file mode 100644 index 0000000..423ac21 --- /dev/null +++ b/third_party/libzip/man/zip_source_filep.html @@ -0,0 +1,137 @@ + + + + + + + ZIP_SOURCE_FILEP(3) + + + + + + + + +
ZIP_SOURCE_FILEP(3)Library Functions ManualZIP_SOURCE_FILEP(3)
+
+
+

+zip_source_filep, + zip_source_filep_create — +
create data source from FILE *
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_filep(zip_t + *archive, FILE + *file, zip_uint64_t + start, zip_int64_t + len);

+

zip_source_t * +
+ zip_source_filep_create(FILE + *file, zip_uint64_t + start, zip_int64_t + len, zip_error_t + *error);

+
+
+

+The functions zip_source_filep() and + zip_source_filep_create() create a zip source from a + file stream. They read len bytes from offset + start from the open file stream + file. If len is 0 or -1, the whole + file (starting from start) is used. +

If the file stream supports seeking, the source can be used to + open a read-only zip archive from.

+

The file stream is closed when the source is being freed, usually + by zip_close(3).

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_filep() fails if: +
+
[]
+
file, start, or + len are invalid.
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3) +
+
+

+zip_source_filep() and + zip_source_filep_create() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_filep.man b/third_party/libzip/man/zip_source_filep.man new file mode 100644 index 0000000..8037262 --- /dev/null +++ b/third_party/libzip/man/zip_source_filep.man @@ -0,0 +1,117 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_filep.mdoc -- create data source from a file stream +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_FILEP" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_filep\fR, +\fBzip_source_filep_create\fR +\- create data source from FILE * +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_filep\fR(\fIzip_t\ *archive\fR, \fIFILE\ *file\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_filep_create\fR(\fIFILE\ *file\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_filep\fR() +and +\fBzip_source_filep_create\fR() +create a zip source from a file stream. +They read +\fIlen\fR +bytes from offset +\fIstart\fR +from the open file stream +\fIfile\fR. +If +\fIlen\fR +is 0 or \-1, the whole file (starting from +\fIstart\fR) +is used. +.PP +If the file stream supports seeking, the source can be used to open +a read-only zip archive from. +.PP +The file stream is closed when the source is being freed, usually +by +zip_close(3). +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_filep\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIfile\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_filep\fR() +and +\fBzip_source_filep_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_filep.mdoc b/third_party/libzip/man/zip_source_filep.mdoc new file mode 100644 index 0000000..848ba76 --- /dev/null +++ b/third_party/libzip/man/zip_source_filep.mdoc @@ -0,0 +1,107 @@ +.\" zip_source_filep.mdoc -- create data source from a file stream +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_FILEP 3 +.Os +.Sh NAME +.Nm zip_source_filep , +.Nm zip_source_filep_create +.Nd create data source from FILE * +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_filep "zip_t *archive" "FILE *file" "zip_uint64_t start" "zip_int64_t len" +.Ft zip_source_t * +.Fn zip_source_filep_create "FILE *file" "zip_uint64_t start" "zip_int64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_filep +and +.Fn zip_source_filep_create +create a zip source from a file stream. +They read +.Ar len +bytes from offset +.Ar start +from the open file stream +.Ar file . +If +.Ar len +is 0 or \-1, the whole file (starting from +.Ar start ) +is used. +.Pp +If the file stream supports seeking, the source can be used to open +a read-only zip archive from. +.Pp +The file stream is closed when the source is being freed, usually +by +.Xr zip_close 3 . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_filep +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar file , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_filep +and +.Fn zip_source_filep_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_free.html b/third_party/libzip/man/zip_source_free.html new file mode 100644 index 0000000..8c75385 --- /dev/null +++ b/third_party/libzip/man/zip_source_free.html @@ -0,0 +1,104 @@ + + + + + + + ZIP_SOURCE_FREE(3) + + + + + + + + +
ZIP_SOURCE_FREE(3)Library Functions ManualZIP_SOURCE_FREE(3)
+
+
+

+zip_source_free — +
free zip data source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_source_free(zip_source_t + *source);

+
+
+

+The function zip_source_free() decrements the reference + count of source and frees it if the reference count + drops to 0. If source is NULL, + it does nothing. +

NOTE: This function should not be called on a + source after it was used successfully in a + zip_open_from_source(3), + zip_file_add(3), or + zip_file_replace(3) call.

+
+
+

+libzip(3), + zip_source(3), + zip_source_keep(3) +
+
+

+zip_source_free() was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_free.man b/third_party/libzip/man/zip_source_free.man new file mode 100644 index 0000000..5f79671 --- /dev/null +++ b/third_party/libzip/man/zip_source_free.man @@ -0,0 +1,81 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_free.mdoc -- free zip data source +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_FREE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_free\fR +\- free zip data source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_source_free\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_free\fR() +decrements the reference count of +\fIsource\fR +and frees it if the reference count drops to 0. +If +\fIsource\fR +is +\fRNULL\fR, +it does nothing. +.PP +\fINOTE\fR: +This function should not be called on a +\fIsource\fR +after it was used successfully in a +zip_open_from_source(3), +zip_file_add(3), +or +zip_file_replace(3) +call. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_keep(3) +.SH "HISTORY" +\fBzip_source_free\fR() +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_free.mdoc b/third_party/libzip/man/zip_source_free.mdoc new file mode 100644 index 0000000..816f7a1 --- /dev/null +++ b/third_party/libzip/man/zip_source_free.mdoc @@ -0,0 +1,76 @@ +.\" zip_source_free.mdoc -- free zip data source +.\" Copyright (C) 2004-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_FREE 3 +.Os +.Sh NAME +.Nm zip_source_free +.Nd free zip data source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_source_free "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_free +decrements the reference count of +.Ar source +and frees it if the reference count drops to 0. +If +.Ar source +is +.Dv NULL , +it does nothing. +.Pp +.Em NOTE : +This function should not be called on a +.Ar source +after it was used successfully in a +.Xr zip_open_from_source 3 , +.Xr zip_file_add 3 , +or +.Xr zip_file_replace 3 +call. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_keep 3 +.Sh HISTORY +.Fn zip_source_free +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_function.html b/third_party/libzip/man/zip_source_function.html new file mode 100644 index 0000000..cc24448 --- /dev/null +++ b/third_party/libzip/man/zip_source_function.html @@ -0,0 +1,333 @@ + + + + + + + ZIP_SOURCE_FUNCTION(3) + + + + + + + + +
ZIP_SOURCE_FUNCTION(3)Library Functions ManualZIP_SOURCE_FUNCTION(3)
+
+
+

+zip_source_function, + zip_source_function_create — +
create data source from function
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_function(zip_t + *archive, + zip_source_callback fn, + void *userdata);

+

zip_source_t * +
+ zip_source_function_create(zip_source_callback + fn, void *userdata, + zip_error_t *error);

+
+
+

+The functions zip_source_function() and + zip_source_function_create() creates a zip source from + the user-provided function fn, which must be of the + following type: +

typedef zip_int64_t + (*zip_source_callback)(void + *userdata, void *data, + zip_uint64_t len, zip_source_cmd_t + cmd);

+

archive or error are + used for reporting errors and can be NULL.

+

When called by the library, the first argument is the + userdata argument supplied to the function. The next + two arguments are a buffer data of size + len when data is passed in or expected to be returned, + or else NULL and 0. The last argument, + cmd, specifies which action the function should + perform.

+

Depending on the uses, there are three useful sets of commands to + be supported by a zip_source_callback():

+
+
read source
+
Providing streamed data (for file data added to archives). Must support + ZIP_SOURCE_OPEN, + ZIP_SOURCE_READ, + ZIP_SOURCE_CLOSE, + ZIP_SOURCE_STAT, and + ZIP_SOURCE_ERROR.
+
seekable read source
+
Same as previous, but from a source allowing reading from arbitrary + offsets (also for read-only zip archive). Must additionally support + ZIP_SOURCE_SEEK, + ZIP_SOURCE_TELL, and + ZIP_SOURCE_SUPPORTS.
+
read/write source
+
Same as previous, but additionally allowing writing (also for writable zip + archives). Must additionally support + ZIP_SOURCE_BEGIN_WRITE, + ZIP_SOURCE_COMMIT_WRITE, + ZIP_SOURCE_ROLLBACK_WRITE, + ZIP_SOURCE_SEEK_WRITE, + ZIP_SOURCE_TELL_WRITE, and + ZIP_SOURCE_REMOVE.
+
+
+

ZIP_SOURCE_BEGIN_WRITE

+Prepare the source for writing. Use this to create any temporary file(s). +
+
+

ZIP_SOURCE_BEGIN_WRITE_CLONING

+Prepare the source for writing, keeping the first len + bytes of the original file. Only implement this command if it is more + efficient than copying the data, and if it does not destructively overwrite + the original file (you still have to be able to execute + ZIP_SOURCE_ROLLBACK_WRITE). +

The next write should happen at byte + offset.

+
+
+

ZIP_SOURCE_CLOSE

+Reading is done. +
+
+

ZIP_SOURCE_COMMIT_WRITE

+Finish writing to the source. Replace the original data with the newly written + data. Clean up temporary files or internal buffers. Subsequently opening and + reading from the source should return the newly written data. +
+
+

ZIP_SOURCE_ERROR

+Get error information. data points to an array of two + ints, which should be filled with the libzip error code and the corresponding + system error code for the error that occurred. See + zip_errors(3) for details on the + error codes. If the source stores error information in a zip_error_t, use + zip_error_to_data(3) and + return its return value. Otherwise, return 2 * sizeof(int). +
+
+

ZIP_SOURCE_FREE

+Clean up and free all resources, including userdata. The + callback function will not be called again. +
+
+

ZIP_SOURCE_OPEN

+Prepare for reading. +
+
+

ZIP_SOURCE_READ

+Read data into the buffer data of size + len. Return the number of bytes placed into + data on success, and zero for end-of-file. +
+
+

ZIP_SOURCE_REMOVE

+Remove the underlying file. This is called if a zip archive is empty when + closed. +
+
+

ZIP_SOURCE_ROLLBACK_WRITE

+Abort writing to the source. Discard written data. Clean up temporary files or + internal buffers. Subsequently opening and reading from the source should + return the original data. +
+
+

ZIP_SOURCE_SEEK

+Specify position to read next byte from, like + fseek(3). Use + ZIP_SOURCE_GET_ARGS(3) to + decode the arguments into the following struct: +
+
+struct zip_source_args_seek {
+    zip_int64_t offset;
+    int whence;
+};
+
+
+

If the size of the source's data is known, use + zip_source_seek_compute_offset(3) + to validate the arguments and compute the new offset.

+
+
+

ZIP_SOURCE_SEEK_WRITE

+Specify position to write next byte to, like + fseek(3). See + ZIP_SOURCE_SEEK for details. +
+
+

ZIP_SOURCE_STAT

+Get meta information for the input data. data points to an + allocated struct zip_stat, which should be initialized + using zip_stat_init(3) and then + filled in. +

For uncompressed, unencrypted data, all information is optional. + However, fill in as much information as is readily available.

+

If the data is compressed, + ZIP_STAT_COMP_METHOD, + ZIP_STAT_SIZE, and + ZIP_STAT_CRC must be filled in.

+

If the data is encrypted, + ZIP_STAT_ENCRYPTION_METHOD, + ZIP_STAT_COMP_METHOD, + ZIP_STAT_SIZE, and + ZIP_STAT_CRC must be filled in.

+

Information only available after the source has been read (e.g., + size) can be omitted in an earlier call. NOTE: + zip_source_function() may be called with this + argument even after being called with + ZIP_SOURCE_CLOSE.

+

Return sizeof(struct zip_stat) on success.

+
+
+

ZIP_SOURCE_SUPPORTS

+Return bitmap specifying which commands are supported. Use + zip_source_make_command_bitmap(3). + If this command is not implemented, the source is assumed to be a read source + without seek support. +
+
+

ZIP_SOURCE_TELL

+Return the current read offset in the source, like + ftell(3). +
+
+

ZIP_SOURCE_TELL_WRITE

+Return the current write offset in the source, like + ftell(3). +
+
+

ZIP_SOURCE_WRITE

+Write data to the source. Return number of bytes written. +
+
+

+Commands should return -1 on error. ZIP_SOURCE_ERROR + will be called to retrieve the error code. On success, commands return 0, + unless specified otherwise in the description above. +
+
+

+The library will always issue ZIP_SOURCE_OPEN before + issuing ZIP_SOURCE_READ, + ZIP_SOURCE_SEEK, or + ZIP_SOURCE_TELL. When it no longer wishes to read from + this source, it will issue ZIP_SOURCE_CLOSE. If the + library wishes to read the data again, it will issue + ZIP_SOURCE_OPEN a second time. If the function is + unable to provide the data again, it should return -1. +

ZIP_SOURCE_BEGIN_WRITE or + ZIP_SOURCE_BEGIN_WRITE_CLONING will be called before + ZIP_SOURCE_WRITE, + ZIP_SOURCE_SEEK_WRITE, or + ZIP_SOURCE_TELL_WRITE. When writing is complete, + either ZIP_SOURCE_COMMIT_WRITE or + ZIP_SOURCE_ROLLBACK_WRITE will be called.

+

ZIP_SOURCE_STAT can be issued at any + time.

+

ZIP_SOURCE_ERROR will only be issued in + response to the function returning -1.

+

ZIP_SOURCE_FREE will be the last command + issued; if ZIP_SOURCE_OPEN was called and succeeded, + ZIP_SOURCE_CLOSE will be called before + ZIP_SOURCE_FREE, and similarly for + ZIP_SOURCE_BEGIN_WRITE or + ZIP_SOURCE_BEGIN_WRITE_CLONING and + ZIP_SOURCE_COMMIT_WRITE or + ZIP_SOURCE_ROLLBACK_WRITE.

+
+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error (unless it is NULL). +
+
+

+zip_source_function() fails if: +
+
[]
+
Required memory could not be allocated.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3), + zip_stat_init(3) +
+
+

+zip_source_function() and + zip_source_function_create() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_function.man b/third_party/libzip/man/zip_source_function.man new file mode 100644 index 0000000..073f56c --- /dev/null +++ b/third_party/libzip/man/zip_source_function.man @@ -0,0 +1,346 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_function.mdoc -- create data source from function +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_FUNCTION" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_function\fR, +\fBzip_source_function_create\fR +\- create data source from function +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_function\fR(\fIzip_t\ *archive\fR, \fIzip_source_callback\ fn\fR, \fIvoid\ *userdata\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_function_create\fR(\fIzip_source_callback\ fn\fR, \fIvoid\ *userdata\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_function\fR() +and +\fBzip_source_function_create\fR() +creates a zip source from the user-provided function +\fIfn\fR, +which must be of the following type: +.PP +\fItypedef zip_int64_t\fR +\fB\fR(*\fPzip_source_callback\fR)\fP\fR(\fIvoid\ *userdata\fR, \fIvoid\ *data\fR, \fIzip_uint64_t\ len\fR, \fIzip_source_cmd_t\ cmd\fR) +.PP +\fIarchive\fR +or +\fIerror\fR +are used for reporting errors and can be +\fRNULL\fR. +.PP +When called by the library, the first argument is the +\fIuserdata\fR +argument supplied to the function. +The next two arguments are a buffer +\fIdata\fR +of size +\fIlen\fR +when data is passed in or expected to be returned, or else +\fRNULL\fR +and 0. +The last argument, +\fIcmd\fR, +specifies which action the function should perform. +.PP +Depending on the uses, there are three useful sets of commands to be supported by a +\fBzip_source_callback\fR(): +.TP 24n +read source +Providing streamed data (for file data added to archives). +Must support +\fRZIP_SOURCE_OPEN\fR, +\fRZIP_SOURCE_READ\fR, +\fRZIP_SOURCE_CLOSE\fR, +\fRZIP_SOURCE_STAT\fR, +and +\fRZIP_SOURCE_ERROR\fR. +.TP 24n +seekable read source +Same as previous, but from a source allowing reading from arbitrary +offsets (also for read-only zip archive). +Must additionally support +\fRZIP_SOURCE_SEEK\fR, +\fRZIP_SOURCE_TELL\fR, +and +\fRZIP_SOURCE_SUPPORTS\fR. +.TP 24n +read/write source +Same as previous, but additionally allowing writing (also for writable +zip archives). +Must additionally support +\fRZIP_SOURCE_BEGIN_WRITE\fR, +\fRZIP_SOURCE_COMMIT_WRITE\fR, +\fRZIP_SOURCE_ROLLBACK_WRITE\fR, +\fRZIP_SOURCE_SEEK_WRITE\fR, +\fRZIP_SOURCE_TELL_WRITE\fR, +and +\fRZIP_SOURCE_REMOVE\fR. +.SS "\fRZIP_SOURCE_BEGIN_WRITE\fR" +Prepare the source for writing. +Use this to create any temporary file(s). +.SS "\fRZIP_SOURCE_BEGIN_WRITE_CLONING\fR" +Prepare the source for writing, keeping the first +\fIlen\fR +bytes of the original file. +Only implement this command if it is more efficient than copying the +data, and if it does not destructively overwrite the original file +(you still have to be able to execute +\fRZIP_SOURCE_ROLLBACK_WRITE\fR). +.PP +The next write should happen at byte +\fIoffset\fR. +.SS "\fRZIP_SOURCE_CLOSE\fR" +Reading is done. +.SS "\fRZIP_SOURCE_COMMIT_WRITE\fR" +Finish writing to the source. +Replace the original data with the newly written data. +Clean up temporary files or internal buffers. +Subsequently opening and reading from the source should return the +newly written data. +.SS "\fRZIP_SOURCE_ERROR\fR" +Get error information. +\fIdata\fR +points to an array of two ints, which should be filled with the libzip +error code and the corresponding system error code for the error that +occurred. +See +zip_errors(3) +for details on the error codes. +If the source stores error information in a zip_error_t, use +zip_error_to_data(3) +and return its return value. +Otherwise, return 2 * sizeof(int). +.SS "\fRZIP_SOURCE_FREE\fR" +Clean up and free all resources, including +\fIuserdata\fR. +The callback function will not be called again. +.SS "\fRZIP_SOURCE_OPEN\fR" +Prepare for reading. +.SS "\fRZIP_SOURCE_READ\fR" +Read data into the buffer +\fIdata\fR +of size +\fIlen\fR. +Return the number of bytes placed into +\fIdata\fR +on success, and zero for end-of-file. +.SS "\fRZIP_SOURCE_REMOVE\fR" +Remove the underlying file. +This is called if a zip archive is empty when closed. +.SS "\fRZIP_SOURCE_ROLLBACK_WRITE\fR" +Abort writing to the source. +Discard written data. +Clean up temporary files or internal buffers. +Subsequently opening and reading from the source should return the +original data. +.SS "\fRZIP_SOURCE_SEEK\fR" +Specify position to read next byte from, like +fseek(3). +Use +ZIP_SOURCE_GET_ARGS(3) +to decode the arguments into the following struct: +.nf +.sp +.RS 0n +struct zip_source_args_seek { + zip_int64_t offset; + int whence; +}; +.RE +.fi +.PP +If the size of the source's data is known, use +zip_source_seek_compute_offset(3) +to validate the arguments and compute the new offset. +.SS "\fRZIP_SOURCE_SEEK_WRITE\fR" +Specify position to write next byte to, like +fseek(3). +See +\fRZIP_SOURCE_SEEK\fR +for details. +.SS "\fRZIP_SOURCE_STAT\fR" +Get meta information for the input data. +\fIdata\fR +points to an allocated +\fIstruct zip_stat\fR, +which should be initialized using +zip_stat_init(3) +and then filled in. +.PP +For uncompressed, unencrypted data, all information is optional. +However, fill in as much information as is readily available. +.PP +If the data is compressed, +\fRZIP_STAT_COMP_METHOD\fR, +\fRZIP_STAT_SIZE\fR, +and +\fRZIP_STAT_CRC\fR +must be filled in. +.PP +If the data is encrypted, +\fRZIP_STAT_ENCRYPTION_METHOD\fR, +\fRZIP_STAT_COMP_METHOD\fR, +\fRZIP_STAT_SIZE\fR, +and +\fRZIP_STAT_CRC\fR +must be filled in. +.PP +Information only available after the source has been read (e.g., size) +can be omitted in an earlier call. +\fINOTE\fR: +\fBzip_source_function\fR() +may be called with this argument even after being called with +\fRZIP_SOURCE_CLOSE\fR. +.PP +Return sizeof(struct zip_stat) on success. +.SS "\fRZIP_SOURCE_SUPPORTS\fR" +Return bitmap specifying which commands are supported. +Use +zip_source_make_command_bitmap(3). +If this command is not implemented, the source is assumed to be a +read source without seek support. +.SS "\fRZIP_SOURCE_TELL\fR" +Return the current read offset in the source, like +ftell(3). +.SS "\fRZIP_SOURCE_TELL_WRITE\fR" +Return the current write offset in the source, like +ftell(3). +.SS "\fRZIP_SOURCE_WRITE\fR" +Write data to the source. +Return number of bytes written. +.SS "Return Values" +Commands should return \-1 on error. +\fRZIP_SOURCE_ERROR\fR +will be called to retrieve the error code. +On success, commands return 0, unless specified otherwise in the +description above. +.SS "Calling Conventions" +The library will always issue +\fRZIP_SOURCE_OPEN\fR +before issuing +\fRZIP_SOURCE_READ\fR, +\fRZIP_SOURCE_SEEK\fR, +or +\fRZIP_SOURCE_TELL\fR. +When it no longer wishes to read from this source, it will issue +\fRZIP_SOURCE_CLOSE\fR. +If the library wishes to read the data again, it will issue +\fRZIP_SOURCE_OPEN\fR +a second time. +If the function is unable to provide the data again, it should +return \-1. +.PP +\fRZIP_SOURCE_BEGIN_WRITE\fR +or +\fRZIP_SOURCE_BEGIN_WRITE_CLONING\fR +will be called before +\fRZIP_SOURCE_WRITE\fR, +\fRZIP_SOURCE_SEEK_WRITE\fR, +or +\fRZIP_SOURCE_TELL_WRITE\fR. +When writing is complete, either +\fRZIP_SOURCE_COMMIT_WRITE\fR +or +\fRZIP_SOURCE_ROLLBACK_WRITE\fR +will be called. +.PP +\fRZIP_SOURCE_STAT\fR +can be issued at any time. +.PP +\fRZIP_SOURCE_ERROR\fR +will only be issued in response to the function +returning \-1. +.PP +\fRZIP_SOURCE_FREE\fR +will be the last command issued; +if +\fRZIP_SOURCE_OPEN\fR +was called and succeeded, +\fRZIP_SOURCE_CLOSE\fR +will be called before +\fRZIP_SOURCE_FREE\fR, +and similarly for +\fRZIP_SOURCE_BEGIN_WRITE\fR +or +\fRZIP_SOURCE_BEGIN_WRITE_CLONING\fR +and +\fRZIP_SOURCE_COMMIT_WRITE\fR +or +\fRZIP_SOURCE_ROLLBACK_WRITE\fR. +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error (unless +it is +\fRNULL\fR). +.SH "ERRORS" +\fBzip_source_function\fR() +fails if: +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3), +zip_stat_init(3) +.SH "HISTORY" +\fBzip_source_function\fR() +and +\fBzip_source_function_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_function.mdoc b/third_party/libzip/man/zip_source_function.mdoc new file mode 100644 index 0000000..a433b37 --- /dev/null +++ b/third_party/libzip/man/zip_source_function.mdoc @@ -0,0 +1,335 @@ +.\" zip_source_function.mdoc -- create data source from function +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_FUNCTION 3 +.Os +.Sh NAME +.Nm zip_source_function , +.Nm zip_source_function_create +.Nd create data source from function +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_function "zip_t *archive" "zip_source_callback fn" "void *userdata" +.Ft zip_source_t * +.Fn zip_source_function_create "zip_source_callback fn" "void *userdata" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_function +and +.Fn zip_source_function_create +creates a zip source from the user-provided function +.Ar fn , +which must be of the following type: +.Pp +.Ft typedef zip_int64_t +.Fo \fR(*\fPzip_source_callback\fR)\fP +.Fa "void *userdata" "void *data" "zip_uint64_t len" "zip_source_cmd_t cmd" +.Fc +.Pp +.Ar archive +or +.Ar error +are used for reporting errors and can be +.Dv NULL . +.Pp +When called by the library, the first argument is the +.Ar userdata +argument supplied to the function. +The next two arguments are a buffer +.Ar data +of size +.Ar len +when data is passed in or expected to be returned, or else +.Dv NULL +and 0. +The last argument, +.Ar cmd , +specifies which action the function should perform. +.Pp +Depending on the uses, there are three useful sets of commands to be supported by a +.Fn zip_source_callback : +.Bl -tag -width seekable-read-sourceXX +.It read source +Providing streamed data (for file data added to archives). +Must support +.Dv ZIP_SOURCE_OPEN , +.Dv ZIP_SOURCE_READ , +.Dv ZIP_SOURCE_CLOSE , +.Dv ZIP_SOURCE_STAT , +and +.Dv ZIP_SOURCE_ERROR . +.It seekable read source +Same as previous, but from a source allowing reading from arbitrary +offsets (also for read-only zip archive). +Must additionally support +.Dv ZIP_SOURCE_SEEK , +.Dv ZIP_SOURCE_TELL , +and +.Dv ZIP_SOURCE_SUPPORTS . +.It read/write source +Same as previous, but additionally allowing writing (also for writable +zip archives). +Must additionally support +.Dv ZIP_SOURCE_BEGIN_WRITE , +.Dv ZIP_SOURCE_COMMIT_WRITE , +.Dv ZIP_SOURCE_ROLLBACK_WRITE , +.Dv ZIP_SOURCE_SEEK_WRITE , +.Dv ZIP_SOURCE_TELL_WRITE , +and +.Dv ZIP_SOURCE_REMOVE . +.El +.Ss Dv ZIP_SOURCE_BEGIN_WRITE +Prepare the source for writing. +Use this to create any temporary file(s). +.Ss Dv ZIP_SOURCE_BEGIN_WRITE_CLONING +Prepare the source for writing, keeping the first +.Ar len +bytes of the original file. +Only implement this command if it is more efficient than copying the +data, and if it does not destructively overwrite the original file +(you still have to be able to execute +.Dv ZIP_SOURCE_ROLLBACK_WRITE ) . +.Pp +The next write should happen at byte +.Ar offset . +.Ss Dv ZIP_SOURCE_CLOSE +Reading is done. +.Ss Dv ZIP_SOURCE_COMMIT_WRITE +Finish writing to the source. +Replace the original data with the newly written data. +Clean up temporary files or internal buffers. +Subsequently opening and reading from the source should return the +newly written data. +.Ss Dv ZIP_SOURCE_ERROR +Get error information. +.Ar data +points to an array of two ints, which should be filled with the libzip +error code and the corresponding system error code for the error that +occurred. +See +.Xr zip_errors 3 +for details on the error codes. +If the source stores error information in a zip_error_t, use +.Xr zip_error_to_data 3 +and return its return value. +Otherwise, return 2 * sizeof(int). +.Ss Dv ZIP_SOURCE_FREE +Clean up and free all resources, including +.Ar userdata . +The callback function will not be called again. +.Ss Dv ZIP_SOURCE_OPEN +Prepare for reading. +.Ss Dv ZIP_SOURCE_READ +Read data into the buffer +.Ar data +of size +.Ar len . +Return the number of bytes placed into +.Ar data +on success, and zero for end-of-file. +.Ss Dv ZIP_SOURCE_REMOVE +Remove the underlying file. +This is called if a zip archive is empty when closed. +.Ss Dv ZIP_SOURCE_ROLLBACK_WRITE +Abort writing to the source. +Discard written data. +Clean up temporary files or internal buffers. +Subsequently opening and reading from the source should return the +original data. +.Ss Dv ZIP_SOURCE_SEEK +Specify position to read next byte from, like +.Xr fseek 3 . +Use +.Xr ZIP_SOURCE_GET_ARGS 3 +to decode the arguments into the following struct: +.Bd -literal +struct zip_source_args_seek { + zip_int64_t offset; + int whence; +}; +.Ed +.Pp +If the size of the source's data is known, use +.Xr zip_source_seek_compute_offset 3 +to validate the arguments and compute the new offset. +.Ss Dv ZIP_SOURCE_SEEK_WRITE +Specify position to write next byte to, like +.Xr fseek 3 . +See +.Dv ZIP_SOURCE_SEEK +for details. +.Ss Dv ZIP_SOURCE_STAT +Get meta information for the input data. +.Ar data +points to an allocated +.Vt struct zip_stat , +which should be initialized using +.Xr zip_stat_init 3 +and then filled in. +.Pp +For uncompressed, unencrypted data, all information is optional. +However, fill in as much information as is readily available. +.Pp +If the data is compressed, +.Dv ZIP_STAT_COMP_METHOD , +.Dv ZIP_STAT_SIZE , +and +.Dv ZIP_STAT_CRC +must be filled in. +.Pp +If the data is encrypted, +.Dv ZIP_STAT_ENCRYPTION_METHOD , +.Dv ZIP_STAT_COMP_METHOD , +.Dv ZIP_STAT_SIZE , +and +.Dv ZIP_STAT_CRC +must be filled in. +.Pp +Information only available after the source has been read (e.g., size) +can be omitted in an earlier call. +.Em NOTE : +.Fn zip_source_function +may be called with this argument even after being called with +.Dv ZIP_SOURCE_CLOSE . +.Pp +Return sizeof(struct zip_stat) on success. +.Ss Dv ZIP_SOURCE_SUPPORTS +Return bitmap specifying which commands are supported. +Use +.Xr zip_source_make_command_bitmap 3 . +If this command is not implemented, the source is assumed to be a +read source without seek support. +.Ss Dv ZIP_SOURCE_TELL +Return the current read offset in the source, like +.Xr ftell 3 . +.Ss Dv ZIP_SOURCE_TELL_WRITE +Return the current write offset in the source, like +.Xr ftell 3 . +.Ss Dv ZIP_SOURCE_WRITE +Write data to the source. +Return number of bytes written. +.Ss Return Values +Commands should return \-1 on error. +.Dv ZIP_SOURCE_ERROR +will be called to retrieve the error code. +On success, commands return 0, unless specified otherwise in the +description above. +.Ss Calling Conventions +The library will always issue +.Dv ZIP_SOURCE_OPEN +before issuing +.Dv ZIP_SOURCE_READ , +.Dv ZIP_SOURCE_SEEK , +or +.Dv ZIP_SOURCE_TELL . +When it no longer wishes to read from this source, it will issue +.Dv ZIP_SOURCE_CLOSE . +If the library wishes to read the data again, it will issue +.Dv ZIP_SOURCE_OPEN +a second time. +If the function is unable to provide the data again, it should +return \-1. +.Pp +.Dv ZIP_SOURCE_BEGIN_WRITE +or +.Dv ZIP_SOURCE_BEGIN_WRITE_CLONING +will be called before +.Dv ZIP_SOURCE_WRITE , +.Dv ZIP_SOURCE_SEEK_WRITE , +or +.Dv ZIP_SOURCE_TELL_WRITE . +When writing is complete, either +.Dv ZIP_SOURCE_COMMIT_WRITE +or +.Dv ZIP_SOURCE_ROLLBACK_WRITE +will be called. +.Pp +.Dv ZIP_SOURCE_STAT +can be issued at any time. +.Pp +.Dv ZIP_SOURCE_ERROR +will only be issued in response to the function +returning \-1. +.Pp +.Dv ZIP_SOURCE_FREE +will be the last command issued; +if +.Dv ZIP_SOURCE_OPEN +was called and succeeded, +.Dv ZIP_SOURCE_CLOSE +will be called before +.Dv ZIP_SOURCE_FREE , +and similarly for +.Dv ZIP_SOURCE_BEGIN_WRITE +or +.Dv ZIP_SOURCE_BEGIN_WRITE_CLONING +and +.Dv ZIP_SOURCE_COMMIT_WRITE +or +.Dv ZIP_SOURCE_ROLLBACK_WRITE . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error (unless +it is +.Dv NULL ) . +.Sh ERRORS +.Fn zip_source_function +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 , +.Xr zip_stat_init 3 +.Sh HISTORY +.Fn zip_source_function +and +.Fn zip_source_function_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_is_deleted.html b/third_party/libzip/man/zip_source_is_deleted.html new file mode 100644 index 0000000..54e3602 --- /dev/null +++ b/third_party/libzip/man/zip_source_is_deleted.html @@ -0,0 +1,103 @@ + + + + + + + ZIP_SOURCE_IS_DELETED(3) + + + + + + + + +
ZIP_SOURCE_IS_DELETED(3)Library Functions ManualZIP_SOURCE_IS_DELETED(3)
+
+
+

+zip_source_is_deleted — +
check if zip_source is deleted
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_is_deleted(zip_source_t + *source);

+
+
+

+The function zip_source_is_deleted() returns whether the + zip_source was deleted. This can for example happen when all entries are + removed from a zip archive. +
+
+

+zip_source_is_deleted() returns 1 if the zip_source is + deleted and 0 otherwise. +
+
+

+libzip(3), + zip_source(3) +
+
+

+zip_source_is_deleted() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_is_deleted.man b/third_party/libzip/man/zip_source_is_deleted.man new file mode 100644 index 0000000..89dab74 --- /dev/null +++ b/third_party/libzip/man/zip_source_is_deleted.man @@ -0,0 +1,67 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_is_deleted.mdoc -- check if zip source is deleted +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_IS_DELETED" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_is_deleted\fR +\- check if zip_source is deleted +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_is_deleted\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_is_deleted\fR() +returns whether the zip_source was deleted. +This can for example happen when all entries are removed from a zip archive. +.SH "RETURN VALUES" +\fBzip_source_is_deleted\fR() +returns 1 if the zip_source is deleted and 0 otherwise. +.SH "SEE ALSO" +libzip(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_is_deleted\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_is_deleted.mdoc b/third_party/libzip/man/zip_source_is_deleted.mdoc new file mode 100644 index 0000000..9903058 --- /dev/null +++ b/third_party/libzip/man/zip_source_is_deleted.mdoc @@ -0,0 +1,62 @@ +.\" zip_source_is_deleted.mdoc -- check if zip source is deleted +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_IS_DELETED 3 +.Os +.Sh NAME +.Nm zip_source_is_deleted +.Nd check if zip_source is deleted +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_is_deleted "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_is_deleted +returns whether the zip_source was deleted. +This can for example happen when all entries are removed from a zip archive. +.Sh RETURN VALUES +.Fn zip_source_is_deleted +returns 1 if the zip_source is deleted and 0 otherwise. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_is_deleted +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_keep.html b/third_party/libzip/man/zip_source_keep.html new file mode 100644 index 0000000..392b82a --- /dev/null +++ b/third_party/libzip/man/zip_source_keep.html @@ -0,0 +1,97 @@ + + + + + + + ZIP_SOURCE_KEEP(3) + + + + + + + + +
ZIP_SOURCE_KEEP(3)Library Functions ManualZIP_SOURCE_KEEP(3)
+
+
+

+zip_source_keep — +
increment reference count of zip data source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_source_keep(zip_source_t + *source);

+
+
+

+The function zip_source_keep() increments the reference + count of source. +
+
+

+libzip(3), + zip_source(3), + zip_source_free(3) +
+
+

+zip_source_keep() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_keep.man b/third_party/libzip/man/zip_source_keep.man new file mode 100644 index 0000000..488673c --- /dev/null +++ b/third_party/libzip/man/zip_source_keep.man @@ -0,0 +1,65 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_keep.mdoc -- increment reference count of zip data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_KEEP" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_keep\fR +\- increment reference count of zip data source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_source_keep\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_keep\fR() +increments the reference count of +\fIsource\fR. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_free(3) +.SH "HISTORY" +\fBzip_source_keep\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_keep.mdoc b/third_party/libzip/man/zip_source_keep.mdoc new file mode 100644 index 0000000..122c4f8 --- /dev/null +++ b/third_party/libzip/man/zip_source_keep.mdoc @@ -0,0 +1,60 @@ +.\" zip_source_keep.mdoc -- increment reference count of zip data source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_KEEP 3 +.Os +.Sh NAME +.Nm zip_source_keep +.Nd increment reference count of zip data source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_source_keep "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_keep +increments the reference count of +.Ar source . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_free 3 +.Sh HISTORY +.Fn zip_source_keep +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_make_command_bitmap.html b/third_party/libzip/man/zip_source_make_command_bitmap.html new file mode 100644 index 0000000..a836bad --- /dev/null +++ b/third_party/libzip/man/zip_source_make_command_bitmap.html @@ -0,0 +1,99 @@ + + + + + + + ZIP_SOURCE_MAKE_COMMAND_BITMAP(3) + + + + + + + + +
ZIP_SOURCE_MAKE_COMMAND_BITMAP(3)Library Functions ManualZIP_SOURCE_MAKE_COMMAND_BITMAP(3)
+
+
+

+zip_source_make_command_bitmap — +
create bitmap of supported source operations
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_make_command_bitmap(zip_source_cmd_t + command, ...);

+
+
+

+The zip_source_make_command_bitmap() function returns a + bitmap of source commands suitable as return value for + ZIP_SOURCE_SUPPORTS. It includes all the commands from + the argument list, which must be terminated by -1. +
+
+

+libzip(3), + zip_source_function(3) +
+
+

+zip_source_make_command_bitmap() was added in libzip + 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_make_command_bitmap.man b/third_party/libzip/man/zip_source_make_command_bitmap.man new file mode 100644 index 0000000..3dc3ed5 --- /dev/null +++ b/third_party/libzip/man/zip_source_make_command_bitmap.man @@ -0,0 +1,67 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_make_command_bitmap -- create bitmap of supported source operations +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_MAKE_COMMAND_BITMAP" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_make_command_bitmap\fR +\- create bitmap of supported source operations +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_make_command_bitmap\fR(\fIzip_source_cmd_t\ command\fR, \fI...\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_source_make_command_bitmap\fR() +function returns a bitmap of source commands suitable as return value +for +\fRZIP_SOURCE_SUPPORTS\fR. +It includes all the commands from the argument list, which must be +terminated by \-1. +.SH "SEE ALSO" +libzip(3), +zip_source_function(3) +.SH "HISTORY" +\fBzip_source_make_command_bitmap\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_make_command_bitmap.mdoc b/third_party/libzip/man/zip_source_make_command_bitmap.mdoc new file mode 100644 index 0000000..28d296f --- /dev/null +++ b/third_party/libzip/man/zip_source_make_command_bitmap.mdoc @@ -0,0 +1,62 @@ +.\" zip_source_make_command_bitmap -- create bitmap of supported source operations +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_MAKE_COMMAND_BITMAP 3 +.Os +.Sh NAME +.Nm zip_source_make_command_bitmap +.Nd create bitmap of supported source operations +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_make_command_bitmap "zip_source_cmd_t command" "..." +.Sh DESCRIPTION +The +.Fn zip_source_make_command_bitmap +function returns a bitmap of source commands suitable as return value +for +.Dv ZIP_SOURCE_SUPPORTS . +It includes all the commands from the argument list, which must be +terminated by \-1. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source_function 3 +.Sh HISTORY +.Fn zip_source_make_command_bitmap +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_open.html b/third_party/libzip/man/zip_source_open.html new file mode 100644 index 0000000..01fecc6 --- /dev/null +++ b/third_party/libzip/man/zip_source_open.html @@ -0,0 +1,108 @@ + + + + + + + ZIP_SOURCE_OPEN(3) + + + + + + + + +
ZIP_SOURCE_OPEN(3)Library Functions ManualZIP_SOURCE_OPEN(3)
+
+
+

+zip_source_open — +
open zip_source for reading
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_open(zip_source_t + *source);

+
+
+

+The function zip_source_open() opens + source for reading. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_close(3), + zip_source_read(3), + zip_source_seek(3), + zip_source_tell(3) +
+
+

+zip_source_open() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_open.man b/third_party/libzip/man/zip_source_open.man new file mode 100644 index 0000000..dc337ba --- /dev/null +++ b/third_party/libzip/man/zip_source_open.man @@ -0,0 +1,75 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_open.mdoc -- open zip source for reading +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_OPEN" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_open\fR +\- open zip_source for reading +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_open\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_open\fR() +opens +\fIsource\fR +for reading. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_close(3), +zip_source_read(3), +zip_source_seek(3), +zip_source_tell(3) +.SH "HISTORY" +\fBzip_source_open\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_open.mdoc b/third_party/libzip/man/zip_source_open.mdoc new file mode 100644 index 0000000..00371f6 --- /dev/null +++ b/third_party/libzip/man/zip_source_open.mdoc @@ -0,0 +1,70 @@ +.\" zip_source_open.mdoc -- open zip source for reading +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_OPEN 3 +.Os +.Sh NAME +.Nm zip_source_open +.Nd open zip_source for reading +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_open "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_open +opens +.Fa source +for reading. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_close 3 , +.Xr zip_source_read 3 , +.Xr zip_source_seek 3 , +.Xr zip_source_tell 3 +.Sh HISTORY +.Fn zip_source_open +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_read.html b/third_party/libzip/man/zip_source_read.html new file mode 100644 index 0000000..9a898ba --- /dev/null +++ b/third_party/libzip/man/zip_source_read.html @@ -0,0 +1,112 @@ + + + + + + + ZIP_SOURCE_READ(3) + + + + + + + + +
ZIP_SOURCE_READ(3)Library Functions ManualZIP_SOURCE_READ(3)
+
+
+

+zip_source_read — +
read data from zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_read(zip_source_t + *source, void + *data, zip_uint64_t + len);

+
+
+

+The function zip_source_read() reads up to + len bytes of data from source at + the current read offset into the buffer data. +

The zip source source has to be opened for + reading by calling + zip_source_open(3) first.

+
+
+

+Upon successful completion the number of bytes read is returned. Upon reading + end-of-file, zero is returned. Otherwise, -1 is returned and the error + information in source is set to indicate the error. +
+
+

+libzip(3), + zip_source(3), + zip_source_seek(3), + zip_source_tell(3), + zip_source_write(3) +
+
+

+zip_source_read() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_read.man b/third_party/libzip/man/zip_source_read.man new file mode 100644 index 0000000..78ea1bf --- /dev/null +++ b/third_party/libzip/man/zip_source_read.man @@ -0,0 +1,83 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_read.mdoc -- read data from zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_READ" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_read\fR +\- read data from zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_read\fR(\fIzip_source_t\ *source\fR, \fIvoid\ *data\fR, \fIzip_uint64_t\ len\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_read\fR() +reads up to +\fIlen\fR +bytes of data from +\fIsource\fR +at the current read offset into the buffer +\fIdata\fR. +.PP +The zip source +\fIsource\fR +has to be opened for reading by calling +zip_source_open(3) +first. +.SH "RETURN VALUES" +Upon successful completion the number of bytes read is returned. +Upon reading end-of-file, zero is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_seek(3), +zip_source_tell(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_read\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_read.mdoc b/third_party/libzip/man/zip_source_read.mdoc new file mode 100644 index 0000000..1e7bc02 --- /dev/null +++ b/third_party/libzip/man/zip_source_read.mdoc @@ -0,0 +1,78 @@ +.\" zip_source_read.mdoc -- read data from zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_READ 3 +.Os +.Sh NAME +.Nm zip_source_read +.Nd read data from zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_read "zip_source_t *source" "void *data" "zip_uint64_t len" +.Sh DESCRIPTION +The function +.Fn zip_source_read +reads up to +.Ar len +bytes of data from +.Ar source +at the current read offset into the buffer +.Ar data . +.Pp +The zip source +.Ar source +has to be opened for reading by calling +.Xr zip_source_open 3 +first. +.Sh RETURN VALUES +Upon successful completion the number of bytes read is returned. +Upon reading end-of-file, zero is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_seek 3 , +.Xr zip_source_tell 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_read +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_rollback_write.html b/third_party/libzip/man/zip_source_rollback_write.html new file mode 100644 index 0000000..b655ba0 --- /dev/null +++ b/third_party/libzip/man/zip_source_rollback_write.html @@ -0,0 +1,110 @@ + + + + + + + ZIP_SOURCE_ROLLBACK_WRITE(3) + + + + + + + + +
ZIP_SOURCE_ROLLBACK_WRITE(3)Library Functions ManualZIP_SOURCE_ROLLBACK_WRITE(3)
+
+
+

+zip_source_rollback_write — +
undo changes to zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_source_rollback_write(zip_source_t + *source);

+
+
+

+The function zip_source_rollback_write() reverts changes + written to source, restoring the data before + zip_source_begin_write(3) + was called. Usually this removes temporary files or frees buffers. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_commit_write(3), + zip_source_seek_write(3), + zip_source_tell_write(3), + zip_source_write(3) +
+
+

+zip_source_rollback_write() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_rollback_write.man b/third_party/libzip/man/zip_source_rollback_write.man new file mode 100644 index 0000000..1665dbe --- /dev/null +++ b/third_party/libzip/man/zip_source_rollback_write.man @@ -0,0 +1,78 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_rollback_write.mdoc -- undo changes to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_ROLLBACK_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_rollback_write\fR +\- undo changes to zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_source_rollback_write\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_rollback_write\fR() +reverts changes written to +\fIsource\fR, +restoring the data before +zip_source_begin_write(3) +was called. +Usually this removes temporary files or frees buffers. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_commit_write(3), +zip_source_seek_write(3), +zip_source_tell_write(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_rollback_write\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_rollback_write.mdoc b/third_party/libzip/man/zip_source_rollback_write.mdoc new file mode 100644 index 0000000..50a2a60 --- /dev/null +++ b/third_party/libzip/man/zip_source_rollback_write.mdoc @@ -0,0 +1,73 @@ +.\" zip_source_rollback_write.mdoc -- undo changes to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_ROLLBACK_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_rollback_write +.Nd undo changes to zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_source_rollback_write "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_rollback_write +reverts changes written to +.Fa source , +restoring the data before +.Xr zip_source_begin_write 3 +was called. +Usually this removes temporary files or frees buffers. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_commit_write 3 , +.Xr zip_source_seek_write 3 , +.Xr zip_source_tell_write 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_rollback_write +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_seek.html b/third_party/libzip/man/zip_source_seek.html new file mode 100644 index 0000000..4063eb8 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek.html @@ -0,0 +1,120 @@ + + + + + + + ZIP_SOURCE_SEEK(3) + + + + + + + + +
ZIP_SOURCE_SEEK(3)Library Functions ManualZIP_SOURCE_SEEK(3)
+
+
+

+zip_source_seek — +
set read offset in zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_seek(zip_source_t + *source, zip_int64_t + offset, int + whence);

+
+
+

+The function zip_source_seek() sets the current read + offset for source. Just like in + fseek(3), depending on the + whence argument, the offset is + counted relative from: +
+
+
+
start of file
+
+
current read offset in file
+
+
end of file
+
+
+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_read(3), + zip_source_tell(3) +
+
+

+zip_source_seek() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_seek.man b/third_party/libzip/man/zip_source_seek.man new file mode 100644 index 0000000..399597e --- /dev/null +++ b/third_party/libzip/man/zip_source_seek.man @@ -0,0 +1,89 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_seek.mdoc -- set read offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_SEEK" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_seek\fR +\- set read offset in zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_seek\fR(\fIzip_source_t\ *source\fR, \fIzip_int64_t\ offset\fR, \fIint\ whence\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_seek\fR() +sets the current read offset for +\fIsource\fR. +Just like in +fseek(3), +depending on the +\fIwhence\fR +argument, the +\fIoffset\fR +is counted relative from: +.RS 6n +.TP 12n +\fRSEEK_SET\fR +start of file +.TP 12n +\fRSEEK_CUR\fR +current read offset in file +.TP 12n +\fRSEEK_END\fR +end of file +.RE +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_read(3), +zip_source_tell(3) +.SH "HISTORY" +\fBzip_source_seek\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_seek.mdoc b/third_party/libzip/man/zip_source_seek.mdoc new file mode 100644 index 0000000..6518ba7 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek.mdoc @@ -0,0 +1,81 @@ +.\" zip_source_seek.mdoc -- set read offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_SEEK 3 +.Os +.Sh NAME +.Nm zip_source_seek +.Nd set read offset in zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_seek "zip_source_t *source" "zip_int64_t offset" "int whence" +.Sh DESCRIPTION +The function +.Fn zip_source_seek +sets the current read offset for +.Fa source . +Just like in +.Xr fseek 3 , +depending on the +.Ar whence +argument, the +.Ar offset +is counted relative from: +.Bl -tag -width SEEK_CURXX -offset indent +.It Dv SEEK_SET +start of file +.It Dv SEEK_CUR +current read offset in file +.It Dv SEEK_END +end of file +.El +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_read 3 , +.Xr zip_source_tell 3 +.Sh HISTORY +.Fn zip_source_seek +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_seek_compute_offset.html b/third_party/libzip/man/zip_source_seek_compute_offset.html new file mode 100644 index 0000000..c6dfa95 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_compute_offset.html @@ -0,0 +1,119 @@ + + + + + + + ZIP_SOURCE_SEEK_COMPUTE_OFFSET(3) + + + + + + + + +
ZIP_SOURCE_SEEK_COMPUTE_OFFSET(3)Library Functions ManualZIP_SOURCE_SEEK_COMPUTE_OFFSET(3)
+
+
+

+zip_source_seek_compute_offset — +
validate arguments and compute offset
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_seek_compute_offset(zip_uint64_t + offset, zip_uint64_t + length, void *data, + zip_uint64_t data_length, + zip_error_t *error);

+
+
+

+Use this function to compute the offset for a + ZIP_SOURCE_SEEK or + ZIP_SOURCE_SEEK_WRITE command. + data and data_length are the + arguments to the source callback, offset is the current + offset and length is the length of the source data or, + for ZIP_SOURCE_SEEK_WRITE, the amount of data written. +
+
+

+On success, it returns the new offset, on error it returns -1 and sets + error. +
+
+

+zip_source_seek_compute_offset() fails if: +
+
[]
+
One of the arguments is invalid or the seek would place the offset outside + the data.
+
+
+
+

+zip_source_function(3) +
+
+

+zip_source_seek_compute_offset() was added in libzip + 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_seek_compute_offset.man b/third_party/libzip/man/zip_source_seek_compute_offset.man new file mode 100644 index 0000000..a1b1cc1 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_compute_offset.man @@ -0,0 +1,85 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_seek_compute_offset.mdoc - validate arguments and compute offset +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_SEEK_COMPUTE_OFFSET" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_seek_compute_offset\fR +\- validate arguments and compute offset +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_seek_compute_offset\fR(\fIzip_uint64_t\ offset\fR, \fIzip_uint64_t\ length\fR, \fIvoid\ *data\fR, \fIzip_uint64_t\ data_length\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +Use this function to compute the offset for a +\fRZIP_SOURCE_SEEK\fR +or +\fRZIP_SOURCE_SEEK_WRITE\fR +command. +\fIdata\fR +and +\fIdata_length\fR +are the arguments to the source callback, +\fIoffset\fR +is the current offset and +\fIlength\fR +is the length of the source data or, for +\fRZIP_SOURCE_SEEK_WRITE\fR, +the amount of data written. +.SH "RETURN VALUES" +On success, it returns the new offset, on error it returns \-1 and +sets +\fIerror\fR. +.SH "ERRORS" +\fBzip_source_seek_compute_offset\fR() +fails if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +One of the arguments is invalid or the seek would place the offset +outside the data. +.SH "SEE ALSO" +zip_source_function(3) +.SH "HISTORY" +\fBzip_source_seek_compute_offset\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_seek_compute_offset.mdoc b/third_party/libzip/man/zip_source_seek_compute_offset.mdoc new file mode 100644 index 0000000..bcf159a --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_compute_offset.mdoc @@ -0,0 +1,81 @@ +.\" zip_source_seek_compute_offset.mdoc - validate arguments and compute offset +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_SEEK_COMPUTE_OFFSET 3 +.Os +.Sh NAME +.Nm zip_source_seek_compute_offset +.Nd validate arguments and compute offset +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_seek_compute_offset "zip_uint64_t offset" "zip_uint64_t length" "void *data" "zip_uint64_t data_length" "zip_error_t *error" +.Sh DESCRIPTION +Use this function to compute the offset for a +.Dv ZIP_SOURCE_SEEK +or +.Dv ZIP_SOURCE_SEEK_WRITE +command. +.Ar data +and +.Ar data_length +are the arguments to the source callback, +.Ar offset +is the current offset and +.Ar length +is the length of the source data or, for +.Dv ZIP_SOURCE_SEEK_WRITE , +the amount of data written. +.Sh RETURN VALUES +On success, it returns the new offset, on error it returns \-1 and +sets +.Ar error . +.Sh ERRORS +.Fn zip_source_seek_compute_offset +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +One of the arguments is invalid or the seek would place the offset +outside the data. +.El +.Sh SEE ALSO +.Xr zip_source_function 3 +.Sh HISTORY +.Fn zip_source_seek_compute_offset +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_seek_write.html b/third_party/libzip/man/zip_source_seek_write.html new file mode 100644 index 0000000..baedea3 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_write.html @@ -0,0 +1,123 @@ + + + + + + + ZIP_SOURCE_SEEK_WRITE(3) + + + + + + + + +
ZIP_SOURCE_SEEK_WRITE(3)Library Functions ManualZIP_SOURCE_SEEK_WRITE(3)
+
+
+

+zip_source_seek_write — +
set write offset in zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_seek_write(zip_source_t + *source, zip_int64_t + offset, int + whence);

+
+
+

+The function zip_source_seek_write() sets the current + write offset for source. Just like in + fseek(3), depending on the + whence argument, the offset is + counted relative from: +
+
+
+
start of file
+
+
current write offset in file
+
+
end of file
+
+
+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_commit_write(3), + zip_source_rollback_write(3), + zip_source_tell_write(3), + zip_source_write(3) +
+
+

+zip_source_seek_write() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_seek_write.man b/third_party/libzip/man/zip_source_seek_write.man new file mode 100644 index 0000000..567588d --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_write.man @@ -0,0 +1,92 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_seek_write.mdoc -- set write offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_SEEK_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_seek_write\fR +\- set write offset in zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_seek_write\fR(\fIzip_source_t\ *source\fR, \fIzip_int64_t\ offset\fR, \fIint\ whence\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_seek_write\fR() +sets the current write offset for +\fIsource\fR. +Just like in +fseek(3), +depending on the +\fIwhence\fR +argument, the +\fIoffset\fR +is counted relative from: +.RS 6n +.TP 12n +\fRSEEK_SET\fR +start of file +.TP 12n +\fRSEEK_CUR\fR +current write offset in file +.TP 12n +\fRSEEK_END\fR +end of file +.RE +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_commit_write(3), +zip_source_rollback_write(3), +zip_source_tell_write(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_seek_write\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_seek_write.mdoc b/third_party/libzip/man/zip_source_seek_write.mdoc new file mode 100644 index 0000000..fac0159 --- /dev/null +++ b/third_party/libzip/man/zip_source_seek_write.mdoc @@ -0,0 +1,84 @@ +.\" zip_source_seek_write.mdoc -- set write offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_SEEK_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_seek_write +.Nd set write offset in zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_seek_write "zip_source_t *source" "zip_int64_t offset" "int whence" +.Sh DESCRIPTION +The function +.Fn zip_source_seek_write +sets the current write offset for +.Fa source . +Just like in +.Xr fseek 3 , +depending on the +.Ar whence +argument, the +.Ar offset +is counted relative from: +.Bl -tag -width SEEK_CURXX -offset indent +.It Dv SEEK_SET +start of file +.It Dv SEEK_CUR +current write offset in file +.It Dv SEEK_END +end of file +.El +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_commit_write 3 , +.Xr zip_source_rollback_write 3 , +.Xr zip_source_tell_write 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_seek_write +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_stat.html b/third_party/libzip/man/zip_source_stat.html new file mode 100644 index 0000000..8b911d2 --- /dev/null +++ b/third_party/libzip/man/zip_source_stat.html @@ -0,0 +1,154 @@ + + + + + + + ZIP_SOURCE_STAT(3) + + + + + + + + +
ZIP_SOURCE_STAT(3)Library Functions ManualZIP_SOURCE_STAT(3)
+
+
+

+zip_source_stat — +
get information about zip_source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_source_stat(zip_source_t + *source, zip_stat_t + *sb);

+
+
+

+The zip_source_stat() function obtains information about + the zip source source +

The sb argument is a pointer to a + struct zip_source_stat (shown below), into which + information about the zip source is placed.

+
+
+struct zip_source_stat {
+    zip_uint64_t valid;                 /* which fields have valid values */
+    const char *name;                   /* name of the file */
+    zip_uint64_t index;                 /* index within archive */
+    zip_uint64_t size;                  /* size of file (uncompressed) */
+    zip_uint64_t comp_size;             /* size of file (compressed) */
+    time_t mtime;                       /* modification time */
+    zip_uint32_t crc;                   /* crc of file data */
+    zip_uint16_t comp_method;           /* compression method used */
+    zip_uint16_t encryption_method;     /* encryption method used */
+    zip_uint32_t flags;                 /* reserved for future use */
+};
+
+
+The structure pointed to by sb must be initialized with + zip_stat_init(3) before calling + zip_source_stat(). +

The valid field of the structure specifies + which other fields are valid. Check if the flag defined by the following + defines are in valid before accessing the fields:

+ +

NOTE: Some fields may only be filled out after + all data has been read from the source, for example the + crc or size fields.

+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in source is set to indicate the + error. +
+
+

+libzip(3), + zip_source(3) +
+
+

+zip_source_stat() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_stat.man b/third_party/libzip/man/zip_source_stat.man new file mode 100644 index 0000000..cbc12ff --- /dev/null +++ b/third_party/libzip/man/zip_source_stat.man @@ -0,0 +1,144 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_stat.mdoc -- get information about zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_STAT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_stat\fR +\- get information about zip_source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_source_stat\fR(\fIzip_source_t\ *source\fR, \fIzip_stat_t\ *sb\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_source_stat\fR() +function obtains information about the zip source +\fIsource\fR +.PP +The +\fIsb\fR +argument is a pointer to a +\fIstruct zip_source_stat\fR +(shown below), into which information about the zip source is placed. +.nf +.sp +.RS 0n +struct zip_source_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char *name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; +.RE +.fi +The structure pointed to by +\fIsb\fR +must be initialized with +\fBzip_stat_init\fR(\fI3\fR) +before calling +\fBzip_source_stat\fR(). +.PP +The +\fIvalid\fR +field of the structure specifies which other fields are valid. +Check if the flag defined by the following defines are in +\fIvalid\fR +before accessing the fields: +.RS 6n +.PD 0 +.TP 37n +\fRZIP_SOURCE_STAT_NAME\fR +\fIname\fR +.TP 37n +\fRZIP_SOURCE_STAT_INDEX\fR +\fIindex\fR +.TP 37n +\fRZIP_SOURCE_STAT_SIZE\fR +\fIsize\fR +.TP 37n +\fRZIP_SOURCE_STAT_COMP_SIZE\fR +\fIcomp_size\fR +.TP 37n +\fRZIP_SOURCE_STAT_MTIME\fR +\fImtime\fR +.TP 37n +\fRZIP_SOURCE_STAT_CRC\fR +\fIcrc\fR +.TP 37n +\fRZIP_SOURCE_STAT_COMP_METHOD\fR +\fIcomp_method\fR +.TP 37n +\fRZIP_SOURCE_STAT_ENCRYPTION_METHOD\fR +\fIencryption_method\fR +.TP 37n +\fRZIP_SOURCE_STAT_FLAGS\fR +\fIflags\fR +.RE +.PD +.PP +\fINOTE\fR: +Some fields may only be filled out after all data has been read from +the source, for example the +\fIcrc\fR +or +\fIsize\fR +fields. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_stat\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_stat.mdoc b/third_party/libzip/man/zip_source_stat.mdoc new file mode 100644 index 0000000..69f4516 --- /dev/null +++ b/third_party/libzip/man/zip_source_stat.mdoc @@ -0,0 +1,125 @@ +.\" zip_source_stat.mdoc -- get information about zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_STAT 3 +.Os +.Sh NAME +.Nm zip_source_stat +.Nd get information about zip_source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_source_stat "zip_source_t *source" "zip_stat_t *sb" +.Sh DESCRIPTION +The +.Fn zip_source_stat +function obtains information about the zip source +.Ar source +.Pp +The +.Ar sb +argument is a pointer to a +.Ft struct zip_source_stat +(shown below), into which information about the zip source is placed. +.Bd -literal +struct zip_source_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char *name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; +.Ed +The structure pointed to by +.Ar sb +must be initialized with +.Fn zip_stat_init 3 +before calling +.Fn zip_source_stat . +.Pp +The +.Ar valid +field of the structure specifies which other fields are valid. +Check if the flag defined by the following defines are in +.Ar valid +before accessing the fields: +.Bl -tag -width ZIP_SOURCE_STAT_ENCRYPTION_METHODXX -compact -offset indent +.It Dv ZIP_SOURCE_STAT_NAME +.Ar name +.It Dv ZIP_SOURCE_STAT_INDEX +.Ar index +.It Dv ZIP_SOURCE_STAT_SIZE +.Ar size +.It Dv ZIP_SOURCE_STAT_COMP_SIZE +.Ar comp_size +.It Dv ZIP_SOURCE_STAT_MTIME +.Ar mtime +.It Dv ZIP_SOURCE_STAT_CRC +.Ar crc +.It Dv ZIP_SOURCE_STAT_COMP_METHOD +.Ar comp_method +.It Dv ZIP_SOURCE_STAT_ENCRYPTION_METHOD +.Ar encryption_method +.It Dv ZIP_SOURCE_STAT_FLAGS +.Ar flags +.El +.Pp +.Em NOTE : +Some fields may only be filled out after all data has been read from +the source, for example the +.Ar crc +or +.Ar size +fields. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_stat +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_tell.html b/third_party/libzip/man/zip_source_tell.html new file mode 100644 index 0000000..6fda2b4 --- /dev/null +++ b/third_party/libzip/man/zip_source_tell.html @@ -0,0 +1,108 @@ + + + + + + + ZIP_SOURCE_TELL(3) + + + + + + + + +
ZIP_SOURCE_TELL(3)Library Functions ManualZIP_SOURCE_TELL(3)
+
+
+

+zip_source_tell — +
report current read offset in zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_tell(zip_source_t + *source);

+
+
+

+The function zip_source_tell() returns the current read + offset for source. The return value can be passed to + zip_source_seek(3) with + whence set to SEEK_SET to return + to the same location in the source. +
+
+

+Upon successful completion the current read offset is returned. Otherwise, -1 is + returned and the error information in source is set to + indicate the error. +
+
+

+libzip(3), + zip_source(3), + zip_source_read(3), + zip_source_tell_write(3) +
+
+

+zip_source_tell() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_tell.man b/third_party/libzip/man/zip_source_tell.man new file mode 100644 index 0000000..088ec86 --- /dev/null +++ b/third_party/libzip/man/zip_source_tell.man @@ -0,0 +1,79 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_tell.mdoc -- report current read offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_TELL" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_tell\fR +\- report current read offset in zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_tell\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_tell\fR() +returns the current read offset +for +\fIsource\fR. +The return value can be passed to +zip_source_seek(3) +with +\fIwhence\fR +set to +\fRSEEK_SET\fR +to return to the same location in the source. +.SH "RETURN VALUES" +Upon successful completion the current read offset is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_read(3), +zip_source_tell_write(3) +.SH "HISTORY" +\fBzip_source_tell\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_tell.mdoc b/third_party/libzip/man/zip_source_tell.mdoc new file mode 100644 index 0000000..e824918 --- /dev/null +++ b/third_party/libzip/man/zip_source_tell.mdoc @@ -0,0 +1,74 @@ +.\" zip_source_tell.mdoc -- report current read offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_TELL 3 +.Os +.Sh NAME +.Nm zip_source_tell +.Nd report current read offset in zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_tell "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_tell +returns the current read offset +for +.Fa source . +The return value can be passed to +.Xr zip_source_seek 3 +with +.Ar whence +set to +.Dv SEEK_SET +to return to the same location in the source. +.Sh RETURN VALUES +Upon successful completion the current read offset is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_read 3 , +.Xr zip_source_tell_write 3 +.Sh HISTORY +.Fn zip_source_tell +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_tell_write.html b/third_party/libzip/man/zip_source_tell_write.html new file mode 100644 index 0000000..778896d --- /dev/null +++ b/third_party/libzip/man/zip_source_tell_write.html @@ -0,0 +1,112 @@ + + + + + + + ZIP_SOURCE_TELL_WRITE(3) + + + + + + + + +
ZIP_SOURCE_TELL_WRITE(3)Library Functions ManualZIP_SOURCE_TELL_WRITE(3)
+
+
+

+zip_source_tell_write — +
report current write offset in zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_tell_write(zip_source_t + *source);

+
+
+

+The function zip_source_tell_write() returns the current + write offset for source. The return value can be passed + to + zip_source_seek_write(3) + with whence set to SEEK_SET to + return to the same location in the source. +
+
+

+Upon successful completion the current write offset is returned. Otherwise, -1 + is returned and the error information in source is set + to indicate the error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_commit_write(3), + zip_source_rollback_write(3), + zip_source_tell(3), + zip_source_write(3) +
+
+

+zip_source_tell_write() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_tell_write.man b/third_party/libzip/man/zip_source_tell_write.man new file mode 100644 index 0000000..4208e5c --- /dev/null +++ b/third_party/libzip/man/zip_source_tell_write.man @@ -0,0 +1,82 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_tell_write.mdoc -- report current write offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_TELL_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_tell_write\fR +\- report current write offset in zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_tell_write\fR(\fIzip_source_t\ *source\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_tell_write\fR() +returns the current write offset +for +\fIsource\fR. +The return value can be passed to +zip_source_seek_write(3) +with +\fIwhence\fR +set to +\fRSEEK_SET\fR +to return to the same location in the source. +.SH "RETURN VALUES" +Upon successful completion the current write offset is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_commit_write(3), +zip_source_rollback_write(3), +zip_source_tell(3), +zip_source_write(3) +.SH "HISTORY" +\fBzip_source_tell_write\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_tell_write.mdoc b/third_party/libzip/man/zip_source_tell_write.mdoc new file mode 100644 index 0000000..00fc3b1 --- /dev/null +++ b/third_party/libzip/man/zip_source_tell_write.mdoc @@ -0,0 +1,77 @@ +.\" zip_source_tell_write.mdoc -- report current write offset in source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_TELL_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_tell_write +.Nd report current write offset in zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_tell_write "zip_source_t *source" +.Sh DESCRIPTION +The function +.Fn zip_source_tell_write +returns the current write offset +for +.Fa source . +The return value can be passed to +.Xr zip_source_seek_write 3 +with +.Ar whence +set to +.Dv SEEK_SET +to return to the same location in the source. +.Sh RETURN VALUES +Upon successful completion the current write offset is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_commit_write 3 , +.Xr zip_source_rollback_write 3 , +.Xr zip_source_tell 3 , +.Xr zip_source_write 3 +.Sh HISTORY +.Fn zip_source_tell_write +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_win32a.html b/third_party/libzip/man/zip_source_win32a.html new file mode 100644 index 0000000..a528c94 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32a.html @@ -0,0 +1,143 @@ + + + + + + + ZIP_SOURCE_WIN32A(3) + + + + + + + + +
ZIP_SOURCE_WIN32A(3)Library Functions ManualZIP_SOURCE_WIN32A(3)
+
+
+

+zip_source_win32a, + zip_source_win32a_create — +
create data source from a Windows ANSI file name
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_win32a(zip_t + *archive, const char + *fname, zip_uint64_t + start, zip_int64_t + len);

+

zip_source_t * +
+ zip_source_win32a_create(const + char *fname, zip_uint64_t + start, zip_int64_t + len, zip_error_t + *error);

+
+
+

+The functions zip_source_win32a() and + zip_source_win32a_create() create a zip source on + Windows using a Windows ANSI name. They open fname and + read len bytes from offset start + from it. If len is 0 or -1, the whole file (starting + from start) is used. +

If the file supports seek, the source can be used to open a zip + archive from.

+

The file is opened and read when the data from the source is used, + usually by zip_close() or + zip_open_from_source().

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_win32a() and + zip_source_win32a_create() fail if: +
+
[]
+
fname, start, or + len are invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Opening fname failed.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3), + zip_source_win32handle(3), + zip_source_win32w(3) +
+
+

+zip_source_win32a() and + zip_source_win32a_create() were added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_win32a.man b/third_party/libzip/man/zip_source_win32a.man new file mode 100644 index 0000000..1001b5d --- /dev/null +++ b/third_party/libzip/man/zip_source_win32a.man @@ -0,0 +1,127 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_win32a.mdoc -- create data source using a win32 ANSI name +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_WIN32A" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_win32a\fR, +\fBzip_source_win32a_create\fR +\- create data source from a Windows ANSI file name +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32a\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32a_create\fR(\fIconst\ char\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_win32a\fR() +and +\fBzip_source_win32a_create\fR() +create a zip source on Windows using a Windows ANSI name. +They open +\fIfname\fR +and read +\fIlen\fR +bytes from offset +\fIstart\fR +from it. +If +\fIlen\fR +is 0 or \-1, the whole file (starting from +\fIstart\fR) +is used. +.PP +If the file supports seek, the source can be used to open a zip archive from. +.PP +The file is opened and read when the data from the source is used, usually by +\fBzip_close\fR() +or +\fBzip_open_from_source\fR(). +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_win32a\fR() +and +\fBzip_source_win32a_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIfname\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_OPEN\fR] +Opening +\fIfname\fR +failed. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3), +zip_source_win32handle(3), +zip_source_win32w(3) +.SH "HISTORY" +\fBzip_source_win32a\fR() +and +\fBzip_source_win32a_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_win32a.mdoc b/third_party/libzip/man/zip_source_win32a.mdoc new file mode 100644 index 0000000..9b6d762 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32a.mdoc @@ -0,0 +1,116 @@ +.\" zip_source_win32a.mdoc -- create data source using a win32 ANSI name +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_WIN32A 3 +.Os +.Sh NAME +.Nm zip_source_win32a , +.Nm zip_source_win32a_create +.Nd create data source from a Windows ANSI file name +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_win32a "zip_t *archive" "const char *fname" "zip_uint64_t start" "zip_int64_t len" +.Ft zip_source_t * +.Fn zip_source_win32a_create "const char *fname" "zip_uint64_t start" "zip_int64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_win32a +and +.Fn zip_source_win32a_create +create a zip source on Windows using a Windows ANSI name. +They open +.Ar fname +and read +.Ar len +bytes from offset +.Ar start +from it. +If +.Ar len +is 0 or \-1, the whole file (starting from +.Ar start ) +is used. +.Pp +If the file supports seek, the source can be used to open a zip archive from. +.Pp +The file is opened and read when the data from the source is used, usually by +.Fn zip_close +or +.Fn zip_open_from_source . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_win32a +and +.Fn zip_source_win32a_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar fname , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_OPEN +Opening +.Ar fname +failed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 , +.Xr zip_source_win32handle 3 , +.Xr zip_source_win32w 3 +.Sh HISTORY +.Fn zip_source_win32a +and +.Fn zip_source_win32a_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_win32handle.html b/third_party/libzip/man/zip_source_win32handle.html new file mode 100644 index 0000000..f186f68 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32handle.html @@ -0,0 +1,143 @@ + + + + + + + ZIP_SOURCE_WIN32HANDLE(3) + + + + + + + + +
ZIP_SOURCE_WIN32HANDLE(3)Library Functions ManualZIP_SOURCE_WIN32HANDLE(3)
+
+
+

+zip_source_win32handle, + zip_source_win32handle_create — +
create data source from a Windows file handle
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_win32handle(zip_t + *archive, HANDLE h, + zip_uint64_t start, + zip_int64_t len);

+

zip_source_t * +
+ zip_source_win32handle_create(HANDLE + h, zip_uint64_t + start, zip_int64_t + len, zip_error_t + *error);

+
+
+

+The functions zip_source_win32handle() and + zip_source_win32handle_create() create a zip source + from a Windows file handle. They open fname and read + len bytes from offset start from + it. If len is 0 or -1, the whole file (starting from + start) is used. +

If the file supports seek, the source can be used to open a zip + archive from.

+

The file is opened and read when the data from the source is used, + usually by zip_close() or + zip_open_from_source().

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_w32handle() and + zip_source_w32handle_create() fail if: +
+
[]
+
fname, start, or + len are invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Opening fname failed.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3), + zip_source_win32a(3), + zip_source_win32w(3) +
+
+

+zip_source_win32handle() and + zip_source_win32handle_create() were added in libzip + 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_win32handle.man b/third_party/libzip/man/zip_source_win32handle.man new file mode 100644 index 0000000..f06a1e8 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32handle.man @@ -0,0 +1,127 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_handle.mdoc -- create data source from a Windows file handle +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_WIN32HANDLE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_win32handle\fR, +\fBzip_source_win32handle_create\fR +\- create data source from a Windows file handle +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32handle\fR(\fIzip_t\ *archive\fR, \fIHANDLE\ h\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32handle_create\fR(\fIHANDLE\ h\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_win32handle\fR() +and +\fBzip_source_win32handle_create\fR() +create a zip source from a Windows file handle. +They open +\fIfname\fR +and read +\fIlen\fR +bytes from offset +\fIstart\fR +from it. +If +\fIlen\fR +is 0 or \-1, the whole file (starting from +\fIstart\fR) +is used. +.PP +If the file supports seek, the source can be used to open a zip archive from. +.PP +The file is opened and read when the data from the source is used, usually by +\fBzip_close\fR() +or +\fBzip_open_from_source\fR(). +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_w32handle\fR() +and +\fBzip_source_w32handle_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIfname\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_OPEN\fR] +Opening +\fIfname\fR +failed. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3), +zip_source_win32a(3), +zip_source_win32w(3) +.SH "HISTORY" +\fBzip_source_win32handle\fR() +and +\fBzip_source_win32handle_create\fR() +were added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_win32handle.mdoc b/third_party/libzip/man/zip_source_win32handle.mdoc new file mode 100644 index 0000000..920fcb5 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32handle.mdoc @@ -0,0 +1,116 @@ +.\" zip_source_handle.mdoc -- create data source from a Windows file handle +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_WIN32HANDLE 3 +.Os +.Sh NAME +.Nm zip_source_win32handle , +.Nm zip_source_win32handle_create +.Nd create data source from a Windows file handle +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_win32handle "zip_t *archive" "HANDLE h" "zip_uint64_t start" "zip_int64_t len" +.Ft zip_source_t * +.Fn zip_source_win32handle_create "HANDLE h" "zip_uint64_t start" "zip_int64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_win32handle +and +.Fn zip_source_win32handle_create +create a zip source from a Windows file handle. +They open +.Ar fname +and read +.Ar len +bytes from offset +.Ar start +from it. +If +.Ar len +is 0 or \-1, the whole file (starting from +.Ar start ) +is used. +.Pp +If the file supports seek, the source can be used to open a zip archive from. +.Pp +The file is opened and read when the data from the source is used, usually by +.Fn zip_close +or +.Fn zip_open_from_source . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_w32handle +and +.Fn zip_source_w32handle_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar fname , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_OPEN +Opening +.Ar fname +failed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 , +.Xr zip_source_win32a 3 , +.Xr zip_source_win32w 3 +.Sh HISTORY +.Fn zip_source_win32handle +and +.Fn zip_source_win32handle_create +were added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_win32w.html b/third_party/libzip/man/zip_source_win32w.html new file mode 100644 index 0000000..5958984 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32w.html @@ -0,0 +1,142 @@ + + + + + + + ZIP_SOURCE_WIN32W(3) + + + + + + + + +
ZIP_SOURCE_WIN32W(3)Library Functions ManualZIP_SOURCE_WIN32W(3)
+
+
+

+zip_source_win32w, + zip_source_win32w_create — +
create data source from a Windows Unicode file name
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_win32w(zip_t + *archive, const wchar_t + *fname, zip_uint64_t + start, zip_int64_t + len);

+

zip_source_t * +
+ zip_source_win32w_create(const + wchar_t *fname, + zip_uint64_t start, + zip_int64_t len, + zip_error_t *error);

+
+
+

+The functions zip_source_win32w() and + zip_source_win32w_create() create a zip source on + Windows using a Windows Unicode name. They open fname + and read len bytes from offset + start from it. If len is 0 or -1, + the whole file (starting from start) is used. +

If the file supports seek, the source can be used to open a zip + archive from.

+

The file is opened and read when the data from the source is used, + usually by zip_close() or + zip_open_from_source().

+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive or error is set to + indicate the error. +
+
+

+zip_source_win32w() and + zip_source_win32w_create() fail if: +
+
[]
+
fname, start, or + len are invalid.
+
[]
+
Required memory could not be allocated.
+
[]
+
Opening fname failed.
+
+
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3), + zip_source_win32a(3), + zip_source_win32handle(3) +
+
+

+zip_source_win32w() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
June 22, 2018NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_win32w.man b/third_party/libzip/man/zip_source_win32w.man new file mode 100644 index 0000000..6e18d59 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32w.man @@ -0,0 +1,125 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_win32w.mdoc -- create data source using a win32 Unicode name +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_WIN32W" "3" "June 22, 2018" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_win32w\fR, +\fBzip_source_win32w_create\fR +\- create data source from a Windows Unicode file name +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32w\fR(\fIzip_t\ *archive\fR, \fIconst\ wchar_t\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.PP +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_win32w_create\fR(\fIconst\ wchar_t\ *fname\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR, \fIzip_error_t\ *error\fR); +.PD +.SH "DESCRIPTION" +The functions +\fBzip_source_win32w\fR() +and +\fBzip_source_win32w_create\fR() +create a zip source on Windows using a Windows Unicode name. +They open +\fIfname\fR +and read +\fIlen\fR +bytes from offset +\fIstart\fR +from it. +If +\fIlen\fR +is 0 or \-1, the whole file (starting from +\fIstart\fR) +is used. +.PP +If the file supports seek, the source can be used to open a zip archive from. +.PP +The file is opened and read when the data from the source is used, usually by +\fBzip_close\fR() +or +\fBzip_open_from_source\fR(). +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +or +\fIerror\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_win32w\fR() +and +\fBzip_source_win32w_create\fR() +fail if: +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIfname\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.TP 19n +[\fRZIP_ER_OPEN\fR] +Opening +\fIfname\fR +failed. +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3), +zip_source_win32a(3), +zip_source_win32handle(3) +.SH "HISTORY" +\fBzip_source_win32w\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_win32w.mdoc b/third_party/libzip/man/zip_source_win32w.mdoc new file mode 100644 index 0000000..75d30f4 --- /dev/null +++ b/third_party/libzip/man/zip_source_win32w.mdoc @@ -0,0 +1,114 @@ +.\" zip_source_win32w.mdoc -- create data source using a win32 Unicode name +.\" Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd June 22, 2018 +.Dt ZIP_SOURCE_WIN32W 3 +.Os +.Sh NAME +.Nm zip_source_win32w , +.Nm zip_source_win32w_create +.Nd create data source from a Windows Unicode file name +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_win32w "zip_t *archive" "const wchar_t *fname" "zip_uint64_t start" "zip_int64_t len" +.Ft zip_source_t * +.Fn zip_source_win32w_create "const wchar_t *fname" "zip_uint64_t start" "zip_int64_t len" "zip_error_t *error" +.Sh DESCRIPTION +The functions +.Fn zip_source_win32w +and +.Fn zip_source_win32w_create +create a zip source on Windows using a Windows Unicode name. +They open +.Ar fname +and read +.Ar len +bytes from offset +.Ar start +from it. +If +.Ar len +is 0 or \-1, the whole file (starting from +.Ar start ) +is used. +.Pp +If the file supports seek, the source can be used to open a zip archive from. +.Pp +The file is opened and read when the data from the source is used, usually by +.Fn zip_close +or +.Fn zip_open_from_source . +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +or +.Ar error +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_win32w +and +.Fn zip_source_win32w_create +fail if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_INVAL +.Ar fname , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.It Bq Er ZIP_ER_OPEN +Opening +.Ar fname +failed. +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 , +.Xr zip_source_win32a 3 , +.Xr zip_source_win32handle 3 +.Sh HISTORY +.Fn zip_source_win32w +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_write.html b/third_party/libzip/man/zip_source_write.html new file mode 100644 index 0000000..70e5c87 --- /dev/null +++ b/third_party/libzip/man/zip_source_write.html @@ -0,0 +1,115 @@ + + + + + + + ZIP_SOURCE_WRITE(3) + + + + + + + + +
ZIP_SOURCE_WRITE(3)Library Functions ManualZIP_SOURCE_WRITE(3)
+
+
+

+zip_source_write — +
write data to zip source
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_int64_t +
+ zip_source_write(zip_source_t + *source, const void + *data, zip_uint64_t + len);

+
+
+

+The function zip_source_write() writes + len bytes from the buffer data to + the zip source source at the current write offset. +

The zip source source has to be prepared for + writing by calling + zip_source_begin_write(3) + first.

+
+
+

+Upon successful completion the number of bytes written is returned. Otherwise, + -1 is returned and the error information in source is + set to indicate the error. +
+
+

+libzip(3), + zip_source(3), + zip_source_begin_write(3), + zip_source_commit_write(3), + zip_source_rollback_write(3), + zip_source_seek_write(3), + zip_source_tell_write(3) +
+
+

+zip_source_write() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_write.man b/third_party/libzip/man/zip_source_write.man new file mode 100644 index 0000000..58d808e --- /dev/null +++ b/third_party/libzip/man/zip_source_write.man @@ -0,0 +1,85 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_write.mdoc -- write data to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_WRITE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_write\fR +\- write data to zip source +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_int64_t\fR +.br +.PD 0 +.HP 4n +\fBzip_source_write\fR(\fIzip_source_t\ *source\fR, \fIconst\ void\ *data\fR, \fIzip_uint64_t\ len\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_write\fR() +writes +\fIlen\fR +bytes from the buffer +\fIdata\fR +to the zip source +\fIsource\fR +at the current write offset. +.PP +The zip source +\fIsource\fR +has to be prepared for writing by calling +zip_source_begin_write(3) +first. +.SH "RETURN VALUES" +Upon successful completion the number of bytes written is returned. +Otherwise, \-1 is returned and the error information in +\fIsource\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_source(3), +zip_source_begin_write(3), +zip_source_commit_write(3), +zip_source_rollback_write(3), +zip_source_seek_write(3), +zip_source_tell_write(3) +.SH "HISTORY" +\fBzip_source_write\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_write.mdoc b/third_party/libzip/man/zip_source_write.mdoc new file mode 100644 index 0000000..00836b0 --- /dev/null +++ b/third_party/libzip/man/zip_source_write.mdoc @@ -0,0 +1,80 @@ +.\" zip_source_write.mdoc -- write data to zip source +.\" Copyright (C) 2014-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_WRITE 3 +.Os +.Sh NAME +.Nm zip_source_write +.Nd write data to zip source +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_int64_t +.Fn zip_source_write "zip_source_t *source" "const void *data" "zip_uint64_t len" +.Sh DESCRIPTION +The function +.Fn zip_source_write +writes +.Ar len +bytes from the buffer +.Ar data +to the zip source +.Ar source +at the current write offset. +.Pp +The zip source +.Ar source +has to be prepared for writing by calling +.Xr zip_source_begin_write 3 +first. +.Sh RETURN VALUES +Upon successful completion the number of bytes written is returned. +Otherwise, \-1 is returned and the error information in +.Ar source +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_source 3 , +.Xr zip_source_begin_write 3 , +.Xr zip_source_commit_write 3 , +.Xr zip_source_rollback_write 3 , +.Xr zip_source_seek_write 3 , +.Xr zip_source_tell_write 3 +.Sh HISTORY +.Fn zip_source_write +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_source_zip.html b/third_party/libzip/man/zip_source_zip.html new file mode 100644 index 0000000..cb79b08 --- /dev/null +++ b/third_party/libzip/man/zip_source_zip.html @@ -0,0 +1,143 @@ + + + + + + + ZIP_SOURCE_ZIP(3) + + + + + + + + +
ZIP_SOURCE_ZIP(3)Library Functions ManualZIP_SOURCE_ZIP(3)
+
+
+

+zip_source_zip — +
create data source from zip file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

zip_source_t * +
+ zip_source_zip(zip_t + *archive, zip_t + *srcarchive, zip_uint64_t + srcidx, zip_flags_t + flags, zip_uint64_t + start, zip_int64_t + len);

+
+
+

+The function zip_source_zip() creates a zip source from + a file in a zip archive. The srcarchive argument is the + (open) zip archive containing the source zip file at index + srcidx. len bytes from offset + start will be used in the zip_source. If + len is 0 or -1, the rest of the file, starting from + start, is used. If start is zero + and len is -1, the whole file will be copied without + decompressing it. +

Supported flags are:

+
+
+
Try to get the original data without any changes that may have been made + to srcarchive after opening it.
+
+
When adding the data from srcarchive, re-compress it + using the current settings instead of copying the compressed data.
+
+
+
+

+Upon successful completion, the created source is returned. Otherwise, + NULL is returned and the error code in + archive is set to indicate the error. +
+
+

+zip_source_zip() fails if: +
+
[]
+
Unchanged data was requested, but it is not available.
+
[]
+
srcarchive, srcidx, + start, or len are + invalid.
+
[]
+
Required memory could not be allocated.
+
+Additionally, it can return all error codes from + zip_stat_index() and + zip_fopen_index(). +
+
+

+libzip(3), + zip_file_add(3), + zip_file_replace(3), + zip_source(3) +
+
+

+zip_source_zip() was added in libzip 1.0. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_source_zip.man b/third_party/libzip/man/zip_source_zip.man new file mode 100644 index 0000000..efbcf0a --- /dev/null +++ b/third_party/libzip/man/zip_source_zip.man @@ -0,0 +1,129 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_source_zip.mdoc -- create data source from zip file +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_SOURCE_ZIP" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_source_zip\fR +\- create data source from zip file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIzip_source_t *\fR +.br +.PD 0 +.HP 4n +\fBzip_source_zip\fR(\fIzip_t\ *archive\fR, \fIzip_t\ *srcarchive\fR, \fIzip_uint64_t\ srcidx\fR, \fIzip_flags_t\ flags\fR, \fIzip_uint64_t\ start\fR, \fIzip_int64_t\ len\fR); +.PD +.SH "DESCRIPTION" +The function +\fBzip_source_zip\fR() +creates a zip source from a file in a zip archive. +The +\fIsrcarchive\fR +argument is the (open) zip archive containing the source zip file +at index +\fIsrcidx\fR. +\fIlen\fR +bytes from offset +\fIstart\fR +will be used in the zip_source. +If +\fIlen\fR +is 0 or \-1, the rest of the file, starting from +\fIstart\fR, +is used. +If +\fIstart\fR +is zero and +\fIlen\fR +is \-1, the whole file will be copied without decompressing it. +.PP +Supported flags are: +.TP 23n +\fRZIP_FL_UNCHANGED\fR +Try to get the original data without any changes that may have been +made to +\fIsrcarchive\fR +after opening it. +.TP 23n +\fRZIP_FL_RECOMPRESS\fR +When adding the data from +\fIsrcarchive\fR, +re-compress it using the current settings instead of copying the +compressed data. +.SH "RETURN VALUES" +Upon successful completion, the created source is returned. +Otherwise, +\fRNULL\fR +is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_source_zip\fR() +fails if: +.TP 19n +[\fRZIP_ER_CHANGED\fR] +Unchanged data was requested, but it is not available. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIsrcarchive\fR, +\fIsrcidx\fR, +\fIstart\fR, +or +\fIlen\fR +are invalid. +.TP 19n +[\fRZIP_ER_MEMORY\fR] +Required memory could not be allocated. +.PD 0 +.PP +Additionally, it can return all error codes from +\fBzip_stat_index\fR() +and +\fBzip_fopen_index\fR(). +.PD +.SH "SEE ALSO" +libzip(3), +zip_file_add(3), +zip_file_replace(3), +zip_source(3) +.SH "HISTORY" +\fBzip_source_zip\fR() +was added in libzip 1.0. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_source_zip.mdoc b/third_party/libzip/man/zip_source_zip.mdoc new file mode 100644 index 0000000..4da7da4 --- /dev/null +++ b/third_party/libzip/man/zip_source_zip.mdoc @@ -0,0 +1,120 @@ +.\" zip_source_zip.mdoc -- create data source from zip file +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_SOURCE_ZIP 3 +.Os +.Sh NAME +.Nm zip_source_zip +.Nd create data source from zip file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft zip_source_t * +.Fn zip_source_zip "zip_t *archive" "zip_t *srcarchive" "zip_uint64_t srcidx" "zip_flags_t flags" "zip_uint64_t start" "zip_int64_t len" +.Sh DESCRIPTION +The function +.Fn zip_source_zip +creates a zip source from a file in a zip archive. +The +.Ar srcarchive +argument is the (open) zip archive containing the source zip file +at index +.Ar srcidx . +.Ar len +bytes from offset +.Ar start +will be used in the zip_source. +If +.Ar len +is 0 or \-1, the rest of the file, starting from +.Ar start , +is used. +If +.Ar start +is zero and +.Ar len +is \-1, the whole file will be copied without decompressing it. +.Pp +Supported flags are: +.Bl -tag -width XZIPXFLXRECOMPRESSXXX +.It Dv ZIP_FL_UNCHANGED +Try to get the original data without any changes that may have been +made to +.Ar srcarchive +after opening it. +.It Dv ZIP_FL_RECOMPRESS +When adding the data from +.Ar srcarchive , +re-compress it using the current settings instead of copying the +compressed data. +.El +.Sh RETURN VALUES +Upon successful completion, the created source is returned. +Otherwise, +.Dv NULL +is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_source_zip +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_CHANGED +Unchanged data was requested, but it is not available. +.It Bq Er ZIP_ER_INVAL +.Ar srcarchive , +.Ar srcidx , +.Ar start , +or +.Ar len +are invalid. +.It Bq Er ZIP_ER_MEMORY +Required memory could not be allocated. +.El +Additionally, it can return all error codes from +.Fn zip_stat_index +and +.Fn zip_fopen_index . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_file_add 3 , +.Xr zip_file_replace 3 , +.Xr zip_source 3 +.Sh HISTORY +.Fn zip_source_zip +was added in libzip 1.0. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_stat.html b/third_party/libzip/man/zip_stat.html new file mode 100644 index 0000000..246adb7 --- /dev/null +++ b/third_party/libzip/man/zip_stat.html @@ -0,0 +1,190 @@ + + + + + + + ZIP_STAT(3) + + + + + + + + +
ZIP_STAT(3)Library Functions ManualZIP_STAT(3)
+
+
+

+zip_stat, zip_stat_index + — +
get information about file
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_stat(zip_t + *archive, const char + *fname, zip_flags_t + flags, zip_stat_t + *sb);

+

int +
+ zip_stat_index(zip_t + *archive, zip_uint64_t + index, zip_flags_t + flags, zip_stat_t + *sb);

+
+
+

+The zip_stat() function obtains information about the + file named fname in archive. The + flags argument specifies how the name lookup should be + done. Its values are described in + zip_name_locate(3). Also, + ZIP_FL_UNCHANGED may be + or'ed to it to request information + about the original file in the archive, ignoring any changes made. +

The zip_stat_index() function obtains + information about the file at position index.

+

The sb argument is a pointer to a + struct zip_stat (shown below), into which information + about the file is placed.

+
+
+struct zip_stat {
+    zip_uint64_t valid;                 /* which fields have valid values */
+    const char *name;                   /* name of the file */
+    zip_uint64_t index;                 /* index within archive */
+    zip_uint64_t size;                  /* size of file (uncompressed) */
+    zip_uint64_t comp_size;             /* size of file (compressed) */
+    time_t mtime;                       /* modification time */
+    zip_uint32_t crc;                   /* crc of file data */
+    zip_uint16_t comp_method;           /* compression method used */
+    zip_uint16_t encryption_method;     /* encryption method used */
+    zip_uint32_t flags;                 /* reserved for future use */
+};
+
+
+The structure pointed to by sb must be allocated before + calling zip_stat() or + zip_stat_index(). +

The valid field of the structure specifies + which other fields are valid. Check if the flag defined by the following + defines are in valid before accessing the fields:

+
+
+
+
name
+
+
index
+
+
size
+
+
comp_size
+
+
mtime
+
+
crc
+
+
comp_method
+
+
encryption_method
+
+
flags
+
+
+
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error information in archive is set to indicate the + error. +
+
+

+The function zip_stat() can fail for any of the errors + specified for the routine + zip_name_locate(3). +

The function zip_stat_index() fails and + sets the error information to ZIP_ER_INVAL if + index is invalid. If + ZIP_FL_UNCHANGED is not set and no information can + be obtained from the source callback, the error information is set to + ZIP_ER_CHANGED.

+
+
+

+libzip(3), + zip_get_num_entries(3), + zip_name_locate(3), + zip_stat_init(3) +
+
+

+zip_stat() was added in libzip 0.6. In libzip 0.11 the + type of flags was changed from int + to zip_flags_t. +

zip_stat_index() was added in libzip 0.6. + In libzip 0.10 the type of index was changed from + int to zip_uint64_t. In libzip + 0.11 the type of flags was changed from + int to zip_flags_t.

+
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_stat.man b/third_party/libzip/man/zip_stat.man new file mode 100644 index 0000000..93b6fdd --- /dev/null +++ b/third_party/libzip/man/zip_stat.man @@ -0,0 +1,203 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_stat.mdoc -- get information about file +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_STAT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_stat\fR, +\fBzip_stat_index\fR +\- get information about file +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_stat\fR(\fIzip_t\ *archive\fR, \fIconst\ char\ *fname\fR, \fIzip_flags_t\ flags\fR, \fIzip_stat_t\ *sb\fR); +.PD +.PP +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_stat_index\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR, \fIzip_flags_t\ flags\fR, \fIzip_stat_t\ *sb\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_stat\fR() +function obtains information about the file named +\fIfname\fR +in +\fIarchive\fR. +The +\fIflags\fR +argument specifies how the name lookup should be done. +Its values are described in +zip_name_locate(3). +Also, +\fRZIP_FL_UNCHANGED\fR +may be +\fIor\fR'ed +to it to request information about the original file in the archive, +ignoring any changes made. +.PP +The +\fBzip_stat_index\fR() +function obtains information about the file at position +\fIindex\fR. +.PP +The +\fIsb\fR +argument is a pointer to a +\fIstruct zip_stat\fR +(shown below), into which information about the file is placed. +.nf +.sp +.RS 0n +struct zip_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char *name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; +.RE +.fi +The structure pointed to by +\fIsb\fR +must be allocated before calling +\fBzip_stat\fR() +or +\fBzip_stat_index\fR(). +.PP +The +\fIvalid\fR +field of the structure specifies which other fields are valid. +Check if the flag defined by the following defines are in +\fIvalid\fR +before accessing the fields: +.RS 6n +.PD 0 +.TP 30n +\fRZIP_STAT_NAME\fR +\fIname\fR +.TP 30n +\fRZIP_STAT_INDEX\fR +\fIindex\fR +.TP 30n +\fRZIP_STAT_SIZE\fR +\fIsize\fR +.TP 30n +\fRZIP_STAT_COMP_SIZE\fR +\fIcomp_size\fR +.TP 30n +\fRZIP_STAT_MTIME\fR +\fImtime\fR +.TP 30n +\fRZIP_STAT_CRC\fR +\fIcrc\fR +.TP 30n +\fRZIP_STAT_COMP_METHOD\fR +\fIcomp_method\fR +.TP 30n +\fRZIP_STAT_ENCRYPTION_METHOD\fR +\fIencryption_method\fR +.TP 30n +\fRZIP_STAT_FLAGS\fR +\fIflags\fR +.RE +.PD +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +The function +\fBzip_stat\fR() +can fail for any of the errors specified for the routine +zip_name_locate(3). +.PP +The function +\fBzip_stat_index\fR() +fails and sets the error information to +\fRZIP_ER_INVAL\fR +if +\fIindex\fR +is invalid. +If +\fRZIP_FL_UNCHANGED\fR +is not set and no information can be obtained from the source +callback, the error information is set to +\fRZIP_ER_CHANGED\fR. +.SH "SEE ALSO" +libzip(3), +zip_get_num_entries(3), +zip_name_locate(3), +zip_stat_init(3) +.SH "HISTORY" +\fBzip_stat\fR() +was added in libzip 0.6. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.PP +\fBzip_stat_index\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +In libzip 0.11 the type of +\fIflags\fR +was changed from +\fIint\fR +to +\fIzip_flags_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_stat.mdoc b/third_party/libzip/man/zip_stat.mdoc new file mode 100644 index 0000000..4d5661e --- /dev/null +++ b/third_party/libzip/man/zip_stat.mdoc @@ -0,0 +1,179 @@ +.\" zip_stat.mdoc -- get information about file +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_STAT 3 +.Os +.Sh NAME +.Nm zip_stat , +.Nm zip_stat_index +.Nd get information about file +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_stat "zip_t *archive" "const char *fname" "zip_flags_t flags" "zip_stat_t *sb" +.Ft int +.Fn zip_stat_index "zip_t *archive" "zip_uint64_t index" "zip_flags_t flags" "zip_stat_t *sb" +.Sh DESCRIPTION +The +.Fn zip_stat +function obtains information about the file named +.Ar fname +in +.Ar archive . +The +.Ar flags +argument specifies how the name lookup should be done. +Its values are described in +.Xr zip_name_locate 3 . +Also, +.Dv ZIP_FL_UNCHANGED +may be +.Em or Ns No 'ed +to it to request information about the original file in the archive, +ignoring any changes made. +.Pp +The +.Fn zip_stat_index +function obtains information about the file at position +.Ar index . +.Pp +The +.Ar sb +argument is a pointer to a +.Ft struct zip_stat +(shown below), into which information about the file is placed. +.Bd -literal +struct zip_stat { + zip_uint64_t valid; /* which fields have valid values */ + const char *name; /* name of the file */ + zip_uint64_t index; /* index within archive */ + zip_uint64_t size; /* size of file (uncompressed) */ + zip_uint64_t comp_size; /* size of file (compressed) */ + time_t mtime; /* modification time */ + zip_uint32_t crc; /* crc of file data */ + zip_uint16_t comp_method; /* compression method used */ + zip_uint16_t encryption_method; /* encryption method used */ + zip_uint32_t flags; /* reserved for future use */ +}; +.Ed +The structure pointed to by +.Ar sb +must be allocated before calling +.Fn zip_stat +or +.Fn zip_stat_index . +.Pp +The +.Ar valid +field of the structure specifies which other fields are valid. +Check if the flag defined by the following defines are in +.Ar valid +before accessing the fields: +.Bl -tag -width ZIP_STAT_ENCRYPTION_METHODXX -compact -offset indent +.It Dv ZIP_STAT_NAME +.Ar name +.It Dv ZIP_STAT_INDEX +.Ar index +.It Dv ZIP_STAT_SIZE +.Ar size +.It Dv ZIP_STAT_COMP_SIZE +.Ar comp_size +.It Dv ZIP_STAT_MTIME +.Ar mtime +.It Dv ZIP_STAT_CRC +.Ar crc +.It Dv ZIP_STAT_COMP_METHOD +.Ar comp_method +.It Dv ZIP_STAT_ENCRYPTION_METHOD +.Ar encryption_method +.It Dv ZIP_STAT_FLAGS +.Ar flags +.El +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error information in +.Ar archive +is set to indicate the error. +.Sh ERRORS +The function +.Fn zip_stat +can fail for any of the errors specified for the routine +.Xr zip_name_locate 3 . +.Pp +The function +.Fn zip_stat_index +fails and sets the error information to +.Er ZIP_ER_INVAL +if +.Ar index +is invalid. +If +.Dv ZIP_FL_UNCHANGED +is not set and no information can be obtained from the source +callback, the error information is set to +.Er ZIP_ER_CHANGED . +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_get_num_entries 3 , +.Xr zip_name_locate 3 , +.Xr zip_stat_init 3 +.Sh HISTORY +.Fn zip_stat +was added in libzip 0.6. +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Pp +.Fn zip_stat_index +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +In libzip 0.11 the type of +.Ar flags +was changed from +.Vt int +to +.Vt zip_flags_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_stat_init.html b/third_party/libzip/man/zip_stat_init.html new file mode 100644 index 0000000..d274b74 --- /dev/null +++ b/third_party/libzip/man/zip_stat_init.html @@ -0,0 +1,109 @@ + + + + + + + ZIP_STAT_INIT(3) + + + + + + + + +
ZIP_STAT_INIT(3)Library Functions ManualZIP_STAT_INIT(3)
+
+
+

+zip_stat_init — +
initialize zip_stat structure
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

void +
+ zip_stat_init(zip_stat_t + *sb);

+
+
+

+The zip_stat_init() function initializes the members of + a struct zip_stat. The current members are described in + zip_stat(3), but this function should + be used to initialize it to make sure none are missed. The structure pointed + to by sb must be allocated before calling + zip_stat_init(). +

This function should be used by functions provided to + zip_source_function(3) + when returning ZIP_SOURCE_STAT information to make + sure all fields are initialized.

+
+
+

+If sb is valid, the function is always successful. +
+
+

+libzip(3), + zip_stat(3) +
+
+

+zip_stat_init() was added in libzip 0.8. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_stat_init.man b/third_party/libzip/man/zip_stat_init.man new file mode 100644 index 0000000..75f3ea9 --- /dev/null +++ b/third_party/libzip/man/zip_stat_init.man @@ -0,0 +1,81 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_stat_init.mdoc -- init zip_stat structure +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_STAT_INIT" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_stat_init\fR +\- initialize zip_stat structure +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIvoid\fR +.br +.PD 0 +.HP 4n +\fBzip_stat_init\fR(\fIzip_stat_t\ *sb\fR); +.PD +.SH "DESCRIPTION" +The +\fBzip_stat_init\fR() +function initializes the members of a struct zip_stat. +The current members are described in +zip_stat(3), +but this function should be used to initialize it to +make sure none are missed. +The structure pointed to by +\fIsb\fR +must be allocated before calling +\fBzip_stat_init\fR(). +.PP +This function should be used by functions provided to +zip_source_function(3) +when returning +\fRZIP_SOURCE_STAT\fR +information to make sure all fields are initialized. +.SH "RETURN VALUES" +If +\fIsb\fR +is valid, the function is always successful. +.SH "SEE ALSO" +libzip(3), +zip_stat(3) +.SH "HISTORY" +\fBzip_stat_init\fR() +was added in libzip 0.8. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_stat_init.mdoc b/third_party/libzip/man/zip_stat_init.mdoc new file mode 100644 index 0000000..0d464a6 --- /dev/null +++ b/third_party/libzip/man/zip_stat_init.mdoc @@ -0,0 +1,76 @@ +.\" zip_stat_init.mdoc -- init zip_stat structure +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_STAT_INIT 3 +.Os +.Sh NAME +.Nm zip_stat_init +.Nd initialize zip_stat structure +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft void +.Fn zip_stat_init "zip_stat_t *sb" +.Sh DESCRIPTION +The +.Fn zip_stat_init +function initializes the members of a struct zip_stat. +The current members are described in +.Xr zip_stat 3 , +but this function should be used to initialize it to +make sure none are missed. +The structure pointed to by +.Ar sb +must be allocated before calling +.Fn zip_stat_init . +.Pp +This function should be used by functions provided to +.Xr zip_source_function 3 +when returning +.Dv ZIP_SOURCE_STAT +information to make sure all fields are initialized. +.Sh RETURN VALUES +If +.Ar sb +is valid, the function is always successful. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_stat 3 +.Sh HISTORY +.Fn zip_stat_init +was added in libzip 0.8. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_unchange.html b/third_party/libzip/man/zip_unchange.html new file mode 100644 index 0000000..20ea1fd --- /dev/null +++ b/third_party/libzip/man/zip_unchange.html @@ -0,0 +1,116 @@ + + + + + + + ZIP_UNCHANGE(3) + + + + + + + + +
ZIP_UNCHANGE(3)Library Functions ManualZIP_UNCHANGE(3)
+
+
+

+zip_unchange — +
undo changes to file in zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_unchange(zip_t + *archive, zip_uint64_t + index);

+
+
+

+Changes to the file at position index are reverted. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+zip_unchange() fails if: +
+
[]
+
Unchanging the name would result in a duplicate name in the archive.
+
[]
+
index is not a valid file index in + zip.
+
+
+
+

+libzip(3), + zip_unchange_all(3), + zip_unchange_archive(3) +
+
+

+zip_unchange() was added in libzip 0.6. In libzip 0.10 + the type of index was changed from + int to zip_uint64_t. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_unchange.man b/third_party/libzip/man/zip_unchange.man new file mode 100644 index 0000000..c7ec25f --- /dev/null +++ b/third_party/libzip/man/zip_unchange.man @@ -0,0 +1,86 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_unchange.mdoc -- undo changes to file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_UNCHANGE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_unchange\fR +\- undo changes to file in zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_unchange\fR(\fIzip_t\ *archive\fR, \fIzip_uint64_t\ index\fR); +.PD +.SH "DESCRIPTION" +Changes to the file at position +\fIindex\fR +are reverted. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "ERRORS" +\fBzip_unchange\fR() +fails if: +.TP 19n +[\fRZIP_ER_EXISTS\fR] +Unchanging the name would result in a duplicate name in the archive. +.TP 19n +[\fRZIP_ER_INVAL\fR] +\fIindex\fR +is not a valid file index in +\fIzip\fR. +.SH "SEE ALSO" +libzip(3), +zip_unchange_all(3), +zip_unchange_archive(3) +.SH "HISTORY" +\fBzip_unchange\fR() +was added in libzip 0.6. +In libzip 0.10 the type of +\fIindex\fR +was changed from +\fIint\fR +to +\fIzip_uint64_t\fR. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_unchange.mdoc b/third_party/libzip/man/zip_unchange.mdoc new file mode 100644 index 0000000..6bde36b --- /dev/null +++ b/third_party/libzip/man/zip_unchange.mdoc @@ -0,0 +1,81 @@ +.\" zip_unchange.mdoc -- undo changes to file in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_UNCHANGE 3 +.Os +.Sh NAME +.Nm zip_unchange +.Nd undo changes to file in zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_unchange "zip_t *archive" "zip_uint64_t index" +.Sh DESCRIPTION +Changes to the file at position +.Ar index +are reverted. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh ERRORS +.Fn zip_unchange +fails if: +.Bl -tag -width Er +.It Bq Er ZIP_ER_EXISTS +Unchanging the name would result in a duplicate name in the archive. +.It Bq Er ZIP_ER_INVAL +.Ar index +is not a valid file index in +.Ar zip . +.El +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_unchange_all 3 , +.Xr zip_unchange_archive 3 +.Sh HISTORY +.Fn zip_unchange +was added in libzip 0.6. +In libzip 0.10 the type of +.Ar index +was changed from +.Vt int +to +.Vt zip_uint64_t . +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_unchange_all.html b/third_party/libzip/man/zip_unchange_all.html new file mode 100644 index 0000000..27f5690 --- /dev/null +++ b/third_party/libzip/man/zip_unchange_all.html @@ -0,0 +1,103 @@ + + + + + + + ZIP_UNCHANGE_ALL(3) + + + + + + + + +
ZIP_UNCHANGE_ALL(3)Library Functions ManualZIP_UNCHANGE_ALL(3)
+
+
+

+zip_unchange_all — +
undo all changes in a zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_unchange_all(zip_t + *archive);

+
+
+

+All changes to files and global information in archive are + reverted. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+libzip(3), + zip_unchange(3), + zip_unchange_archive(3) +
+
+

+zip_unchange_all() was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_unchange_all.man b/third_party/libzip/man/zip_unchange_all.man new file mode 100644 index 0000000..4fcbee3 --- /dev/null +++ b/third_party/libzip/man/zip_unchange_all.man @@ -0,0 +1,69 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_unchange_all.mdoc -- undo changes to all files in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_UNCHANGE_ALL" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_unchange_all\fR +\- undo all changes in a zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_unchange_all\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +All changes to files and global information in +\fIarchive\fR +are reverted. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_unchange(3), +zip_unchange_archive(3) +.SH "HISTORY" +\fBzip_unchange_all\fR() +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_unchange_all.mdoc b/third_party/libzip/man/zip_unchange_all.mdoc new file mode 100644 index 0000000..b676eb5 --- /dev/null +++ b/third_party/libzip/man/zip_unchange_all.mdoc @@ -0,0 +1,64 @@ +.\" zip_unchange_all.mdoc -- undo changes to all files in zip archive +.\" Copyright (C) 2003-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_UNCHANGE_ALL 3 +.Os +.Sh NAME +.Nm zip_unchange_all +.Nd undo all changes in a zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_unchange_all "zip_t *archive" +.Sh DESCRIPTION +All changes to files and global information in +.Ar archive +are reverted. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_unchange 3 , +.Xr zip_unchange_archive 3 +.Sh HISTORY +.Fn zip_unchange_all +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zip_unchange_archive.html b/third_party/libzip/man/zip_unchange_archive.html new file mode 100644 index 0000000..770709c --- /dev/null +++ b/third_party/libzip/man/zip_unchange_archive.html @@ -0,0 +1,103 @@ + + + + + + + ZIP_UNCHANGE_ARCHIVE(3) + + + + + + + + +
ZIP_UNCHANGE_ARCHIVE(3)Library Functions ManualZIP_UNCHANGE_ARCHIVE(3)
+
+
+

+zip_unchange_archive — +
undo global changes to zip archive
+
+
+

+libzip (-lzip) +
+
+

+#include <zip.h> +

int +
+ zip_unchange_archive(zip_t + *archive);

+
+
+

+Revert all global changes to the archive archive. This + reverts changes to the archive comment and global flags. +
+
+

+Upon successful completion 0 is returned. Otherwise, -1 is returned and the + error code in archive is set to indicate the error. +
+
+

+libzip(3), + zip_unchange(3), + zip_unchange_all(3) +
+
+

+zip_unchange_archive() was added in libzip 0.7. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zip_unchange_archive.man b/third_party/libzip/man/zip_unchange_archive.man new file mode 100644 index 0000000..430eafc --- /dev/null +++ b/third_party/libzip/man/zip_unchange_archive.man @@ -0,0 +1,69 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zip_unchange_archive.mdoc -- undo changes to all files in zip archive +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIP_UNCHANGE_ARCHIVE" "3" "December 18, 2017" "NiH" "Library Functions Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzip_unchange_archive\fR +\- undo global changes to zip archive +.SH "LIBRARY" +libzip (-lzip) +.SH "SYNOPSIS" +\fB#include \fR +.sp +\fIint\fR +.br +.PD 0 +.HP 4n +\fBzip_unchange_archive\fR(\fIzip_t\ *archive\fR); +.PD +.SH "DESCRIPTION" +Revert all global changes to the archive +\fIarchive\fR. +This reverts changes to the archive comment and global flags. +.SH "RETURN VALUES" +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +\fIarchive\fR +is set to indicate the error. +.SH "SEE ALSO" +libzip(3), +zip_unchange(3), +zip_unchange_all(3) +.SH "HISTORY" +\fBzip_unchange_archive\fR() +was added in libzip 0.7. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zip_unchange_archive.mdoc b/third_party/libzip/man/zip_unchange_archive.mdoc new file mode 100644 index 0000000..b3b3d3f --- /dev/null +++ b/third_party/libzip/man/zip_unchange_archive.mdoc @@ -0,0 +1,64 @@ +.\" zip_unchange_archive.mdoc -- undo changes to all files in zip archive +.\" Copyright (C) 2006-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIP_UNCHANGE_ARCHIVE 3 +.Os +.Sh NAME +.Nm zip_unchange_archive +.Nd undo global changes to zip archive +.Sh LIBRARY +libzip (-lzip) +.Sh SYNOPSIS +.In zip.h +.Ft int +.Fn zip_unchange_archive "zip_t *archive" +.Sh DESCRIPTION +Revert all global changes to the archive +.Ar archive . +This reverts changes to the archive comment and global flags. +.Sh RETURN VALUES +Upon successful completion 0 is returned. +Otherwise, \-1 is returned and the error code in +.Ar archive +is set to indicate the error. +.Sh SEE ALSO +.Xr libzip 3 , +.Xr zip_unchange 3 , +.Xr zip_unchange_all 3 +.Sh HISTORY +.Fn zip_unchange_archive +was added in libzip 0.7. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zipcmp.html b/third_party/libzip/man/zipcmp.html new file mode 100644 index 0000000..0cfdeee --- /dev/null +++ b/third_party/libzip/man/zipcmp.html @@ -0,0 +1,122 @@ + + + + + + + ZIPCMP(1) + + + + + + + + +
ZIPCMP(1)General Commands ManualZIPCMP(1)
+
+
+

+zipcmp — +
compare contents of zip archives
+
+
+

+ + + + + +
zipcmp[-hipqtVv] archive1 + archive2
+
+
+

+zipcmp compares the zip archives or directories + archive1 and archive2 and checks + if they contain the same files, comparing their names, uncompressed sizes, and + CRCs. File order and compressed size differences are ignored. +

Supported options:

+
+
+
Display a short help message and exit.
+
+
Compare names ignoring case distinctions.
+
+
Enable paranoid checks. Compares extra fields and other meta data. + (Automatically disabled if one of the archives is a directory.)
+
+
Quiet mode. Compare -v.
+
+
Test zip files by comparing the contents to their checksums.
+
+
Display version information and exit.
+
+
Verbose mode. Print details about differences to stdout. (This is the + default.)
+
+
+
+

+zipcmp exits 0 if the two archives contain the same + files, 1 if they differ, and >1 if an error occurred. +
+
+

+zipmerge(1), + ziptool(1), + libzip(3) +
+
+

+zipcmp was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zipcmp.man b/third_party/libzip/man/zipcmp.man new file mode 100644 index 0000000..58cf205 --- /dev/null +++ b/third_party/libzip/man/zipcmp.man @@ -0,0 +1,96 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zipcmp.mdoc -- compare zip archives +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIPCMP" "1" "December 18, 2017" "NiH" "General Commands Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzipcmp\fR +\- compare contents of zip archives +.SH "SYNOPSIS" +.HP 7n +\fBzipcmp\fR +[\fB\-hipqtVv\fR] +\fIarchive1\ archive2\fR +.SH "DESCRIPTION" +\fBzipcmp\fR +compares the zip archives or directories +\fIarchive1\fR +and +\fIarchive2\fR +and checks if they contain the same files, comparing their names, +uncompressed sizes, and CRCs. +File order and compressed size differences are ignored. +.PP +Supported options: +.TP 5n +\fB\-h\fR +Display a short help message and exit. +.TP 5n +\fB\-i\fR +Compare names ignoring case distinctions. +.TP 5n +\fB\-p\fR +Enable paranoid checks. +Compares extra fields and other meta data. +(Automatically disabled if one of the archives is a directory.) +.TP 5n +\fB\-q\fR +Quiet mode. +Compare +\fB\-v\fR. +.TP 5n +\fB\-t\fR +Test zip files by comparing the contents to their checksums. +.TP 5n +\fB\-V\fR +Display version information and exit. +.TP 5n +\fB\-v\fR +Verbose mode. +Print details about differences to stdout. +(This is the default.) +.SH "EXIT STATUS" +\fBzipcmp\fR +exits 0 if the two archives contain the same files, 1 if they differ, +and >1 if an error occurred. +.SH "SEE ALSO" +zipmerge(1), +ziptool(1), +libzip(3) +.SH "HISTORY" +\fBzipcmp\fR +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zipcmp.mdoc b/third_party/libzip/man/zipcmp.mdoc new file mode 100644 index 0000000..a3bc508 --- /dev/null +++ b/third_party/libzip/man/zipcmp.mdoc @@ -0,0 +1,90 @@ +.\" zipcmp.mdoc -- compare zip archives +.\" Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIPCMP 1 +.Os +.Sh NAME +.Nm zipcmp +.Nd compare contents of zip archives +.Sh SYNOPSIS +.Nm +.Op Fl hipqtVv +.Ar archive1 archive2 +.Sh DESCRIPTION +.Nm +compares the zip archives or directories +.Ar archive1 +and +.Ar archive2 +and checks if they contain the same files, comparing their names, +uncompressed sizes, and CRCs. +File order and compressed size differences are ignored. +.Pp +Supported options: +.Bl -tag -width MMM +.It Fl h +Display a short help message and exit. +.It Fl i +Compare names ignoring case distinctions. +.It Fl p +Enable paranoid checks. +Compares extra fields and other meta data. +(Automatically disabled if one of the archives is a directory.) +.It Fl q +Quiet mode. +Compare +.Fl v . +.It Fl t +Test zip files by comparing the contents to their checksums. +.It Fl V +Display version information and exit. +.It Fl v +Verbose mode. +Print details about differences to stdout. +(This is the default.) +.El +.Sh EXIT STATUS +.Nm +exits 0 if the two archives contain the same files, 1 if they differ, +and >1 if an error occurred. +.Sh SEE ALSO +.Xr zipmerge 1 , +.Xr ziptool 1 , +.Xr libzip 3 +.Sh HISTORY +.Nm +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/zipmerge.html b/third_party/libzip/man/zipmerge.html new file mode 100644 index 0000000..ce2d819 --- /dev/null +++ b/third_party/libzip/man/zipmerge.html @@ -0,0 +1,125 @@ + + + + + + + ZIPMERGE(1) + + + + + + + + +
ZIPMERGE(1)General Commands ManualZIPMERGE(1)
+
+
+

+zipmerge — +
merge zip archives
+
+
+

+ + + + + +
zipmerge[-DhIiSsV] target-zip + source-zip [source-zip + ...]
+
+
+

+zipmerge merges the source zip archives + source-zip into the target zip archive + target-zip. By default, files in the source zip archives + overwrite existing files of the same name in the target zip archive. +

Supported options:

+
+
+
Ignore directory components in file name comparisons. This option is slow + for archives with many files.
+
+
Display a short help message and exit.
+
+
Ignore case in file name comparisons This option is slow for archives with + many files.
+
+
Ask before overwriting files. See also -s.
+
+
Do not overwrite files that have the same size and CRC32 in both the + source and target archives.
+
+
When -i is given, do not before overwriting files + that have the same size and CRC32.
+
+
Display version information and exit.
+
+
+
+

+zipmerge exits 0 on success and >1 if an error + occurred. +
+
+

+zipcmp(1), + ziptool(1), + libzip(3) +
+
+

+zipmerge was added in libzip 0.6. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/zipmerge.man b/third_party/libzip/man/zipmerge.man new file mode 100644 index 0000000..5ea5ef6 --- /dev/null +++ b/third_party/libzip/man/zipmerge.man @@ -0,0 +1,97 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" zipmerge.mdoc -- merge zip archives +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIPMERGE" "1" "December 18, 2017" "NiH" "General Commands Manual" +.nh +.if n .ad l +.SH "NAME" +\fBzipmerge\fR +\- merge zip archives +.SH "SYNOPSIS" +.HP 9n +\fBzipmerge\fR +[\fB\-DhIiSsV\fR] +\fItarget-zip\fR +\fIsource-zip\fR\ [\fIsource-zip\ ...\fR] +.SH "DESCRIPTION" +\fBzipmerge\fR +merges the source zip archives +\fIsource-zip\fR +into the target zip archive +\fItarget-zip\fR. +By default, files in the source zip archives overwrite +existing files of the same name in the target zip archive. +.PP +Supported options: +.TP 5n +\fB\-D\fR +Ignore directory components in file name comparisons. +This option is slow for archives with many files. +.TP 5n +\fB\-h\fR +Display a short help message and exit. +.TP 5n +\fB\-I\fR +Ignore case in file name comparisons +This option is slow for archives with many files. +.TP 5n +\fB\-i\fR +Ask before overwriting files. +See also +\fB\-s\fR. +.TP 5n +\fB\-S\fR +Do not overwrite files that have the same size and +CRC32 in both the source and target archives. +.TP 5n +\fB\-s\fR +When +\fB\-i\fR +is given, do not before overwriting files that have the same size +and CRC32. +.TP 5n +\fB\-V\fR +Display version information and exit. +.SH "EXIT STATUS" +\fBzipmerge\fR +exits 0 on success and >1 if an error occurred. +.SH "SEE ALSO" +zipcmp(1), +ziptool(1), +libzip(3) +.SH "HISTORY" +\fBzipmerge\fR +was added in libzip 0.6. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/zipmerge.mdoc b/third_party/libzip/man/zipmerge.mdoc new file mode 100644 index 0000000..9c99514 --- /dev/null +++ b/third_party/libzip/man/zipmerge.mdoc @@ -0,0 +1,91 @@ +.\" zipmerge.mdoc -- merge zip archives +.\" Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIPMERGE 1 +.Os +.Sh NAME +.Nm zipmerge +.Nd merge zip archives +.Sh SYNOPSIS +.Nm +.Op Fl DhIiSsV +.Ar target-zip +.Ar source-zip Op Ar source-zip ... +.Sh DESCRIPTION +.Nm +merges the source zip archives +.Ar source-zip +into the target zip archive +.Ar target-zip . +By default, files in the source zip archives overwrite +existing files of the same name in the target zip archive. +.Pp +Supported options: +.Bl -tag -width MMM +.It Fl D +Ignore directory components in file name comparisons. +This option is slow for archives with many files. +.It Fl h +Display a short help message and exit. +.It Fl I +Ignore case in file name comparisons +This option is slow for archives with many files. +.It Fl i +Ask before overwriting files. +See also +.Fl s . +.It Fl S +Do not overwrite files that have the same size and +CRC32 in both the source and target archives. +.It Fl s +When +.Fl i +is given, do not before overwriting files that have the same size +and CRC32. +.It Fl V +Display version information and exit. +.El +.Sh EXIT STATUS +.Nm +exits 0 on success and >1 if an error occurred. +.Sh SEE ALSO +.Xr zipcmp 1 , +.Xr ziptool 1 , +.Xr libzip 3 +.Sh HISTORY +.Nm +was added in libzip 0.6. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/man/ziptool.html b/third_party/libzip/man/ziptool.html new file mode 100644 index 0000000..ea9f406 --- /dev/null +++ b/third_party/libzip/man/ziptool.html @@ -0,0 +1,315 @@ + + + + + + + ZIPTOOL(1) + + + + + + + + +
ZIPTOOL(1)General Commands ManualZIPTOOL(1)
+
+
+

+ziptool — +
modify zip archives
+
+
+

+ + + + + +
ziptool[-ceghnrst] [-l + length] [-o + offset] zip-archive + command [command-args ...] + [command [command-args ...] + ...]
+
+
+

+ziptool modifies the zip archive + zip-archive according to the + commands given. +

Supported options:

+
+
+
Check zip archive consistency when opening it.
+
+
Error if archive already exists (only useful with + -n).
+
+
Guess file name encoding (for stat command).
+
+
Display help.
+
+ length
+
Only read length bytes of archive. See also + -o.
+
+
Create archive if it doesn't exist. See also + -e.
+
+ offset
+
Start reading input archive from offset. See also + -l.
+
+
Print raw file name encoding without translation (for + stat command).
+
+
Follow file name convention strictly (for stat + command).
+
+
Disregard current file contents, if any. Note: use this + with care, it deletes all existing file contents when you modify the + archive.
+
+
+

+For all commands below, the index is zero-based. In other words, the first entry + in the zip archive has index 0. +

Supported commands and arguments are:

+
+
+ name content
+
Add file called name using the string + content from the command line as data.
+
+ name
+
Add directory name.
+
+ name file_to_add offset len
+
Add file name to archive, using + len bytes from the file + file_to_add as input data, starting at + offset.
+
+ name archivename index offset len
+
Add file called name to archive using data from + another zip archive archivename using the entry with + index index and reading len + bytes from offset.
+
+ index
+
Output file contents for entry index to stdout.
+
+ index flags
+
Print the number of extra fields for archive entry + index using flags.
+
+ index extra_id flags
+
Print number of extra fields of type extra_id for + archive entry index using + flags.
+
+ index
+
Remove entry at index from zip archive.
+
+ index extra_idx flags
+
Remove extra field number extra_idx from archive + entry index using flags.
+
+ index extra_id extra_index flags
+
Remove extra field number extra_index of type + extra_id from archive entry + index using flags.
+
+
Print archive comment.
+
+ index extra_index flags
+
Print extra field extra_index for archive entry + index using flags.
+
+ index extra_id extra_index flags
+
Print extra field extra_index of type + extra_id for archive entry + index using flags.
+
+ index
+
Get file comment for archive entry index.
+
+ flags
+
Print number of entries in archive using flags.
+
+ name flags
+
Find entry in archive with the filename name using + flags and print its index.
+
+ index name
+
Rename archive entry index to + name.
+
+ index data
+
Replace file contents for archive entry index with + the string data.
+
+ comment
+
Set archive comment to comment.
+
+ index extra_id extra_index flags value
+
Set extra field number extra_index of type + extra_id for archive entry + index using flags to + value.
+
+ index comment
+
Set file comment for archive entry index to string + comment.
+
+ index method compression_flags
+
Set file compression method for archive entry index + to method using + compression_flags. Note: + Currently, compression_flags are ignored.
+
+ index method password
+
Set file encryption method for archive entry index + to method with password + password.
+
+ index timestamp
+
Set file modification time for archive entry index + to UNIX mtime timestamp.
+
+ timestamp
+
Set file modification time for all archive entries to UNIX mtime + timestamp.
+
+ password
+
Set default password for encryption/decryption to + password.
+
+ index
+
Print information about archive entry index.
+
+
+
+

+Some commands take flag arguments. Supported flags are: + +
+
+

+Some commands take compression method arguments. Supported methods are: + +
+
+

+Some commands take encryption method arguments. Supported methods are: + +
+
+
+

+The ziptool utility exits 0 on success, + and >0 if an error occurs. +
+
+

+Add a file called teststring.txt to the zip archive + testbuffer.zip with data “This is a + test.\n” where “\n” is replaced with a newline character: +
+
+ziptool testbuffer.zip add teststring.txt \"This is a test.\n\"
+
+
+

Delete the first file from the zip archive + testfile.zip:

+
+
+ziptool testfile.zip delete 0
+
+
+
+
+

+zipcmp(1), + zipmerge(1), + libzip(3) +
+
+

+ziptool was added in libzip 1.1. +
+
+

+Dieter Baron + <dillo@nih.at> and + Thomas Klausner + <tk@giga.or.at> +
+
+ + + + + +
December 18, 2017NetBSD 8.99.35
+ + diff --git a/third_party/libzip/man/ziptool.man b/third_party/libzip/man/ziptool.man new file mode 100644 index 0000000..da9829a --- /dev/null +++ b/third_party/libzip/man/ziptool.man @@ -0,0 +1,389 @@ +.\" Automatically generated from an mdoc input file. Do not edit. +.\" ziptool.mdoc -- modify zip archives in multiple ways +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.TH "ZIPTOOL" "1" "December 18, 2017" "NiH" "General Commands Manual" +.nh +.if n .ad l +.SH "NAME" +\fBziptool\fR +\- modify zip archives +.SH "SYNOPSIS" +.HP 8n +\fBziptool\fR +[\fB\-ceghnrst\fR] +[\fB\-l\fR\ \fIlength\fR] +[\fB\-o\fR\ \fIoffset\fR] +\fIzip-archive\fR +\fBcommand\fR\ [\fIcommand-args\ ...\fR] +[\fBcommand\fR\ [\fIcommand-args\ ...\fR]\ ...] +.SH "DESCRIPTION" +\fBziptool\fR +modifies the zip archive +\fIzip-archive\fR +according to the +\fIcommands\fR +given. +.PP +Supported options: +.TP 13n +\fB\-c\fR +Check zip archive consistency when opening it. +.TP 13n +\fB\-e\fR +Error if archive already exists (only useful with +\fB\-n\fR). +.TP 13n +\fB\-g\fR +Guess file name encoding (for +\fBstat\fR +command). +.TP 13n +\fB\-h\fR +Display help. +.TP 13n +\fB\-l\fR \fIlength\fR +Only read +\fIlength\fR +bytes of archive. +See also +\fB\-o\fR. +.TP 13n +\fB\-n\fR +Create archive if it doesn't exist. +See also +\fB\-e\fR. +.TP 13n +\fB\-o\fR \fIoffset\fR +Start reading input archive from +\fIoffset\fR. +See also +\fB\-l\fR. +.TP 13n +\fB\-r\fR +Print raw file name encoding without translation (for +\fBstat\fR +command). +.TP 13n +\fB\-s\fR +Follow file name convention strictly (for +\fBstat\fR +command). +.TP 13n +\fB\-t\fR +Disregard current file contents, if any. +\fINote\fR: +use this with care, it deletes all existing file contents when +you modify the archive. +.SS "Commands" +For all commands below, the index is zero-based. +In other words, the first entry in the zip archive has index 0. +.PP +Supported commands and arguments are: +.TP 12n +\fBadd\fR \fIname content\fR +Add file called +\fIname\fR +using the string +\fIcontent\fR +from the command line as data. +.TP 12n +\fBadd_dir\fR \fIname\fR +Add directory +\fIname\fR. +.TP 12n +\fBadd_file\fR \fIname file_to_add offset len\fR +Add file +\fIname\fR +to archive, using +\fIlen\fR +bytes from the file +\fIfile_to_add\fR +as input data, starting at +\fIoffset\fR. +.TP 12n +\fBadd_from_zip\fR \fIname archivename index offset len\fR +Add file called +\fIname\fR +to archive using data from another zip archive +\fIarchivename\fR +using the entry with index +\fIindex\fR +and reading +\fIlen\fR +bytes from +\fIoffset\fR. +.TP 12n +\fBcat\fR \fIindex\fR +Output file contents for entry +\fIindex\fR +to stdout. +.TP 12n +\fBcount_extra\fR \fIindex flags\fR +Print the number of extra fields for archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBcount_extra_by_id\fR \fIindex extra_id flags\fR +Print number of extra fields of type +\fIextra_id\fR +for archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBdelete\fR \fIindex\fR +Remove entry at +\fIindex\fR +from zip archive. +.TP 12n +\fBdelete_extra\fR \fIindex extra_idx flags\fR +Remove extra field number +\fIextra_idx\fR +from archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBdelete_extra_by_id\fR \fIindex extra_id extra_index flags\fR +Remove extra field number +\fIextra_index\fR +of type +\fIextra_id\fR +from archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBget_archive_comment\fR +Print archive comment. +.TP 12n +\fBget_extra\fR \fIindex extra_index flags\fR +Print extra field +\fIextra_index\fR +for archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBget_extra_by_id\fR \fIindex extra_id extra_index flags\fR +Print extra field +\fIextra_index\fR +of type +\fIextra_id\fR +for archive entry +\fIindex\fR +using +\fIflags\fR. +.TP 12n +\fBget_file_comment\fR \fIindex\fR +Get file comment for archive entry +\fIindex\fR. +.TP 12n +\fBget_num_entries\fR \fIflags\fR +Print number of entries in archive using +\fIflags\fR. +.TP 12n +\fBname_locate\fR \fIname flags\fR +Find entry in archive with the filename +\fIname\fR +using +\fIflags\fR +and print its index. +.TP 12n +\fBrename\fR \fIindex name\fR +Rename archive entry +\fIindex\fR +to +\fIname\fR. +.TP 12n +\fBreplace_file_contents\fR \fIindex data\fR +Replace file contents for archive entry +\fIindex\fR +with the string +\fIdata\fR. +.TP 12n +\fBset_archive_comment\fR \fIcomment\fR +Set archive comment to +\fIcomment\fR. +.TP 12n +\fBset_extra\fR \fIindex extra_id extra_index flags value\fR +Set extra field number +\fIextra_index\fR +of type +\fIextra_id\fR +for archive entry +\fIindex\fR +using +\fIflags\fR +to +\fIvalue\fR. +.TP 12n +\fBset_file_comment\fR \fIindex comment\fR +Set file comment for archive entry +\fIindex\fR +to string +\fIcomment\fR. +.TP 12n +\fBset_file_compression\fR \fIindex method compression_flags\fR +Set file compression method for archive entry +\fIindex\fR +to +\fImethod\fR +using +\fIcompression_flags\fR. +\fINote\fR: +Currently, +\fIcompression_flags\fR +are ignored. +.TP 12n +\fBset_file_encryption\fR \fIindex method password\fR +Set file encryption method for archive entry +\fIindex\fR +to +\fImethod\fR +with password +\fIpassword\fR. +.TP 12n +\fBset_file_mtime\fR \fIindex timestamp\fR +Set file modification time for archive entry +\fIindex\fR +to UNIX mtime +\fItimestamp\fR. +.TP 12n +\fBset_file_mtime_all\fR \fItimestamp\fR +Set file modification time for all archive entries to UNIX mtime +\fItimestamp\fR. +.TP 12n +\fBset_password\fR \fIpassword\fR +Set default password for encryption/decryption to +\fIpassword\fR. +.TP 12n +\fBstat\fR \fIindex\fR +Print information about archive entry +\fIindex\fR. +.SS "Flags" +Some commands take flag arguments. +Supported flags are: +.RS 6n +.PD 0 +.TP 5n +\fIC\fR +\fRZIP_FL_NOCASE\fR +.TP 5n +\fIc\fR +\fRZIP_FL_CENTRAL\fR +.TP 5n +\fId\fR +\fRZIP_FL_NODIR\fR +.TP 5n +\fIl\fR +\fRZIP_FL_LOCAL\fR +.TP 5n +\fIu\fR +\fRZIP_FL_UNCHANGED\fR +.RE +.PD +.SS "Compression Methods" +Some commands take compression method arguments. +Supported methods are: +.RS 6n +.PD 0 +.TP 4n +\fB\(bu\fR +\fRdefault\fR +.TP 4n +\fB\(bu\fR +\fRdeflate\fR +.TP 4n +\fB\(bu\fR +\fRstore\fR +.RE +.PD +.SS "Encryption Methods" +Some commands take encryption method arguments. +Supported methods are: +.RS 6n +.PD 0 +.TP 4n +\fB\(bu\fR +\fRnone\fR +.TP 4n +\fB\(bu\fR +\fRAES-128\fR +.TP 4n +\fB\(bu\fR +\fRAES-192\fR +.TP 4n +\fB\(bu\fR +\fRAES-256\fR +.RE +.PD +.SH "EXIT STATUS" +.br +The \fBziptool\fR utility exits\~0 on success, and\~>0 if an error occurs. +.SH "EXAMPLES" +Add a file called +\fIteststring.txt\fR +to the zip archive +\fItestbuffer.zip\fR +with data +\(lqThis is a test.\en\(rq +where +\(lq\en\(rq +is replaced with a newline character: +.nf +.sp +.RS 6n +ziptool testbuffer.zip add teststring.txt \\"This is a test.\en\\" +.RE +.fi +.PP +Delete the first file from the zip archive +\fItestfile.zip\fR: +.nf +.sp +.RS 6n +ziptool testfile.zip delete 0 +.RE +.fi +.SH "SEE ALSO" +zipcmp(1), +zipmerge(1), +libzip(3) +.SH "HISTORY" +\fBziptool\fR +was added in libzip 1.1. +.SH "AUTHORS" +Dieter Baron <\fIdillo@nih.at\fR> +and +Thomas Klausner <\fItk@giga.or.at\fR> diff --git a/third_party/libzip/man/ziptool.mdoc b/third_party/libzip/man/ziptool.mdoc new file mode 100644 index 0000000..751eeb0 --- /dev/null +++ b/third_party/libzip/man/ziptool.mdoc @@ -0,0 +1,330 @@ +.\" ziptool.mdoc -- modify zip archives in multiple ways +.\" Copyright (C) 2016-2017 Dieter Baron and Thomas Klausner +.\" +.\" This file is part of libzip, a library to manipulate ZIP archives. +.\" The authors can be contacted at +.\" +.\" 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. +.\" 3. The names of the authors may not be used to endorse or promote +.\" products derived from this software without specific prior +.\" written permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +.\" +.Dd December 18, 2017 +.Dt ZIPTOOL 1 +.Os +.Sh NAME +.Nm ziptool +.Nd modify zip archives +.Sh SYNOPSIS +.Nm +.Op Fl ceghnrst +.Op Fl l Ar length +.Op Fl o Ar offset +.Ar zip-archive +.Cm command Op Ar command-args ... +.Op Cm command Oo Ar command-args ... Oc ... +.Sh DESCRIPTION +.Nm +modifies the zip archive +.Ar zip-archive +according to the +.Ar commands +given. +.Pp +Supported options: +.Bl -tag -width MoMoffsetMM +.It Fl c +Check zip archive consistency when opening it. +.It Fl e +Error if archive already exists (only useful with +.Fl n ) . +.It Fl g +Guess file name encoding (for +.Cm stat +command). +.It Fl h +Display help. +.It Fl l Ar length +Only read +.Ar length +bytes of archive. +See also +.Fl o . +.It Fl n +Create archive if it doesn't exist. +See also +.Fl e . +.It Fl o Ar offset +Start reading input archive from +.Ar offset . +See also +.Fl l . +.It Fl r +Print raw file name encoding without translation (for +.Cm stat +command). +.It Fl s +Follow file name convention strictly (for +.Cm stat +command). +.It Fl t +Disregard current file contents, if any. +.Em Note : +use this with care, it deletes all existing file contents when +you modify the archive. +.El +.Ss Commands +For all commands below, the index is zero-based. +In other words, the first entry in the zip archive has index 0. +.Pp +Supported commands and arguments are: +.Bl -tag -width 10n +.It Cm add Ar name content +Add file called +.Ar name +using the string +.Ar content +from the command line as data. +.It Cm add_dir Ar name +Add directory +.Ar name . +.It Cm add_file Ar name file_to_add offset len +Add file +.Ar name +to archive, using +.Ar len +bytes from the file +.Ar file_to_add +as input data, starting at +.Ar offset . +.It Cm add_from_zip Ar name archivename index offset len +Add file called +.Ar name +to archive using data from another zip archive +.Ar archivename +using the entry with index +.Ar index +and reading +.Ar len +bytes from +.Ar offset . +.It Cm cat Ar index +Output file contents for entry +.Ar index +to stdout. +.It Cm count_extra Ar index flags +Print the number of extra fields for archive entry +.Ar index +using +.Ar flags . +.It Cm count_extra_by_id Ar index extra_id flags +Print number of extra fields of type +.Ar extra_id +for archive entry +.Ar index +using +.Ar flags . +.It Cm delete Ar index +Remove entry at +.Ar index +from zip archive. +.It Cm delete_extra Ar index extra_idx flags +Remove extra field number +.Ar extra_idx +from archive entry +.Ar index +using +.Ar flags . +.It Cm delete_extra_by_id Ar index extra_id extra_index flags +Remove extra field number +.Ar extra_index +of type +.Ar extra_id +from archive entry +.Ar index +using +.Ar flags . +.It Cm get_archive_comment +Print archive comment. +.It Cm get_extra Ar index extra_index flags +Print extra field +.Ar extra_index +for archive entry +.Ar index +using +.Ar flags . +.It Cm get_extra_by_id Ar index extra_id extra_index flags +Print extra field +.Ar extra_index +of type +.Ar extra_id +for archive entry +.Ar index +using +.Ar flags . +.It Cm get_file_comment Ar index +Get file comment for archive entry +.Ar index . +.It Cm get_num_entries Ar flags +Print number of entries in archive using +.Ar flags . +.It Cm name_locate Ar name flags +Find entry in archive with the filename +.Ar name +using +.Ar flags +and print its index. +.It Cm rename Ar index name +Rename archive entry +.Ar index +to +.Ar name . +.It Cm replace_file_contents Ar index data +Replace file contents for archive entry +.Ar index +with the string +.Ar data . +.It Cm set_archive_comment Ar comment +Set archive comment to +.Ar comment . +.It Cm set_extra Ar index extra_id extra_index flags value +Set extra field number +.Ar extra_index +of type +.Ar extra_id +for archive entry +.Ar index +using +.Ar flags +to +.Ar value . +.It Cm set_file_comment Ar index comment +Set file comment for archive entry +.Ar index +to string +.Ar comment . +.It Cm set_file_compression Ar index method compression_flags +Set file compression method for archive entry +.Ar index +to +.Ar method +using +.Ar compression_flags . +.Em Note : +Currently, +.Ar compression_flags +are ignored. +.It Cm set_file_encryption Ar index method password +Set file encryption method for archive entry +.Ar index +to +.Ar method +with password +.Ar password . +.It Cm set_file_mtime Ar index timestamp +Set file modification time for archive entry +.Ar index +to UNIX mtime +.Ar timestamp . +.It Cm set_file_mtime_all Ar timestamp +Set file modification time for all archive entries to UNIX mtime +.Ar timestamp . +.It Cm set_password Ar password +Set default password for encryption/decryption to +.Ar password . +.It Cm stat Ar index +Print information about archive entry +.Ar index . +.El +.Ss Flags +Some commands take flag arguments. +Supported flags are: +.Bl -tag -width MMM -compact -offset indent +.It Ar C +.Dv ZIP_FL_NOCASE +.It Ar c +.Dv ZIP_FL_CENTRAL +.It Ar d +.Dv ZIP_FL_NODIR +.It Ar l +.Dv ZIP_FL_LOCAL +.It Ar u +.Dv ZIP_FL_UNCHANGED +.El +.Ss Compression Methods +Some commands take compression method arguments. +Supported methods are: +.Bl -bullet -compact -offset indent +.It +.Dv default +.It +.Dv deflate +.It +.Dv store +.El +.Ss Encryption Methods +Some commands take encryption method arguments. +Supported methods are: +.Bl -bullet -compact -offset indent +.It +.Dv none +.It +.Dv AES-128 +.It +.Dv AES-192 +.It +.Dv AES-256 +.El +.Sh EXIT STATUS +.Ex -std +.Sh EXAMPLES +Add a file called +.Pa teststring.txt +to the zip archive +.Pa testbuffer.zip +with data +.Dq This is a test.\en +where +.Dq \en +is replaced with a newline character: +.Bd -literal -offset indent +ziptool testbuffer.zip add teststring.txt \\"This is a test.\en\\" +.Ed +.Pp +Delete the first file from the zip archive +.Pa testfile.zip : +.Bd -literal -offset indent +ziptool testfile.zip delete 0 +.Ed +.Sh SEE ALSO +.Xr zipcmp 1 , +.Xr zipmerge 1 , +.Xr libzip 3 +.Sh HISTORY +.Nm +was added in libzip 1.1. +.Sh AUTHORS +.An -nosplit +.An Dieter Baron Aq Mt dillo@nih.at +and +.An Thomas Klausner Aq Mt tk@giga.or.at diff --git a/third_party/libzip/regress/CMakeLists.txt b/third_party/libzip/regress/CMakeLists.txt new file mode 100644 index 0000000..6337e16 --- /dev/null +++ b/third_party/libzip/regress/CMakeLists.txt @@ -0,0 +1,206 @@ +CHECK_FUNCTION_EXISTS(getopt HAVE_GETOPT) +IF(NOT HAVE_GETOPT) + SET(SRC_EXTRA_FILES ../src/getopt.c) +ENDIF() + +SET(TEST_PROGRAMS + add_from_filep + fopen_unchanged + fseek + nonrandomopentest +) + +SET(GETOPT_USERS + fread + tryopen +) + +ADD_EXECUTABLE(can_clone_file can_clone_file.c) + +SET(ENV{srcdir} ${CMAKE_CURRENT_SOURCE_DIR}) +FOREACH(PROGRAM ${TEST_PROGRAMS}) + ADD_EXECUTABLE(${PROGRAM} ${PROGRAM}.c) + TARGET_LINK_LIBRARIES(${PROGRAM} zip) +ENDFOREACH() + +ADD_EXECUTABLE(hole hole.c ${SRC_EXTRA_FILES} source_hole.c) +TARGET_LINK_LIBRARIES(hole zip) + +ADD_EXECUTABLE(ziptool_regress ziptool_regress.c ${SRC_EXTRA_FILES} source_hole.c) +TARGET_LINK_LIBRARIES(ziptool_regress zip) + +#ADD_LIBRARY(malloc MODULE malloc.c) +#TARGET_LINK_LIBRARIES(malloc ${CMAKE_DL_LIBS}) +ADD_LIBRARY(nonrandomopen MODULE nonrandomopen.c) +TARGET_LINK_LIBRARIES(nonrandomopen ${CMAKE_DL_LIBS}) + +FOREACH(PROGRAM ${GETOPT_USERS}) + ADD_EXECUTABLE(${PROGRAM} ${PROGRAM}.c ${SRC_EXTRA_FILES}) + TARGET_LINK_LIBRARIES(${PROGRAM} zip) +ENDFOREACH() + +# for appveyor builds +#SET(CMAKE_MSVCIDE_RUN_PATH C:/projects/libzip/vstudio/zlib/installed/bin;C:/projects/libzip/vstudio/zlib/installed/lib;C:/projects/libzip/build/lib/Release) + +ADD_CUSTOM_TARGET(cleanup + COMMAND ${CMAKE_COMMAND} -DDIR=${CMAKE_CURRENT_BINARY_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/cleanup.cmake + ) + +ADD_CUSTOM_TARGET(testinput + ALL + VERBATIM + COMMAND cmake -E tar x ${CMAKE_CURRENT_SOURCE_DIR}/manyfiles-zip.zip + COMMAND cmake -E tar x ${CMAKE_CURRENT_SOURCE_DIR}/bigzero-zip.zip + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/manyfiles-zip.zip ${CMAKE_CURRENT_SOURCE_DIR}/bigzero-zip.zip +) + +SET_PROPERTY(DIRECTORY PROPERTY ADDITIONAL_MAKE_CLEAN_FILES + bigzero.zip + manyfiles-133000.zip + manyfiles-65536.zip + manyfiles-fewer.zip + manyfiles-more.zip + manyfiles-zip64-modulo.zip + manyfiles-zip64.zip + manyfiles.zip +) + +SET(EXTRA_TESTS + add_dir.test + add_from_buffer.test + add_from_file.test + add_from_file_duplicate.test + add_from_file_twice_duplicate.test + add_from_filep.test + add_from_stdin.test + add_from_zip_closed.test + add_from_zip_deflated.test + add_from_zip_deflated2.test + add_from_zip_partial_deflated.test + add_from_zip_partial_stored.test + add_from_zip_stored.test + add_stored.test + add_stored_in_memory.test + buffer-fragment-read.test + buffer-fragment-write.test + clone-buffer-add.test + clone-buffer-delete.test + clone-buffer-replace.test + clone-fs-add.test + clone-fs-delete.test + clone-fs-replace.test + cm-default.test + count_entries.test + decrypt-correct-password-aes128.test + decrypt-correct-password-aes192.test + decrypt-correct-password-aes256.test + decrypt-correct-password-pkware.test + decrypt-no-password-aes256.test + decrypt-wrong-password-aes128.test + decrypt-wrong-password-aes192.test + decrypt-wrong-password-aes256.test + decrypt-wrong-password-pkware.test + delete_add_same.test + delete_invalid.test + delete_last.test + delete_multiple_last.test + delete_multiple_partial.test + delete_renamed_rename.test + encrypt.test + encryption-nonrandom-aes128.test + encryption-nonrandom-aes192.test + encryption-nonrandom-aes256.test + encryption-remove.test + extra_add.test + extra_add_multiple.test + extra_count.test + extra_count_by_id.test + extra_count_ignore_zip64.test + extra_delete.test + extra_delete_by_id.test + extra_field_align.test + extra_get.test + extra_get_by_id.test + extra_set.test + extra_set_modify_c.test + extra_set_modify_l.test + fdopen_ok.test + file_comment_encmismatch.test + fopen_unchanged.test + fread.test + fseek_deflated.test + fseek_fail.test + fseek_ok.test + get_comment.test + junk_at_end.test + junk_at_start.test + name_locate.test + open_cons_extrabytes.test + open_empty.test + open_empty_2.test + open_extrabytes.test + open_file_count.test + open_filename_duplicate.test + open_filename_duplicate_consistency.test + open_filename_duplicate_empty.test + open_filename_duplicate_empty_consistency.test + open_filename_empty.test + open_incons.test + open_many_fail.test + open_many_ok.test + open_multidisk.test + open_new_but_exists.test + open_new_ok.test + open_nonarchive.test + open_nosuchfile.test + open_ok.test + open_too_short.test + open_truncate.test + open_zip64_3mf.test + open_zip64_ok.test + preload.test + progress.test + rename_ascii.test + rename_cp437.test + rename_deleted.test + rename_fail.test + rename_ok.test + rename_utf8.test + rename_utf8_encmismatch.test + set_comment_all.test + set_comment_localonly.test + set_comment_removeglobal.test + set_comment_revert.test + set_compression_bzip2_to_deflate.test + set_compression_deflate_to_bzip2.test + set_compression_deflate_to_deflate.test + set_compression_deflate_to_store.test + set_compression_store_to_bzip2.test + set_compression_store_to_deflate.test + set_compression_store_to_store.test + set_compression_unknown.test + stat_index_cp437_guess.test + stat_index_cp437_raw.test + stat_index_cp437_strict.test + stat_index_fileorder.test + stat_index_streamed.test + stat_index_streamed_zip64.test + stat_index_utf8_guess.test + stat_index_utf8_raw.test + stat_index_utf8_strict.test + stat_index_utf8_unmarked_strict.test + stat_index_zip64.test + utf-8-standardization.test + zip-in-archive-comment.test + zip64_creation.test + zip64_stored_creation.test +) + +FOREACH(CASE ${EXTRA_TESTS}) + ADD_TEST(${CASE} perl ${CMAKE_BINARY_DIR}/regress/runtest ${CMAKE_CURRENT_SOURCE_DIR}/${CASE}) + SET_TESTS_PROPERTIES(${CASE} PROPERTIES SKIP_RETURN_CODE 77) +ENDFOREACH() + +INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/../lib ${CMAKE_CURRENT_SOURCE_DIR}/../src ${CMAKE_CURRENT_BINARY_DIR}/..) + +ADD_CUSTOM_TARGET(check COMMAND ${CMAKE_CTEST_COMMAND}) diff --git a/third_party/libzip/regress/NiHTest.pm b/third_party/libzip/regress/NiHTest.pm new file mode 100644 index 0000000..736ebae --- /dev/null +++ b/third_party/libzip/regress/NiHTest.pm @@ -0,0 +1,1437 @@ +package NiHTest; + +use strict; +use warnings; + +use Cwd; +use File::Copy; +use File::Path qw(mkpath remove_tree); +use Getopt::Long qw(:config posix_default bundling no_ignore_case); +use IPC::Open3; +use Storable qw(dclone); +use Symbol 'gensym'; +use UNIVERSAL; + +#use Data::Dumper qw(Dumper); + +# NiHTest -- package to run regression tests +# Copyright (C) 2002-2016 Dieter Baron and Thomas Klausner +# +# This file is part of ckmame, a program to check rom sets for MAME. +# The authors can be contacted at +# +# 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. +# 3. The names of the authors may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. + +# runtest TESTNAME +# +# files: +# TESTNAME.test: test scenario +# +# test scenario: +# Lines beginning with # are comments. +# +# The following commands are recognized; return and args must +# appear exactly once, the others are optional. +# +# args ARGS +# run program with command line arguments ARGS +# +# description TEXT +# description of what test is for +# +# features FEATURE ... +# only run test if all FEATUREs are present, otherwise skip it. +# +# file TEST IN OUT +# copy file IN as TEST, compare against OUT after program run. +# +# file-del TEST IN +# copy file IN as TEST, check that it is removed by program. +# +# file-new TEST OUT +# check that file TEST is created by program and compare +# against OUT. +# +# mkdir MODE NAME +# create directory NAME with permissions MODE. +# +# pipefile FILE +# pipe FILE to program's stdin. +# +# pipein COMMAND ARGS ... +# pipe output of running COMMAND to program's stdin. +# +# precheck COMMAND ARGS ... +# if COMMAND exits with non-zero status, skip test. +# +# preload LIBRARY +# pre-load LIBRARY before running program. +# +# program PRG +# run PRG instead of ckmame. +# +# return RET +# RET is the expected exit code +# +# setenv VAR VALUE +# set environment variable VAR to VALUE. +# +# stderr TEXT +# program is expected to produce the error message TEXT. If +# multiple stderr commands are used, the messages are +# expected in the order given. +# +# stderr-replace REGEX REPLACEMENT +# run regex replacement over expected and got stderr output. +# +# stdout TEXT +# program is expected to print TEXT to stdout. If multiple +# stdout commands are used, the messages are expected in +# the order given. +# +# touch MTIME FILE +# set last modified timestamp of FILE to MTIME (seconds since epoch). +# If FILE doesn't exist, an empty file is created. +# +# ulimit C VALUE +# set ulimit -C to VALUE while running the program. +# +# exit status +# runtest uses the following exit codes: +# 0: test passed +# 1: test failed +# 2: other error +# 77: test was skipped +# +# environment variables: +# RUN_GDB: if set, run gdb on program in test environment +# KEEP_BROKEN: if set, don't delete test environment if test failed +# NO_CLEANUP: if set, don't delete test environment +# SETUP_ONLY: if set, exit after creating test environment +# VERBOSE: if set, be more verbose (e. g., output diffs) + +my %EXIT_CODES = ( + PASS => 0, + FAIL => 1, + SKIP => 77, + ERROR => 99 + ); + +# MARK: - Public API + +sub new { + my $class = UNIVERSAL::isa ($_[0], __PACKAGE__) ? shift : __PACKAGE__; + my $self = bless {}, $class; + + my ($opts) = @_; + + $self->{default_program} = $opts->{default_program}; + $self->{zipcmp} = $opts->{zipcmp} // 'zipcmp'; + $self->{zipcmp_flags} = $opts->{zipcmp_flags} // '-p'; + + $self->{directives} = { + args => { type => 'string...', once => 1, required => 1 }, + description => { type => 'string', once => 1 }, + features => { type => 'string...', once => 1 }, + file => { type => 'string string string' }, + 'file-del' => { type => 'string string' }, + 'file-new' => { type => 'string string' }, + mkdir => { type => 'string string' }, + pipefile => { type => 'string', once => 1 }, + pipein => { type => 'string', once => 1 }, + precheck => { type => 'string...' }, + preload => { type => 'string', once => 1 }, + program => { type => 'string', once => 1 }, + 'return' => { type => 'int', once => 1, required => 1 }, + setenv => { type => 'string string' }, + stderr => { type => 'string' }, + 'stderr-replace' => { type => 'string string' }, + stdout => { type => 'string' }, + touch => { type => 'int string' }, + ulimit => { type => 'char string' } + }; + + $self->{compare_by_type} = {}; + $self->{copy_by_type} = {}; + $self->{hooks} = {}; + + $self->get_variable('srcdir', $opts); + $self->get_variable('top_builddir', $opts); + + $self->{in_sandbox} = 0; + + $self->{verbose} = $ENV{VERBOSE}; + $self->{keep_broken} = $ENV{KEEP_BROKEN}; + $self->{no_cleanup} = $ENV{NO_CLEANUP}; + $self->{setup_only} = $ENV{SETUP_ONLY}; + + return $self; +} + + +sub add_comparator { + my ($self, $ext, $sub) = @_; + + return $self->add_file_proc('compare_by_type', $ext, $sub); +} + + +sub add_copier { + my ($self, $ext, $sub) = @_; + + return $self->add_file_proc('copy_by_type', $ext, $sub); +} + + +sub add_directive { + my ($self, $name, $def) = @_; + + if (exists($self->{directives}->{$name})) { + $self->die("directive $name already defined"); + } + + # TODO: validate $def + + $self->{directives}->{$name} = $def; + + return 1; +} + + +sub add_file_proc { + my ($self, $proc, $ext, $sub) = @_; + + $self->{$proc}->{$ext} = [] unless (defined($self->{$proc}->{$ext})); + unshift @{$self->{$proc}->{$ext}}, $sub; + + return 1; +} + + +sub add_hook { + my ($self, $hook, $sub) = @_; + + $self->{hooks}->{$hook} = [] unless (defined($self->{hooks}->{$hook})); + push @{$self->{hooks}->{$hook}}, $sub; + + return 1; +} + + +sub add_variant { + my ($self, $name, $hooks) = @_; + + if (!defined($self->{variants})) { + $self->{variants} = []; + $self->add_directive('variants' => { type => 'string...', once => 1 }); + } + for my $variant (@{$self->{variants}}) { + if ($variant->{name} eq $name) { + $self->die("variant $name already defined"); + } + } + + push @{$self->{variants}}, { name => $name, hooks => $hooks }; + + return 1; +} + + +sub end { + my ($self, @results) = @_; + + my $result = 'PASS'; + + for my $r (@results) { + if ($r eq 'ERROR' || ($r eq 'FAIL' && $result ne 'ERROR')) { + $result = $r; + } + } + + $self->end_test($result); +} + + +sub run { + my ($self, @argv) = @_; + + $self->setup(@argv); + + $self->end($self->runtest()); +} + + +sub runtest { + my ($self) = @_; + + if (defined($self->{variants})) { + my @results = (); + $self->{original_test} = $self->{test}; + + my %variants; + + if (defined($self->{test}->{variants})) { + %variants = map { $_ => 1; } @{$self->{test}->{variants}}; + } + + for my $variant (@{$self->{variants}}) { + next if (defined($self->{test}->{variants}) && !exists($variants{$variant->{name}})); + + $self->{variant_hooks} = $variant->{hooks}; + $self->{test} = dclone($self->{original_test}); + $self->{variant} = $variant->{name}; + $self->mangle_test_for_variant(); + push @results, $self->runtest_one($variant->{name}); + } + + return @results; + } + else { + return $self->runtest_one(); + } +} + + +sub runtest_one { + my ($self, $tag) = @_; + + $ENV{TZ} = "UTC"; + $ENV{LC_CTYPE} = "C"; + $ENV{POSIXLY_CORRECT} = 1; + $self->sandbox_create($tag); + $self->sandbox_enter(); + + my $ok = 1; + $ok &= $self->copy_files(); + $ok &= $self->run_hook('post_copy_files'); + $ok &= $self->touch_files(); + $ok &= $self->run_hook('prepare_sandbox'); + return 'ERROR' unless ($ok); + + if ($self->{setup_only}) { + $self->sandbox_leave(); + return 'SKIP'; + } + + for my $env (@{$self->{test}->{'setenv'}}) { + $ENV{$env->[0]} = $env->[1]; + } + my $preload_env_var = 'LD_PRELOAD'; + if ($^O eq 'darwin') { + $preload_env_var = 'DYLD_INSERT_LIBRARIES'; + } + if (defined($self->{test}->{'preload'})) { + if (-f cwd() . "/../.libs/$self->{test}->{'preload'}") { + $ENV{$preload_env_var} = cwd() . "/../.libs/$self->{test}->{'preload'}"; + } else { + $ENV{$preload_env_var} = cwd() . "/../lib$self->{test}->{'preload'}"; + } + } + + $self->run_program(); + + for my $env (@{$self->{test}->{'setenv'}}) { + delete ${ENV{$env->[0]}}; + } + if (defined($self->{test}->{'preload'})) { + delete ${ENV{$preload_env_var}}; + } + + if ($self->{test}->{stdout}) { + $self->{expected_stdout} = [ @{$self->{test}->{stdout}} ]; + } + else { + $self->{expected_stdout} = []; + } + if ($self->{test}->{stderr}) { + $self->{expected_stderr} = [ @{$self->{test}->{stderr}} ]; + } + else { + $self->{expected_stderr} = []; + } + + $self->run_hook('post_run_program'); + + my @failed = (); + + if ($self->{exit_status} != ($self->{test}->{return} // 0)) { + push @failed, 'exit status'; + if ($self->{verbose}) { + print "Unexpected exit status:\n"; + print "-" . ($self->{test}->{return} // 0) . "\n+$self->{exit_status}\n"; + } + } + + if (!$self->compare_arrays($self->{expected_stdout}, $self->{stdout}, 'output')) { + push @failed, 'output'; + } + if (!$self->compare_arrays($self->{expected_stderr}, $self->{stderr}, 'error output')) { + push @failed, 'error output'; + } + if (!$self->compare_files()) { + push @failed, 'files'; + } + + $self->{failed} = \@failed; + + $self->run_hook('checks'); + + my $result = scalar(@{$self->{failed}}) == 0 ? 'PASS' : 'FAIL'; + + $self->sandbox_leave(); + if (!($self->{no_cleanup} || ($self->{keep_broken} && $result eq 'FAIL'))) { + $self->sandbox_remove(); + } + + $self->print_test_result($tag, $result, join ', ', @{$self->{failed}}); + + return $result; +} + + +sub setup { + my ($self, @argv) = @_; + + my @save_argv = @ARGV; + @ARGV = @argv; + my $ok = GetOptions( + 'help|h' => \my $help, + 'keep-broken|k' => \$self->{keep_broken}, + 'no-cleanup' => \$self->{no_cleanup}, + # 'run-gdb' => \$self->{run_gdb}, + 'setup-only' => \$self->{setup_only}, + 'verbose|v' => \$self->{verbose} + ); + @argv = @ARGV; + @ARGV = @save_argv; + + if (!$ok || scalar(@argv) != 1 || $help) { + print STDERR "Usage: $0 [-hv] [--keep-broken] [--no-cleanup] [--setup-only] testcase\n"; + exit(1); + } + + my $testcase = shift @argv; + + $testcase .= '.test' unless ($testcase =~ m/\.test$/); + + my $testcase_file = $self->find_file($testcase); + + $self->die("cannot find test case $testcase") unless ($testcase_file); + + $testcase =~ s,^(?:.*/)?([^/]*)\.test$,$1,; + $self->{testname} = $testcase; + + $self->die("error in test case definition") unless $self->parse_case($testcase_file); + + $self->check_features_requirement() if ($self->{test}->{features}); + $self->run_precheck() if ($self->{test}->{precheck}); + + $self->end_test('SKIP') if ($self->{test}->{preload} && $^O eq 'darwin'); +} + + +# MARK: - Internal Methods + +sub add_file { + my ($self, $file) = @_; + + if (defined($self->{files}->{$file->{destination}})) { + $self->warn("duplicate specification for input file $file->{destination}"); + return undef; + } + + $self->{files}->{$file->{destination}} = $file; + + return 1; +} + + +sub check_features_requirement() { + my ($self) = @_; + + my %features; + + my $fh; + unless (open($fh, '<', "$self->{top_builddir}/config.h")) { + $self->die("cannot open config.h in top builddir $self->{top_builddir}"); + } + while (my $line = <$fh>) { + if ($line =~ m/^#define HAVE_([A-Z0-9_a-z]*)/) { + $features{$1} = 1; + } + } + close($fh); + + my @missing = (); + for my $feature (@{$self->{test}->{features}}) { + if (!$features{$feature}) { + push @missing, $feature; + } + } + + if (scalar @missing > 0) { + my $reason = "missing features"; + if (scalar(@missing) == 1) { + $reason = "missing feature"; + } + $self->print_test_result('SKIP', "$reason: " . (join ' ', @missing)); + $self->end_test('SKIP'); + } + + return 1; +} + + +sub comparator_zip { + my ($self, $got, $expected) = @_; + + my @args = ($self->{zipcmp}, $self->{verbose} ? '-v' : '-q'); + push @args, $self->{zipcmp_flags} if ($self->{zipcmp_flags}); + push @args, ($expected, $got); + + my $ret = system(@args); + + return $ret == 0; +} + + +sub compare_arrays() { + my ($self, $a, $b, $tag) = @_; + + my $ok = 1; + + if (scalar(@$a) != scalar(@$b)) { + $ok = 0; + } + else { + for (my $i = 0; $i < scalar(@$a); $i++) { + if ($a->[$i] ne $b->[$i]) { + $ok = 0; + last; + } + } + } + + if (!$ok && $self->{verbose}) { + print "Unexpected $tag:\n"; + print "--- expected\n+++ got\n"; + + diff_arrays($a, $b); + } + + return $ok; +} + +sub file_cmp($$) { + my ($a, $b) = @_; + my $result = 0; + open my $fha, "< $a"; + open my $fhb, "< $b"; + binmode $fha; + binmode $fhb; + BYTE: while (!eof $fha && !eof $fhb) { + if (getc $fha ne getc $fhb) { + $result = 1; + last BYTE; + } + } + $result = 1 if eof $fha != eof $fhb; + close $fha; + close $fhb; + return $result; +} + +sub compare_file($$$) { + my ($self, $got, $expected) = @_; + + my $real_expected = $self->find_file($expected); + unless ($real_expected) { + $self->warn("cannot find expected result file $expected"); + return 0; + } + + my $ok = $self->run_comparator($got, $real_expected); + + if (!defined($ok)) { + my $ret; + if ($self->{verbose}) { + $ret = system('diff', '-u', $real_expected, $got); + } + else { + $ret = file_cmp($real_expected, $got); + } + $ok = ($ret == 0); + } + + return $ok; +} + +sub list_files { + my ($root) = @_; + my $ls; + + my @files = (); + my @dirs = ($root); + + while (scalar(@dirs) > 0) { + my $dir = shift @dirs; + + opendir($ls, $dir); + unless ($ls) { + # TODO: handle error + } + while (my $entry = readdir($ls)) { + my $file = "$dir/$entry"; + if ($dir eq '.') { + $file = $entry; + } + + if (-f $file) { + push @files, "$file"; + } + if (-d $file && $entry ne '.' && $entry ne '..') { + push @dirs, "$file"; + } + } + closedir($ls); + } + + return @files; +} + +sub compare_files() { + my ($self) = @_; + + my $ok = 1; + + + my @files_got = sort(list_files(".")); + my @files_should = (); + + for my $file (sort keys %{$self->{files}}) { + push @files_should, $file if ($self->{files}->{$file}->{result} || $self->{files}->{$file}->{ignore}); + } + + $self->{files_got} = \@files_got; + $self->{files_should} = \@files_should; + + unless ($self->run_hook('post_list_files')) { + return 0; + } + + $ok = $self->compare_arrays($self->{files_should}, $self->{files_got}, 'files'); + + for my $file (@{$self->{files_got}}) { + my $file_def = $self->{files}->{$file}; + next unless ($file_def && $file_def->{result}); + + $ok &= $self->compare_file($file, $file_def->{result}); + } + + return $ok; +} + + +sub copy_files { + my ($self) = @_; + + my $ok = 1; + + for my $filename (sort keys %{$self->{files}}) { + my $file = $self->{files}->{$filename}; + next unless ($file->{source}); + + my $src = $self->find_file($file->{source}); + unless ($src) { + $self->warn("cannot find input file $file->{source}"); + $ok = 0; + next; + } + + if ($file->{destination} =~ m,/,) { + my $dir = $file->{destination}; + $dir =~ s,/[^/]*$,,; + if (! -d $dir) { + mkpath($dir); + } + } + + my $this_ok = $self->run_copier($src, $file->{destination}); + if (defined($this_ok)) { + $ok &= $this_ok; + } + else { + unless (copy($src, $file->{destination})) { + $self->warn("cannot copy $src to $file->{destination}: $!"); + $ok = 0; + } + } + } + + if (defined($self->{test}->{mkdir})) { + for my $dir_spec (@{$self->{test}->{mkdir}}) { + my ($mode, $dir) = @$dir_spec; + if (! -d $dir) { + unless (mkdir($dir, oct($mode))) { + $self->warn("cannot create directory $dir: $!"); + $ok = 0; + } + } + } + } + + $self->die("failed to copy input files") unless ($ok); +} + + +sub die() { + my ($self, $msg) = @_; + + print STDERR "$0: $msg\n" if ($msg); + + $self->end_test('ERROR'); +} + + +sub end_test { + my ($self, $status) = @_; + + my $exit_code = $EXIT_CODES{$status} // $EXIT_CODES{ERROR}; + + $self->exit($exit_code); +} + + + +sub exit() { + my ($self, $status) = @_; + ### TODO: cleanup + + exit($status); +} + + +sub find_file() { + my ($self, $fname) = @_; + + for my $dir (('', "$self->{srcdir}/")) { + my $f = "$dir$fname"; + $f = "../$f" if ($self->{in_sandbox} && $dir !~ m,^/,); + + return $f if (-f $f); + } + + return undef; +} + + +sub get_extension { + my ($self, $fname) = @_; + + my $ext = $fname; + if ($ext =~ m/\./) { + $ext =~ s/.*\.//; + } + else { + $ext = ''; + } + + return $ext; +} + + +sub get_variable { + my ($self, $name, $opts) = @_; + + $self->{$name} = $opts->{$name} // $ENV{$name}; + if (!defined($self->{$name}) || $self->{$name} eq '') { + my $fh; + unless (open($fh, '<', 'Makefile')) { + $self->die("cannot open Makefile: $!"); + } + while (my $line = <$fh>) { + chomp $line; + if ($line =~ m/^$name = (.*)/) { + $self->{$name} = $1; + last; + } + } + close ($fh); + } + if (!defined($self->{$name} || $self->{$name} eq '')) { + $self->die("cannot get variable $name"); + } +} + + +sub mangle_test_for_variant { + my ($self) = @_; + + $self->{test}->{stdout} = $self->strip_tags($self->{variant}, $self->{test}->{stdout}); + $self->{test}->{stderr} = $self->strip_tags($self->{variant}, $self->{test}->{stderr}); + $self->run_hook('mangle_test'); + + return 1; +} + +sub parse_args { + my ($self, $type, $str) = @_; + + if ($type eq 'string...') { + my $args = []; + + while ($str ne '') { + if ($str =~ m/^\"/) { + unless ($str =~ m/^\"([^\"]*)\"\s*(.*)/) { + $self->warn_file_line("unclosed quote in [$str]"); + return undef; + } + push @$args, $1; + $str = $2; + } + else { + $str =~ m/^(\S+)\s*(.*)/; + push @$args, $1; + $str = $2; + } + } + + return $args; + } + elsif ($type =~ m/(\s|\.\.\.$)/) { + my $ellipsis = 0; + if ($type =~ m/(.*)\.\.\.$/) { + $ellipsis = 1; + $type = $1; + } + my @types = split /\s+/, $type; + my @strs = split /\s+/, $str; + my $optional = 0; + for (my $i = scalar(@types) - 1; $i >= 0; $i--) { + last unless ($types[$i] =~ m/(.*)\?$/); + $types[$i] = $1; + $optional++; + } + + if ($ellipsis && $optional > 0) { + # TODO: check this when registering a directive + $self->warn_file_line("can't use ellipsis together with optional arguments"); + return undef; + } + if (!$ellipsis && (scalar(@strs) < scalar(@types) - $optional || scalar(@strs) > scalar(@types))) { + my $expected = scalar(@types); + if ($optional > 0) { + $expected = ($expected - $optional) . "-$expected"; + } + $self->warn_file_line("expected $expected arguments, got " . (scalar(@strs))); + return undef; + } + + my $args = []; + + my $n = scalar(@types); + for (my $i=0; $iparse_args(($i >= $n ? $types[$n-1] : $types[$i]), $strs[$i]); + return undef unless (defined($val)); + push @$args, $val; + } + + return $args; + } + else { + if ($type eq 'string') { + return $str; + } + elsif ($type eq 'int') { + if ($str !~ m/^\d+$/) { + $self->warn_file_line("illegal int [$str]"); + return undef; + } + return $str+0; + } + elsif ($type eq 'char') { + if ($str !~ m/^.$/) { + $self->warn_file_line("illegal char [$str]"); + return undef; + } + return $str; + } + else { + $self->warn_file_line("unknown type $type"); + return undef; + } + } +} + + +sub parse_case() { + my ($self, $fname) = @_; + + my $ok = 1; + + open TST, "< $fname" or $self->die("cannot open test case $fname: $!"); + + $self->{testcase_fname} = $fname; + + my %test = (); + + while (my $line = ) { + chomp $line; + + next if ($line =~ m/^\#/); + + unless ($line =~ m/(\S*)(?:\s(.*))?/) { + $self->warn_file_line("cannot parse line $line"); + $ok = 0; + next; + } + my ($cmd, $argstring) = ($1, $2//""); + + my $def = $self->{directives}->{$cmd}; + + unless ($def) { + $self->warn_file_line("unknown directive $cmd in test file"); + $ok = 0; + next; + } + + my $args = $self->parse_args($def->{type}, $argstring); + + unless (defined($args)) { + $ok = 0; + next; + } + + if ($def->{once}) { + if (defined($test{$cmd})) { + $self->warn_file_line("directive $cmd appeared twice in test file"); + } + $test{$cmd} = $args; + } + else { + $test{$cmd} = [] unless (defined($test{$cmd})); + push @{$test{$cmd}}, $args; + } + } + + close TST; + + return undef unless ($ok); + + for my $cmd (sort keys %test) { + if ($self->{directives}->{$cmd}->{required} && !defined($test{$cmd})) { + $self->warn_file("required directive $cmd missing in test file"); + $ok = 0; + } + } + + if ($test{pipefile} && $test{pipein}) { + $self->warn_file("both pipefile and pipein set, choose one"); + $ok = 0; + } + + if (defined($self->{variants})) { + if (defined($test{variants})) { + for my $name (@{$test{variants}}) { + my $found = 0; + for my $variant (@{$self->{variants}}) { + if ($name eq $variant->{name}) { + $found = 1; + last; + } + } + if ($found == 0) { + $self->warn_file("unknown variant $name"); + $ok = 0; + } + } + } + } + + return undef unless ($ok); + + if (defined($test{'stderr-replace'}) && defined($test{stderr})) { + $test{stderr} = [ map { $self->stderr_rewrite($test{'stderr-replace'}, $_); } @{$test{stderr}} ]; + } + + if (!defined($test{program})) { + $test{program} = $self->{default_program}; + } + + $self->{test} = \%test; + + $self->run_hook('mangle_program'); + + if (!$self->parse_postprocess_files()) { + return 0; + } + + return $self->run_hook('post_parse'); +} + + +sub parse_postprocess_files { + my ($self) = @_; + + $self->{files} = {}; + + my $ok = 1; + + for my $file (@{$self->{test}->{file}}) { + $ok = 0 unless ($self->add_file({ source => $file->[1], destination => $file->[0], result => $file->[2] })); + } + + for my $file (@{$self->{test}->{'file-del'}}) { + $ok = 0 unless ($self->add_file({ source => $file->[1], destination => $file->[0], result => undef })); + } + + for my $file (@{$self->{test}->{'file-new'}}) { + $ok = 0 unless ($self->add_file({ source => undef, destination => $file->[0], result => $file->[1] })); + } + + return $ok; +} + + +sub print_test_result { + my ($self, $tag, $result, $reason) = @_; + + if ($self->{verbose}) { + print "$self->{testname}"; + print " ($tag)" if ($tag); + print " -- $result"; + print ": $reason" if ($reason); + print "\n"; + } +} + + +sub run_comparator { + my ($self, $got, $expected) = @_; + + return $self->run_file_proc('compare_by_type', $got, $expected); +} + + +sub run_copier { + my ($self, $src, $dest) = @_; + + return $self->run_file_proc('copy_by_type', $src, $dest); +} + + +sub run_file_proc { + my ($self, $proc, $got, $expected) = @_; + + my $ext = ($self->get_extension($got)) . '/' . ($self->get_extension($expected)); + + if ($self->{variant}) { + if (defined($self->{$proc}->{"$self->{variant}/$ext"})) { + for my $sub (@{$self->{$proc}->{"$self->{variant}/$ext"}}) { + my $ret = $sub->($self, $got, $expected); + return $ret if (defined($ret)); + } + } + } + if (defined($self->{$proc}->{$ext})) { + for my $sub (@{$self->{$proc}->{$ext}}) { + my $ret = $sub->($self, $got, $expected); + return $ret if (defined($ret)); + } + } + + return undef; +} + + +sub run_hook { + my ($self, $hook) = @_; + + my $ok = 1; + + my @hooks = (); + + if (defined($self->{variant_hooks}) && defined($self->{variant_hooks}->{$hook})) { + push @hooks, $self->{variant_hooks}->{$hook}; + } + if (defined($self->{hooks}->{$hook})) { + push @hooks, @{$self->{hooks}->{$hook}}; + } + + for my $sub (@hooks) { + unless ($sub->($self, $hook, $self->{variant})) { + $self->warn("hook $hook failed"); + $ok = 0; + } + } + + return $ok; +} +sub args_decode { + + + my ($str, $srcdir) = @_; + + if ($str =~ m/\\/) { + $str =~ s/\\a/\a/gi; + $str =~ s/\\b/\b/gi; + $str =~ s/\\f/\f/gi; + $str =~ s/\\n/\n/gi; + $str =~ s/\\r/\r/gi; + $str =~ s/\\t/\t/gi; + $str =~ s/\\v/\cK/gi; + $str =~ s/\\s/ /gi; + # TODO: \xhh, \ooo + $str =~ s/\\(.)/$1/g; + } + + if ($srcdir !~ m,^/,) { + $srcdir = "../$srcdir"; + } + + if ($str =~ m/^\$srcdir(.*)/) { + $str = "$srcdir$1"; + } + + return $str; +} + + +sub run_precheck { + my ($self) = @_; + + for my $precheck (@{$self->{test}->{precheck}}) { + unless (system(@{$precheck}) == 0) { + $self->print_test_result('SKIP', "precheck failed"); + $self->end_test('SKIP'); + } + } + + return 1; +} + + +sub run_program { + my ($self) = @_; + goto &pipein_win32 if $^O eq 'MSWin32' && $self->{test}->{pipein}; + my ($stdin, $stdout, $stderr); + $stderr = gensym; + + my @cmd = ('../' . $self->{test}->{program}, map ({ args_decode($_, $self->{srcdir}); } @{$self->{test}->{args}})); + + ### TODO: catch errors? + + my $pid; + if ($self->{test}->{pipefile}) { + open(SPLAT, '<', $self->{test}->{pipefile}); + my $is_marked = eof SPLAT; # mark used + $pid = open3("<&SPLAT", $stdout, $stderr, @cmd); + } + else { + $pid = open3($stdin, $stdout, $stderr, @cmd); + } + $self->{stdout} = []; + $self->{stderr} = []; + + if ($self->{test}->{pipein}) { + my $fh; + open($fh, "$self->{test}->{pipein} |"); + if (!defined($fh)) { + $self->die("cannot run pipein command [$self->{test}->{pipein}: $!"); + } + while (my $line = <$fh>) { + print $stdin $line; + } + close($fh); + close($stdin); + } + + while (my $line = <$stdout>) { + if ($^O eq 'MSWin32') { + $line =~ s/[\r\n]+$//; + } + else { + chomp $line; + } + push @{$self->{stdout}}, $line; + } + my $prg = $self->{test}->{program}; + $prg =~ s,.*/,,; + while (my $line = <$stderr>) { + if ($^O eq 'MSWin32') { + $line =~ s/[\r\n]+$//; + } + else { + chomp $line; + } + + $line =~ s/^[^: ]*$prg: //; + if (defined($self->{test}->{'stderr-replace'})) { + $line = $self->stderr_rewrite($self->{test}->{'stderr-replace'}, $line); + } + push @{$self->{stderr}}, $line; + } + + waitpid($pid, 0); + + $self->{exit_status} = $? >> 8; +} + +sub pipein_win32() { + my ($self) = @_; + + my $cmd = "$self->{test}->{pipein}| ..\\$self->{test}->{program} " . join(' ', map ({ args_decode($_, $self->{srcdir}); } @{$self->{test}->{args}})); + my ($success, $error_message, $full_buf, $stdout_buf, $stderr_buf) = IPC::Cmd::run(command => $cmd); + if (!$success) { + ### TODO: catch errors? + } + + my @stdout = map { s/[\r\n]+$// } @$stdout_buf; + $self->{stdout} = \@stdout; + $self->{stderr} = []; + + my $prg = $self->{test}->{program}; + $prg =~ s,.*/,,; + foreach my $line (@$stderr_buf) { + $line =~ s/[\r\n]+$//; + + $line =~ s/^[^: ]*$prg: //; + if (defined($self->{test}->{'stderr-replace'})) { + $line = $self->stderr_rewrite($self->{test}->{'stderr-replace'}, $line); + } + push @{$self->{stderr}}, $line; + } + + $self->{exit_status} = 1; + if ($success) { + $self->{exit_status} = 0; + } + elsif ($error_message =~ /exited with value ([0-9]+)$/) { + $self->{exit_status} = $1 + 0; + } +} + +sub sandbox_create { + my ($self, $tag) = @_; + + $tag = ($tag ? "-$tag" : ""); + $self->{sandbox_dir} = "sandbox-$self->{testname}$tag.d$$"; + + $self->die("sandbox $self->{sandbox_dir} already exists") if (-e $self->{sandbox_dir}); + + mkdir($self->{sandbox_dir}) or $self->die("cannot create sandbox $self->{sandbox_dir}: $!"); + + return 1; +} + + +sub sandbox_enter { + my ($self) = @_; + + $self->die("internal error: cannot enter sandbox before creating it") unless (defined($self->{sandbox_dir})); + + return if ($self->{in_sandbox}); + + chdir($self->{sandbox_dir}) or $self->die("cannot cd into sandbox $self->{sandbox_dir}: $!"); + + $self->{in_sandbox} = 1; +} + + +sub sandbox_leave { + my ($self) = @_; + + return if (!$self->{in_sandbox}); + + chdir('..') or $self->die("cannot leave sandbox: $!"); + + $self->{in_sandbox} = 0; +} + + +sub sandbox_remove { + my ($self) = @_; + + my $ok = 1; + remove_tree($self->{sandbox_dir}); + + return $ok; +} + + +sub strip_tags { + my ($self, $tag, $lines) = @_; + + my @stripped = (); + + for my $line (@$lines) { + if ($line =~ m/^<([a-zA-Z0-9_]*)> (.*)/) { + if ($1 eq $tag) { + push @stripped, $2; + } + } + else { + push @stripped, $line; + } + } + + return \@stripped; +} + + +sub touch_files { + my ($self) = @_; + + my $ok = 1; + + if (defined($self->{test}->{touch})) { + for my $args (@{$self->{test}->{touch}}) { + my ($mtime, $fname) = @$args; + + if (!-f $fname) { + my $fh; + unless (open($fh, "> $fname") and close($fh)) { + # TODO: error message + $ok = 0; + next; + } + } + unless (utime($mtime, $mtime, $fname) == 1) { + # TODO: error message + $ok = 0; + } + } + } + + return $ok; +} + + +sub warn { + my ($self, $msg) = @_; + + print STDERR "$0: $msg\n"; +} + + +sub warn_file { + my ($self, $msg) = @_; + + $self->warn("$self->{testcase_fname}: $msg"); +} + + +sub warn_file_line { + my ($self, $msg) = @_; + + $self->warn("$self->{testcase_fname}:$.: $msg"); +} + +sub stderr_rewrite { + my ($self, $pattern, $line) = @_; + for my $repl (@{$pattern}) { + $line =~ s/$repl->[0]/$repl->[1]/; + } + return $line; +} + + +# MARK: array diff + +sub diff_arrays { + my ($a, $b) = @_; + + my ($i, $j); + for ($i = $j = 0; $i < scalar(@$a) || $j < scalar(@$b);) { + if ($i >= scalar(@$a)) { + print "+$b->[$j]\n"; + $j++; + } + elsif ($j >= scalar(@$b)) { + print "-$a->[$i]\n"; + $i++; + } + elsif ($a->[$i] eq $b->[$j]) { + print " $a->[$i]\n"; + $i++; + $j++; + } + else { + my ($off_a, $off_b) = find_best_offsets($a, $i, $b, $j); + my ($off_b_2, $off_a_2) = find_best_offsets($b, $j, $a, $i); + + if ($off_a + $off_b > $off_a_2 + $off_b_2) { + $off_a = $off_a_2; + $off_b = $off_b_2; + } + + for (my $off = 0; $off < $off_a; $off++) { + print "-$a->[$i]\n"; + $i++; + } + for (my $off = 0; $off < $off_b; $off++) { + print "+$b->[$j]\n"; + $j++; + } + } + } + +} + +sub find_best_offsets { + my ($a, $i, $b, $j) = @_; + + my ($best_a, $best_b); + + for (my $off_a = 0; $off_a < (defined($best_a) ? $best_a + $best_b : scalar(@$a) - $i); $off_a++) { + my $off_b = find_entry($a->[$i+$off_a], $b, $j, defined($best_a) ? $best_a + $best_b - $off_a : scalar(@$b) - $j); + + next unless (defined($off_b)); + + if (!defined($best_a) || $best_a + $best_b > $off_a + $off_b) { + $best_a = $off_a; + $best_b = $off_b; + } + } + + if (!defined($best_a)) { + return (scalar(@$a) - $i, scalar(@$b) - $j); + } + + return ($best_a, $best_b); +} + +sub find_entry { + my ($entry, $array, $start, $max_offset) = @_; + + for (my $offset = 0; $offset < $max_offset; $offset++) { + return $offset if ($array->[$start + $offset] eq $entry); + } + + return undef; +} + +1; diff --git a/third_party/libzip/regress/add_dir.test b/third_party/libzip/regress/add_dir.test new file mode 100644 index 0000000..b6a4d37 --- /dev/null +++ b/third_party/libzip/regress/add_dir.test @@ -0,0 +1,4 @@ +# add directories to zip +return 0 +args testdir.zip add_dir testdir/ add_dir testdir-noslash +file-new testdir.zip testdir.zip diff --git a/third_party/libzip/regress/add_from_buffer.test b/third_party/libzip/regress/add_from_buffer.test new file mode 100644 index 0000000..6963c58 --- /dev/null +++ b/third_party/libzip/regress/add_from_buffer.test @@ -0,0 +1,4 @@ +# add buffer contents as file to zip +return 0 +args testbuffer.zip add teststring.txt "This is a test, and it seems to have been successful.\n" +file-new testbuffer.zip testbuffer.zip diff --git a/third_party/libzip/regress/add_from_file.test b/third_party/libzip/regress/add_from_file.test new file mode 100644 index 0000000..4f97d27 --- /dev/null +++ b/third_party/libzip/regress/add_from_file.test @@ -0,0 +1,5 @@ +# add file to zip +return 0 +args -- testfile.zip add_file testfile.txt testfile.txt 0 -1 +file testfile.txt testfile.txt testfile.txt +file-new testfile.zip testfile.zip diff --git a/third_party/libzip/regress/add_from_file_duplicate.test b/third_party/libzip/regress/add_from_file_duplicate.test new file mode 100644 index 0000000..018b260 --- /dev/null +++ b/third_party/libzip/regress/add_from_file_duplicate.test @@ -0,0 +1,6 @@ +# add already existing file to zip, making duplicate names +return 1 +args -- testfile.zip add_file testfile.txt testfile.txt 0 -1 +file testfile.txt testfile.txt testfile.txt +file testfile.zip testfile.zip testfile.zip +stderr can't add file 'testfile.txt': File already exists diff --git a/third_party/libzip/regress/add_from_file_twice_duplicate.test b/third_party/libzip/regress/add_from_file_twice_duplicate.test new file mode 100644 index 0000000..511c90b --- /dev/null +++ b/third_party/libzip/regress/add_from_file_twice_duplicate.test @@ -0,0 +1,6 @@ +# add file to zip twice, making duplicate names +return 1 +args -- testfile.zip add_file testfile.txt testfile.txt 0 -1 add_file testfile.txt testfile.txt 0 -1 +file testfile.txt testfile.txt testfile.txt +file-new testfile.zip testfile.zip +stderr can't add file 'testfile.txt': File already exists diff --git a/third_party/libzip/regress/add_from_filep.c b/third_party/libzip/regress/add_from_filep.c new file mode 100644 index 0000000..d477580 --- /dev/null +++ b/third_party/libzip/regress/add_from_filep.c @@ -0,0 +1,97 @@ +/* + add_from_filep.c -- test case for adding file to archive + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include + +#include "zip.h" + +static const char *prg; + +int +main(int argc, char *argv[]) { + const char *archive; + const char *file; + const char *name; + zip_t *za; + zip_source_t *zs; + int err; + FILE *fp; + + prg = argv[0]; + + if (argc != 3) { + fprintf(stderr, "usage: %s archive file\n", prg); + return 1; + } + + archive = argv[1]; + file = argv[2]; + + if ((za = zip_open(archive, ZIP_CREATE, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "%s: can't open zip archive '%s': %s\n", prg, archive, zip_error_strerror(&error)); + zip_error_fini(&error); + return 1; + } + + if ((fp = fopen(file, "r")) == NULL) { + fprintf(stderr, "%s: can't open input file '%s': %s\n", prg, file, strerror(errno)); + return 1; + } + + if ((zs = zip_source_filep(za, fp, 0, -1)) == NULL) { + fprintf(stderr, "%s: error creating file source for '%s': %s\n", prg, file, zip_strerror(za)); + return 1; + } + + if ((name = strrchr(file, '/')) == NULL) + name = file; + + if (zip_add(za, name, zs) == -1) { + zip_source_free(zs); + fprintf(stderr, "%s: can't add file '%s': %s\n", prg, file, zip_strerror(za)); + return 1; + } + + if (zip_close(za) == -1) { + fprintf(stderr, "%s: can't close zip archive '%s': %s\n", prg, archive, zip_strerror(za)); + return 1; + } + + return 0; +} diff --git a/third_party/libzip/regress/add_from_filep.test b/third_party/libzip/regress/add_from_filep.test new file mode 100644 index 0000000..3a2a8cf --- /dev/null +++ b/third_party/libzip/regress/add_from_filep.test @@ -0,0 +1,6 @@ +# add file to zip +program add_from_filep +return 0 +args testfile.zip testfile.txt +file testfile.txt testfile.txt testfile.txt +file-new testfile.zip testfile.zip diff --git a/third_party/libzip/regress/add_from_stdin.test b/third_party/libzip/regress/add_from_stdin.test new file mode 100644 index 0000000..6736438 --- /dev/null +++ b/third_party/libzip/regress/add_from_stdin.test @@ -0,0 +1,5 @@ +# add stdin to zip +pipein echo This is a test, and it seems to have been successful. +args -- teststdin.zip add_file teststring.txt /dev/stdin 0 -1 +return 0 +file-new teststdin.zip teststdin.zip diff --git a/third_party/libzip/regress/add_from_zip_closed.test b/third_party/libzip/regress/add_from_zip_closed.test new file mode 100644 index 0000000..4c52e56 --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_closed.test @@ -0,0 +1,5 @@ +# add deflated file from zip to zip, but close the source before it can be read +return 1 +args -- testfile.zip add_from_zip abac-repeat.txt testdeflated.zzip 0 0 -1 zin_close 0 +file testdeflated.zzip testdeflated.zip testdeflated.zip +stderr can't close zip archive 'testfile.zip': Containing zip archive was closed diff --git a/third_party/libzip/regress/add_from_zip_deflated.test b/third_party/libzip/regress/add_from_zip_deflated.test new file mode 100644 index 0000000..ecff27d --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_deflated.test @@ -0,0 +1,5 @@ +# add deflated file from zip to zip +return 0 +args -- testfile.zip add_from_zip abac-repeat.txt testdeflated.zzip 0 0 -1 +file testdeflated.zzip testdeflated.zip testdeflated.zip +file-new testfile.zip testdeflated.zip diff --git a/third_party/libzip/regress/add_from_zip_deflated2.test b/third_party/libzip/regress/add_from_zip_deflated2.test new file mode 100644 index 0000000..ad7b4b6 --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_deflated2.test @@ -0,0 +1,5 @@ +# add deflated files from zip to zip +return 0 +args -- testfile.zip add_from_zip abac-repeat.txt testdeflated.zzip 0 0 -1 add_from_zip abac-repeat2.txt testdeflated.zzip 0 0 -1 +file testdeflated.zzip testdeflated.zip testdeflated.zip +file-new testfile.zip testdeflated2.zip diff --git a/third_party/libzip/regress/add_from_zip_partial_deflated.test b/third_party/libzip/regress/add_from_zip_partial_deflated.test new file mode 100644 index 0000000..69e95c6 --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_partial_deflated.test @@ -0,0 +1,5 @@ +# add parts of a file from zip to zip +return 0 +args -- testfile.zip add_from_zip first firstsecond.zzip 0 0 9 add_from_zip second firstsecond.zzip 0 9 -1 +file firstsecond.zzip firstsecond.zip firstsecond.zip +file-new testfile.zip firstsecond-split-stored.zip diff --git a/third_party/libzip/regress/add_from_zip_partial_stored.test b/third_party/libzip/regress/add_from_zip_partial_stored.test new file mode 100644 index 0000000..41ebf21 --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_partial_stored.test @@ -0,0 +1,5 @@ +# add parts of a file from zip to zip +return 0 +args -- testfile.zip add_from_zip first firstsecond.zzip 1 0 9 add_from_zip second firstsecond.zzip 1 9 -1 +file firstsecond.zzip firstsecond.zip firstsecond.zip +file-new testfile.zip firstsecond-split-stored.zip diff --git a/third_party/libzip/regress/add_from_zip_stored.test b/third_party/libzip/regress/add_from_zip_stored.test new file mode 100644 index 0000000..2fcbe80 --- /dev/null +++ b/third_party/libzip/regress/add_from_zip_stored.test @@ -0,0 +1,5 @@ +# add stored file from zip to zip +return 0 +args -- testfile.zip add_from_zip abac-repeat.txt teststored.zzip 0 0 -1 +file teststored.zzip teststored.zip teststored.zip +file-new testfile.zip testdeflated.zip diff --git a/third_party/libzip/regress/add_stored.test b/third_party/libzip/regress/add_stored.test new file mode 100644 index 0000000..ea96f25 --- /dev/null +++ b/third_party/libzip/regress/add_stored.test @@ -0,0 +1,4 @@ +# add file, set compression method to ZIP_CM_STORE +return 0 +args -n test.zip add foo foo set_file_compression 0 store 0 +file-new test.zip foo-stored.zip diff --git a/third_party/libzip/regress/add_stored_in_memory.test b/third_party/libzip/regress/add_stored_in_memory.test new file mode 100644 index 0000000..50467c6 --- /dev/null +++ b/third_party/libzip/regress/add_stored_in_memory.test @@ -0,0 +1,4 @@ +# add file, set compression method to ZIP_CM_STORE +return 0 +args -mn test.zip add foo foo set_file_compression 0 store 0 +file-new test.zip foo-stored.zip diff --git a/third_party/libzip/regress/bigstored.zh b/third_party/libzip/regress/bigstored.zh new file mode 100644 index 0000000..359a943 Binary files /dev/null and b/third_party/libzip/regress/bigstored.zh differ diff --git a/third_party/libzip/regress/bigzero-zip.zip b/third_party/libzip/regress/bigzero-zip.zip new file mode 100644 index 0000000..158cb6d Binary files /dev/null and b/third_party/libzip/regress/bigzero-zip.zip differ diff --git a/third_party/libzip/regress/bogus.zip b/third_party/libzip/regress/bogus.zip new file mode 100644 index 0000000..7e538b6 --- /dev/null +++ b/third_party/libzip/regress/bogus.zip @@ -0,0 +1 @@ +bogus data diff --git a/third_party/libzip/regress/broken.zip b/third_party/libzip/regress/broken.zip new file mode 100644 index 0000000..2008c32 Binary files /dev/null and b/third_party/libzip/regress/broken.zip differ diff --git a/third_party/libzip/regress/buffer-fragment-read.test b/third_party/libzip/regress/buffer-fragment-read.test new file mode 100644 index 0000000..1337560 --- /dev/null +++ b/third_party/libzip/regress/buffer-fragment-read.test @@ -0,0 +1,5 @@ +# test reading from a buffer fragment source +return 0 +args -mF 1024 test.zip cat 1 +file test.zip cm-default.zip cm-default.zip +stdout uncompressable diff --git a/third_party/libzip/regress/buffer-fragment-write.test b/third_party/libzip/regress/buffer-fragment-write.test new file mode 100644 index 0000000..f3ebc1e --- /dev/null +++ b/third_party/libzip/regress/buffer-fragment-write.test @@ -0,0 +1,4 @@ +# rename file inside zip archive +return 0 +args -mF 100 rename.zip rename 1 notfile2 +file rename.zip testcomment.zip rename_ok.zip diff --git a/third_party/libzip/regress/can_clone_file.c b/third_party/libzip/regress/can_clone_file.c new file mode 100644 index 0000000..401e576 --- /dev/null +++ b/third_party/libzip/regress/can_clone_file.c @@ -0,0 +1,124 @@ +/* + can_clone_file.c -- does the current filesystem support cloning + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include + +#include "config.h" + +#ifdef HAVE_CLONEFILE +#include +#include +#include +#include +#elif defined(HAVE_FICLONERANGE) +#include +#include +#include +#endif + +int +main(int argc, char *argv[]) { +#ifdef HAVE_CLONEFILE + struct statfs fs; + struct attrlist attribute_list; + struct { + uint32_t size; + vol_capabilities_attr_t capabilities; + } volume_attributes; + + if (statfs(".", &fs) < 0) { + fprintf(stderr, "%s: can't get mount point of current directory: %s\n", argv[0], strerror(errno)); + exit(1); + } + + /* Not all volumes support clonefile(). A volume can be tested for + clonefile() support by using getattrlist(2) to get the volume + capabilities attribute ATTR_VOL_CAPABILITIES, and then testing the + VOL_CAP_INT_CLONE flag. */ + + memset(&attribute_list, 0, sizeof(attribute_list)); + attribute_list.bitmapcount = ATTR_BIT_MAP_COUNT; + attribute_list.volattr = ATTR_VOL_INFO | ATTR_VOL_CAPABILITIES; + memset(&volume_attributes, 0, sizeof(volume_attributes)); + + if (getattrlist(fs.f_mntonname, &attribute_list, &volume_attributes, sizeof(volume_attributes), 0) < 0) { + fprintf(stderr, "%s: can't get volume capabilities of '%s': %s\n", argv[0], fs.f_mntonname, strerror(errno)); + exit(1); + } + + if (volume_attributes.capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_CLONE) { + exit(0); + } +#elif defined(HAVE_FICLONERANGE) + char namea[32] = "a.fioclone.XXXXXX"; + char nameb[32] = "b.fioclone.XXXXXX"; + int fda, fdb, ret; + struct file_clone_range range; + + if ((fda = mkstemp(namea)) < 0) { + fprintf(stderr, "can't create temp file a: %s\n", strerror(errno)); + exit(1); + } + if ((fdb = mkstemp(nameb)) < 0) { + fprintf(stderr, "can't create temp file b: %s\n", strerror(errno)); + (void)close(fda); + (void)remove(namea); + exit(1); + } + if (write(fda, "test\n", 5) < 0) { + fprintf(stderr, "can't write temp file a: %s\n", strerror(errno)); + (void)close(fda); + (void)remove(namea); + close(fdb); + (void)remove(nameb); + exit(1); + } + range.src_fd = fda; + range.src_offset = 0; + range.src_length = 0; + range.dest_offset = 0; + ret = ioctl(fdb, FICLONERANGE, &range); + (void)close(fda); + (void)close(fdb); + (void)remove(namea); + (void)remove(nameb); + if (ret >= 0) { + exit(0); + } +#endif + + exit(1); +} diff --git a/third_party/libzip/regress/cleanup.cmake b/third_party/libzip/regress/cleanup.cmake new file mode 100644 index 0000000..94fd13f --- /dev/null +++ b/third_party/libzip/regress/cleanup.cmake @@ -0,0 +1,7 @@ +# expect variable DIR +FILE(GLOB CLEANDIRS "${DIR}/sandbox-*.d[0-9]*") +IF (CLEANDIRS) + MESSAGE(STATUS "Removing ${CLEANDIRS}") + FILE(REMOVE_RECURSE ${CLEANDIRS}) +ENDIF() + diff --git a/third_party/libzip/regress/clone-buffer-add.test b/third_party/libzip/regress/clone-buffer-add.test new file mode 100644 index 0000000..c66791b --- /dev/null +++ b/third_party/libzip/regress/clone-buffer-add.test @@ -0,0 +1,4 @@ +# test cloning archive from buffer, add new file +return 0 +args -mF 100 test.zzip add new "A new file." set_file_mtime 3 1512998132 +file test.zzip gap.zip gap-add.zip diff --git a/third_party/libzip/regress/clone-buffer-delete.test b/third_party/libzip/regress/clone-buffer-delete.test new file mode 100644 index 0000000..221f8d2 --- /dev/null +++ b/third_party/libzip/regress/clone-buffer-delete.test @@ -0,0 +1,4 @@ +# test cloning archive from buffer, deleteing a file +return 0 +args -mF 100 test.zzip delete 2 +file test.zzip gap.zip gap-delete.zip diff --git a/third_party/libzip/regress/clone-buffer-replace.test b/third_party/libzip/regress/clone-buffer-replace.test new file mode 100644 index 0000000..cb21f33 --- /dev/null +++ b/third_party/libzip/regress/clone-buffer-replace.test @@ -0,0 +1,4 @@ +# test cloning archive from buffer, replacing a file +return 0 +args -mF 100 test.zzip replace_file_contents 2 "A changed file." set_file_mtime 2 1512998082 +file test.zzip gap.zip gap-replace.zip diff --git a/third_party/libzip/regress/clone-fs-add.test b/third_party/libzip/regress/clone-fs-add.test new file mode 100644 index 0000000..f187cb7 --- /dev/null +++ b/third_party/libzip/regress/clone-fs-add.test @@ -0,0 +1,5 @@ +# test cloning archive from filesystem, add new file +precheck ./can_clone_file +return 0 +args test.zzip add new "A new file." set_file_mtime 3 1512998132 +file test.zzip gap.zip gap-add.zip diff --git a/third_party/libzip/regress/clone-fs-delete.test b/third_party/libzip/regress/clone-fs-delete.test new file mode 100644 index 0000000..b2e63cc --- /dev/null +++ b/third_party/libzip/regress/clone-fs-delete.test @@ -0,0 +1,5 @@ +# test cloning archive from filesystem, deleteing a file +precheck ./can_clone_file +return 0 +args test.zzip delete 2 +file test.zzip gap.zip gap-delete.zip diff --git a/third_party/libzip/regress/clone-fs-replace.test b/third_party/libzip/regress/clone-fs-replace.test new file mode 100644 index 0000000..3d3b8f3 --- /dev/null +++ b/third_party/libzip/regress/clone-fs-replace.test @@ -0,0 +1,5 @@ +# test cloning archive from filesystem, replacing a file +precheck ./can_clone_file +return 0 +args test.zzip replace_file_contents 2 "A changed file." set_file_mtime 2 1512998082 +file test.zzip gap.zip gap-replace.zip diff --git a/third_party/libzip/regress/cm-default.test b/third_party/libzip/regress/cm-default.test new file mode 100644 index 0000000..03e7200 --- /dev/null +++ b/third_party/libzip/regress/cm-default.test @@ -0,0 +1,5 @@ +# test default compression stores if smaller +return 0 +args -n test.zip add compressable aaaaaaaaaaaaaa add uncompressable uncompressable add_nul large-compressable 8200 add_file large-uncompressable large-uncompressable 0 -1 +file-new test.zip cm-default.zip +file large-uncompressable large-uncompressable large-uncompressable diff --git a/third_party/libzip/regress/cm-default.zip b/third_party/libzip/regress/cm-default.zip new file mode 100644 index 0000000..3eba2a3 Binary files /dev/null and b/third_party/libzip/regress/cm-default.zip differ diff --git a/third_party/libzip/regress/count_entries.test b/third_party/libzip/regress/count_entries.test new file mode 100644 index 0000000..564acdc --- /dev/null +++ b/third_party/libzip/regress/count_entries.test @@ -0,0 +1,5 @@ +# zip_open: count entries for archive with >65k entries +args manyfiles.zip get_num_entries 0 +return 0 +file manyfiles.zip manyfiles.zip manyfiles.zip +stdout 70000 entries in archive diff --git a/third_party/libzip/regress/decrypt-correct-password-aes128.test b/third_party/libzip/regress/decrypt-correct-password-aes128.test new file mode 100644 index 0000000..470ba30 --- /dev/null +++ b/third_party/libzip/regress/decrypt-correct-password-aes128.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using correct password +features CRYPTO +return 0 +args encrypt.zzip set_password foofoofoo cat 1 +file encrypt.zzip encrypt-aes128.zip encrypt-aes128.zip +stdout encrypted diff --git a/third_party/libzip/regress/decrypt-correct-password-aes192.test b/third_party/libzip/regress/decrypt-correct-password-aes192.test new file mode 100644 index 0000000..a66dd16 --- /dev/null +++ b/third_party/libzip/regress/decrypt-correct-password-aes192.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using correct password +features CRYPTO +return 0 +args encrypt.zzip set_password foofoofoo cat 1 +file encrypt.zzip encrypt-aes192.zip encrypt-aes192.zip +stdout encrypted diff --git a/third_party/libzip/regress/decrypt-correct-password-aes256.test b/third_party/libzip/regress/decrypt-correct-password-aes256.test new file mode 100644 index 0000000..4eddea8 --- /dev/null +++ b/third_party/libzip/regress/decrypt-correct-password-aes256.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using correct password +features CRYPTO +return 0 +args encrypt.zzip set_password foofoofoo cat 1 +file encrypt.zzip encrypt-aes256.zip encrypt-aes256.zip +stdout encrypted diff --git a/third_party/libzip/regress/decrypt-correct-password-pkware.test b/third_party/libzip/regress/decrypt-correct-password-pkware.test new file mode 100644 index 0000000..c126394 --- /dev/null +++ b/third_party/libzip/regress/decrypt-correct-password-pkware.test @@ -0,0 +1,5 @@ +# test decryption support, extract file using correct password +return 0 +args encrypt.zzip set_password foo cat 0 +file encrypt.zzip encrypt.zip encrypt.zip +stdout foo diff --git a/third_party/libzip/regress/decrypt-no-password-aes256.test b/third_party/libzip/regress/decrypt-no-password-aes256.test new file mode 100644 index 0000000..6140a42 --- /dev/null +++ b/third_party/libzip/regress/decrypt-no-password-aes256.test @@ -0,0 +1,6 @@ +# test AES decryption support, no password provided +features CRYPTO +return 1 +args encrypt.zzip cat 1 +file encrypt.zzip encrypt-aes256.zip encrypt-aes256.zip +stderr can't open file at index '1': No password provided diff --git a/third_party/libzip/regress/decrypt-wrong-password-aes128.test b/third_party/libzip/regress/decrypt-wrong-password-aes128.test new file mode 100644 index 0000000..fa4b789 --- /dev/null +++ b/third_party/libzip/regress/decrypt-wrong-password-aes128.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using wrong password +features CRYPTO +return 1 +args encrypt.zzip set_password notfoonotfoo cat 1 +file encrypt.zzip encrypt-aes128.zip encrypt-aes128.zip +stderr can't open file at index '1': Wrong password provided diff --git a/third_party/libzip/regress/decrypt-wrong-password-aes192.test b/third_party/libzip/regress/decrypt-wrong-password-aes192.test new file mode 100644 index 0000000..f04d0da --- /dev/null +++ b/third_party/libzip/regress/decrypt-wrong-password-aes192.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using wrong password +features CRYPTO +return 1 +args encrypt.zzip set_password notfoonotfoo cat 1 +file encrypt.zzip encrypt-aes192.zip encrypt-aes192.zip +stderr can't open file at index '1': Wrong password provided diff --git a/third_party/libzip/regress/decrypt-wrong-password-aes256.test b/third_party/libzip/regress/decrypt-wrong-password-aes256.test new file mode 100644 index 0000000..836b5b1 --- /dev/null +++ b/third_party/libzip/regress/decrypt-wrong-password-aes256.test @@ -0,0 +1,6 @@ +# test AES decryption support, extract file using wrong password +features CRYPTO +return 1 +args encrypt.zzip set_password notfoonotfoo cat 1 +file encrypt.zzip encrypt-aes256.zip encrypt-aes256.zip +stderr can't open file at index '1': Wrong password provided diff --git a/third_party/libzip/regress/decrypt-wrong-password-pkware.test b/third_party/libzip/regress/decrypt-wrong-password-pkware.test new file mode 100644 index 0000000..0274955 --- /dev/null +++ b/third_party/libzip/regress/decrypt-wrong-password-pkware.test @@ -0,0 +1,5 @@ +# test decryption support, extract file using wrong password +return 1 +args encrypt.zzip set_password notfoo cat 0 +file encrypt.zzip encrypt.zip encrypt.zip +stderr can't open file at index '0': Wrong password provided diff --git a/third_party/libzip/regress/delete_add_same.test b/third_party/libzip/regress/delete_add_same.test new file mode 100644 index 0000000..54c0e5a --- /dev/null +++ b/third_party/libzip/regress/delete_add_same.test @@ -0,0 +1,5 @@ +# delete entry in zip archive then add file of same name +# time is now(), so use zipcmp +return 0 +args testfile.zip delete 0 add testfile.txt test +file testfile.zip testfile.zip test2.zip diff --git a/third_party/libzip/regress/delete_invalid.test b/third_party/libzip/regress/delete_invalid.test new file mode 100644 index 0000000..9a06306 --- /dev/null +++ b/third_party/libzip/regress/delete_invalid.test @@ -0,0 +1,5 @@ +# delete last entry in zip archive +return 1 +args testfile.zzip delete 5 +file testfile.zzip testfile.zip testfile.zip +stderr can't delete file at index '5': Invalid argument diff --git a/third_party/libzip/regress/delete_last.test b/third_party/libzip/regress/delete_last.test new file mode 100644 index 0000000..3b415b5 --- /dev/null +++ b/third_party/libzip/regress/delete_last.test @@ -0,0 +1,4 @@ +# delete last entry in zip archive +return 0 +args testfile.zzip delete 0 +file-del testfile.zzip testfile.zip diff --git a/third_party/libzip/regress/delete_multiple_last.test b/third_party/libzip/regress/delete_multiple_last.test new file mode 100644 index 0000000..71ac983 --- /dev/null +++ b/third_party/libzip/regress/delete_multiple_last.test @@ -0,0 +1,4 @@ +# delete multiple entries in zip archive, emptying it +return 0 +args testfile.zzip delete 0 delete 1 delete 2 delete 3 +file-del testfile.zzip testcomment.zip diff --git a/third_party/libzip/regress/delete_multiple_partial.test b/third_party/libzip/regress/delete_multiple_partial.test new file mode 100644 index 0000000..272fab3 --- /dev/null +++ b/third_party/libzip/regress/delete_multiple_partial.test @@ -0,0 +1,4 @@ +# delete some entries in zip archive +return 0 +args testfile.zip delete 1 delete 3 +file testfile.zip testcomment.zip testcomment13.zip diff --git a/third_party/libzip/regress/delete_renamed_rename.test b/third_party/libzip/regress/delete_renamed_rename.test new file mode 100644 index 0000000..e81996c --- /dev/null +++ b/third_party/libzip/regress/delete_renamed_rename.test @@ -0,0 +1,5 @@ +# delete renamed entry in zip archive then rename file to same name +# file date is now(), so use zipcmp +return 0 +args testfile.zip rename 0 something add test test delete 0 rename 1 testfile.txt +file testfile.zip testfile.zip test2.zip diff --git a/third_party/libzip/regress/encrypt-aes128-noentropy.zip b/third_party/libzip/regress/encrypt-aes128-noentropy.zip new file mode 100644 index 0000000..c588fc9 Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes128-noentropy.zip differ diff --git a/third_party/libzip/regress/encrypt-aes128.zip b/third_party/libzip/regress/encrypt-aes128.zip new file mode 100644 index 0000000..e48c3c9 Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes128.zip differ diff --git a/third_party/libzip/regress/encrypt-aes192-noentropy.zip b/third_party/libzip/regress/encrypt-aes192-noentropy.zip new file mode 100644 index 0000000..59605a0 Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes192-noentropy.zip differ diff --git a/third_party/libzip/regress/encrypt-aes192.zip b/third_party/libzip/regress/encrypt-aes192.zip new file mode 100644 index 0000000..98865ce Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes192.zip differ diff --git a/third_party/libzip/regress/encrypt-aes256-noentropy.zip b/third_party/libzip/regress/encrypt-aes256-noentropy.zip new file mode 100644 index 0000000..742ada6 Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes256-noentropy.zip differ diff --git a/third_party/libzip/regress/encrypt-aes256.zip b/third_party/libzip/regress/encrypt-aes256.zip new file mode 100644 index 0000000..6349cb2 Binary files /dev/null and b/third_party/libzip/regress/encrypt-aes256.zip differ diff --git a/third_party/libzip/regress/encrypt-none.zip b/third_party/libzip/regress/encrypt-none.zip new file mode 100644 index 0000000..0a2f770 Binary files /dev/null and b/third_party/libzip/regress/encrypt-none.zip differ diff --git a/third_party/libzip/regress/encrypt.test b/third_party/libzip/regress/encrypt.test new file mode 100644 index 0000000..f9aad43 --- /dev/null +++ b/third_party/libzip/regress/encrypt.test @@ -0,0 +1,23 @@ +# test encryption support +# TODO: only checks recognition of encrypted entries for now. +return 0 +args encrypt.zzip stat 0 stat 1 +file encrypt.zzip encrypt.zip encrypt.zip +stdout name: 'encrypted' +stdout index: '0' +stdout size: '4' +stdout compressed size: '16' +stdout mtime: 'Mon Apr 24 2006 16:01:34' +stdout crc: '7e3265a8' +stdout compression method: '0' +stdout encryption method: '1' +stdout +stdout name: 'plain' +stdout index: '1' +stdout size: '4' +stdout compressed size: '4' +stdout mtime: 'Mon Apr 24 2006 16:01:42' +stdout crc: '7e3265a8' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/encrypt.zip b/third_party/libzip/regress/encrypt.zip new file mode 100644 index 0000000..e50aa38 Binary files /dev/null and b/third_party/libzip/regress/encrypt.zip differ diff --git a/third_party/libzip/regress/encrypt_plus_extra.zip b/third_party/libzip/regress/encrypt_plus_extra.zip new file mode 100644 index 0000000..4a26309 Binary files /dev/null and b/third_party/libzip/regress/encrypt_plus_extra.zip differ diff --git a/third_party/libzip/regress/encrypt_plus_extra_modified_c.zip b/third_party/libzip/regress/encrypt_plus_extra_modified_c.zip new file mode 100644 index 0000000..f50d649 Binary files /dev/null and b/third_party/libzip/regress/encrypt_plus_extra_modified_c.zip differ diff --git a/third_party/libzip/regress/encrypt_plus_extra_modified_l.zip b/third_party/libzip/regress/encrypt_plus_extra_modified_l.zip new file mode 100644 index 0000000..a546022 Binary files /dev/null and b/third_party/libzip/regress/encrypt_plus_extra_modified_l.zip differ diff --git a/third_party/libzip/regress/encryption-nonrandom-aes128.test b/third_party/libzip/regress/encryption-nonrandom-aes128.test new file mode 100644 index 0000000..fa21efe --- /dev/null +++ b/third_party/libzip/regress/encryption-nonrandom-aes128.test @@ -0,0 +1,6 @@ +features CRYPTO +description encrypt file without entropy, to make results repeatable +return 0 +preload nonrandomopen.so +args encrypt.zzip set_file_encryption 1 AES-128 no-entropy +file encrypt.zzip encrypt-none.zip encrypt-aes128-noentropy.zip diff --git a/third_party/libzip/regress/encryption-nonrandom-aes192.test b/third_party/libzip/regress/encryption-nonrandom-aes192.test new file mode 100644 index 0000000..bd0ebc4 --- /dev/null +++ b/third_party/libzip/regress/encryption-nonrandom-aes192.test @@ -0,0 +1,6 @@ +features CRYPTO +description encrypt file without entropy, to make results repeatable +return 0 +preload nonrandomopen.so +args encrypt.zzip set_file_encryption 1 AES-192 no-entropy +file encrypt.zzip encrypt-none.zip encrypt-aes192-noentropy.zip diff --git a/third_party/libzip/regress/encryption-nonrandom-aes256.test b/third_party/libzip/regress/encryption-nonrandom-aes256.test new file mode 100644 index 0000000..ee6be9f --- /dev/null +++ b/third_party/libzip/regress/encryption-nonrandom-aes256.test @@ -0,0 +1,6 @@ +features CRYPTO +description encrypt file without entropy, to make results repeatable +return 0 +preload nonrandomopen.so +args encrypt.zzip set_file_encryption 1 AES-256 no-entropy +file encrypt.zzip encrypt-none.zip encrypt-aes256-noentropy.zip diff --git a/third_party/libzip/regress/encryption-remove.test b/third_party/libzip/regress/encryption-remove.test new file mode 100644 index 0000000..2079100 --- /dev/null +++ b/third_party/libzip/regress/encryption-remove.test @@ -0,0 +1,5 @@ +# test AES decryption support, remove encryption from file that has it +features CRYPTO +return 0 +args encrypt.zzip set_password foofoofoo set_file_encryption 1 none "" +file encrypt.zzip encrypt-aes128.zip encrypt-none.zip diff --git a/third_party/libzip/regress/extra_add.test b/third_party/libzip/regress/extra_add.test new file mode 100644 index 0000000..c2020f1 --- /dev/null +++ b/third_party/libzip/regress/extra_add.test @@ -0,0 +1,7 @@ +# add extra field +#args encrypt.zip set_extra 0 2345 65535 cl extrafieldcontent +args encrypt.zip set_extra 0 2345 65535 cl extrafieldcontent get_extra_by_id 0 2345 0 c get_extra_by_id 0 2345 0 l +return 0 +file encrypt.zip encrypt.zip encrypt_plus_extra.zip +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 diff --git a/third_party/libzip/regress/extra_add_multiple.test b/third_party/libzip/regress/extra_add_multiple.test new file mode 100644 index 0000000..2623755 --- /dev/null +++ b/third_party/libzip/regress/extra_add_multiple.test @@ -0,0 +1,8 @@ +# add extra fields +args testfile.zip set_extra 0 2345 65535 cl extra1 set_extra 0 2345 65535 cl extra2 set_extra 0 2345 0 c extra1c set_extra 0 2345 1 l extra2l get_extra_by_id 0 2345 0 c get_extra_by_id 0 2345 1 c get_extra_by_id 0 2345 0 l get_extra_by_id 0 2345 1 l +return 0 +file testfile.zip testfile.zip testfile-plus-extra.zip +stdout Extra field 0x0929: len 7, data 0x65787472613163 +stdout Extra field 0x0929: len 6, data 0x657874726132 +stdout Extra field 0x0929: len 6, data 0x657874726131 +stdout Extra field 0x0929: len 7, data 0x6578747261326c diff --git a/third_party/libzip/regress/extra_count.test b/third_party/libzip/regress/extra_count.test new file mode 100644 index 0000000..7d80e02 --- /dev/null +++ b/third_party/libzip/regress/extra_count.test @@ -0,0 +1,10 @@ +# count extra fields for index +args encrypt.zip count_extra 0 l count_extra 0 c count_extra 0 lc count_extra 1 l count_extra 1 c count_extra 1 lc +return 0 +file encrypt.zip encrypt.zip encrypt.zip +stdout Extra field count: 2 +stdout Extra field count: 2 +stdout Extra field count: 4 +stdout Extra field count: 2 +stdout Extra field count: 2 +stdout Extra field count: 4 diff --git a/third_party/libzip/regress/extra_count_by_id.test b/third_party/libzip/regress/extra_count_by_id.test new file mode 100644 index 0000000..5029935 --- /dev/null +++ b/third_party/libzip/regress/extra_count_by_id.test @@ -0,0 +1,22 @@ +# count extra fields for index +args encrypt.zip count_extra_by_id 0 0 l count_extra_by_id 0 1 l count_extra_by_id 0 21589 l count_extra_by_id 0 30805 l count_extra_by_id 0 21844 l count_extra_by_id 0 12345 l count_extra_by_id 0 0 c count_extra_by_id 0 1 c count_extra_by_id 0 21589 c count_extra_by_id 0 30805 c count_extra_by_id 0 21844 c count_extra_by_id 0 12345 c count_extra_by_id 0 0 cl count_extra_by_id 0 1 cl count_extra_by_id 0 21589 cl count_extra_by_id 0 30805 cl count_extra_by_id 0 21844 cl count_extra_by_id 0 12345 cl +return 0 +file encrypt.zip encrypt.zip encrypt.zip +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 1 +stdout Extra field count: 1 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 1 +stdout Extra field count: 1 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 2 +stdout Extra field count: 2 +stdout Extra field count: 0 +stdout Extra field count: 0 diff --git a/third_party/libzip/regress/extra_count_ignore_zip64.test b/third_party/libzip/regress/extra_count_ignore_zip64.test new file mode 100644 index 0000000..1766997 --- /dev/null +++ b/third_party/libzip/regress/extra_count_ignore_zip64.test @@ -0,0 +1,7 @@ +# count extra fields for index +args bigzero.zip count_extra 0 l count_extra 0 c count_extra 0 lc +return 0 +file bigzero.zip bigzero.zip bigzero.zip +stdout Extra field count: 0 +stdout Extra field count: 0 +stdout Extra field count: 0 diff --git a/third_party/libzip/regress/extra_delete.test b/third_party/libzip/regress/extra_delete.test new file mode 100644 index 0000000..9bccc90 --- /dev/null +++ b/third_party/libzip/regress/extra_delete.test @@ -0,0 +1,14 @@ +# delete extra field by index +args encrypt.zip get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l delete_extra 0 2 c delete_extra 0 0 l get_extra 0 0 c get_extra 0 1 c get_extra 0 0 l get_extra 0 1 l +file encrypt.zip encrypt_plus_extra.zip encrypt.zip +return 0 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 diff --git a/third_party/libzip/regress/extra_delete_by_id.test b/third_party/libzip/regress/extra_delete_by_id.test new file mode 100644 index 0000000..4c8fa00 --- /dev/null +++ b/third_party/libzip/regress/extra_delete_by_id.test @@ -0,0 +1,6 @@ +# delete extra field by id and index +#args encrypt.zip set_extra 0 2345 65535 cl extrafieldcontent +args encrypt.zip delete_extra_by_id 0 2345 0 c delete_extra_by_id 0 2345 0 l get_extra_by_id 0 2345 0 c +return 1 +file encrypt.zip encrypt_plus_extra.zip encrypt.zip +stderr can't get extra field data for file at index 0, extra field id 2345, ef index 0, flags 512: No such file diff --git a/third_party/libzip/regress/extra_field_align.test b/third_party/libzip/regress/extra_field_align.test new file mode 100644 index 0000000..fe42977 --- /dev/null +++ b/third_party/libzip/regress/extra_field_align.test @@ -0,0 +1,32 @@ +# try opening simulated Android APK zipaligned files, and similar inconsistent files +setenv LANG C +program tryopen +file extra_field_align_1-0.zzip extra_field_align_1-0.zip extra_field_align_1-0.zip +file extra_field_align_1-ff.zzip extra_field_align_1-ff.zip extra_field_align_1-ff.zip +file extra_field_align_2-0.zzip extra_field_align_2-0.zip extra_field_align_2-0.zip +file extra_field_align_2-ff.zzip extra_field_align_2-ff.zip extra_field_align_2-ff.zip +file extra_field_align_3-0.zzip extra_field_align_3-0.zip extra_field_align_3-0.zip +file extra_field_align_3-ff.zzip extra_field_align_3-ff.zip extra_field_align_3-ff.zip +file extra_field_align_4-ff.zzip extra_field_align_4-ff.zip extra_field_align_4-ff.zip +file extra_field_align_1-ef_00.zzip extra_field_align_1-ef_00.zip extra_field_align_1-ef_00.zip +file extra_field_align_1-ef_ff.zzip extra_field_align_1-ef_ff.zip extra_field_align_1-ef_ff.zip +file extra_field_align_2-ef_00.zzip extra_field_align_2-ef_00.zip extra_field_align_2-ef_00.zip +file extra_field_align_2-ef_ff.zzip extra_field_align_2-ef_ff.zip extra_field_align_2-ef_ff.zip +file extra_field_align_3-ef_00.zzip extra_field_align_3-ef_00.zip extra_field_align_3-ef_00.zip +file extra_field_align_3-ef_ff.zzip extra_field_align_3-ef_ff.zip extra_field_align_3-ef_ff.zip +args -c extra_field_align_1-0.zzip extra_field_align_1-ff.zzip extra_field_align_2-0.zzip extra_field_align_2-ff.zzip extra_field_align_3-0.zzip extra_field_align_3-ff.zzip extra_field_align_4-ff.zzip extra_field_align_1-ef_00.zzip extra_field_align_1-ef_ff.zzip extra_field_align_2-ef_00.zzip extra_field_align_2-ef_ff.zzip extra_field_align_3-ef_00.zzip extra_field_align_3-ef_ff.zzip +return 1 +stdout opening 'extra_field_align_1-0.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_1-ff.zzip' returned error 21 +stdout opening 'extra_field_align_2-0.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_2-ff.zzip' returned error 21 +stdout opening 'extra_field_align_3-0.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_3-ff.zzip' returned error 21 +stdout opening 'extra_field_align_4-ff.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_1-ef_00.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_1-ef_ff.zzip' returned error 21 +stdout opening 'extra_field_align_2-ef_00.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_2-ef_ff.zzip' returned error 21 +stdout opening 'extra_field_align_3-ef_00.zzip' succeeded, 1 entries +stdout opening 'extra_field_align_3-ef_ff.zzip' returned error 21 +stderr 6 errors diff --git a/third_party/libzip/regress/extra_field_align_1-0.zip b/third_party/libzip/regress/extra_field_align_1-0.zip new file mode 100644 index 0000000..11aaaac Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_1-0.zip differ diff --git a/third_party/libzip/regress/extra_field_align_1-ef_00.zip b/third_party/libzip/regress/extra_field_align_1-ef_00.zip new file mode 100644 index 0000000..c07777b Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_1-ef_00.zip differ diff --git a/third_party/libzip/regress/extra_field_align_1-ef_ff.zip b/third_party/libzip/regress/extra_field_align_1-ef_ff.zip new file mode 100644 index 0000000..d62e0ec Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_1-ef_ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_1-ff.zip b/third_party/libzip/regress/extra_field_align_1-ff.zip new file mode 100644 index 0000000..6b05df2 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_1-ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_2-0.zip b/third_party/libzip/regress/extra_field_align_2-0.zip new file mode 100644 index 0000000..c7072d2 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_2-0.zip differ diff --git a/third_party/libzip/regress/extra_field_align_2-ef_00.zip b/third_party/libzip/regress/extra_field_align_2-ef_00.zip new file mode 100644 index 0000000..68e4089 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_2-ef_00.zip differ diff --git a/third_party/libzip/regress/extra_field_align_2-ef_ff.zip b/third_party/libzip/regress/extra_field_align_2-ef_ff.zip new file mode 100644 index 0000000..be9510b Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_2-ef_ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_2-ff.zip b/third_party/libzip/regress/extra_field_align_2-ff.zip new file mode 100644 index 0000000..7bf88a0 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_2-ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_3-0.zip b/third_party/libzip/regress/extra_field_align_3-0.zip new file mode 100644 index 0000000..401e7b0 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_3-0.zip differ diff --git a/third_party/libzip/regress/extra_field_align_3-ef_00.zip b/third_party/libzip/regress/extra_field_align_3-ef_00.zip new file mode 100644 index 0000000..326f98d Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_3-ef_00.zip differ diff --git a/third_party/libzip/regress/extra_field_align_3-ef_ff.zip b/third_party/libzip/regress/extra_field_align_3-ef_ff.zip new file mode 100644 index 0000000..ab9d81f Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_3-ef_ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_3-ff.zip b/third_party/libzip/regress/extra_field_align_3-ff.zip new file mode 100644 index 0000000..c6fde73 Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_3-ff.zip differ diff --git a/third_party/libzip/regress/extra_field_align_4-ff.zip b/third_party/libzip/regress/extra_field_align_4-ff.zip new file mode 100644 index 0000000..c23966f Binary files /dev/null and b/third_party/libzip/regress/extra_field_align_4-ff.zip differ diff --git a/third_party/libzip/regress/extra_get.test b/third_party/libzip/regress/extra_get.test new file mode 100644 index 0000000..4f45887 --- /dev/null +++ b/third_party/libzip/regress/extra_get.test @@ -0,0 +1,9 @@ +# get extra fields for index +args encrypt.zip get_extra 0 0 l get_extra 0 0 c get_extra 0 1 l get_extra 0 1 c get_extra 0 2 l +return 1 +file encrypt.zip encrypt.zip encrypt.zip +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x7855: len 0 +stderr can't get extra field data for file at index 0, extra field 2, flags 256: No such file diff --git a/third_party/libzip/regress/extra_get_by_id.test b/third_party/libzip/regress/extra_get_by_id.test new file mode 100644 index 0000000..67f4967 --- /dev/null +++ b/third_party/libzip/regress/extra_get_by_id.test @@ -0,0 +1,9 @@ +# get extra_by_id fields for index +args encrypt.zip get_extra_by_id 0 21589 0 l get_extra_by_id 0 30805 0 l get_extra_by_id 0 21589 0 c get_extra_by_id 0 30805 0 c get_extra_by_id 0 21544 0 c +return 1 +file encrypt.zip encrypt.zip encrypt.zip +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stderr can't get extra field data for file at index 0, extra field id 21544, ef index 0, flags 512: No such file diff --git a/third_party/libzip/regress/extra_set.test b/third_party/libzip/regress/extra_set.test new file mode 100644 index 0000000..ccdbdc9 --- /dev/null +++ b/third_party/libzip/regress/extra_set.test @@ -0,0 +1,14 @@ +# set extra field +args -- encrypt get_extra 0 0 c get_extra 0 1 c get_extra 0 0 l get_extra 0 1 l set_extra 0 2345 -1 l extrafieldcontent set_extra 0 2345 -1 c extrafieldcontent get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l +file encrypt encrypt.zip encrypt_plus_extra.zip +return 0 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 diff --git a/third_party/libzip/regress/extra_set_modify_c.test b/third_party/libzip/regress/extra_set_modify_c.test new file mode 100644 index 0000000..dca49f4 --- /dev/null +++ b/third_party/libzip/regress/extra_set_modify_c.test @@ -0,0 +1,16 @@ +# change existing central extra field +args encrypt.zip get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l set_extra 0 2345 0 c Extrafieldcontent get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l +file encrypt.zip encrypt_plus_extra.zip encrypt_plus_extra_modified_c.zip +return 0 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x45787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 diff --git a/third_party/libzip/regress/extra_set_modify_l.test b/third_party/libzip/regress/extra_set_modify_l.test new file mode 100644 index 0000000..4dda9b7 --- /dev/null +++ b/third_party/libzip/regress/extra_set_modify_l.test @@ -0,0 +1,16 @@ +# change existing local extra field +args encrypt.zip get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l set_extra 0 2345 0 l Extrafieldcontent get_extra 0 0 c get_extra 0 1 c get_extra 0 2 c get_extra 0 0 l get_extra 0 1 l get_extra 0 2 l +file encrypt.zip encrypt_plus_extra.zip encrypt_plus_extra_modified_l.zip +return 0 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 +stdout Extra field 0x5455: len 5, data 0x033dda4c44 +stdout Extra field 0x7855: len 0 +stdout Extra field 0x0929: len 17, data 0x65787472616669656c64636f6e74656e74 +stdout Extra field 0x0929: len 17, data 0x45787472616669656c64636f6e74656e74 +stdout Extra field 0x5455: len 9, data 0x033dda4c444dda4c44 +stdout Extra field 0x7855: len 4, data 0x64001400 diff --git a/third_party/libzip/regress/fdopen_ok.test b/third_party/libzip/regress/fdopen_ok.test new file mode 100644 index 0000000..192419c --- /dev/null +++ b/third_party/libzip/regress/fdopen_ok.test @@ -0,0 +1,15 @@ +# zip_fdopen: stdin opens fine +program ../src/ziptool +args /dev/stdin stat 0 +pipefile test.zip +return 0 +file test.zip test.zip test.zip +stdout name: 'test' +stdout index: '0' +stdout size: '5' +stdout compressed size: '5' +stdout mtime: 'Mon Oct 06 2003 15:46:42' +stdout crc: '3bb935c6' +stdout compression method: '0' +stdout encryption method: '0' +stdout \ No newline at end of file diff --git a/third_party/libzip/regress/file_comment_encmismatch.test b/third_party/libzip/regress/file_comment_encmismatch.test new file mode 100644 index 0000000..a2b8209 --- /dev/null +++ b/third_party/libzip/regress/file_comment_encmismatch.test @@ -0,0 +1,4 @@ +# set file comment to UTF-8 for CP437 encoded filename (adds InfoZIP extra field) +return 0 +args testfile.zip set_file_comment 0 ÄÖÜßäöü +file testfile.zip test-cp437.zip test-cp437-comment-utf-8.zip diff --git a/third_party/libzip/regress/filename_duplicate.zip b/third_party/libzip/regress/filename_duplicate.zip new file mode 100644 index 0000000..96a11e7 Binary files /dev/null and b/third_party/libzip/regress/filename_duplicate.zip differ diff --git a/third_party/libzip/regress/filename_duplicate_empty.zip b/third_party/libzip/regress/filename_duplicate_empty.zip new file mode 100644 index 0000000..c4af0d8 Binary files /dev/null and b/third_party/libzip/regress/filename_duplicate_empty.zip differ diff --git a/third_party/libzip/regress/filename_empty.zip b/third_party/libzip/regress/filename_empty.zip new file mode 100644 index 0000000..d32e4e7 Binary files /dev/null and b/third_party/libzip/regress/filename_empty.zip differ diff --git a/third_party/libzip/regress/fileorder.zip b/third_party/libzip/regress/fileorder.zip new file mode 100644 index 0000000..3fcd81a Binary files /dev/null and b/third_party/libzip/regress/fileorder.zip differ diff --git a/third_party/libzip/regress/firstsecond-split-deflated.zip b/third_party/libzip/regress/firstsecond-split-deflated.zip new file mode 100644 index 0000000..35b9a5c Binary files /dev/null and b/third_party/libzip/regress/firstsecond-split-deflated.zip differ diff --git a/third_party/libzip/regress/firstsecond-split-stored.zip b/third_party/libzip/regress/firstsecond-split-stored.zip new file mode 100644 index 0000000..35f0684 Binary files /dev/null and b/third_party/libzip/regress/firstsecond-split-stored.zip differ diff --git a/third_party/libzip/regress/firstsecond.zip b/third_party/libzip/regress/firstsecond.zip new file mode 100644 index 0000000..a9117e3 Binary files /dev/null and b/third_party/libzip/regress/firstsecond.zip differ diff --git a/third_party/libzip/regress/foo-stored.zip b/third_party/libzip/regress/foo-stored.zip new file mode 100644 index 0000000..d3adc80 Binary files /dev/null and b/third_party/libzip/regress/foo-stored.zip differ diff --git a/third_party/libzip/regress/fopen_unchanged.c b/third_party/libzip/regress/fopen_unchanged.c new file mode 100644 index 0000000..497d810 --- /dev/null +++ b/third_party/libzip/regress/fopen_unchanged.c @@ -0,0 +1,91 @@ +/* + fopen_unchanged.c -- test case for adding file and reading from unchanged + Copyright (C) 2012-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include + +#include "zip.h" + +const char *teststr = "This is a test.\n"; +const char *file = "teststring.txt"; + +int +main(int argc, char *argv[]) { + const char *archive; + zip_t *za; + zip_source_t *zs; + int err; + + if (argc != 2) { + fprintf(stderr, "usage: %s archive\n", argv[0]); + return 1; + } + + archive = argv[1]; + + if ((za = zip_open(archive, ZIP_CREATE, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "can't open zip archive '%s': %s\n", archive, zip_error_strerror(&error)); + zip_error_fini(&error); + return 1; + } + + if ((zs = zip_source_buffer(za, teststr, strlen(teststr), 0)) == NULL) { + fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za)); + exit(1); + } + + if (zip_add(za, file, zs) == -1) { + fprintf(stderr, "can't add file '%s': %s\n", file, zip_strerror(za)); + (void)zip_source_free(zs); + (void)zip_close(za); + return 1; + } + + if (zip_fopen(za, file, ZIP_FL_UNCHANGED) == NULL) { + fprintf(stderr, "can't zip_fopen file '%s': %s\n", file, zip_strerror(za)); + (void)zip_discard(za); + return 1; + } + + if (zip_close(za) == -1) { + fprintf(stderr, "can't close zip archive '%s': %s\n", archive, zip_strerror(za)); + return 1; + } + + return 0; +} diff --git a/third_party/libzip/regress/fopen_unchanged.test b/third_party/libzip/regress/fopen_unchanged.test new file mode 100644 index 0000000..885f8b7 --- /dev/null +++ b/third_party/libzip/regress/fopen_unchanged.test @@ -0,0 +1,5 @@ +# add buffer contents as file to zip, then read unchanged from it +program fopen_unchanged +return 1 +args testbuffer.zip +stderr can't zip_fopen file 'teststring.txt': No such file diff --git a/third_party/libzip/regress/fread.c b/third_party/libzip/regress/fread.c new file mode 100644 index 0000000..e27351c --- /dev/null +++ b/third_party/libzip/regress/fread.c @@ -0,0 +1,214 @@ +/* + fread.c -- test cases for reading from zip archives + Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif + +#include "zip.h" + +enum when { WHEN_NEVER, WHEN_OPEN, WHEN_READ, WHEN_CLOSE }; + +const char *when_name[] = {"no", "zip_fopen", "zip_fread", "zip_fclose"}; + +static int do_read(zip_t *z, const char *name, zip_flags_t flags, enum when when_ex, int ze_ex, int se_ex); + +int verbose; + +const char *progname; +#define USAGE "usage: %s [-v] archive\n" + +int +main(int argc, char *argv[]) { + int fail, ze; + int c; + zip_t *z; + zip_source_t *zs; + char *archive; + zip_int64_t idx; + + verbose = 0; + fail = 0; + + progname = argv[0]; + + while ((c = getopt(argc, argv, "v")) != -1) { + switch (c) { + case 'v': + verbose = 1; + break; + + default: + fprintf(stderr, USAGE, progname); + return 1; + } + } + + + if (argc - optind != 1) { + fprintf(stderr, USAGE, progname); + return 1; + } + + archive = argv[optind]; + + if ((z = zip_open(archive, 0, &ze)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, ze); + fprintf(stderr, "%s: can't open zip archive '%s': %s\n", progname, archive, zip_error_strerror(&error)); + zip_error_fini(&error); + return 1; + } + + fail += do_read(z, "storedok", 0, WHEN_NEVER, 0, 0); + fail += do_read(z, "deflateok", 0, WHEN_NEVER, 0, 0); + fail += do_read(z, "storedcrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0); + fail += do_read(z, "deflatecrcerror", 0, WHEN_READ, ZIP_ER_CRC, 0); + fail += do_read(z, "deflatezliberror", 0, WHEN_READ, ZIP_ER_ZLIB, -3); + fail += do_read(z, NULL, 0, WHEN_OPEN, ZIP_ER_INVAL, 0); + fail += do_read(z, "nosuchfile", 0, WHEN_OPEN, ZIP_ER_NOENT, 0); + fail += do_read(z, "deflatezliberror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0); + fail += do_read(z, "deflatecrcerror", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0); + fail += do_read(z, "storedcrcerror", ZIP_FL_COMPRESSED, WHEN_READ, ZIP_ER_CRC, 0); + fail += do_read(z, "storedok", ZIP_FL_COMPRESSED, WHEN_NEVER, 0, 0); + + fail += do_read(z, "cryptok", 0, WHEN_OPEN, ZIP_ER_NOPASSWD, 0); + zip_set_default_password(z, "crypt"); + fail += do_read(z, "cryptok", 0, WHEN_NEVER, 0, 0); + zip_set_default_password(z, "wrong"); + fail += do_read(z, "cryptok", 0, WHEN_OPEN, ZIP_ER_WRONGPASSWD, 0); + zip_set_default_password(z, NULL); + + zs = zip_source_buffer(z, "asdf", 4, 0); + if ((idx = zip_name_locate(z, "storedok", 0)) < 0) { + fprintf(stderr, "%s: can't locate 'storedok' in zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + fail++; + } + else { + if (zip_replace(z, (zip_uint64_t)idx, zs) < 0) { + fprintf(stderr, "%s: can't replace 'storedok' in zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + fail++; + } + else { + fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0); + fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0); + } + } + if ((idx = zip_name_locate(z, "storedok", 0)) < 0) { + fprintf(stderr, "%s: can't locate 'storedok' in zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + fail++; + } + else { + if (zip_delete(z, (zip_uint64_t)idx) < 0) { + fprintf(stderr, "%s: can't replace 'storedok' in zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + fail++; + } + else { + fail += do_read(z, "storedok", 0, WHEN_OPEN, ZIP_ER_NOENT, 0); + fail += do_read(z, "storedok", ZIP_FL_UNCHANGED, WHEN_NEVER, 0, 0); + } + } + zs = zip_source_buffer(z, "asdf", 4, 0); + if (zip_file_add(z, "new_file", zs, 0) < 0) { + fprintf(stderr, "%s: can't add file to zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + fail++; + } + else { + fail += do_read(z, "new_file", 0, WHEN_OPEN, ZIP_ER_CHANGED, 0); + } + + zip_unchange_all(z); + if (zip_close(z) == -1) { + fprintf(stderr, "%s: can't close zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + return 1; + } + + exit(fail ? 1 : 0); +} + + +static int +do_read(zip_t *z, const char *name, zip_flags_t flags, enum when when_ex, int ze_ex, int se_ex) { + zip_file_t *zf; + enum when when_got; + zip_error_t error_got, error_ex; + zip_error_t *zf_error; + int err; + char b[8192]; + zip_int64_t n; + + when_got = WHEN_NEVER; + zip_error_init(&error_got); + zip_error_init(&error_ex); + zip_error_set(&error_ex, ze_ex, se_ex); + + if ((zf = zip_fopen(z, name, flags)) == NULL) { + when_got = WHEN_OPEN; + zf_error = zip_get_error(z); + zip_error_set(&error_got, zip_error_code_zip(zf_error), zip_error_code_system(zf_error)); + } + else { + while ((n = zip_fread(zf, b, sizeof(b))) > 0) + ; + if (n < 0) { + when_got = WHEN_READ; + zf_error = zip_file_get_error(zf); + zip_error_set(&error_got, zip_error_code_zip(zf_error), zip_error_code_system(zf_error)); + } + err = zip_fclose(zf); + if (when_got == WHEN_NEVER && err != 0) { + when_got = WHEN_CLOSE; + zip_error_init_with_code(&error_got, err); + } + } + + if (when_got != when_ex || zip_error_code_zip(&error_got) != zip_error_code_zip(&error_ex) || zip_error_code_system(&error_got) != zip_error_code_system(&error_ex)) { + printf("%s: %s: got %s error (%s), expected %s error (%s)\n", progname, name, when_name[when_got], zip_error_strerror(&error_got), when_name[when_ex], zip_error_strerror(&error_ex)); + zip_error_fini(&error_got); + zip_error_fini(&error_ex); + return 1; + } + else if (verbose) + printf("%s: %s: passed\n", progname, name); + + return 0; +} diff --git a/third_party/libzip/regress/fread.test b/third_party/libzip/regress/fread.test new file mode 100644 index 0000000..234e1a1 --- /dev/null +++ b/third_party/libzip/regress/fread.test @@ -0,0 +1,5 @@ +# various tests for zip_fread +program fread +args broken.zip +return 0 +file broken.zip broken.zip broken.zip diff --git a/third_party/libzip/regress/fseek.c b/third_party/libzip/regress/fseek.c new file mode 100644 index 0000000..19f3c40 --- /dev/null +++ b/third_party/libzip/regress/fseek.c @@ -0,0 +1,99 @@ +/* + fseek.c -- test tool for seeking in zip archives + Copyright (C) 2016-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "compat.h" + +#include + +#include "zip.h" + +const char *progname; +#define USAGE "usage: %s archive index offset\n" + +int +main(int argc, char *argv[]) { + int ze; + zip_t *z; + zip_file_t *zf; + char *archive; + zip_int64_t offset, n; + zip_uint64_t index; + char b[1024]; + + progname = argv[0]; + + if (argc != 4) { + fprintf(stderr, USAGE, progname); + return 1; + } + + archive = argv[1]; + index = strtoull(argv[2], NULL, 10); + offset = (zip_int64_t)strtoull(argv[3], NULL, 10); + + if ((z = zip_open(archive, 0, &ze)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, ze); + fprintf(stderr, "%s: can't open zip archive '%s': %s\n", progname, archive, zip_error_strerror(&error)); + zip_error_fini(&error); + return 1; + } + + if ((zf = zip_fopen_index(z, index, 0)) == NULL) { + fprintf(stderr, "%s: can't open file in archive '%s': %s\n", progname, archive, zip_error_strerror(zip_file_get_error(zf))); + zip_close(z); + return 1; + } + + if (zip_fseek(zf, offset, SEEK_SET) < 0) { + fprintf(stderr, "%s: zip_fseek failed: %s\n", progname, zip_error_strerror(zip_file_get_error(zf))); + zip_close(z); + return 1; + } + + while ((n = zip_fread(zf, b, sizeof(b))) > 0) { + printf("%.*s", (int)n, b); + } + if (n < 0) { + fprintf(stderr, "%s: zip_fread failed: %s\n", progname, zip_error_strerror(zip_file_get_error(zf))); + zip_close(z); + return 1; + } + + if (zip_close(z) == -1) { + fprintf(stderr, "%s: can't close zip archive '%s': %s\n", progname, archive, zip_strerror(z)); + return 1; + } + + return 0; +} diff --git a/third_party/libzip/regress/fseek_deflated.test b/third_party/libzip/regress/fseek_deflated.test new file mode 100644 index 0000000..7c560af --- /dev/null +++ b/third_party/libzip/regress/fseek_deflated.test @@ -0,0 +1,6 @@ +# unsuccessful fseek test because data is compressed +program fseek +args test.zip 0 2 +return 1 +file test.zip testdeflated.zip testdeflated.zip +stderr zip_fseek failed: Operation not supported diff --git a/third_party/libzip/regress/fseek_fail.test b/third_party/libzip/regress/fseek_fail.test new file mode 100644 index 0000000..be78a9a --- /dev/null +++ b/third_party/libzip/regress/fseek_fail.test @@ -0,0 +1,6 @@ +# successful fseek test +program fseek +args test.zip 0 8 +return 1 +file test.zip test.zip test.zip +stderr zip_fseek failed: Invalid argument diff --git a/third_party/libzip/regress/fseek_ok.test b/third_party/libzip/regress/fseek_ok.test new file mode 100644 index 0000000..29cfe67 --- /dev/null +++ b/third_party/libzip/regress/fseek_ok.test @@ -0,0 +1,6 @@ +# successful fseek test +program fseek +args test.zip 0 2 +return 0 +file test.zip test.zip test.zip +stdout st diff --git a/third_party/libzip/regress/gap-add.zip b/third_party/libzip/regress/gap-add.zip new file mode 100644 index 0000000..d70bfbd Binary files /dev/null and b/third_party/libzip/regress/gap-add.zip differ diff --git a/third_party/libzip/regress/gap-delete.zip b/third_party/libzip/regress/gap-delete.zip new file mode 100644 index 0000000..7d73d00 Binary files /dev/null and b/third_party/libzip/regress/gap-delete.zip differ diff --git a/third_party/libzip/regress/gap-replace.zip b/third_party/libzip/regress/gap-replace.zip new file mode 100644 index 0000000..610ca06 Binary files /dev/null and b/third_party/libzip/regress/gap-replace.zip differ diff --git a/third_party/libzip/regress/gap.zip b/third_party/libzip/regress/gap.zip new file mode 100644 index 0000000..85e3bc7 Binary files /dev/null and b/third_party/libzip/regress/gap.zip differ diff --git a/third_party/libzip/regress/get_comment.test b/third_party/libzip/regress/get_comment.test new file mode 100644 index 0000000..5f2df0a --- /dev/null +++ b/third_party/libzip/regress/get_comment.test @@ -0,0 +1,14 @@ +# show comments of a zip archive +return 0 +args testcomment.zip get_archive_comment get_file_comment 0 get_file_comment 1 get_file_comment 2 get_file_comment 3 +file testcomment.zip testcomment.zip testcomment.zip +stdout Archive comment: This is the archive comment for the file. +stdout +stdout Long. +stdout +stdout Longer. +stdout +stdout No comment for 'file1' +stdout File comment for 'file2': First one had no comment. +stdout File comment for 'file3': Third one. +stdout File comment for 'file4': Last. diff --git a/third_party/libzip/regress/hole.c b/third_party/libzip/regress/hole.c new file mode 100644 index 0000000..5f24966 --- /dev/null +++ b/third_party/libzip/regress/hole.c @@ -0,0 +1,195 @@ +/* + hole.c -- convert huge files with mostly NULs to/from source_hole + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif + +#include "zip.h" + +/* public API */ + +zip_source_t *source_hole_create(const char *, int flags, zip_error_t *); + +const char *progname; + + +static int +copy_source(zip_source_t *from, zip_source_t *to) { + zip_uint8_t buf[8192]; + zip_int64_t n; + + if (zip_source_open(from) < 0) { + fprintf(stderr, "%s: can't open source for reading: %s\n", progname, zip_error_strerror(zip_source_error(from))); + return -1; + } + + if (zip_source_begin_write(to) < 0) { + fprintf(stderr, "%s: can't open source for writing: %s\n", progname, zip_error_strerror(zip_source_error(to))); + zip_source_close(from); + return -1; + } + + while ((n = zip_source_read(from, buf, sizeof(buf))) > 0) { + if (zip_source_write(to, buf, (zip_uint64_t)n) != n) { + fprintf(stderr, "%s: can't write to source: %s\n", progname, zip_error_strerror(zip_source_error(to))); + zip_source_close(from); + zip_source_rollback_write(to); + return -1; + } + } + + if (n < 0) { + fprintf(stderr, "%s: can't read from source: %s\n", progname, zip_error_strerror(zip_source_error(from))); + zip_source_close(from); + zip_source_rollback_write(to); + return -1; + } + + zip_source_close(from); + + if (zip_source_commit_write(to) < 0) { + fprintf(stderr, "%s: can't commit source: %s\n", progname, zip_error_strerror(zip_source_error(to))); + zip_source_rollback_write(to); + return -1; + } + + return 0; +} + + +static zip_source_t * +open_compressed(const char *fname, int flags) { + zip_error_t error; + zip_source_t *src; + + zip_error_init(&error); + + if ((src = source_hole_create(fname, flags, &error)) == NULL) { + fprintf(stderr, "%s: can't open compressed file %s: %s\n", progname, fname, zip_error_strerror(&error)); + zip_error_fini(&error); + exit(1); + } + + return src; +} + + +static zip_source_t * +open_file(const char *fname) { + zip_error_t error; + zip_source_t *src; + + zip_error_init(&error); + + if ((src = zip_source_file_create(fname, 0, 0, &error)) == NULL) { + fprintf(stderr, "%s: can't open file %s: %s\n", progname, fname, zip_error_strerror(&error)); + zip_error_fini(&error); + exit(1); + } + + return src; +} + + +static void +usage(void) { + fprintf(stderr, "usage: %s [-du] in out\n", progname); + fprintf(stderr, "\nOptions:\n -d decompress in\n -u update in\n"); + exit(1); +} + + +int +main(int argc, char **argv) { + zip_source_t *from; + zip_source_t *to; + int c, err; + int compress = 1; + int decompress = 0; + + progname = argv[0]; + + while ((c = getopt(argc, argv, "du")) != -1) { + switch (c) { + case 'd': + compress = 0; + decompress = 1; + break; + + case 'u': + compress = 1; + decompress = 1; + break; + + default: + usage(); + break; + } + } + + if (optind + 2 != argc) { + usage(); + } + + if (decompress) { + from = open_compressed(argv[optind], 0); + } + else { + from = open_file(argv[optind]); + } + + if (compress) { + to = open_compressed(argv[optind + 1], ZIP_CREATE); + } + else { + to = open_file(argv[optind + 1]); + } + + err = copy_source(from, to); + + zip_source_free(from); + zip_source_free(to); + + exit(err < 0 ? 1 : 0); +} diff --git a/third_party/libzip/regress/incons-archive-comment-longer.zip b/third_party/libzip/regress/incons-archive-comment-longer.zip new file mode 100644 index 0000000..28d7ed3 Binary files /dev/null and b/third_party/libzip/regress/incons-archive-comment-longer.zip differ diff --git a/third_party/libzip/regress/incons-archive-comment-shorter.zip b/third_party/libzip/regress/incons-archive-comment-shorter.zip new file mode 100644 index 0000000..d23cad4 Binary files /dev/null and b/third_party/libzip/regress/incons-archive-comment-shorter.zip differ diff --git a/third_party/libzip/regress/incons-cdoffset.zip b/third_party/libzip/regress/incons-cdoffset.zip new file mode 100644 index 0000000..153e7a8 Binary files /dev/null and b/third_party/libzip/regress/incons-cdoffset.zip differ diff --git a/third_party/libzip/regress/incons-central-compression-method.zip b/third_party/libzip/regress/incons-central-compression-method.zip new file mode 100644 index 0000000..1bf78f2 Binary files /dev/null and b/third_party/libzip/regress/incons-central-compression-method.zip differ diff --git a/third_party/libzip/regress/incons-central-compsize-larger-toolarge.zip b/third_party/libzip/regress/incons-central-compsize-larger-toolarge.zip new file mode 100644 index 0000000..1c82ef6 Binary files /dev/null and b/third_party/libzip/regress/incons-central-compsize-larger-toolarge.zip differ diff --git a/third_party/libzip/regress/incons-central-compsize-larger.zip b/third_party/libzip/regress/incons-central-compsize-larger.zip new file mode 100644 index 0000000..67e9a99 Binary files /dev/null and b/third_party/libzip/regress/incons-central-compsize-larger.zip differ diff --git a/third_party/libzip/regress/incons-central-compsize-smaller.zip b/third_party/libzip/regress/incons-central-compsize-smaller.zip new file mode 100644 index 0000000..97dd14a Binary files /dev/null and b/third_party/libzip/regress/incons-central-compsize-smaller.zip differ diff --git a/third_party/libzip/regress/incons-central-crc.zip b/third_party/libzip/regress/incons-central-crc.zip new file mode 100644 index 0000000..1f882ac Binary files /dev/null and b/third_party/libzip/regress/incons-central-crc.zip differ diff --git a/third_party/libzip/regress/incons-central-date.zip b/third_party/libzip/regress/incons-central-date.zip new file mode 100644 index 0000000..6c831ca Binary files /dev/null and b/third_party/libzip/regress/incons-central-date.zip differ diff --git a/third_party/libzip/regress/incons-central-file-comment-longer.zip b/third_party/libzip/regress/incons-central-file-comment-longer.zip new file mode 100644 index 0000000..b34c661 Binary files /dev/null and b/third_party/libzip/regress/incons-central-file-comment-longer.zip differ diff --git a/third_party/libzip/regress/incons-central-file-comment-shorter.zip b/third_party/libzip/regress/incons-central-file-comment-shorter.zip new file mode 100644 index 0000000..7769a9a Binary files /dev/null and b/third_party/libzip/regress/incons-central-file-comment-shorter.zip differ diff --git a/third_party/libzip/regress/incons-central-magic-bad.zip b/third_party/libzip/regress/incons-central-magic-bad.zip new file mode 100644 index 0000000..954563b Binary files /dev/null and b/third_party/libzip/regress/incons-central-magic-bad.zip differ diff --git a/third_party/libzip/regress/incons-central-magic-bad2.zip b/third_party/libzip/regress/incons-central-magic-bad2.zip new file mode 100644 index 0000000..f99d9b7 Binary files /dev/null and b/third_party/libzip/regress/incons-central-magic-bad2.zip differ diff --git a/third_party/libzip/regress/incons-central-size-larger.zip b/third_party/libzip/regress/incons-central-size-larger.zip new file mode 100644 index 0000000..0779ce6 Binary files /dev/null and b/third_party/libzip/regress/incons-central-size-larger.zip differ diff --git a/third_party/libzip/regress/incons-data.zip b/third_party/libzip/regress/incons-data.zip new file mode 100644 index 0000000..e2ab58a Binary files /dev/null and b/third_party/libzip/regress/incons-data.zip differ diff --git a/third_party/libzip/regress/incons-ef-central-size-wrong.zip b/third_party/libzip/regress/incons-ef-central-size-wrong.zip new file mode 100644 index 0000000..a3f4cc1 Binary files /dev/null and b/third_party/libzip/regress/incons-ef-central-size-wrong.zip differ diff --git a/third_party/libzip/regress/incons-ef-local-id-size.zip b/third_party/libzip/regress/incons-ef-local-id-size.zip new file mode 100644 index 0000000..44ce2f7 Binary files /dev/null and b/third_party/libzip/regress/incons-ef-local-id-size.zip differ diff --git a/third_party/libzip/regress/incons-ef-local-id.zip b/third_party/libzip/regress/incons-ef-local-id.zip new file mode 100644 index 0000000..aad5521 Binary files /dev/null and b/third_party/libzip/regress/incons-ef-local-id.zip differ diff --git a/third_party/libzip/regress/incons-ef-local-size.zip b/third_party/libzip/regress/incons-ef-local-size.zip new file mode 100644 index 0000000..ad16710 Binary files /dev/null and b/third_party/libzip/regress/incons-ef-local-size.zip differ diff --git a/third_party/libzip/regress/incons-eocd-magic-bad.zip b/third_party/libzip/regress/incons-eocd-magic-bad.zip new file mode 100644 index 0000000..9e49e56 Binary files /dev/null and b/third_party/libzip/regress/incons-eocd-magic-bad.zip differ diff --git a/third_party/libzip/regress/incons-file-count-high.zip b/third_party/libzip/regress/incons-file-count-high.zip new file mode 100644 index 0000000..876a886 Binary files /dev/null and b/third_party/libzip/regress/incons-file-count-high.zip differ diff --git a/third_party/libzip/regress/incons-file-count-low.zip b/third_party/libzip/regress/incons-file-count-low.zip new file mode 100644 index 0000000..4af9038 Binary files /dev/null and b/third_party/libzip/regress/incons-file-count-low.zip differ diff --git a/third_party/libzip/regress/incons-file-count-overflow.zip b/third_party/libzip/regress/incons-file-count-overflow.zip new file mode 100644 index 0000000..461722c Binary files /dev/null and b/third_party/libzip/regress/incons-file-count-overflow.zip differ diff --git a/third_party/libzip/regress/incons-local-compression-method.zip b/third_party/libzip/regress/incons-local-compression-method.zip new file mode 100644 index 0000000..2e70f59 Binary files /dev/null and b/third_party/libzip/regress/incons-local-compression-method.zip differ diff --git a/third_party/libzip/regress/incons-local-compsize-larger.zip b/third_party/libzip/regress/incons-local-compsize-larger.zip new file mode 100644 index 0000000..6fc27e0 Binary files /dev/null and b/third_party/libzip/regress/incons-local-compsize-larger.zip differ diff --git a/third_party/libzip/regress/incons-local-compsize-smaller.zip b/third_party/libzip/regress/incons-local-compsize-smaller.zip new file mode 100644 index 0000000..75f1463 Binary files /dev/null and b/third_party/libzip/regress/incons-local-compsize-smaller.zip differ diff --git a/third_party/libzip/regress/incons-local-crc.zip b/third_party/libzip/regress/incons-local-crc.zip new file mode 100644 index 0000000..6f74b15 Binary files /dev/null and b/third_party/libzip/regress/incons-local-crc.zip differ diff --git a/third_party/libzip/regress/incons-local-filename-long.zip b/third_party/libzip/regress/incons-local-filename-long.zip new file mode 100644 index 0000000..42b4a1f Binary files /dev/null and b/third_party/libzip/regress/incons-local-filename-long.zip differ diff --git a/third_party/libzip/regress/incons-local-filename-missing.zip b/third_party/libzip/regress/incons-local-filename-missing.zip new file mode 100644 index 0000000..71d3eb2 Binary files /dev/null and b/third_party/libzip/regress/incons-local-filename-missing.zip differ diff --git a/third_party/libzip/regress/incons-local-filename-short.zip b/third_party/libzip/regress/incons-local-filename-short.zip new file mode 100644 index 0000000..c69be1b Binary files /dev/null and b/third_party/libzip/regress/incons-local-filename-short.zip differ diff --git a/third_party/libzip/regress/incons-local-filename.zip b/third_party/libzip/regress/incons-local-filename.zip new file mode 100644 index 0000000..1878235 Binary files /dev/null and b/third_party/libzip/regress/incons-local-filename.zip differ diff --git a/third_party/libzip/regress/incons-local-magic-bad.zip b/third_party/libzip/regress/incons-local-magic-bad.zip new file mode 100644 index 0000000..9a6a061 Binary files /dev/null and b/third_party/libzip/regress/incons-local-magic-bad.zip differ diff --git a/third_party/libzip/regress/incons-local-size-larger.zip b/third_party/libzip/regress/incons-local-size-larger.zip new file mode 100644 index 0000000..4e0bb43 Binary files /dev/null and b/third_party/libzip/regress/incons-local-size-larger.zip differ diff --git a/third_party/libzip/regress/junk-at-end.zip b/third_party/libzip/regress/junk-at-end.zip new file mode 100644 index 0000000..30387b3 Binary files /dev/null and b/third_party/libzip/regress/junk-at-end.zip differ diff --git a/third_party/libzip/regress/junk-at-start.zip b/third_party/libzip/regress/junk-at-start.zip new file mode 100644 index 0000000..8c98325 Binary files /dev/null and b/third_party/libzip/regress/junk-at-start.zip differ diff --git a/third_party/libzip/regress/junk_at_end.test b/third_party/libzip/regress/junk_at_end.test new file mode 100644 index 0000000..41d9455 --- /dev/null +++ b/third_party/libzip/regress/junk_at_end.test @@ -0,0 +1,5 @@ +# test archive with junk at end of file +args -l 412 junk-at-end.zzip get_num_entries 0 +return 0 +file junk-at-end.zzip junk-at-end.zip junk-at-end.zip +stdout 3 entries in archive \ No newline at end of file diff --git a/third_party/libzip/regress/junk_at_start.test b/third_party/libzip/regress/junk_at_start.test new file mode 100644 index 0000000..d018ffc --- /dev/null +++ b/third_party/libzip/regress/junk_at_start.test @@ -0,0 +1,5 @@ +# test archive with junk at start of file +args -o 4 junk-at-start.zzip get_num_entries 0 +return 0 +file junk-at-start.zzip junk-at-start.zip junk-at-start.zip +stdout 3 entries in archive \ No newline at end of file diff --git a/third_party/libzip/regress/large-uncompressable b/third_party/libzip/regress/large-uncompressable new file mode 100644 index 0000000..e7e26d9 Binary files /dev/null and b/third_party/libzip/regress/large-uncompressable differ diff --git a/third_party/libzip/regress/malloc.c b/third_party/libzip/regress/malloc.c new file mode 100644 index 0000000..ba5a105 --- /dev/null +++ b/third_party/libzip/regress/malloc.c @@ -0,0 +1,162 @@ +/* + malloc.c -- override *alloc() to allow testing special cases + Copyright (C) 2015-2018 Dieter Baron and Thomas Klausner + + This file is part of ckmame, a program to check rom sets for MAME. + The authors can be contacted at + + 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. + 3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +/* #include */ +#include +#define __USE_GNU +#include +#undef __USE_GNU + +#include "config.h" + +#if !defined(RTLD_NEXT) +#define RTLD_NEXT RTLD_DEFAULT +#endif + +#if defined(HAVE___PROGNAME) +extern char *__progname; +#endif + +#if defined(HAVE_GETPROGNAME) +/* all fine */ +#else +const char * +getprogname(void) { +#if defined(HAVE___PROGNAME) + return __progname; +#else + return NULL; +#endif +} +#endif + +static int inited = 0; +static size_t count = 0; +static size_t max_count = 0; +static size_t min_size = 0; +static void *(*real_malloc)(size_t size) = NULL; +static void *(*real_calloc)(size_t number, size_t size) = NULL; +static void *(*real_realloc)(void *ptr, size_t size) = NULL; + +static const char *myname = NULL; + +/* TODO: add sentinel -- check if particular size is malloced before doing other stuff */ +/* TODO: catch free for sentinel too */ +/* TODO: optionally, catch malloc of particular size */ + +static void +init(void) { + char *foo; + myname = getprogname(); + if (!myname) + myname = "(unknown)"; + if ((foo = getenv("MALLOC_MAX_COUNT")) != NULL) + max_count = strtoul(foo, NULL, 0); + if ((foo = getenv("MALLOC_MIN_SIZE")) != NULL) + min_size = strtoul(foo, NULL, 0); + real_calloc = dlsym(RTLD_NEXT, "calloc"); + if (!real_calloc) + abort(); + real_malloc = dlsym(RTLD_NEXT, "malloc"); + if (!real_malloc) + abort(); + real_realloc = dlsym(RTLD_NEXT, "realloc"); + if (!real_realloc) + abort(); + inited = 1; +} + +void * +calloc(size_t number, size_t size) { + void *ret; + + if (!inited) { + init(); + } + + if (number >= min_size / size && count >= max_count) { + errno = ENOMEM; + return NULL; + } + + ret = real_calloc(number, size); + if (size >= min_size) { + count++; + } + + return ret; +} + +void * +malloc(size_t size) { + void *ret; + + if (!inited) { + init(); + } + + if (size >= min_size && count >= max_count) { + errno = ENOMEM; + return NULL; + } + + ret = real_malloc(size); + if (size >= min_size) { + count++; + } + + return ret; +} + +void * +realloc(void *ptr, size_t size) { + void *ret; + + if (!inited) { + init(); + } + + if (size >= min_size && count >= max_count) { + errno = ENOMEM; + return NULL; + } + + ret = real_realloc(ptr, size); + if (size >= min_size) { + count++; + } + + return ret; +} diff --git a/third_party/libzip/regress/manyfiles-zip.zip b/third_party/libzip/regress/manyfiles-zip.zip new file mode 100644 index 0000000..19ad57d Binary files /dev/null and b/third_party/libzip/regress/manyfiles-zip.zip differ diff --git a/third_party/libzip/regress/multidisk.zip b/third_party/libzip/regress/multidisk.zip new file mode 100644 index 0000000..28dafb9 Binary files /dev/null and b/third_party/libzip/regress/multidisk.zip differ diff --git a/third_party/libzip/regress/name_locate.test b/third_party/libzip/regress/name_locate.test new file mode 100644 index 0000000..1f79231 --- /dev/null +++ b/third_party/libzip/regress/name_locate.test @@ -0,0 +1,27 @@ +# various tests for zip_name_locate +args test.zip name_locate nosuchfile 0 name_locate test 0 name_locate "" 0 name_locate TeSt 0 name_locate TeSt C name_locate testdir/test2 0 name_locate tesTdir/tESt2 C name_locate testdir/test2 d name_locate tesTdir/tESt2 dC name_locate test2 0 name_locate test2 d name_locate TeST2 dC delete 0 name_locate test 0 name_locate test u add new teststring name_locate new 0 name_locate new u add "" teststring name_locate "" 0 unchange_all name_locate test 0 name_locate new 0 +stderr can't find entry with name 'nosuchfile' using flags '0' +stdout name 'test' using flags '0' found at index 0 +stderr can't find entry with name '' using flags '0' +stderr can't find entry with name 'TeSt' using flags '0' +stdout name 'TeSt' using flags 'C' found at index 0 +stdout name 'testdir/test2' using flags '0' found at index 2 +stdout name 'tesTdir/tESt2' using flags 'C' found at index 2 +stderr can't find entry with name 'testdir/test2' using flags 'd' +stderr can't find entry with name 'tesTdir/tESt2' using flags 'dC' +stderr can't find entry with name 'test2' using flags '0' +stdout name 'test2' using flags 'd' found at index 2 +stdout name 'TeST2' using flags 'dC' found at index 2 +# delete 0 +stderr can't find entry with name 'test' using flags '0' +stdout name 'test' using flags 'u' found at index 0 +# add "new" +stdout name 'new' using flags '0' found at index 3 +stderr can't find entry with name 'new' using flags 'u' +# add "" +stdout name '' using flags '0' found at index 4 +# unchange all +stdout name 'test' using flags '0' found at index 0 +stderr can't find entry with name 'new' using flags '0' +return 0 +file test.zip test.zip test.zip diff --git a/third_party/libzip/regress/nonrandomopen.c b/third_party/libzip/regress/nonrandomopen.c new file mode 100644 index 0000000..c9833e0 --- /dev/null +++ b/third_party/libzip/regress/nonrandomopen.c @@ -0,0 +1,50 @@ +/* + nonrandomopen.c -- override zip_random + + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of ckmame, a program to check rom sets for MAME. + The authors can be contacted at + + 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. + 3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 + +#include "compat.h" + +#ifdef HAVE_UNISTD_H +#include +#endif + +#include "zipint.h" + +bool +zip_random(zip_uint8_t *buffer, zip_uint16_t length) { + memset(buffer, 0, length); + + return true; +} diff --git a/third_party/libzip/regress/nonrandomopentest.c b/third_party/libzip/regress/nonrandomopentest.c new file mode 100644 index 0000000..1ed6249 --- /dev/null +++ b/third_party/libzip/regress/nonrandomopentest.c @@ -0,0 +1,57 @@ +/* + nonrandomopentest.c -- test nonrandomopen.so + Copyright (C) 2017-2018 Dieter Baron and Thomas Klausner + + This file is part of ckmame, a program to check rom sets for MAME. + The authors can be contacted at + + 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. + 3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "zipint.h" + +#include +#include + +int +main(int argc, const char *argv[]) { + zip_uint8_t buf[1024]; + int i; + +#ifdef HAVE_CRYPTO + if (!zip_random(buf, sizeof(buf))) { + fprintf(stderr, "zip_random returned false\n"); + exit(1); + } + for (i = 0; i < sizeof(buf); i++) { + if (buf[i] != 0) { + fprintf(stderr, "non-zero byte found\n"); + exit(1); + } + } +#endif + exit(0); +} diff --git a/third_party/libzip/regress/open_cons_extrabytes.test b/third_party/libzip/regress/open_cons_extrabytes.test new file mode 100644 index 0000000..beeb90e --- /dev/null +++ b/third_party/libzip/regress/open_cons_extrabytes.test @@ -0,0 +1,7 @@ +# zip_open: file has extra bytes at end of archive +program tryopen +file testextrabytes.zzip testextrabytes.zip testextrabytes.zip +args -c testextrabytes.zzip +return 1 +stdout opening 'testextrabytes.zzip' returned error 21 +stderr 1 errors diff --git a/third_party/libzip/regress/open_empty.test b/third_party/libzip/regress/open_empty.test new file mode 100644 index 0000000..8f05d29 --- /dev/null +++ b/third_party/libzip/regress/open_empty.test @@ -0,0 +1,6 @@ +# zip_open: file contains no entry, but is valid +program tryopen +file testempty.zip testempty.zip testempty.zip +args testempty.zip +return 0 +stdout opening 'testempty.zip' succeeded, 0 entries diff --git a/third_party/libzip/regress/open_empty_2.test b/third_party/libzip/regress/open_empty_2.test new file mode 100644 index 0000000..07a5358 --- /dev/null +++ b/third_party/libzip/regress/open_empty_2.test @@ -0,0 +1,6 @@ +# zip_open: 0 size file is recognized as empty zip +program tryopen +file testfile.txt testfile.txt testfile.txt +args testfile.txt +return 0 +stdout opening 'testfile.txt' succeeded, 0 entries diff --git a/third_party/libzip/regress/open_extrabytes.test b/third_party/libzip/regress/open_extrabytes.test new file mode 100644 index 0000000..1cfce24 --- /dev/null +++ b/third_party/libzip/regress/open_extrabytes.test @@ -0,0 +1,6 @@ +# zip_open: file has extra bytes at end of archive +program tryopen +file testextrabytes.zzip testextrabytes.zip testextrabytes.zip +args testextrabytes.zzip +return 0 +stdout opening 'testextrabytes.zzip' succeeded, 1 entries diff --git a/third_party/libzip/regress/open_file_count.test b/third_party/libzip/regress/open_file_count.test new file mode 100644 index 0000000..56f0447 --- /dev/null +++ b/third_party/libzip/regress/open_file_count.test @@ -0,0 +1,12 @@ +# zip_open: various inconsistent files +setenv LANG C +program tryopen +file incons-file-count-high.zzip incons-file-count-high.zip incons-file-count-high.zip +file incons-file-count-low.zzip incons-file-count-low.zip incons-file-count-low.zip +file incons-file-count-overflow.zzip incons-file-count-overflow.zip incons-file-count-overflow.zip +args incons-file-count-high.zzip incons-file-count-low.zzip incons-file-count-overflow.zzip +return 1 +stdout opening 'incons-file-count-high.zzip' returned error 21 +stdout opening 'incons-file-count-low.zzip' returned error 21 +stdout opening 'incons-file-count-overflow.zzip' returned error 14 +stderr 3 errors diff --git a/third_party/libzip/regress/open_filename_duplicate.test b/third_party/libzip/regress/open_filename_duplicate.test new file mode 100644 index 0000000..5204db6 --- /dev/null +++ b/third_party/libzip/regress/open_filename_duplicate.test @@ -0,0 +1,6 @@ +# zip_open: file opens fine even though same file name appears twice +program tryopen +args filename_duplicate.zzip +return 0 +file filename_duplicate.zzip filename_duplicate.zip filename_duplicate.zip +stdout opening 'filename_duplicate.zzip' succeeded, 2 entries diff --git a/third_party/libzip/regress/open_filename_duplicate_consistency.test b/third_party/libzip/regress/open_filename_duplicate_consistency.test new file mode 100644 index 0000000..e82cf75 --- /dev/null +++ b/third_party/libzip/regress/open_filename_duplicate_consistency.test @@ -0,0 +1,7 @@ +# zip_open: file opens fine even though same file name appears twice +program tryopen +args -c filename_duplicate.zzip +return 1 +file filename_duplicate.zzip filename_duplicate.zip filename_duplicate.zip +stdout opening 'filename_duplicate.zzip' returned error 10 +stderr 1 errors diff --git a/third_party/libzip/regress/open_filename_duplicate_empty.test b/third_party/libzip/regress/open_filename_duplicate_empty.test new file mode 100644 index 0000000..ea143b6 --- /dev/null +++ b/third_party/libzip/regress/open_filename_duplicate_empty.test @@ -0,0 +1,6 @@ +# zip_open: file opens fine even though same file name (empty file name) appears twice +program tryopen +args filename_duplicate_empty.zzip +return 0 +file filename_duplicate_empty.zzip filename_duplicate_empty.zip filename_duplicate_empty.zip +stdout opening 'filename_duplicate_empty.zzip' succeeded, 2 entries diff --git a/third_party/libzip/regress/open_filename_duplicate_empty_consistency.test b/third_party/libzip/regress/open_filename_duplicate_empty_consistency.test new file mode 100644 index 0000000..6570195 --- /dev/null +++ b/third_party/libzip/regress/open_filename_duplicate_empty_consistency.test @@ -0,0 +1,7 @@ +# zip_open: file opens fine even though same file name (empty file name) appears twice +program tryopen +args -c filename_duplicate_empty.zzip +return 1 +file filename_duplicate_empty.zzip filename_duplicate_empty.zip filename_duplicate_empty.zip +stdout opening 'filename_duplicate_empty.zzip' returned error 10 +stderr 1 errors diff --git a/third_party/libzip/regress/open_filename_empty.test b/third_party/libzip/regress/open_filename_empty.test new file mode 100644 index 0000000..96f3efc --- /dev/null +++ b/third_party/libzip/regress/open_filename_empty.test @@ -0,0 +1,6 @@ +# zip_open: file opens fine even though file name has length 0 +program tryopen +args filename_empty.zip +return 0 +file filename_empty.zip filename_empty.zip filename_empty.zip +stdout opening 'filename_empty.zip' succeeded, 1 entries diff --git a/third_party/libzip/regress/open_incons.test b/third_party/libzip/regress/open_incons.test new file mode 100644 index 0000000..0843816 --- /dev/null +++ b/third_party/libzip/regress/open_incons.test @@ -0,0 +1,74 @@ +# zip_open: various inconsistent files +setenv LANG C +program tryopen +file incons-archive-comment-longer.zzip incons-archive-comment-longer.zip incons-archive-comment-longer.zip +file incons-archive-comment-shorter.zzip incons-archive-comment-shorter.zip incons-archive-comment-shorter.zip +file incons-cdoffset.zzip incons-cdoffset.zip incons-cdoffset.zip +file incons-central-compression-method.zzip incons-central-compression-method.zip incons-central-compression-method.zip +file incons-central-compsize-larger.zzip incons-central-compsize-larger.zip incons-central-compsize-larger.zip +file incons-central-compsize-larger-toolarge.zzip incons-central-compsize-larger-toolarge.zip incons-central-compsize-larger-toolarge.zip +file incons-central-compsize-smaller.zzip incons-central-compsize-smaller.zip incons-central-compsize-smaller.zip +file incons-central-crc.zzip incons-central-crc.zip incons-central-crc.zip +file incons-central-date.zzip incons-central-date.zip incons-central-date.zip +file incons-central-file-comment-longer.zzip incons-central-file-comment-longer.zip incons-central-file-comment-longer.zip +file incons-central-file-comment-shorter.zzip incons-central-file-comment-shorter.zip incons-central-file-comment-shorter.zip +file incons-central-magic-bad.zzip incons-central-magic-bad.zip incons-central-magic-bad.zip +file incons-central-magic-bad2.zzip incons-central-magic-bad2.zip incons-central-magic-bad2.zip +file incons-central-size-larger.zzip incons-central-size-larger.zip incons-central-size-larger.zip +file incons-data.zzip incons-data.zip incons-data.zip +file incons-ef-central-size-wrong.zzip incons-ef-central-size-wrong.zip incons-ef-central-size-wrong.zip +file incons-ef-local-id-size.zzip incons-ef-local-id-size.zip incons-ef-local-id-size.zip +file incons-ef-local-id.zzip incons-ef-local-id.zip incons-ef-local-id.zip +file incons-ef-local-size.zzip incons-ef-local-size.zip incons-ef-local-size.zip +file incons-eocd-magic-bad.zzip incons-eocd-magic-bad.zip incons-eocd-magic-bad.zip +file incons-file-count-high.zzip incons-file-count-high.zip incons-file-count-high.zip +file incons-file-count-low.zzip incons-file-count-low.zip incons-file-count-low.zip +file incons-file-count-overflow.zzip incons-file-count-overflow.zip incons-file-count-overflow.zip +file incons-local-compression-method.zzip incons-local-compression-method.zip incons-local-compression-method.zip +file incons-local-compsize-larger.zzip incons-local-compsize-larger.zip incons-local-compsize-larger.zip +file incons-local-compsize-smaller.zzip incons-local-compsize-smaller.zip incons-local-compsize-smaller.zip +file incons-local-crc.zzip incons-local-crc.zip incons-local-crc.zip +file incons-local-filename-long.zzip incons-local-filename-long.zip incons-local-filename-long.zip +file incons-local-filename-missing.zzip incons-local-filename-missing.zip incons-local-filename-missing.zip +file incons-local-filename-short.zzip incons-local-filename-short.zip incons-local-filename-short.zip +file incons-local-filename.zzip incons-local-filename.zip incons-local-filename.zip +file incons-local-magic-bad.zzip incons-local-magic-bad.zip incons-local-magic-bad.zip +file incons-local-size-larger.zzip incons-local-size-larger.zip incons-local-size-larger.zip +args -c incons-archive-comment-longer.zzip incons-archive-comment-shorter.zzip incons-cdoffset.zzip incons-central-compression-method.zzip incons-central-compsize-larger-toolarge.zzip incons-central-compsize-larger.zzip incons-central-compsize-smaller.zzip incons-central-crc.zzip incons-central-date.zzip incons-central-file-comment-longer.zzip incons-central-file-comment-shorter.zzip incons-central-magic-bad.zzip incons-central-magic-bad2.zzip incons-central-size-larger.zzip incons-data.zzip incons-ef-central-size-wrong.zzip incons-ef-local-id-size.zzip incons-ef-local-id.zzip incons-ef-local-size.zzip incons-eocd-magic-bad.zzip incons-file-count-high.zzip incons-file-count-low.zzip incons-file-count-overflow.zzip incons-local-compression-method.zzip incons-local-compsize-larger.zzip incons-local-compsize-smaller.zzip incons-local-crc.zzip incons-local-filename-long.zzip incons-local-filename-missing.zzip incons-local-filename-short.zzip incons-local-filename.zzip incons-local-magic-bad.zzip incons-local-size-larger.zzip +return 1 +stdout opening 'incons-archive-comment-longer.zzip' returned error 21 +stdout opening 'incons-archive-comment-shorter.zzip' returned error 21 +stdout opening 'incons-cdoffset.zzip' returned error 21 +stdout opening 'incons-central-compression-method.zzip' returned error 21 +stdout opening 'incons-central-compsize-larger-toolarge.zzip' returned error 19 +stdout opening 'incons-central-compsize-larger.zzip' returned error 21 +stdout opening 'incons-central-compsize-smaller.zzip' returned error 21 +stdout opening 'incons-central-crc.zzip' returned error 21 +stdout opening 'incons-central-date.zzip' returned error 21 +stdout opening 'incons-central-file-comment-longer.zzip' returned error 21 +stdout opening 'incons-central-file-comment-shorter.zzip' returned error 21 +stdout opening 'incons-central-magic-bad.zzip' returned error 19 +stdout opening 'incons-central-magic-bad2.zzip' returned error 19 +stdout opening 'incons-central-size-larger.zzip' returned error 21 +# tryopen does not test checksums, so this is fine. +stdout opening 'incons-data.zzip' succeeded, 1 entries +stdout opening 'incons-ef-central-size-wrong.zzip' returned error 21 +stdout opening 'incons-ef-local-id-size.zzip' returned error 21 +# different extra fields local vs. central is fine +stdout opening 'incons-ef-local-id.zzip' succeeded, 1 entries +stdout opening 'incons-ef-local-size.zzip' returned error 21 +stdout opening 'incons-eocd-magic-bad.zzip' returned error 19 +stdout opening 'incons-file-count-high.zzip' returned error 21 +stdout opening 'incons-file-count-low.zzip' returned error 21 +stdout opening 'incons-file-count-overflow.zzip' returned error 14 +stdout opening 'incons-local-compression-method.zzip' returned error 21 +stdout opening 'incons-local-compsize-larger.zzip' returned error 21 +stdout opening 'incons-local-compsize-smaller.zzip' returned error 21 +stdout opening 'incons-local-crc.zzip' returned error 21 +stdout opening 'incons-local-filename-long.zzip' returned error 17 +stdout opening 'incons-local-filename-missing.zzip' returned error 21 +stdout opening 'incons-local-filename-short.zzip' returned error 21 +stdout opening 'incons-local-filename.zzip' returned error 21 +stdout opening 'incons-local-magic-bad.zzip' returned error 19 +stdout opening 'incons-local-size-larger.zzip' returned error 21 +stderr 31 errors diff --git a/third_party/libzip/regress/open_many_fail.test b/third_party/libzip/regress/open_many_fail.test new file mode 100644 index 0000000..d0c154d --- /dev/null +++ b/third_party/libzip/regress/open_many_fail.test @@ -0,0 +1,11 @@ +# zip_open: files with >65k that have issues +program tryopen +args manyfiles-zip64-modulo.zzip manyfiles-fewer.zzip manyfiles-more.zzip +return 1 +file manyfiles-zip64-modulo.zzip manyfiles-zip64-modulo.zip manyfiles-zip64-modulo.zip +file manyfiles-fewer.zzip manyfiles-fewer.zip manyfiles-fewer.zip +file manyfiles-more.zzip manyfiles-more.zip manyfiles-more.zip +stdout opening 'manyfiles-zip64-modulo.zzip' returned error 21 +stdout opening 'manyfiles-fewer.zzip' returned error 21 +stdout opening 'manyfiles-more.zzip' returned error 21 +stderr 3 errors \ No newline at end of file diff --git a/third_party/libzip/regress/open_many_ok.test b/third_party/libzip/regress/open_many_ok.test new file mode 100644 index 0000000..248868d --- /dev/null +++ b/third_party/libzip/regress/open_many_ok.test @@ -0,0 +1,12 @@ +# zip_open: files open fine, have > 65k entries +program tryopen +args manyfiles.zip manyfiles-zip64.zip manyfiles-133000.zip manyfiles-65536.zip +return 0 +file manyfiles.zip manyfiles.zip manyfiles.zip +file manyfiles-zip64.zip manyfiles-zip64.zip manyfiles-zip64.zip +file manyfiles-133000.zip manyfiles-133000.zip manyfiles-133000.zip +file manyfiles-65536.zip manyfiles-65536.zip manyfiles-65536.zip +stdout opening 'manyfiles.zip' succeeded, 70000 entries +stdout opening 'manyfiles-zip64.zip' succeeded, 70000 entries +stdout opening 'manyfiles-133000.zip' succeeded, 133000 entries +stdout opening 'manyfiles-65536.zip' succeeded, 65536 entries diff --git a/third_party/libzip/regress/open_multidisk.test b/third_party/libzip/regress/open_multidisk.test new file mode 100644 index 0000000..1da4a5c --- /dev/null +++ b/third_party/libzip/regress/open_multidisk.test @@ -0,0 +1,7 @@ +# zip_open: file is part of a multi-disk zip archive +program tryopen +args test.piz +return 1 +file test.piz multidisk.zip multidisk.zip +stdout opening 'test.piz' returned error 1 +stderr 1 errors diff --git a/third_party/libzip/regress/open_new_but_exists.test b/third_party/libzip/regress/open_new_but_exists.test new file mode 100644 index 0000000..002ccb4 --- /dev/null +++ b/third_party/libzip/regress/open_new_but_exists.test @@ -0,0 +1,7 @@ +# zip_open: file shall be created but already exists +program tryopen +args -e test.zip +return 1 +file test.zip test.zip test.zip +stdout opening 'test.zip' returned error 10 +stderr 1 errors diff --git a/third_party/libzip/regress/open_new_ok.test b/third_party/libzip/regress/open_new_ok.test new file mode 100644 index 0000000..b1452c7 --- /dev/null +++ b/third_party/libzip/regress/open_new_ok.test @@ -0,0 +1,5 @@ +# zip_open: create new archive +program tryopen +args -n new.zip +return 0 +stdout opening 'new.zip' succeeded, 0 entries diff --git a/third_party/libzip/regress/open_nonarchive.test b/third_party/libzip/regress/open_nonarchive.test new file mode 100644 index 0000000..44c4836 --- /dev/null +++ b/third_party/libzip/regress/open_nonarchive.test @@ -0,0 +1,7 @@ +# zip_open: file is not a zip archive +program tryopen +file CMakeLists.txt CMakeLists.txt CMakeLists.txt +args CMakeLists.txt +return 1 +stdout opening 'CMakeLists.txt' returned error 19 +stderr 1 errors diff --git a/third_party/libzip/regress/open_nosuchfile.test b/third_party/libzip/regress/open_nosuchfile.test new file mode 100644 index 0000000..6932164 --- /dev/null +++ b/third_party/libzip/regress/open_nosuchfile.test @@ -0,0 +1,6 @@ +# zip_open: file doesn't exist +program tryopen +args nosuchfile +return 1 +stdout opening 'nosuchfile' returned error 9 +stderr 1 errors diff --git a/third_party/libzip/regress/open_ok.test b/third_party/libzip/regress/open_ok.test new file mode 100644 index 0000000..dd1f38e --- /dev/null +++ b/third_party/libzip/regress/open_ok.test @@ -0,0 +1,6 @@ +# zip_open: file opens fine +program tryopen +args test.zip +return 0 +file test.zip test.zip test.zip +stdout opening 'test.zip' succeeded, 3 entries diff --git a/third_party/libzip/regress/open_too_short.test b/third_party/libzip/regress/open_too_short.test new file mode 100644 index 0000000..b7434ba --- /dev/null +++ b/third_party/libzip/regress/open_too_short.test @@ -0,0 +1,7 @@ +# zip_open: file is too short for even a central directory entry +program tryopen +args test.piz +return 1 +file test.piz bogus.zip bogus.zip +stdout opening 'test.piz' returned error 19 +stderr 1 errors diff --git a/third_party/libzip/regress/open_truncate.test b/third_party/libzip/regress/open_truncate.test new file mode 100644 index 0000000..7ef7537 --- /dev/null +++ b/third_party/libzip/regress/open_truncate.test @@ -0,0 +1,6 @@ +# zip_open: file opens fine and gets truncated +program tryopen +args -t test.zip +return 0 +file-del test.zip test.zip +stdout opening 'test.zip' succeeded, 0 entries diff --git a/third_party/libzip/regress/open_zip64_3mf.test b/third_party/libzip/regress/open_zip64_3mf.test new file mode 100644 index 0000000..4a57154 --- /dev/null +++ b/third_party/libzip/regress/open_zip64_3mf.test @@ -0,0 +1,6 @@ +# zip_open: ZIP64 file opens fine even when most eocd entries are 0xff (3MF format) +program tryopen +args test.zip +return 0 +file test.zip zip64-3mf.zip zip64-3mf.zip +stdout opening 'test.zip' succeeded, 1 entries diff --git a/third_party/libzip/regress/open_zip64_ok.test b/third_party/libzip/regress/open_zip64_ok.test new file mode 100644 index 0000000..ac33f9a --- /dev/null +++ b/third_party/libzip/regress/open_zip64_ok.test @@ -0,0 +1,6 @@ +# zip_open: ZIP64 file opens fine +program tryopen +args test.zip +return 0 +file test.zip zip64.zip zip64.zip +stdout opening 'test.zip' succeeded, 1 entries diff --git a/third_party/libzip/regress/preload.test b/third_party/libzip/regress/preload.test new file mode 100644 index 0000000..5a62114 --- /dev/null +++ b/third_party/libzip/regress/preload.test @@ -0,0 +1,4 @@ +description test if preload works +program nonrandomopentest +return 0 +preload nonrandomopen.so diff --git a/third_party/libzip/regress/progress.test b/third_party/libzip/regress/progress.test new file mode 100644 index 0000000..8604db2 --- /dev/null +++ b/third_party/libzip/regress/progress.test @@ -0,0 +1,10 @@ +# test default compression stores if smaller; print progress +return 0 +args -n test.zip print_progress add compressable aaaaaaaaaaaaaa add uncompressable uncompressable add_nul large-compressable 8200 add_file large-uncompressable large-uncompressable 0 -1 +file-new test.zip cm-default.zip +file large-uncompressable large-uncompressable large-uncompressable +stdout 0.0% done +stdout 25.0% done +stdout 50.0% done +stdout 75.0% done +stdout 100.0% done diff --git a/third_party/libzip/regress/rename_ascii.test b/third_party/libzip/regress/rename_ascii.test new file mode 100644 index 0000000..0010ca4 --- /dev/null +++ b/third_party/libzip/regress/rename_ascii.test @@ -0,0 +1,4 @@ +# rename file to ASCII name in zip archive +return 0 +args testfile rename 0 testfile.txt +file testfile testfile-UTF8.zip testfile.zip diff --git a/third_party/libzip/regress/rename_cp437.test b/third_party/libzip/regress/rename_cp437.test new file mode 100644 index 0000000..5a01250 --- /dev/null +++ b/third_party/libzip/regress/rename_cp437.test @@ -0,0 +1,4 @@ +# rename file to CP437 name in zip archive (fails) +return 0 +args testfile.zip rename 0 ‚ƒ„…†‡ˆ‰Š‹ŒŽ +file testfile.zip testfile.zip testfile-cp437.zip diff --git a/third_party/libzip/regress/rename_deleted.test b/third_party/libzip/regress/rename_deleted.test new file mode 100644 index 0000000..9dcc7c3 --- /dev/null +++ b/third_party/libzip/regress/rename_deleted.test @@ -0,0 +1,5 @@ +# rename deleted entry in zip archive (fails) +return 1 +args testfile.zip delete 1 delete 3 rename 1 othername +file testfile.zip testcomment.zip testcomment13.zip +stderr can't rename file at index '1' to 'othername': Entry has been deleted diff --git a/third_party/libzip/regress/rename_fail.test b/third_party/libzip/regress/rename_fail.test new file mode 100644 index 0000000..185f4e2 --- /dev/null +++ b/third_party/libzip/regress/rename_fail.test @@ -0,0 +1,5 @@ +# rename file inside zip archive, but file name already exists +return 1 +args rename.zip rename 0 file4 +file rename.zip testcomment.zip testcomment.zip +stderr can't rename file at index '0' to 'file4': File already exists diff --git a/third_party/libzip/regress/rename_ok.test b/third_party/libzip/regress/rename_ok.test new file mode 100644 index 0000000..b76df9c --- /dev/null +++ b/third_party/libzip/regress/rename_ok.test @@ -0,0 +1,4 @@ +# rename file inside zip archive +return 0 +args rename.zip rename 1 notfile2 +file rename.zip testcomment.zip rename_ok.zip diff --git a/third_party/libzip/regress/rename_ok.zip b/third_party/libzip/regress/rename_ok.zip new file mode 100644 index 0000000..ad07306 Binary files /dev/null and b/third_party/libzip/regress/rename_ok.zip differ diff --git a/third_party/libzip/regress/rename_utf8.test b/third_party/libzip/regress/rename_utf8.test new file mode 100644 index 0000000..391ebeb --- /dev/null +++ b/third_party/libzip/regress/rename_utf8.test @@ -0,0 +1,4 @@ +# rename file to UTF-8 name in zip archive +return 0 +args testfile rename 0 ÄÖÜßäöü +file testfile testfile.zip testfile-UTF8.zip diff --git a/third_party/libzip/regress/rename_utf8_encmismatch.test b/third_party/libzip/regress/rename_utf8_encmismatch.test new file mode 100644 index 0000000..075bca1 --- /dev/null +++ b/third_party/libzip/regress/rename_utf8_encmismatch.test @@ -0,0 +1,4 @@ +# rename file to UTF-8 name in zip archive with CP437 comment (sets InfoZIP UTF-8 Name Extension) +return 0 +args testfile rename 0 ÄÖÜßäöü +file testfile test-cp437-fc.zip test-cp437-fc-utf-8-filename.zip diff --git a/third_party/libzip/regress/runtest.in b/third_party/libzip/regress/runtest.in new file mode 100644 index 0000000..a6eb140 --- /dev/null +++ b/third_party/libzip/regress/runtest.in @@ -0,0 +1,60 @@ +#!/usr/bin/env perl + +# runtest -- run regression tests +# Copyright (C) 2002-2014 Dieter Baron and Thomas Klausner +# +# This file is part of ckmame, a program to check rom sets for MAME. +# The authors can be contacted at +# +# 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. +# 3. The names of the authors may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. + + +use strict; + +BEGIN { push @INC, '@abs_srcdir@'; } + +use NiHTest; + +my $test = NiHTest::new({ default_program => 'ziptool_regress', srcdir => '@srcdir@', top_builddir => '@top_builddir@', zipcmp => '../../src/zipcmp', zipcmp_flags => '-p' }); + +sub mangle_test { + my ($test, $variant) = @_; + + if (defined($test->{test}->{preload})) { + if (!defined($test->{test}->{features})) { + $test->{test}->{features} = []; + } + push @{$test->{test}->{features}}, 'SHARED'; + } + + return 1; +} + + +$test->add_comparator('zip/zip', \&NiHTest::comparator_zip); +$test->add_hook('post_parse', \&mangle_test); + +$test->run(@ARGV); diff --git a/third_party/libzip/regress/set_comment_all.test b/third_party/libzip/regress/set_comment_all.test new file mode 100644 index 0000000..5902f98 --- /dev/null +++ b/third_party/libzip/regress/set_comment_all.test @@ -0,0 +1,4 @@ +# change local and global comments in a zip archive +return 0 +args testcomment.zip set_archive_comment "This is the new,\r\nmultiline archive comment.\r\nAin't it nice?" set_file_comment 0 "File comment no 0" set_file_comment 1 "File comment no 1" set_file_comment 2 "File comment no 2" set_file_comment 3 "File comment no 3" +file testcomment.zip testcomment.zip testchanged.zip diff --git a/third_party/libzip/regress/set_comment_localonly.test b/third_party/libzip/regress/set_comment_localonly.test new file mode 100644 index 0000000..08f7b8e --- /dev/null +++ b/third_party/libzip/regress/set_comment_localonly.test @@ -0,0 +1,4 @@ +# change file comments in a zip archive +return 0 +args testcomment.zip set_file_comment 0 "File comment no 0" set_file_comment 1 "File comment no 1" set_file_comment 3 "File comment no 3" set_file_comment 2 "" +file testcomment.zip testcomment.zip testchangedlocal.zip diff --git a/third_party/libzip/regress/set_comment_removeglobal.test b/third_party/libzip/regress/set_comment_removeglobal.test new file mode 100644 index 0000000..b469b37 --- /dev/null +++ b/third_party/libzip/regress/set_comment_removeglobal.test @@ -0,0 +1,4 @@ +# remove archive comment +return 0 +args testcomment.zip set_archive_comment "" +file testcomment.zip testcomment.zip testcommentremoved.zip diff --git a/third_party/libzip/regress/set_comment_revert.test b/third_party/libzip/regress/set_comment_revert.test new file mode 100644 index 0000000..da61c37 --- /dev/null +++ b/third_party/libzip/regress/set_comment_revert.test @@ -0,0 +1,4 @@ +# start changing local and global comments, but revert before closing +return 0 +args testcomment.zip set_archive_comment "some long string, a bit longer than this at least" set_file_comment 0 "File comment no 0" set_file_comment 1 "File comment no 1" set_file_comment 3 "File comment no 3" set_file_comment 2 "" unchange_all +file testcomment.zip testcomment.zip testcomment.zip diff --git a/third_party/libzip/regress/set_compression_bzip2_to_deflate.test b/third_party/libzip/regress/set_compression_bzip2_to_deflate.test new file mode 100644 index 0000000..bdfacb5 --- /dev/null +++ b/third_party/libzip/regress/set_compression_bzip2_to_deflate.test @@ -0,0 +1,5 @@ +# change method from bzip2 to deflated +features LIBBZ2 +return 0 +args test.zip set_file_compression 0 deflate 0 +file test.zip testbzip2.zip testdeflated.zip diff --git a/third_party/libzip/regress/set_compression_deflate_to_bzip2.test b/third_party/libzip/regress/set_compression_deflate_to_bzip2.test new file mode 100644 index 0000000..197b435 --- /dev/null +++ b/third_party/libzip/regress/set_compression_deflate_to_bzip2.test @@ -0,0 +1,5 @@ +# change method from deflated to bzip2 +features LIBBZ2 +return 0 +args test.zip set_file_compression 0 bzip2 0 +file test.zip testdeflated.zip testbzip2.zip diff --git a/third_party/libzip/regress/set_compression_deflate_to_deflate.test b/third_party/libzip/regress/set_compression_deflate_to_deflate.test new file mode 100644 index 0000000..e0b3121 --- /dev/null +++ b/third_party/libzip/regress/set_compression_deflate_to_deflate.test @@ -0,0 +1,4 @@ +# change method from deflated to deflated (no change) +return 0 +args test.zip set_file_compression 0 deflate 0 +file test.zip testdeflated.zip testdeflated.zip diff --git a/third_party/libzip/regress/set_compression_deflate_to_store.test b/third_party/libzip/regress/set_compression_deflate_to_store.test new file mode 100644 index 0000000..1678b9c --- /dev/null +++ b/third_party/libzip/regress/set_compression_deflate_to_store.test @@ -0,0 +1,4 @@ +# change method from deflated to stored +return 0 +args test.zip set_file_compression 0 store 0 +file test.zip testdeflated.zip teststored.zip diff --git a/third_party/libzip/regress/set_compression_store_to_bzip2.test b/third_party/libzip/regress/set_compression_store_to_bzip2.test new file mode 100644 index 0000000..28bddd7 --- /dev/null +++ b/third_party/libzip/regress/set_compression_store_to_bzip2.test @@ -0,0 +1,5 @@ +# change method from stored to bzip2 +features LIBBZ2 +return 0 +args test.zip set_file_compression 0 bzip2 0 +file test.zip teststored.zip testbzip2.zip diff --git a/third_party/libzip/regress/set_compression_store_to_deflate.test b/third_party/libzip/regress/set_compression_store_to_deflate.test new file mode 100644 index 0000000..1f83492 --- /dev/null +++ b/third_party/libzip/regress/set_compression_store_to_deflate.test @@ -0,0 +1,4 @@ +# change method from stored to deflated +return 0 +args test.zip set_file_compression 0 deflate 0 +file test.zip teststored.zip testdeflated.zip diff --git a/third_party/libzip/regress/set_compression_store_to_store.test b/third_party/libzip/regress/set_compression_store_to_store.test new file mode 100644 index 0000000..66cf3dd --- /dev/null +++ b/third_party/libzip/regress/set_compression_store_to_store.test @@ -0,0 +1,4 @@ +# change method from stored to stored (no change) +return 0 +args test.zip set_file_compression 0 store 0 +file test.zip teststored.zip teststored.zip diff --git a/third_party/libzip/regress/set_compression_unknown.test b/third_party/libzip/regress/set_compression_unknown.test new file mode 100644 index 0000000..9ebf688 --- /dev/null +++ b/third_party/libzip/regress/set_compression_unknown.test @@ -0,0 +1,5 @@ +# change method to unknown +return 1 +args test.zip set_file_compression 0 unknown 0 +file test.zip teststored.zip teststored.zip +stderr can't set file compression method at index '0' to 'unknown', flags '0': Compression method not supported diff --git a/third_party/libzip/regress/set_file_mtime.test b/third_party/libzip/regress/set_file_mtime.test new file mode 100644 index 0000000..477fd06 --- /dev/null +++ b/third_party/libzip/regress/set_file_mtime.test @@ -0,0 +1,4 @@ +# change mtime in a zip archive +return 0 +args testfile set_file_mtime 0 1407272201 +file testfile testfile.zip testfile2014.zip diff --git a/third_party/libzip/regress/source_hole.c b/third_party/libzip/regress/source_hole.c new file mode 100644 index 0000000..dc3eec3 --- /dev/null +++ b/third_party/libzip/regress/source_hole.c @@ -0,0 +1,573 @@ +/* + source_hole.c -- source for handling huge files that are mostly NULs + Copyright (C) 2014-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include "zip.h" + +/* public API */ + +zip_source_t *source_hole_create(const char *, int flags, zip_error_t *); + + +#ifndef EFTYPE +#define EFTYPE EINVAL +#endif + + +#define MY_MIN(a, b) ((a) < (b) ? (a) : (b)) + +#define FRAGMENT_SIZE (8 * 1024) + +#define MARK_BEGIN "NiH0" +#define MARK_DATA "NiH1" +#define MARK_NUL "NiH2" + + +typedef struct buffer { + zip_uint64_t fragment_size; + zip_uint8_t **fragment; + zip_uint64_t nfragments; + zip_uint64_t size; + zip_uint64_t offset; +} buffer_t; + +static void buffer_free(buffer_t *buffer); +static buffer_t *buffer_from_file(const char *fname, int flags, zip_error_t *error); +static buffer_t *buffer_new(void); +static zip_int64_t buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length, zip_error_t *error); +static int buffer_read_file(buffer_t *buffer, FILE *f, zip_error_t *error); +static zip_int64_t buffer_seek(buffer_t *buffer, void *data, zip_uint64_t length, zip_error_t *error); +static int buffer_to_file(buffer_t *buffer, const char *fname, zip_error_t *error); +static zip_int64_t buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *error); +static zip_uint64_t get_u64(const zip_uint8_t *b); +static int only_nul(const zip_uint8_t *data, zip_uint64_t length); +static int write_nuls(zip_uint64_t n, FILE *f); +static int write_u64(zip_uint64_t u64, FILE *f); + + +typedef struct hole { + zip_error_t error; + char *fname; + buffer_t *in; + buffer_t *out; +} hole_t; + +static hole_t *hole_new(const char *fname, int flags, zip_error_t *error); +static zip_int64_t source_hole_cb(void *ud, void *data, zip_uint64_t length, zip_source_cmd_t command); + + +zip_source_t * +source_hole_create(const char *fname, int flags, zip_error_t *error) { + hole_t *ud = hole_new(fname, flags, error); + + if (ud == NULL) { + return NULL; + } + return zip_source_function_create(source_hole_cb, ud, error); +} + + +static void +buffer_free(buffer_t *buffer) { + zip_uint64_t i; + + if (buffer == NULL) { + return; + } + + if (buffer->fragment) { + for (i = 0; i < buffer->nfragments; i++) { + free(buffer->fragment[i]); + } + free(buffer->fragment); + } + free(buffer); +} + + +static buffer_t * +buffer_from_file(const char *fname, int flags, zip_error_t *error) { + buffer_t *buffer; + FILE *f; + + if ((buffer = buffer_new()) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((flags & ZIP_TRUNCATE) == 0) { + if ((f = fopen(fname, "rb")) == NULL) { + if (!(errno == ENOENT && (flags & ZIP_CREATE))) { + buffer_free(buffer); + return NULL; + } + } + else { + if (buffer_read_file(buffer, f, error) < 0) { + buffer_free(buffer); + fclose(f); + return NULL; + } + fclose(f); + } + } + + return buffer; +} + + +static buffer_t * +buffer_new(void) { + buffer_t *buffer; + + if ((buffer = (buffer_t *)malloc(sizeof(*buffer))) == NULL) { + return NULL; + } + + buffer->fragment = NULL; + buffer->nfragments = 0; + buffer->fragment_size = FRAGMENT_SIZE; + buffer->size = 0; + buffer->offset = 0; + + return buffer; +} + + +static zip_int64_t +buffer_read(buffer_t *buffer, zip_uint8_t *data, zip_uint64_t length, zip_error_t *error) { + zip_uint64_t n, i, fragment_offset; + + length = MY_MIN(length, buffer->size - buffer->offset); + + if (length == 0) { + return 0; + } + if (length > ZIP_INT64_MAX) { + return -1; + } + + i = buffer->offset / buffer->fragment_size; + fragment_offset = buffer->offset % buffer->fragment_size; + n = 0; + while (n < length) { + zip_uint64_t left = MY_MIN(length - n, buffer->fragment_size - fragment_offset); + + if (buffer->fragment[i]) { + memcpy(data + n, buffer->fragment[i] + fragment_offset, left); + } + else { + memset(data + n, 0, left); + } + + n += left; + i++; + fragment_offset = 0; + } + + buffer->offset += n; + return (zip_int64_t)n; +} + + +static int +buffer_read_file(buffer_t *buffer, FILE *f, zip_error_t *error) { + zip_uint8_t b[20]; + zip_uint64_t i; + + if (fread(b, 20, 1, f) != 1) { + zip_error_set(error, ZIP_ER_READ, errno); + return -1; + } + + if (memcmp(b, MARK_BEGIN, 4) != 0) { + zip_error_set(error, ZIP_ER_READ, EFTYPE); + return -1; + } + + buffer->fragment_size = get_u64(b + 4); + buffer->size = get_u64(b + 12); + + if (buffer->size + buffer->fragment_size < buffer->size) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + buffer->nfragments = (buffer->size + buffer->fragment_size - 1) / buffer->fragment_size; + if ((buffer->nfragments > SIZE_MAX / sizeof(buffer->fragment[0])) || ((buffer->fragment = (zip_uint8_t **)malloc(sizeof(buffer->fragment[0]) * buffer->nfragments)) == NULL)) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + + for (i = 0; i < buffer->nfragments; i++) { + buffer->fragment[i] = NULL; + } + + i = 0; + while (i < buffer->nfragments) { + if (fread(b, 4, 1, f) != 1) { + zip_error_set(error, ZIP_ER_READ, errno); + return -1; + } + + if (memcmp(b, MARK_DATA, 4) == 0) { + if (buffer->fragment_size > SIZE_MAX) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + if ((buffer->fragment[i] = (zip_uint8_t *)malloc(buffer->fragment_size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + if (fread(buffer->fragment[i], buffer->fragment_size, 1, f) != 1) { + zip_error_set(error, ZIP_ER_READ, errno); + return -1; + } + i++; + } + else if (memcmp(b, MARK_NUL, 4) == 0) { + if (fread(b, 8, 1, f) != 1) { + zip_error_set(error, ZIP_ER_READ, errno); + return -1; + } + i += get_u64(b); + } + else { + zip_error_set(error, ZIP_ER_READ, EFTYPE); + return -1; + } + } + + return 0; +} + +static zip_int64_t +buffer_seek(buffer_t *buffer, void *data, zip_uint64_t length, zip_error_t *error) { + zip_int64_t new_offset = zip_source_seek_compute_offset(buffer->offset, buffer->size, data, length, error); + + if (new_offset < 0) { + return -1; + } + + buffer->offset = (zip_uint64_t)new_offset; + return 0; +} + + +static int +buffer_to_file(buffer_t *buffer, const char *fname, zip_error_t *error) { + FILE *f = fopen(fname, "wb"); + zip_uint64_t i; + zip_uint64_t nul_run; + + if (f == NULL) { + zip_error_set(error, ZIP_ER_OPEN, errno); + return -1; + } + + fwrite(MARK_BEGIN, 4, 1, f); + write_u64(buffer->fragment_size, f); + write_u64(buffer->size, f); + + nul_run = 0; + for (i = 0; i * buffer->fragment_size < buffer->size; i++) { + if (buffer->fragment[i] == NULL || only_nul(buffer->fragment[i], buffer->fragment_size)) { + nul_run++; + } + else { + if (nul_run > 0) { + write_nuls(nul_run, f); + nul_run = 0; + } + fwrite(MARK_DATA, 4, 1, f); + + fwrite(buffer->fragment[i], 1, buffer->fragment_size, f); + } + } + + if (nul_run > 0) { + write_nuls(nul_run, f); + } + + if (fclose(f) != 0) { + zip_error_set(error, ZIP_ER_WRITE, errno); + return -1; + } + + return 0; +} + + +static zip_int64_t +buffer_write(buffer_t *buffer, const zip_uint8_t *data, zip_uint64_t length, zip_error_t *error) { + zip_uint8_t **fragment; + if (buffer->offset + length > buffer->nfragments * buffer->fragment_size) { + zip_uint64_t needed_fragments = (buffer->offset + length + buffer->fragment_size - 1) / buffer->fragment_size; + zip_uint64_t new_capacity = buffer->nfragments; + zip_uint64_t i; + + if (new_capacity == 0) { + new_capacity = 4; + } + while (new_capacity < needed_fragments) { + new_capacity *= 2; + } + + fragment = realloc(buffer->fragment, new_capacity * sizeof(*fragment)); + + if (fragment == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + + for (i = buffer->nfragments; i < new_capacity; i++) { + fragment[i] = NULL; + } + + buffer->fragment = fragment; + buffer->nfragments = new_capacity; + } + + if (!only_nul(data, length)) { + zip_uint64_t idx, n, fragment_offset; + + idx = buffer->offset / buffer->fragment_size; + fragment_offset = buffer->offset % buffer->fragment_size; + n = 0; + + while (n < length) { + zip_uint64_t left = MY_MIN(length - n, buffer->fragment_size - fragment_offset); + + if (buffer->fragment[idx] == NULL) { + if ((buffer->fragment[idx] = (zip_uint8_t *)malloc(buffer->fragment_size)) == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return -1; + } + memset(buffer->fragment[idx], 0, buffer->fragment_size); + } + memcpy(buffer->fragment[idx] + fragment_offset, data + n, left); + + n += left; + idx++; + fragment_offset = 0; + } + } + + buffer->offset += length; + if (buffer->offset > buffer->size) { + buffer->size = buffer->offset; + } + + return (zip_int64_t)length; +} + + +static zip_uint64_t +get_u64(const zip_uint8_t *b) { + zip_uint64_t i; + + i = (zip_uint64_t)b[0] << 56 | (zip_uint64_t)b[1] << 48 | (zip_uint64_t)b[2] << 40 | (zip_uint64_t)b[3] << 32 | (zip_uint64_t)b[4] << 24 | (zip_uint64_t)b[5] << 16 | (zip_uint64_t)b[6] << 8 | (zip_uint64_t)b[7]; + + return i; +} + + +static int +only_nul(const zip_uint8_t *data, zip_uint64_t length) { + zip_uint64_t i; + + for (i = 0; i < length; i++) { + if (data[i] != '\0') { + return 0; + } + } + + return 1; +} + + +static int +write_nuls(zip_uint64_t n, FILE *f) { + if (fwrite(MARK_NUL, 4, 1, f) != 1) { + return -1; + } + return write_u64(n, f); +} + + +static int +write_u64(zip_uint64_t u64, FILE *f) { + zip_uint8_t b[8]; + + b[0] = (zip_uint8_t)((u64 >> 56) & 0xff); + b[1] = (zip_uint8_t)((u64 >> 48) & 0xff); + b[2] = (zip_uint8_t)((u64 >> 40) & 0xff); + b[3] = (zip_uint8_t)((u64 >> 32) & 0xff); + b[4] = (zip_uint8_t)((u64 >> 24) & 0xff); + b[5] = (zip_uint8_t)((u64 >> 16) & 0xff); + b[6] = (zip_uint8_t)((u64 >> 8) & 0xff); + b[7] = (zip_uint8_t)(u64 & 0xff); + + return fwrite(b, 8, 1, f) == 1 ? 0 : -1; +} + + +static void +hole_free(hole_t *hole) { + if (hole == NULL) { + return; + } + zip_error_fini(&hole->error); + buffer_free(hole->in); + buffer_free(hole->out); + free(hole->fname); + free(hole); +} + + +static hole_t * +hole_new(const char *fname, int flags, zip_error_t *error) { + hole_t *ctx = (hole_t *)malloc(sizeof(*ctx)); + + if (ctx == NULL) { + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->fname = strdup(fname)) == NULL) { + free(ctx); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + + if ((ctx->in = buffer_from_file(fname, flags, error)) == NULL) { + free(ctx); + return NULL; + } + + zip_error_init(&ctx->error); + ctx->out = NULL; + + return ctx; +} + + +static zip_int64_t +source_hole_cb(void *ud, void *data, zip_uint64_t length, zip_source_cmd_t command) { + hole_t *ctx = (hole_t *)ud; + + switch (command) { + case ZIP_SOURCE_BEGIN_WRITE: + ctx->out = buffer_new(); + return 0; + + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_COMMIT_WRITE: + if (buffer_to_file(ctx->out, ctx->fname, &ctx->error) < 0) { + return -1; + } + buffer_free(ctx->in); + ctx->in = ctx->out; + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, length); + + case ZIP_SOURCE_FREE: + hole_free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + ctx->in->offset = 0; + return 0; + + case ZIP_SOURCE_READ: + return buffer_read(ctx->in, data, length, &ctx->error); + + case ZIP_SOURCE_REMOVE: + buffer_free(ctx->in); + ctx->in = buffer_new(); + buffer_free(ctx->out); + ctx->out = NULL; + (void)remove(ctx->fname); + return 0; + + case ZIP_SOURCE_ROLLBACK_WRITE: + buffer_free(ctx->out); + ctx->out = NULL; + return 0; + + case ZIP_SOURCE_SEEK: + return buffer_seek(ctx->in, data, length, &ctx->error); + + case ZIP_SOURCE_SEEK_WRITE: + return buffer_seek(ctx->out, data, length, &ctx->error); + + case ZIP_SOURCE_STAT: { + zip_stat_t *st = ZIP_SOURCE_GET_ARGS(zip_stat_t, data, length, &ctx->error); + + if (st == NULL) { + return -1; + } + + /* TODO: return ENOENT if fname doesn't exist */ + + st->valid |= ZIP_STAT_SIZE; + st->size = ctx->in->size; + return 0; + } + + case ZIP_SOURCE_TELL: + return (zip_int64_t)ctx->in->offset; + + case ZIP_SOURCE_TELL_WRITE: + return (zip_int64_t)ctx->out->offset; + + case ZIP_SOURCE_WRITE: + return buffer_write(ctx->out, data, length, &ctx->error); + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_CLOSE, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_REMOVE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_STAT, ZIP_SOURCE_TELL, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_WRITE, -1); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} diff --git a/third_party/libzip/regress/stat_index_cp437_guess.test b/third_party/libzip/regress/stat_index_cp437_guess.test new file mode 100644 index 0000000..f1abd1a --- /dev/null +++ b/third_party/libzip/regress/stat_index_cp437_guess.test @@ -0,0 +1,148 @@ +# guess CP437 file names and autoconvert them +args test-cp437.zip stat 0 stat 1 stat 2 stat 3 stat 4 stat 5 stat 6 stat 7 stat 8 stat 9 stat 10 stat 11 stat 12 stat 13 stat 14 stat 15 +return 0 +file test-cp437.zip test-cp437.zip test-cp437.zip +stdout name: '☺☻♥♦♣♠•○◘◙♂♀♪♫☼►' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '◄↕‼¶§▬↨↑↓→â†âˆŸâ†”▲▼ ' +stdout index: '1' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '!"#$%&'()*+,-./0' +stdout index: '2' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:58' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '123456789:;<=>?@' +stdout index: '3' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:04' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ABCDEFGHIJKLMNOP' +stdout index: '4' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'QRSTUVWXYZ[\]^_`' +stdout index: '5' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:12' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'abcdefghijklmnop' +stdout index: '6' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:18' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'qrstuvwxyz{|}~~Ç' +stdout index: '7' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:22' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'üéâäàåçêëèïîìÄÅÉ' +stdout index: '8' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:26' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'æÆôöòûùÿÖÜ¢£¥₧ƒá' +stdout index: '9' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:30' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'íóúñѪº¿âŒÂ¬Â½Â¼Â¡Â«Â»â–‘' +stdout index: '10' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:36' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '▒▓│┤╡╢╖╕╣║╗â•╜╛â”â””' +stdout index: '11' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:40' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨' +stdout index: '12' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:44' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '╤╥╙╘╒╓╫╪┘┌█▄▌â–▀α' +stdout index: '13' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ßΓπΣσµτΦΘΩδ∞φε∩≡' +stdout index: '14' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â Â ' +stdout index: '15' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:53:02' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_cp437_raw.test b/third_party/libzip/regress/stat_index_cp437_raw.test new file mode 100644 index 0000000..79104f0 --- /dev/null +++ b/third_party/libzip/regress/stat_index_cp437_raw.test @@ -0,0 +1,149 @@ +# get raw file names them from archive +args -r test-cp437.zip stat 0 stat 1 stat 2 stat 3 stat 4 stat 5 stat 6 stat 7 stat 8 stat 9 stat 10 stat 11 stat 12 stat 13 stat 14 stat 15 +return 0 +file test-cp437.zip test-cp437.zip test-cp437.zip +stdout name: '  +stdout ' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: ' ' +stdout index: '1' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '!"#$%&'()*+,-./0' +stdout index: '2' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:58' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '123456789:;<=>?@' +stdout index: '3' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:04' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ABCDEFGHIJKLMNOP' +stdout index: '4' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'QRSTUVWXYZ[\]^_`' +stdout index: '5' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:12' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'abcdefghijklmnop' +stdout index: '6' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:18' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'qrstuvwxyz{|}~~€' +stdout index: '7' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:22' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '‚ƒ„…†‡ˆ‰Š‹ŒŽ' +stdout index: '8' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:26' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '‘’“”•–—˜™š›œžŸ ' +stdout index: '9' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:30' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '¡¢£¤¥¦§¨©ª«¬­®¯°' +stdout index: '10' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:36' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '±²³´µ¶·¸¹º»¼½¾¿À' +stdout index: '11' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:40' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐ' +stdout index: '12' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:44' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ÑÒÓÔÕÖרÙÚÛÜÝÞßà' +stdout index: '13' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'áâãäåæçèéêëìíîïð' +stdout index: '14' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ñòóôõö÷øùúûüýþÿÿ' +stdout index: '15' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:53:02' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_cp437_strict.test b/third_party/libzip/regress/stat_index_cp437_strict.test new file mode 100644 index 0000000..a34a0e6 --- /dev/null +++ b/third_party/libzip/regress/stat_index_cp437_strict.test @@ -0,0 +1,148 @@ +# strictly follow ZIP spec and expect CP437 file names, and autoconvert them +args -s test-cp437.zip stat 0 stat 1 stat 2 stat 3 stat 4 stat 5 stat 6 stat 7 stat 8 stat 9 stat 10 stat 11 stat 12 stat 13 stat 14 stat 15 +return 0 +file test-cp437.zip test-cp437.zip test-cp437.zip +stdout name: '☺☻♥♦♣♠•○◘◙♂♀♪♫☼►' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '◄↕‼¶§▬↨↑↓→â†âˆŸâ†”▲▼ ' +stdout index: '1' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '!"#$%&'()*+,-./0' +stdout index: '2' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:51:58' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '123456789:;<=>?@' +stdout index: '3' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:04' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ABCDEFGHIJKLMNOP' +stdout index: '4' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'QRSTUVWXYZ[\]^_`' +stdout index: '5' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:12' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'abcdefghijklmnop' +stdout index: '6' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:18' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'qrstuvwxyz{|}~~Ç' +stdout index: '7' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:22' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'üéâäàåçêëèïîìÄÅÉ' +stdout index: '8' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:26' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'æÆôöòûùÿÖÜ¢£¥₧ƒá' +stdout index: '9' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:30' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'íóúñѪº¿âŒÂ¬Â½Â¼Â¡Â«Â»â–‘' +stdout index: '10' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:36' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '▒▓│┤╡╢╖╕╣║╗â•╜╛â”â””' +stdout index: '11' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:40' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '┴┬├─┼╞╟╚╔╩╦╠â•╬╧╨' +stdout index: '12' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:44' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '╤╥╙╘╒╓╫╪┘┌█▄▌â–▀α' +stdout index: '13' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:50' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'ßΓπΣσµτΦΘΩδ∞φε∩≡' +stdout index: '14' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:52:54' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: '±≥≤⌠⌡÷≈°∙·√â¿Â²â– Â Â ' +stdout index: '15' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Feb 17 2012 20:53:02' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_fileorder.test b/third_party/libzip/regress/stat_index_fileorder.test new file mode 100644 index 0000000..24b02b4 --- /dev/null +++ b/third_party/libzip/regress/stat_index_fileorder.test @@ -0,0 +1,22 @@ +# zip_open: entries ordered by central directory order +args fileorder.zzip stat 0 stat 1 +return 0 +file fileorder.zzip fileorder.zip fileorder.zip +stdout name: 'file1' +stdout index: '0' +stdout size: '5' +stdout compressed size: '5' +stdout mtime: 'Fri Apr 27 2012 23:21:42' +stdout crc: '9ee760e5' +stdout compression method: '0' +stdout encryption method: '0' +stdout +stdout name: 'file2' +stdout index: '1' +stdout size: '5' +stdout compressed size: '5' +stdout mtime: 'Fri Apr 27 2012 23:21:44' +stdout crc: '7ee315f' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_streamed.test b/third_party/libzip/regress/stat_index_streamed.test new file mode 100644 index 0000000..a2b3048 --- /dev/null +++ b/third_party/libzip/regress/stat_index_streamed.test @@ -0,0 +1,13 @@ +# stat file in streamed zip file +args streamed stat 0 +file streamed streamed.zip streamed.zip +return 0 +stdout name: '-' +stdout index: '0' +stdout size: '2' +stdout compressed size: '4' +stdout mtime: 'Wed Apr 25 2012 10:20:38' +stdout crc: 'ddeaa107' +stdout compression method: '8' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_streamed_zip64.test b/third_party/libzip/regress/stat_index_streamed_zip64.test new file mode 100644 index 0000000..18a8694 --- /dev/null +++ b/third_party/libzip/regress/stat_index_streamed_zip64.test @@ -0,0 +1,13 @@ +# stat file in streamed zip file +args streamed stat 0 +file streamed streamed-zip64.zip streamed-zip64.zip +return 0 +stdout name: '-' +stdout index: '0' +stdout size: '2' +stdout compressed size: '4' +stdout mtime: 'Wed Apr 25 2012 10:20:38' +stdout crc: 'ddeaa107' +stdout compression method: '8' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_utf8_guess.test b/third_party/libzip/regress/stat_index_utf8_guess.test new file mode 100644 index 0000000..898db2d --- /dev/null +++ b/third_party/libzip/regress/stat_index_utf8_guess.test @@ -0,0 +1,13 @@ +# guess UTF-8 file names +args test-utf8.zip stat 0 +return 0 +file test-utf8.zip test-utf8.zip test-utf8.zip +stdout name: 'ÄÖÜäöüßćçĉéèêëē' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Sat Feb 18 2012 00:15:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_utf8_raw.test b/third_party/libzip/regress/stat_index_utf8_raw.test new file mode 100644 index 0000000..881a18b --- /dev/null +++ b/third_party/libzip/regress/stat_index_utf8_raw.test @@ -0,0 +1,13 @@ +# print UTF-8 file names +args -r test-utf8.zip stat 0 +return 0 +file test-utf8.zip test-utf8.zip test-utf8.zip +stdout name: 'ÄÖÜäöüßćçĉéèêëē' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Sat Feb 18 2012 00:15:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_utf8_strict.test b/third_party/libzip/regress/stat_index_utf8_strict.test new file mode 100644 index 0000000..af1bb81 --- /dev/null +++ b/third_party/libzip/regress/stat_index_utf8_strict.test @@ -0,0 +1,14 @@ +# follow strict rules and convert UTF-8 as if it was CP437, but not +# if the files are marked as having UTF-8 names +args -s test-utf8.zip stat 0 +return 0 +file test-utf8.zip test-utf8.zip test-utf8.zip +stdout name: 'ÄÖÜäöüßćçĉéèêëē' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Sat Feb 18 2012 00:15:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_utf8_unmarked_strict.test b/third_party/libzip/regress/stat_index_utf8_unmarked_strict.test new file mode 100644 index 0000000..07954dd --- /dev/null +++ b/third_party/libzip/regress/stat_index_utf8_unmarked_strict.test @@ -0,0 +1,14 @@ +# follow strict rules and convert UTF-8 as if it was CP437, +# if not marked otherwise (in this case: not marked) +args -s test-utf8-unmarked.zip stat 0 +return 0 +file test-utf8-unmarked.zip test-utf8-unmarked.zip test-utf8-unmarked.zip +stdout name: '├ä├û├£├ñ├╢├â•├ƒ─ç├º─ë├âŒâ”œÂ¿â”œÂ¬â”œÂ½â”€Ã´' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Sat Feb 18 2012 00:15:08' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/stat_index_zip64.test b/third_party/libzip/regress/stat_index_zip64.test new file mode 100644 index 0000000..c3f420c --- /dev/null +++ b/third_party/libzip/regress/stat_index_zip64.test @@ -0,0 +1,13 @@ +# stat file in zip64 zip file +args bigzero stat 0 +file bigzero bigzero.zip bigzero.zip +return 0 +stdout name: 'bigzero' +stdout index: '0' +stdout size: '4294967296' +stdout compressed size: '4168157' +stdout mtime: 'Thu Mar 15 2012 14:54:06' +stdout crc: 'd202ef8d' +stdout compression method: '8' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/streamed-zip64.zip b/third_party/libzip/regress/streamed-zip64.zip new file mode 100644 index 0000000..8588619 Binary files /dev/null and b/third_party/libzip/regress/streamed-zip64.zip differ diff --git a/third_party/libzip/regress/streamed.zip b/third_party/libzip/regress/streamed.zip new file mode 100644 index 0000000..737d56f Binary files /dev/null and b/third_party/libzip/regress/streamed.zip differ diff --git a/third_party/libzip/regress/test-cp437-comment-utf-8.zip b/third_party/libzip/regress/test-cp437-comment-utf-8.zip new file mode 100644 index 0000000..04fbaac Binary files /dev/null and b/third_party/libzip/regress/test-cp437-comment-utf-8.zip differ diff --git a/third_party/libzip/regress/test-cp437-fc-utf-8-filename.zip b/third_party/libzip/regress/test-cp437-fc-utf-8-filename.zip new file mode 100644 index 0000000..7aeb809 Binary files /dev/null and b/third_party/libzip/regress/test-cp437-fc-utf-8-filename.zip differ diff --git a/third_party/libzip/regress/test-cp437-fc.zip b/third_party/libzip/regress/test-cp437-fc.zip new file mode 100644 index 0000000..0c4f04d Binary files /dev/null and b/third_party/libzip/regress/test-cp437-fc.zip differ diff --git a/third_party/libzip/regress/test-cp437.zip b/third_party/libzip/regress/test-cp437.zip new file mode 100644 index 0000000..066531e Binary files /dev/null and b/third_party/libzip/regress/test-cp437.zip differ diff --git a/third_party/libzip/regress/test-utf8-unmarked.zip b/third_party/libzip/regress/test-utf8-unmarked.zip new file mode 100644 index 0000000..1bcb703 Binary files /dev/null and b/third_party/libzip/regress/test-utf8-unmarked.zip differ diff --git a/third_party/libzip/regress/test-utf8.zip b/third_party/libzip/regress/test-utf8.zip new file mode 100644 index 0000000..3045e20 Binary files /dev/null and b/third_party/libzip/regress/test-utf8.zip differ diff --git a/third_party/libzip/regress/test.zip b/third_party/libzip/regress/test.zip new file mode 100644 index 0000000..e4efd71 Binary files /dev/null and b/third_party/libzip/regress/test.zip differ diff --git a/third_party/libzip/regress/test2.zip b/third_party/libzip/regress/test2.zip new file mode 100644 index 0000000..ed2f60f Binary files /dev/null and b/third_party/libzip/regress/test2.zip differ diff --git a/third_party/libzip/regress/testbuffer.zip b/third_party/libzip/regress/testbuffer.zip new file mode 100644 index 0000000..91e7d8a Binary files /dev/null and b/third_party/libzip/regress/testbuffer.zip differ diff --git a/third_party/libzip/regress/testbzip2.zip b/third_party/libzip/regress/testbzip2.zip new file mode 100644 index 0000000..7c9a9e7 Binary files /dev/null and b/third_party/libzip/regress/testbzip2.zip differ diff --git a/third_party/libzip/regress/testchanged.zip b/third_party/libzip/regress/testchanged.zip new file mode 100644 index 0000000..d5169c9 Binary files /dev/null and b/third_party/libzip/regress/testchanged.zip differ diff --git a/third_party/libzip/regress/testchangedlocal.zip b/third_party/libzip/regress/testchangedlocal.zip new file mode 100644 index 0000000..1c8b301 Binary files /dev/null and b/third_party/libzip/regress/testchangedlocal.zip differ diff --git a/third_party/libzip/regress/testcomment.zip b/third_party/libzip/regress/testcomment.zip new file mode 100644 index 0000000..45dc18d Binary files /dev/null and b/third_party/libzip/regress/testcomment.zip differ diff --git a/third_party/libzip/regress/testcomment13.zip b/third_party/libzip/regress/testcomment13.zip new file mode 100644 index 0000000..bd6e1c3 Binary files /dev/null and b/third_party/libzip/regress/testcomment13.zip differ diff --git a/third_party/libzip/regress/testcommentremoved.zip b/third_party/libzip/regress/testcommentremoved.zip new file mode 100644 index 0000000..b2e4d05 Binary files /dev/null and b/third_party/libzip/regress/testcommentremoved.zip differ diff --git a/third_party/libzip/regress/testdeflated.zip b/third_party/libzip/regress/testdeflated.zip new file mode 100644 index 0000000..7f6ab1c Binary files /dev/null and b/third_party/libzip/regress/testdeflated.zip differ diff --git a/third_party/libzip/regress/testdeflated2.zip b/third_party/libzip/regress/testdeflated2.zip new file mode 100644 index 0000000..b5ded7d Binary files /dev/null and b/third_party/libzip/regress/testdeflated2.zip differ diff --git a/third_party/libzip/regress/testdir.zip b/third_party/libzip/regress/testdir.zip new file mode 100644 index 0000000..b1e13e1 Binary files /dev/null and b/third_party/libzip/regress/testdir.zip differ diff --git a/third_party/libzip/regress/testempty.zip b/third_party/libzip/regress/testempty.zip new file mode 100644 index 0000000..15cb0ec Binary files /dev/null and b/third_party/libzip/regress/testempty.zip differ diff --git a/third_party/libzip/regress/testextrabytes.zip b/third_party/libzip/regress/testextrabytes.zip new file mode 100644 index 0000000..f2a3fb2 Binary files /dev/null and b/third_party/libzip/regress/testextrabytes.zip differ diff --git a/third_party/libzip/regress/testfile-UTF8.zip b/third_party/libzip/regress/testfile-UTF8.zip new file mode 100644 index 0000000..7279615 Binary files /dev/null and b/third_party/libzip/regress/testfile-UTF8.zip differ diff --git a/third_party/libzip/regress/testfile-cp437.zip b/third_party/libzip/regress/testfile-cp437.zip new file mode 100644 index 0000000..169a903 Binary files /dev/null and b/third_party/libzip/regress/testfile-cp437.zip differ diff --git a/third_party/libzip/regress/testfile-plus-extra.zip b/third_party/libzip/regress/testfile-plus-extra.zip new file mode 100644 index 0000000..09a6c03 Binary files /dev/null and b/third_party/libzip/regress/testfile-plus-extra.zip differ diff --git a/omaha/third_party/__init__.py b/third_party/libzip/regress/testfile.txt similarity index 100% rename from omaha/third_party/__init__.py rename to third_party/libzip/regress/testfile.txt diff --git a/third_party/libzip/regress/testfile.zip b/third_party/libzip/regress/testfile.zip new file mode 100644 index 0000000..2fa5ba0 Binary files /dev/null and b/third_party/libzip/regress/testfile.zip differ diff --git a/third_party/libzip/regress/testfile2014.zip b/third_party/libzip/regress/testfile2014.zip new file mode 100644 index 0000000..1d75d46 Binary files /dev/null and b/third_party/libzip/regress/testfile2014.zip differ diff --git a/third_party/libzip/regress/teststdin.zip b/third_party/libzip/regress/teststdin.zip new file mode 100644 index 0000000..e1a40a8 Binary files /dev/null and b/third_party/libzip/regress/teststdin.zip differ diff --git a/third_party/libzip/regress/teststored.zip b/third_party/libzip/regress/teststored.zip new file mode 100644 index 0000000..138c6ad Binary files /dev/null and b/third_party/libzip/regress/teststored.zip differ diff --git a/third_party/libzip/regress/tryopen.c b/third_party/libzip/regress/tryopen.c new file mode 100644 index 0000000..32c96c8 --- /dev/null +++ b/third_party/libzip/regress/tryopen.c @@ -0,0 +1,111 @@ +/* + tryopen.c -- tool for tests that try opening zip archives + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif + +#include "compat.h" +#include "zip.h" + +const char *usage = "usage: %s [-cent] file\n\n" + "\t-c\tcheck consistency\n" + "\t-e\texclusively open archive\n" + "\t-n\tcreate new file\n" + "\t-t\ttruncate file to size 0\n"; + + +int +main(int argc, char *argv[]) { + const char *fname; + zip_t *z; + int c, flags, ze; + zip_int64_t count; + int error; + + flags = 0; + + while ((c = getopt(argc, argv, "cent")) != -1) { + switch (c) { + case 'c': + flags |= ZIP_CHECKCONS; + break; + case 'e': + flags |= ZIP_EXCL; + break; + case 'n': + flags |= ZIP_CREATE; + break; + case 't': + flags |= ZIP_TRUNCATE; + break; + + default: + fprintf(stderr, usage, argv[0]); + return 1; + } + } + + error = 0; + for (; optind < argc; optind++) { + fname = argv[optind]; + errno = 0; + + if ((z = zip_open(fname, flags, &ze)) != NULL) { + count = zip_get_num_entries(z, 0); + printf("opening '%s' succeeded, %" PRIu64 " entries\n", fname, count); + zip_close(z); + continue; + } + + printf("opening '%s' returned error %d", fname, ze); + if (zip_error_get_sys_type(ze) == ZIP_ET_SYS) + printf("/%d", errno); + printf("\n"); + error++; + } + + if (error > 0) + fprintf(stderr, "%d errors\n", error); + + return error ? 1 : 0; +} diff --git a/third_party/libzip/regress/utf-8-standardization-input.zip b/third_party/libzip/regress/utf-8-standardization-input.zip new file mode 100644 index 0000000..67e3acf Binary files /dev/null and b/third_party/libzip/regress/utf-8-standardization-input.zip differ diff --git a/third_party/libzip/regress/utf-8-standardization-output.zip b/third_party/libzip/regress/utf-8-standardization-output.zip new file mode 100644 index 0000000..2507a76 Binary files /dev/null and b/third_party/libzip/regress/utf-8-standardization-output.zip differ diff --git a/third_party/libzip/regress/utf-8-standardization.test b/third_party/libzip/regress/utf-8-standardization.test new file mode 100644 index 0000000..35d4808 --- /dev/null +++ b/third_party/libzip/regress/utf-8-standardization.test @@ -0,0 +1,4 @@ +# replace file contents and make UTF-8 name +return 0 +args testfile.zzip replace_file_contents 0 "Some new content for the file." set_file_mtime 0 1406885162 +file testfile.zzip utf-8-standardization-input.zip utf-8-standardization-output.zip diff --git a/third_party/libzip/regress/zip-in-archive-comment.test b/third_party/libzip/regress/zip-in-archive-comment.test new file mode 100644 index 0000000..4838a8f --- /dev/null +++ b/third_party/libzip/regress/zip-in-archive-comment.test @@ -0,0 +1,13 @@ +# stat file in zip that contains archive comment to find out if it detected the right one of the two +args zip-in-archive-comment.zip stat 0 +file zip-in-archive-comment.zip zip-in-archive-comment.zip zip-in-archive-comment.zip +return 0 +stdout name: 'testfile.txt' +stdout index: '0' +stdout size: '0' +stdout compressed size: '0' +stdout mtime: 'Fri Jul 15 2005 16:37:14' +stdout crc: '0' +stdout compression method: '0' +stdout encryption method: '0' +stdout diff --git a/third_party/libzip/regress/zip-in-archive-comment.zip b/third_party/libzip/regress/zip-in-archive-comment.zip new file mode 100644 index 0000000..20a412b Binary files /dev/null and b/third_party/libzip/regress/zip-in-archive-comment.zip differ diff --git a/third_party/libzip/regress/zip64-3mf.zip b/third_party/libzip/regress/zip64-3mf.zip new file mode 100644 index 0000000..a2ccf24 Binary files /dev/null and b/third_party/libzip/regress/zip64-3mf.zip differ diff --git a/third_party/libzip/regress/zip64.zip b/third_party/libzip/regress/zip64.zip new file mode 100644 index 0000000..c1ba76b Binary files /dev/null and b/third_party/libzip/regress/zip64.zip differ diff --git a/third_party/libzip/regress/zip64_creation.test b/third_party/libzip/regress/zip64_creation.test new file mode 100644 index 0000000..f216088 --- /dev/null +++ b/third_party/libzip/regress/zip64_creation.test @@ -0,0 +1,4 @@ +# create big zip64 zip file from scratch +args bigzero.zip add_nul bigzero 4294967296 +file-new bigzero.zip bigzero.zip +return 0 diff --git a/third_party/libzip/regress/zip64_stored_creation.test b/third_party/libzip/regress/zip64_stored_creation.test new file mode 100644 index 0000000..92ee02c --- /dev/null +++ b/third_party/libzip/regress/zip64_stored_creation.test @@ -0,0 +1,4 @@ +# create big zip64 zip file from scratch +args -H bigstored.zh add_nul bigzero 4294967296 set_file_compression 0 0 0 set_file_mtime 0 0 add_nul smallzero 16384 set_file_compression 1 0 0 set_file_mtime 1 0 +file-new bigstored.zh bigstored.zh +return 0 diff --git a/third_party/libzip/regress/ziptool_regress.c b/third_party/libzip/regress/ziptool_regress.c new file mode 100644 index 0000000..daf3d62 --- /dev/null +++ b/third_party/libzip/regress/ziptool_regress.c @@ -0,0 +1,392 @@ +#include "zip.h" + +#define ZIP_MIN(a, b) ((a) < (b) ? (a) : (b)) + +#define FOR_REGRESS + +typedef enum { SOURCE_TYPE_NONE, SOURCE_TYPE_IN_MEMORY, SOURCE_TYPE_HOLE } source_type_t; + +source_type_t source_type = SOURCE_TYPE_NONE; +zip_uint64_t fragment_size = 0; + +static int add_nul(int argc, char *argv[]); +static int unchange_all(int argc, char *argv[]); +static int zin_close(int argc, char *argv[]); + +#define OPTIONS_REGRESS "F:Hm" + +#define USAGE_REGRESS " [-Hm] [-F fragment-size]" + +#define GETOPT_REGRESS \ + case 'H': \ + source_type = SOURCE_TYPE_HOLE; \ + break; \ + case 'm': \ + source_type = SOURCE_TYPE_IN_MEMORY; \ + break; \ + case 'F': \ + fragment_size = strtoull(optarg, NULL, 10); \ + break; + +#define DISPATCH_REGRESS \ + {"add_nul", 2, "name length", "add NUL bytes", add_nul}, {"unchange_all", 0, "", "revert all changes", unchange_all}, { "zin_close", 1, "index", "close input zip_source (for internal tests)", zin_close } + + +zip_t *ziptool_open(const char *archive, int flags, zip_error_t *error, zip_uint64_t offset, zip_uint64_t len); + + +#include "ziptool.c" + + +zip_source_t *memory_src = NULL; + +zip_source_t *source_hole_create(const char *, int flags, zip_error_t *); + +static zip_t *read_to_memory(const char *archive, int flags, zip_error_t *error, zip_source_t **srcp); +static zip_source_t *source_nul(zip_t *za, zip_uint64_t length); + + +static int +add_nul(int argc, char *argv[]) { + zip_source_t *zs; + zip_uint64_t length = strtoull(argv[1], NULL, 10); + + if ((zs = source_nul(za, length)) == NULL) { + fprintf(stderr, "can't create zip_source for length: %s\n", zip_strerror(za)); + return -1; + } + + if (zip_add(za, argv[0], zs) == -1) { + zip_source_free(zs); + fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +unchange_all(int argc, char *argv[]) { + if (zip_unchange_all(za) < 0) { + fprintf(stderr, "can't revert changes to archive: %s\n", zip_strerror(za)); + return -1; + } + return 0; +} + +static int +zin_close(int argc, char *argv[]) { + zip_uint64_t idx; + + idx = strtoull(argv[0], NULL, 10); + if (idx >= z_in_count) { + fprintf(stderr, "invalid argument '%" PRIu64 "', only %d zip sources open\n", idx, z_in_count); + return -1; + } + if (zip_close(z_in[idx]) < 0) { + fprintf(stderr, "can't close source archive: %s\n", zip_strerror(z_in[idx])); + return -1; + } + z_in[idx] = z_in[z_in_count]; + z_in_count--; + + return 0; +} + + +static zip_t * +read_hole(const char *archive, int flags, zip_error_t *error) { + zip_source_t *src = NULL; + zip_t *zs = NULL; + + if (strcmp(archive, "/dev/stdin") == 0) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + + if ((src = source_hole_create(archive, flags, error)) == NULL || (zs = zip_open_from_source(src, flags, error)) == NULL) { + zip_source_free(src); + } + + return zs; +} + + +static zip_t * +read_to_memory(const char *archive, int flags, zip_error_t *error, zip_source_t **srcp) { + zip_source_t *src; + zip_t *zb; + FILE *fp; + + if (strcmp(archive, "/dev/stdin") == 0) { + zip_error_set(error, ZIP_ER_OPNOTSUPP, 0); + return NULL; + } + + if ((fp = fopen(archive, "r")) == NULL) { + if (errno == ENOENT) { + src = zip_source_buffer_create(NULL, 0, 0, error); + } + else { + zip_error_set(error, ZIP_ER_OPEN, errno); + return NULL; + } + } + else { + struct stat st; + + if (fstat(fileno(fp), &st) < 0) { + fclose(fp); + zip_error_set(error, ZIP_ER_OPEN, errno); + return NULL; + } + if (fragment_size == 0) { + char *buf; + if ((buf = malloc((size_t)st.st_size)) == NULL) { + fclose(fp); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + if (fread(buf, (size_t)st.st_size, 1, fp) < 1) { + free(buf); + fclose(fp); + zip_error_set(error, ZIP_ER_READ, errno); + return NULL; + } + src = zip_source_buffer_create(buf, (zip_uint64_t)st.st_size, 1, error); + if (src == NULL) { + free(buf); + } + } + else { + zip_uint64_t nfragments, i, left; + zip_buffer_fragment_t *fragments; + + nfragments = ((size_t)st.st_size + fragment_size - 1) / fragment_size; + if ((fragments = malloc(sizeof(fragments[0]) * nfragments)) == NULL) { + fclose(fp); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + for (i = 0; i < nfragments; i++) { + left = ZIP_MIN(fragment_size, (size_t)st.st_size - i * fragment_size); + if ((fragments[i].data = malloc(left)) == NULL) { +#ifndef __clang_analyzer__ + /* fragments is initialized up to i - 1*/ + while (--i > 0) { + free(fragments[i].data); + } +#endif + free(fragments); + fclose(fp); + zip_error_set(error, ZIP_ER_MEMORY, 0); + return NULL; + } + fragments[i].length = left; + if (fread(fragments[i].data, left, 1, fp) < 1) { +#ifndef __clang_analyzer__ + /* fragments is initialized up to i - 1*/ + while (--i > 0) { + free(fragments[i].data); + } +#endif + free(fragments); + fclose(fp); + zip_error_set(error, ZIP_ER_READ, errno); + return NULL; + } + } + src = zip_source_buffer_fragment_create(fragments, nfragments, 1, error); + if (src == NULL) { + for (i = 0; i < nfragments; i++) { + free(fragments[i].data); + } + free(fragments); + fclose(fp); + return NULL; + } + free(fragments); + } + fclose(fp); + } + if (src == NULL) { + return NULL; + } + zb = zip_open_from_source(src, flags, error); + if (zb == NULL) { + zip_source_free(src); + return NULL; + } + zip_source_keep(src); + *srcp = src; + return zb; +} + + +typedef struct source_nul { + zip_error_t error; + zip_uint64_t length; + zip_uint64_t offset; +} source_nul_t; + +static zip_int64_t +source_nul_cb(void *ud, void *data, zip_uint64_t length, zip_source_cmd_t command) { + source_nul_t *ctx = (source_nul_t *)ud; + + switch (command) { + case ZIP_SOURCE_CLOSE: + return 0; + + case ZIP_SOURCE_ERROR: + return zip_error_to_data(&ctx->error, data, length); + + case ZIP_SOURCE_FREE: + free(ctx); + return 0; + + case ZIP_SOURCE_OPEN: + ctx->offset = 0; + return 0; + + case ZIP_SOURCE_READ: + if (length > ZIP_INT64_MAX) { + zip_error_set(&ctx->error, ZIP_ER_INVAL, 0); + return -1; + } + + if (length > ctx->length - ctx->offset) { + length = ctx->length - ctx->offset; + } + + memset(data, 0, length); + ctx->offset += length; + return (zip_int64_t)length; + + case ZIP_SOURCE_STAT: { + zip_stat_t *st = ZIP_SOURCE_GET_ARGS(zip_stat_t, data, length, &ctx->error); + + if (st == NULL) { + return -1; + } + + st->valid |= ZIP_STAT_SIZE; + st->size = ctx->length; + + return 0; + } + + case ZIP_SOURCE_SUPPORTS: + return zip_source_make_command_bitmap(ZIP_SOURCE_CLOSE, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_STAT, -1); + + default: + zip_error_set(&ctx->error, ZIP_ER_OPNOTSUPP, 0); + return -1; + } +} + +static zip_source_t * +source_nul(zip_t *zs, zip_uint64_t length) { + source_nul_t *ctx; + zip_source_t *src; + + if ((ctx = (source_nul_t *)malloc(sizeof(*ctx))) == NULL) { + zip_error_set(zip_get_error(zs), ZIP_ER_MEMORY, 0); + return NULL; + } + + zip_error_init(&ctx->error); + ctx->length = length; + ctx->offset = 0; + + if ((src = zip_source_function(zs, source_nul_cb, ctx)) == NULL) { + free(ctx); + return NULL; + } + + return src; +} + + +static int +write_memory_src_to_file(const char *archive, zip_source_t *src) { + zip_stat_t zst; + char *buf; + FILE *fp; + + if (zip_source_stat(src, &zst) < 0) { + fprintf(stderr, "zip_source_stat on buffer failed: %s\n", zip_error_strerror(zip_source_error(src))); + return -1; + } + if (zip_source_open(src) < 0) { + if (zip_error_code_zip(zip_source_error(src)) == ZIP_ER_DELETED) { + if (unlink(archive) < 0 && errno != ENOENT) { + fprintf(stderr, "unlink failed: %s\n", strerror(errno)); + return -1; + } + return 0; + } + fprintf(stderr, "zip_source_open on buffer failed: %s\n", zip_error_strerror(zip_source_error(src))); + return -1; + } + if ((buf = malloc(zst.size)) == NULL) { + fprintf(stderr, "malloc failed: %s\n", strerror(errno)); + zip_source_close(src); + return -1; + } + if (zip_source_read(src, buf, zst.size) < (zip_int64_t)zst.size) { + fprintf(stderr, "zip_source_read on buffer failed: %s\n", zip_error_strerror(zip_source_error(src))); + zip_source_close(src); + free(buf); + return -1; + } + zip_source_close(src); + if ((fp = fopen(archive, "wb")) == NULL) { + fprintf(stderr, "fopen failed: %s\n", strerror(errno)); + free(buf); + return -1; + } + if (fwrite(buf, zst.size, 1, fp) < 1) { + fprintf(stderr, "fwrite failed: %s\n", strerror(errno)); + free(buf); + fclose(fp); + return -1; + } + free(buf); + if (fclose(fp) != 0) { + fprintf(stderr, "fclose failed: %s\n", strerror(errno)); + return -1; + } + return 0; +} + + +zip_t * +ziptool_open(const char *archive, int flags, zip_error_t *error, zip_uint64_t offset, zip_uint64_t len) { + switch (source_type) { + case SOURCE_TYPE_NONE: + za = read_from_file(archive, flags, error, offset, len); + break; + + case SOURCE_TYPE_IN_MEMORY: + za = read_to_memory(archive, flags, error, &memory_src); + break; + + case SOURCE_TYPE_HOLE: + za = read_hole(archive, flags, error); + break; + } + + return za; +} + + +int +ziptool_post_close(const char *archive) { + if (source_type == SOURCE_TYPE_IN_MEMORY) { + if (write_memory_src_to_file(archive, memory_src) < 0) { + return -1; + } + zip_source_free(memory_src); + } + + return 0; +} diff --git a/third_party/libzip/src/CMakeLists.txt b/third_party/libzip/src/CMakeLists.txt new file mode 100644 index 0000000..ad1f38c --- /dev/null +++ b/third_party/libzip/src/CMakeLists.txt @@ -0,0 +1,18 @@ +INCLUDE_DIRECTORIES(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/../lib ${CMAKE_CURRENT_BINARY_DIR}/..) + +CHECK_FUNCTION_EXISTS(getopt HAVE_GETOPT) +IF(NOT HAVE_GETOPT) + SET(SRC_EXTRA_FILES getopt.c) +ENDIF(NOT HAVE_GETOPT) + +ADD_EXECUTABLE(zipcmp zipcmp.c ${SRC_EXTRA_FILES}) +TARGET_LINK_LIBRARIES(zipcmp zip) +INSTALL(TARGETS zipcmp RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + +ADD_EXECUTABLE(zipmerge zipmerge.c ${SRC_EXTRA_FILES}) +TARGET_LINK_LIBRARIES(zipmerge zip) +INSTALL(TARGETS zipmerge RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) + +ADD_EXECUTABLE(ziptool ziptool.c ${SRC_EXTRA_FILES}) +TARGET_LINK_LIBRARIES(ziptool zip) +INSTALL(TARGETS ziptool RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/third_party/libzip/src/getopt.c b/third_party/libzip/src/getopt.c new file mode 100644 index 0000000..befd672 --- /dev/null +++ b/third_party/libzip/src/getopt.c @@ -0,0 +1,110 @@ +/* + * getopt.c -- + * + * Standard UNIX getopt function. Code is from BSD. + * + * Copyright (c) 1987-2002 The Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * A. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * B. 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. + * C. Neither the names of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * 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 REGENTS 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. + */ + +/* #if !defined(lint) + * static char sccsid[] = "@(#)getopt.c 8.2 (Berkeley) 4/2/94"; + * #endif + */ +#include +#include +#include + +#include "getopt.h" + +int opterr = 1, /* if error message should be printed */ + optind = 1, /* index into parent argv vector */ + optopt, /* character checked for validity */ + optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ + +#define BADCH (int)'?' +#define BADARG (int)':' +#define EMSG "" + +/* + * getopt -- + * Parse argc/argv argument vector. + */ +int +getopt(int nargc, char *const *nargv, const char *ostr) { + static char *place = EMSG; /* option letter processing */ + char *oli; /* option letter list index */ + + if (optreset || !*place) { /* update scanning pointer */ + optreset = 0; + if (optind >= nargc || *(place = nargv[optind]) != '-') { + place = EMSG; + return (EOF); + } + if (place[1] && *++place == '-') { /* found "--" */ + ++optind; + place = EMSG; + return (EOF); + } + } /* option letter okay? */ + if ((optopt = (int)*place++) == (int)':' || !(oli = (char *)strchr(ostr, optopt))) { + /* + * if the user didn't specify '-' as an option, + * assume it means EOF. + */ + if (optopt == (int)'-') + return (EOF); + if (!*place) + ++optind; + if (opterr && *ostr != ':') + (void)fprintf(stderr, "illegal option -- %c\n", optopt); + return (BADCH); + } + if (*++oli != ':') { /* don't need argument */ + optarg = NULL; + if (!*place) + ++optind; + } + else { /* need an argument */ + if (*place) /* no white space */ + optarg = place; + else if (nargc <= ++optind) { /* no arg */ + place = EMSG; + if (*ostr == ':') + return (BADARG); + if (opterr) + (void)fprintf(stderr, "option requires an argument -- %c\n", optopt); + return (BADCH); + } + else /* white space */ + optarg = nargv[optind]; + place = EMSG; + ++optind; + } + return (optopt); /* dump back option letter */ +} diff --git a/third_party/libzip/src/getopt.h b/third_party/libzip/src/getopt.h new file mode 100644 index 0000000..01dcd93 --- /dev/null +++ b/third_party/libzip/src/getopt.h @@ -0,0 +1,51 @@ +#ifndef _HAD_GETOPT_H +#define _HAD_GETOPT_H + +/* + getopt.h -- header for getopt() replacement function + Copyright (C) 1999-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +extern char *optarg; +extern int optind; +extern int opterr; + +extern int getopt(int, char *const *, const char *); + +#ifdef __cplusplus +} +#endif + +#endif /* _HAD_GETOPT_H */ diff --git a/third_party/libzip/src/zipcmp.c b/third_party/libzip/src/zipcmp.c new file mode 100644 index 0000000..c452684 --- /dev/null +++ b/third_party/libzip/src/zipcmp.c @@ -0,0 +1,700 @@ +/* + zipcmp.c -- compare zip files + Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include +#include +#include +#include +#include +#ifdef HAVE_STRINGS_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_FTS_H +#include +#endif +#include + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif + +#include "compat.h" +#include "zip.h" + +struct archive { + const char *name; + zip_t *za; + zip_uint64_t nentry; + struct entry *entry; + const char *comment; + size_t comment_length; +}; + +struct ef { + const char *name; + zip_uint16_t flags; + zip_uint16_t id; + zip_uint16_t size; + const zip_uint8_t *data; +}; + +struct entry { + char *name; + zip_uint64_t size; + zip_uint32_t crc; + zip_uint32_t comp_method; + struct ef *extra_fields; + zip_uint16_t n_extra_fields; + const char *comment; + zip_uint32_t comment_length; +}; + + +const char *progname; + +#define PROGRAM "zipcmp" + +#define USAGE "usage: %s [-hipqtVv] archive1 archive2\n" + +char help_head[] = PROGRAM " (" PACKAGE ") by Dieter Baron and Thomas Klausner\n\n"; + +char help[] = "\n\ + -h display this help message\n\ + -i compare names ignoring case distinctions\n\ + -p compare as many details as possible\n\ + -q be quiet\n\ + -t test zip files (compare file contents to checksum)\n\ + -V display version number\n\ + -v be verbose (print differences, default)\n\ +\n\ +Report bugs to .\n"; + +char version_string[] = PROGRAM " (" PACKAGE " " VERSION ")\n\ +Copyright (C) 2003-2018 Dieter Baron and Thomas Klausner\n\ +" PACKAGE " comes with ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n"; + +#define OPTIONS "hVipqtv" + + +#define BOTH_ARE_ZIPS(a) (a[0].za && a[1].za) + +static int comment_compare(const char *c1, size_t l1, const char *c2, size_t l2); +static int compare_list(char *const name[], const void *l[], const zip_uint64_t n[], int size, int (*cmp)(const void *, const void *), int (*checks)(char *const name[2], const void *, const void *), void (*print)(const void *)); +static int compare_zip(char *const zn[]); +static int ef_compare(char *const name[2], const struct entry *e1, const struct entry *e2); +static int ef_order(const void *a, const void *b); +static void ef_print(const void *p); +static int ef_read(zip_t *za, zip_uint64_t idx, struct entry *e); +static int entry_cmp(const void *p1, const void *p2); +static int entry_paranoia_checks(char *const name[2], const void *p1, const void *p2); +static void entry_print(const void *p); +static int is_directory(const char *name); +#ifdef HAVE_FTS_H +static int list_directory(const char *name, struct archive *a); +#endif +static int list_zip(const char *name, struct archive *a); +static int test_file(zip_t *za, zip_uint64_t idx, zip_uint64_t size, zip_uint32_t crc); + +int ignore_case, test_files, paranoid, verbose; +int header_done; + + +int +main(int argc, char *const argv[]) { + int c; + + progname = argv[0]; + + ignore_case = 0; + test_files = 0; + paranoid = 0; + verbose = 1; + + while ((c = getopt(argc, argv, OPTIONS)) != -1) { + switch (c) { + case 'i': + ignore_case = 1; + break; + case 'p': + paranoid = 1; + break; + case 'q': + verbose = 0; + break; + case 't': + test_files = 1; + break; + case 'v': + verbose = 1; + break; + + case 'h': + fputs(help_head, stdout); + printf(USAGE, progname); + fputs(help, stdout); + exit(0); + case 'V': + fputs(version_string, stdout); + exit(0); + + default: + fprintf(stderr, USAGE, progname); + exit(2); + } + } + + if (argc != optind + 2) { + fprintf(stderr, USAGE, progname); + exit(2); + } + + exit((compare_zip(argv + optind) == 0) ? 0 : 1); +} + + +static int +compare_zip(char *const zn[]) { + struct archive a[2]; + struct entry *e[2]; + zip_uint64_t n[2]; + int i; + int res; + + for (i = 0; i < 2; i++) { + a[i].name = zn[i]; + a[i].entry = NULL; + a[i].nentry = 0; + a[i].za = NULL; + a[i].comment = NULL; + a[i].comment_length = 0; + + if (is_directory(zn[i])) { +#ifndef HAVE_FTS_H + fprintf(stderr, "%s: reading directories not supported\n", progname); + exit(2); +#else + if (list_directory(zn[i], a + i) < 0) + exit(2); + paranoid = 0; /* paranoid checks make no sense for directories, since they compare zip metadata */ +#endif + } + else { + if (list_zip(zn[i], a + i) < 0) + exit(2); + } + if (a[i].nentry > 0) + qsort(a[i].entry, a[i].nentry, sizeof(a[i].entry[0]), entry_cmp); + } + + header_done = 0; + + e[0] = a[0].entry; + e[1] = a[1].entry; + n[0] = a[0].nentry; + n[1] = a[1].nentry; + res = compare_list(zn, (const void **)e, n, sizeof(e[i][0]), entry_cmp, paranoid ? entry_paranoia_checks : NULL, entry_print); + + if (paranoid) { + if (comment_compare(a[0].comment, a[0].comment_length, a[1].comment, a[1].comment_length) != 0) { + if (verbose) { + printf("--- archive comment (%ld)\n", a[0].comment_length); + printf("+++ archive comment (%ld)\n", a[1].comment_length); + } + res = 1; + } + } + + for (i = 0; i < 2; i++) + if (a[i].za) + zip_close(a[i].za); + + switch (res) { + case 0: + exit(0); + + case 1: + exit(1); + + default: + exit(2); + } +} + +#ifdef HAVE_FTS_H +static zip_int64_t +compute_crc(const char *fname) { + FILE *f; + uLong crc = crc32(0L, Z_NULL, 0); + size_t n; + Bytef buffer[8192]; + + + if ((f = fopen(fname, "r")) == NULL) { + fprintf(stderr, "%s: can't open %s: %s\n", progname, fname, strerror(errno)); + return -1; + } + + while ((n = fread(buffer, 1, sizeof(buffer), f)) > 0) { + crc = crc32(crc, buffer, (unsigned int)n); + } + + if (ferror(f)) { + fprintf(stderr, "%s: read error on %s: %s\n", progname, fname, strerror(errno)); + fclose(f); + return -1; + } + + fclose(f); + + return (zip_int64_t)crc; +} +#endif + + +static int +is_directory(const char *name) { + struct stat st; + + if (stat(name, &st) < 0) + return 0; + + return S_ISDIR(st.st_mode); +} + + +#ifdef HAVE_FTS_H +static int +list_directory(const char *name, struct archive *a) { + FTS *fts; + FTSENT *ent; + zip_uint64_t nalloc; + size_t prefix_length; + + char *const names[2] = {(char *)name, NULL}; + + + if ((fts = fts_open(names, FTS_NOCHDIR | FTS_LOGICAL, NULL)) == NULL) { + fprintf(stderr, "%s: can't open directory '%s': %s\n", progname, name, strerror(errno)); + return -1; + } + prefix_length = strlen(name) + 1; + + nalloc = 0; + + while ((ent = fts_read(fts))) { + zip_int64_t crc; + + switch (ent->fts_info) { + case FTS_D: + case FTS_DOT: + case FTS_DP: + case FTS_DEFAULT: + case FTS_SL: + case FTS_NSOK: + break; + + case FTS_DC: + case FTS_DNR: + case FTS_ERR: + case FTS_NS: + case FTS_SLNONE: + /* TODO: error */ + fts_close(fts); + return -1; + + case FTS_F: + if (a->nentry >= nalloc) { + nalloc += 16; + if (nalloc > SIZE_MAX / sizeof(a->entry[0])) { + fprintf(stderr, "%s: malloc failure\n", progname); + exit(1); + } + a->entry = realloc(a->entry, sizeof(a->entry[0]) * nalloc); + if (a->entry == NULL) { + fprintf(stderr, "%s: malloc failure\n", progname); + exit(1); + } + } + + a->entry[a->nentry].name = strdup(ent->fts_path + prefix_length); + a->entry[a->nentry].size = (zip_uint64_t)ent->fts_statp->st_size; + if ((crc = compute_crc(ent->fts_accpath)) < 0) { + fts_close(fts); + return -1; + } + + a->entry[a->nentry].crc = (zip_uint32_t)crc; + a->nentry++; + break; + } + } + + if (fts_close(fts)) { + fprintf(stderr, "%s: error closing directory '%s': %s\n", progname, a->name, strerror(errno)); + return -1; + } + + return 0; +} +#endif + + +static int +list_zip(const char *name, struct archive *a) { + zip_t *za; + int err; + struct zip_stat st; + unsigned int i; + + if ((za = zip_open(name, paranoid ? ZIP_CHECKCONS : 0, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "%s: cannot open zip archive '%s': %s\n", progname, name, zip_error_strerror(&error)); + zip_error_fini(&error); + return -1; + } + + a->za = za; + a->nentry = (zip_uint64_t)zip_get_num_entries(za, 0); + + if (a->nentry == 0) + a->entry = NULL; + else { + if ((a->nentry > SIZE_MAX / sizeof(a->entry[0])) || (a->entry = (struct entry *)malloc(sizeof(a->entry[0]) * a->nentry)) == NULL) { + fprintf(stderr, "%s: malloc failure\n", progname); + exit(1); + } + + for (i = 0; i < a->nentry; i++) { + zip_stat_index(za, i, 0, &st); + a->entry[i].name = strdup(st.name); + a->entry[i].size = st.size; + a->entry[i].crc = st.crc; + if (test_files) + test_file(za, i, st.size, st.crc); + if (paranoid) { + a->entry[i].comp_method = st.comp_method; + ef_read(za, i, a->entry + i); + a->entry[i].comment = zip_file_get_comment(za, i, &a->entry[i].comment_length, 0); + } + else { + a->entry[i].comp_method = 0; + a->entry[i].n_extra_fields = 0; + } + } + + if (paranoid) { + int length; + a->comment = zip_get_archive_comment(za, &length, 0); + a->comment_length = (size_t)length; + } + else { + a->comment = NULL; + a->comment_length = 0; + } + } + + return 0; +} + + +static int +comment_compare(const char *c1, size_t l1, const char *c2, size_t l2) { + if (l1 != l2) + return 1; + + if (l1 == 0) + return 0; + + if (c1 == NULL || c2 == NULL) + return c1 == c2; + + return memcmp(c1, c2, (size_t)l2); +} + + +static int +compare_list(char *const name[2], const void *l[2], const zip_uint64_t n[2], int size, int (*cmp)(const void *, const void *), int (*check)(char *const name[2], const void *, const void *), void (*print)(const void *)) { + unsigned int i[2]; + int j, c; + int diff; + +#define INC(k) (i[k]++, l[k] = ((const char *)l[k]) + size) +#define PRINT(k) \ + do { \ + if (header_done == 0 && verbose) { \ + printf("--- %s\n+++ %s\n", name[0], name[1]); \ + header_done = 1; \ + } \ + if (verbose) { \ + printf("%c ", (k) ? '+' : '-'); \ + print(l[k]); \ + } \ + diff = 1; \ + } while (0) + + i[0] = i[1] = 0; + diff = 0; + while (i[0] < n[0] && i[1] < n[1]) { + c = cmp(l[0], l[1]); + + if (c == 0) { + if (check) + diff |= check(name, l[0], l[1]); + INC(0); + INC(1); + } + else if (c < 0) { + PRINT(0); + INC(0); + } + else { + PRINT(1); + INC(1); + } + } + + for (j = 0; j < 2; j++) { + while (i[j] < n[j]) { + PRINT(j); + INC(j); + } + } + + return diff; +} + + +static int +ef_read(zip_t *za, zip_uint64_t idx, struct entry *e) { + zip_int16_t n_local, n_central; + zip_uint16_t i; + + if ((n_local = zip_file_extra_fields_count(za, idx, ZIP_FL_LOCAL)) < 0 || (n_central = zip_file_extra_fields_count(za, idx, ZIP_FL_CENTRAL)) < 0) { + return -1; + } + + e->n_extra_fields = (zip_uint16_t)(n_local + n_central); + + if ((e->extra_fields = (struct ef *)malloc(sizeof(e->extra_fields[0]) * e->n_extra_fields)) == NULL) + return -1; + + for (i = 0; i < n_local; i++) { + e->extra_fields[i].name = e->name; + e->extra_fields[i].data = zip_file_extra_field_get(za, idx, i, &e->extra_fields[i].id, &e->extra_fields[i].size, ZIP_FL_LOCAL); + if (e->extra_fields[i].data == NULL) + return -1; + e->extra_fields[i].flags = ZIP_FL_LOCAL; + } + for (; i < e->n_extra_fields; i++) { + e->extra_fields[i].name = e->name; + e->extra_fields[i].data = zip_file_extra_field_get(za, idx, (zip_uint16_t)(i - n_local), &e->extra_fields[i].id, &e->extra_fields[i].size, ZIP_FL_CENTRAL); + if (e->extra_fields[i].data == NULL) + return -1; + e->extra_fields[i].flags = ZIP_FL_CENTRAL; + } + + qsort(e->extra_fields, e->n_extra_fields, sizeof(e->extra_fields[0]), ef_order); + + return 0; +} + + +static int +ef_compare(char *const name[2], const struct entry *e1, const struct entry *e2) { + struct ef *ef[2]; + zip_uint64_t n[2]; + + ef[0] = e1->extra_fields; + ef[1] = e2->extra_fields; + n[0] = e1->n_extra_fields; + n[1] = e2->n_extra_fields; + + return compare_list(name, (const void **)ef, n, sizeof(struct ef), ef_order, NULL, ef_print); +} + + +static int +ef_order(const void *ap, const void *bp) { + const struct ef *a, *b; + + a = (struct ef *)ap; + b = (struct ef *)bp; + + if (a->flags != b->flags) + return a->flags - b->flags; + if (a->id != b->id) + return a->id - b->id; + if (a->size != b->size) + return a->size - b->size; + return memcmp(a->data, b->data, a->size); +} + + +static void +ef_print(const void *p) { + const struct ef *ef = (struct ef *)p; + int i; + + printf(" %s ", ef->name); + printf("%04x %c <", ef->id, ef->flags == ZIP_FL_LOCAL ? 'l' : 'c'); + for (i = 0; i < ef->size; i++) + printf("%s%02x", i ? " " : "", ef->data[i]); + printf(">\n"); +} + + +static int +entry_cmp(const void *p1, const void *p2) { + const struct entry *e1, *e2; + int c; + + e1 = (struct entry *)p1; + e2 = (struct entry *)p2; + + if ((c = (ignore_case ? strcasecmp : strcmp)(e1->name, e2->name)) != 0) + return c; + if (e1->size != e2->size) { + if (e1->size > e2->size) + return 1; + else + return -1; + } + if (e1->crc != e2->crc) + return (int)e1->crc - (int)e2->crc; + + return 0; +} + + +static int +entry_paranoia_checks(char *const name[2], const void *p1, const void *p2) { + const struct entry *e1, *e2; + int ret; + + e1 = (struct entry *)p1; + e2 = (struct entry *)p2; + + ret = 0; + + if (ef_compare(name, e1, e2) != 0) + ret = 1; + + if (e1->comp_method != e2->comp_method) { + if (verbose) { + if (header_done == 0) { + printf("--- %s\n+++ %s\n", name[0], name[1]); + header_done = 1; + } + printf("--- %s ", e1->name); + printf("method %u\n", e1->comp_method); + printf("+++ %s ", e1->name); + printf("method %u\n", e2->comp_method); + } + ret = 1; + } + if (comment_compare(e1->comment, e1->comment_length, e2->comment, e2->comment_length) != 0) { + if (verbose) { + if (header_done == 0) { + printf("--- %s\n+++ %s\n", name[0], name[1]); + header_done = 1; + } + printf("--- %s ", e1->name); + printf("comment %d\n", e1->comment_length); + printf("+++ %s ", e1->name); + printf("comment %d\n", e2->comment_length); + } + ret = 1; + } + + return ret; +} + + +static void +entry_print(const void *p) { + const struct entry *e; + + e = (struct entry *)p; + + /* TODO PRId64 */ + printf("%10lu %08x %s\n", (unsigned long)e->size, e->crc, e->name); +} + + +static int +test_file(zip_t *za, zip_uint64_t idx, zip_uint64_t size, zip_uint32_t crc) { + zip_file_t *zf; + char buf[8192]; + zip_uint64_t nsize; + zip_int64_t n; + zip_uint32_t ncrc; + + if ((zf = zip_fopen_index(za, idx, 0)) == NULL) { + fprintf(stderr, "%s: cannot open file %" PRIu64 " in archive: %s\n", progname, idx, zip_strerror(za)); + return -1; + } + + ncrc = (zip_uint32_t)crc32(0, NULL, 0); + nsize = 0; + + while ((n = zip_fread(zf, buf, sizeof(buf))) > 0) { + nsize += (zip_uint64_t)n; + ncrc = (zip_uint32_t)crc32(ncrc, (const Bytef *)buf, (unsigned int)n); + } + + if (n < 0) { + fprintf(stderr, "%s: error reading file %" PRIu64 " in archive: %s\n", progname, idx, zip_file_strerror(zf)); + zip_fclose(zf); + return -1; + } + + zip_fclose(zf); + + if (nsize != size) { + fprintf(stderr, "%s: file %" PRIu64 ": unexpected length %" PRId64 " (should be %" PRId64 ")\n", progname, idx, nsize, size); + return -2; + } + if (ncrc != crc) { + fprintf(stderr, "%s: file %" PRIu64 ": unexpected length %x (should be %x)\n", progname, idx, ncrc, crc); + return -2; + } + + return 0; +} diff --git a/third_party/libzip/src/zipmerge.c b/third_party/libzip/src/zipmerge.c new file mode 100644 index 0000000..3b26c95 --- /dev/null +++ b/third_party/libzip/src/zipmerge.c @@ -0,0 +1,284 @@ +/* + zipmerge.c -- merge zip archives + Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 +#include +#include +#include +#include + +#include "config.h" + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif + +#include "compat.h" +#include "zip.h" + +char *progname; + +#define PROGRAM "zipmerge" + +#define USAGE "usage: %s [-DhIiSsV] target-zip zip...\n" + +char help_head[] = PROGRAM " (" PACKAGE ") by Dieter Baron and Thomas Klausner\n\n"; + +char help[] = "\n\ + -h display this help message\n\ + -V display version number\n\ + -D ignore directory component in file names\n\ + -I ignore case in file names\n\ + -i ask before overwriting files\n\ + -S don't overwrite identical files\n\ + -s overwrite identical files without asking\n\ +\n\ +Report bugs to .\n"; + +char version_string[] = PROGRAM " (" PACKAGE " " VERSION ")\n\ +Copyright (C) 2004-2018 Dieter Baron and Thomas Klausner\n\ +" PACKAGE " comes with ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n"; + +#define OPTIONS "hVDiIsS" + +#define CONFIRM_ALL_YES 0x001 +#define CONFIRM_ALL_NO 0x002 +#define CONFIRM_SAME_YES 0x010 +#define CONFIRM_SAME_NO 0x020 + +int confirm; +zip_flags_t name_flags; + +static int confirm_replace(zip_t *, const char *, zip_uint64_t, zip_t *, const char *, zip_uint64_t); +static zip_t *merge_zip(zip_t *, const char *, const char *); + + +int +main(int argc, char *argv[]) { + zip_t *za; + zip_t **zs; + int c, err; + unsigned int i, n; + char *tname; + + progname = argv[0]; + + confirm = CONFIRM_ALL_YES; + name_flags = 0; + + while ((c = getopt(argc, argv, OPTIONS)) != -1) { + switch (c) { + case 'D': + name_flags |= ZIP_FL_NODIR; + break; + case 'i': + confirm &= ~CONFIRM_ALL_YES; + break; + case 'I': + name_flags |= ZIP_FL_NOCASE; + break; + case 's': + confirm &= ~CONFIRM_SAME_NO; + confirm |= CONFIRM_SAME_YES; + break; + case 'S': + confirm &= ~CONFIRM_SAME_YES; + confirm |= CONFIRM_SAME_NO; + break; + + case 'h': + fputs(help_head, stdout); + printf(USAGE, progname); + fputs(help, stdout); + exit(0); + case 'V': + fputs(version_string, stdout); + exit(0); + + default: + fprintf(stderr, USAGE, progname); + exit(2); + } + } + + if (argc < optind + 2) { + fprintf(stderr, USAGE, progname); + exit(2); + } + + tname = argv[optind++]; + argv += optind; + + n = (unsigned int)(argc - optind); + if ((zs = (zip_t **)malloc(sizeof(zs[0]) * n)) == NULL) { + fprintf(stderr, "%s: out of memory\n", progname); + exit(1); + } + + if ((za = zip_open(tname, ZIP_CREATE, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "%s: can't open zip archive '%s': %s\n", progname, tname, zip_error_strerror(&error)); + zip_error_fini(&error); + exit(1); + } + + for (i = 0; i < n; i++) { + if ((zs[i] = merge_zip(za, tname, argv[i])) == NULL) + exit(1); + } + + if (zip_close(za) < 0) { + fprintf(stderr, "%s: cannot write zip archive '%s': %s\n", progname, tname, zip_strerror(za)); + exit(1); + } + + for (i = 0; i < n; i++) + zip_close(zs[i]); + + exit(0); +} + + +static int +confirm_replace(zip_t *za, const char *tname, zip_uint64_t it, zip_t *zs, const char *sname, zip_uint64_t is) { + char line[1024]; + struct zip_stat st, ss; + + if (confirm & CONFIRM_ALL_YES) + return 1; + else if (confirm & CONFIRM_ALL_NO) + return 0; + + if (zip_stat_index(za, it, ZIP_FL_UNCHANGED, &st) < 0) { + fprintf(stderr, "%s: cannot stat file %" PRIu64 " in '%s': %s\n", progname, it, tname, zip_strerror(za)); + return -1; + } + if (zip_stat_index(zs, is, 0, &ss) < 0) { + fprintf(stderr, "%s: cannot stat file %" PRIu64 " in '%s': %s\n", progname, is, sname, zip_strerror(zs)); + return -1; + } + + if (st.size == ss.size && st.crc == ss.crc) { + if (confirm & CONFIRM_SAME_YES) + return 1; + else if (confirm & CONFIRM_SAME_NO) + return 0; + } + + printf("replace '%s' (%" PRIu64 " / %08x) in `%s'\n" + " with '%s' (%" PRIu64 " / %08x) from `%s'? ", + st.name, st.size, st.crc, tname, ss.name, ss.size, ss.crc, sname); + fflush(stdout); + + if (fgets(line, sizeof(line), stdin) == NULL) { + fprintf(stderr, "%s: read error from stdin: %s\n", progname, strerror(errno)); + return -1; + } + + if (tolower((unsigned char)line[0]) == 'y') + return 1; + + return 0; +} + + +static zip_t * +merge_zip(zip_t *za, const char *tname, const char *sname) { + zip_t *zs; + zip_source_t *source; + zip_int64_t ret, idx; + zip_uint64_t i; + int err; + const char *fname; + + if ((zs = zip_open(sname, 0, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "%s: can't open zip archive '%s': %s\n", progname, sname, zip_error_strerror(&error)); + zip_error_fini(&error); + return NULL; + } + + ret = zip_get_num_entries(zs, 0); + if (ret < 0) { + fprintf(stderr, "%s: cannot get number of entries for '%s': %s\n", progname, sname, zip_strerror(za)); + return NULL; + } + for (i = 0; i < (zip_uint64_t)ret; i++) { + fname = zip_get_name(zs, i, 0); + + if ((idx = zip_name_locate(za, fname, name_flags)) >= 0) { + switch (confirm_replace(za, tname, (zip_uint64_t)idx, zs, sname, i)) { + case 0: + break; + + case 1: + if ((source = zip_source_zip(za, zs, i, 0, 0, 0)) == NULL || zip_replace(za, (zip_uint64_t)idx, source) < 0) { + zip_source_free(source); + fprintf(stderr, "%s: cannot replace '%s' in `%s': %s\n", progname, fname, tname, zip_strerror(za)); + zip_close(zs); + return NULL; + } + break; + + case -1: + zip_close(zs); + return NULL; + + default: + fprintf(stderr, + "%s: internal error: " + "unexpected return code from confirm (%d)\n", + progname, err); + zip_close(zs); + return NULL; + } + } + else { + if ((source = zip_source_zip(za, zs, i, 0, 0, 0)) == NULL || zip_add(za, fname, source) < 0) { + zip_source_free(source); + fprintf(stderr, "%s: cannot add '%s' to `%s': %s\n", progname, fname, tname, zip_strerror(za)); + zip_close(zs); + return NULL; + } + } + } + + return zs; +} diff --git a/third_party/libzip/src/ziptool.c b/third_party/libzip/src/ziptool.c new file mode 100644 index 0000000..e33b9b5 --- /dev/null +++ b/third_party/libzip/src/ziptool.c @@ -0,0 +1,911 @@ +/* + ziptool.c -- tool for modifying zip archive in multiple ways + Copyright (C) 2012-2019 Dieter Baron and Thomas Klausner + + This file is part of libzip, a library to manipulate ZIP archives. + The authors can be contacted at + + 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. + 3. The names of the authors may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 "config.h" + +#include +#include +#include +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef _WIN32 +/* WIN32 needs for _O_BINARY */ +#include +#ifndef STDIN_FILENO +#define STDIN_FILENO _fileno(stdin) +#endif +#endif + +#ifndef HAVE_GETOPT +#include "getopt.h" +#endif +extern int optopt; + +#include "compat.h" +#include "zip.h" + +typedef struct dispatch_table_s { + const char *cmdline_name; + int argument_count; + const char *arg_names; + const char *description; + int (*function)(int argc, char *argv[]); +} dispatch_table_t; + +static zip_flags_t get_flags(const char *arg); +static zip_int32_t get_compression_method(const char *arg); +static zip_uint16_t get_encryption_method(const char *arg); +static void hexdump(const zip_uint8_t *data, zip_uint16_t len); +int ziptool_post_close(const char *archive); + +#ifndef FOR_REGRESS +#define OPTIONS_REGRESS "" +#define USAGE_REGRESS "" +#endif + +zip_t *za, *z_in[16]; +unsigned int z_in_count; +zip_flags_t stat_flags; + +static int +add(int argc, char *argv[]) { + zip_source_t *zs; + + if ((zs = zip_source_buffer(za, argv[1], strlen(argv[1]), 0)) == NULL) { + fprintf(stderr, "can't create zip_source from buffer: %s\n", zip_strerror(za)); + return -1; + } + + if (zip_add(za, argv[0], zs) == -1) { + zip_source_free(zs); + fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +add_dir(int argc, char *argv[]) { + /* add directory */ + if (zip_add_dir(za, argv[0]) < 0) { + fprintf(stderr, "can't add directory '%s': %s\n", argv[0], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +add_file(int argc, char *argv[]) { + zip_source_t *zs; + zip_uint64_t start = strtoull(argv[2], NULL, 10); + zip_int64_t len = strtoll(argv[3], NULL, 10); + + if (strcmp(argv[1], "/dev/stdin") == 0) { + if ((zs = zip_source_filep(za, stdin, start, len)) == NULL) { + fprintf(stderr, "can't create zip_source from stdin: %s\n", zip_strerror(za)); + return -1; + } + } + else { + if ((zs = zip_source_file(za, argv[1], start, len)) == NULL) { + fprintf(stderr, "can't create zip_source from file: %s\n", zip_strerror(za)); + return -1; + } + } + + if (zip_add(za, argv[0], zs) == -1) { + zip_source_free(zs); + fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +add_from_zip(int argc, char *argv[]) { + zip_uint64_t idx, start; + zip_int64_t len; + int err; + zip_source_t *zs; + /* add from another zip file */ + idx = strtoull(argv[2], NULL, 10); + start = strtoull(argv[3], NULL, 10); + len = strtoll(argv[4], NULL, 10); + if ((z_in[z_in_count] = zip_open(argv[1], ZIP_CHECKCONS, &err)) == NULL) { + zip_error_t error; + zip_error_init_with_code(&error, err); + fprintf(stderr, "can't open zip archive '%s': %s\n", argv[1], zip_error_strerror(&error)); + zip_error_fini(&error); + return -1; + } + if ((zs = zip_source_zip(za, z_in[z_in_count], idx, 0, start, len)) == NULL) { + fprintf(stderr, "error creating file source from '%s' index '%" PRIu64 "': %s\n", argv[1], idx, zip_strerror(za)); + zip_close(z_in[z_in_count]); + return -1; + } + if (zip_add(za, argv[0], zs) == -1) { + fprintf(stderr, "can't add file '%s': %s\n", argv[0], zip_strerror(za)); + zip_source_free(zs); + zip_close(z_in[z_in_count]); + return -1; + } + z_in_count++; + return 0; +} + +static int +cat(int argc, char *argv[]) { + /* output file contents to stdout */ + zip_uint64_t idx; + zip_int64_t n; + zip_file_t *zf; + char buf[8192]; + int err; + idx = strtoull(argv[0], NULL, 10); + +#ifdef _WIN32 + /* Need to set stdout to binary mode for Windows */ + setmode(fileno(stdout), _O_BINARY); +#endif + if ((zf = zip_fopen_index(za, idx, 0)) == NULL) { + fprintf(stderr, "can't open file at index '%" PRIu64 "': %s\n", idx, zip_strerror(za)); + return -1; + } + while ((n = zip_fread(zf, buf, sizeof(buf))) > 0) { + if (fwrite(buf, (size_t)n, 1, stdout) != 1) { + zip_fclose(zf); + fprintf(stderr, "can't write file contents to stdout: %s\n", strerror(errno)); + return -1; + } + } + if (n == -1) { + fprintf(stderr, "can't read file at index '%" PRIu64 "': %s\n", idx, zip_file_strerror(zf)); + zip_fclose(zf); + return -1; + } + if ((err = zip_fclose(zf)) != 0) { + zip_error_t error; + + zip_error_init_with_code(&error, err); + fprintf(stderr, "can't close file at index '%" PRIu64 "': %s\n", idx, zip_error_strerror(&error)); + return -1; + } + + return 0; +} + +static int +count_extra(int argc, char *argv[]) { + zip_int16_t count; + zip_uint64_t idx; + zip_flags_t ceflags = 0; + idx = strtoull(argv[0], NULL, 10); + ceflags = get_flags(argv[1]); + if ((count = zip_file_extra_fields_count(za, idx, ceflags)) < 0) { + fprintf(stderr, "can't get extra field count for file at index '%" PRIu64 "': %s\n", idx, zip_strerror(za)); + return -1; + } + else { + printf("Extra field count: %d\n", count); + } + return 0; +} + +static int +count_extra_by_id(int argc, char *argv[]) { + zip_int16_t count; + zip_uint16_t eid; + zip_flags_t ceflags = 0; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + eid = (zip_uint16_t)strtoull(argv[1], NULL, 10); + ceflags = get_flags(argv[2]); + if ((count = zip_file_extra_fields_count_by_id(za, idx, eid, ceflags)) < 0) { + fprintf(stderr, "can't get extra field count for file at index '%" PRIu64 "' and for id '%d': %s\n", idx, eid, zip_strerror(za)); + return -1; + } + else { + printf("Extra field count: %d\n", count); + } + return 0; +} + +static int delete (int argc, char *argv[]) { + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + if (zip_delete(za, idx) < 0) { + fprintf(stderr, "can't delete file at index '%" PRIu64 "': %s\n", idx, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +delete_extra(int argc, char *argv[]) { + zip_flags_t geflags; + zip_uint16_t eid; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + eid = (zip_uint16_t)strtoull(argv[1], NULL, 10); + geflags = get_flags(argv[2]); + if ((zip_file_extra_field_delete(za, idx, eid, geflags)) < 0) { + fprintf(stderr, "can't delete extra field data for file at index '%" PRIu64 "', extra field id '%d': %s\n", idx, eid, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +delete_extra_by_id(int argc, char *argv[]) { + zip_flags_t geflags; + zip_uint16_t eid, eidx; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + eid = (zip_uint16_t)strtoull(argv[1], NULL, 10); + eidx = (zip_uint16_t)strtoull(argv[2], NULL, 10); + geflags = get_flags(argv[3]); + if ((zip_file_extra_field_delete_by_id(za, idx, eid, eidx, geflags)) < 0) { + fprintf(stderr, "can't delete extra field data for file at index '%" PRIu64 "', extra field id '%d', extra field idx '%d': %s\n", idx, eid, eidx, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +get_archive_comment(int argc, char *argv[]) { + const char *comment; + int len; + /* get archive comment */ + if ((comment = zip_get_archive_comment(za, &len, 0)) == NULL) + printf("No archive comment\n"); + else + printf("Archive comment: %.*s\n", len, comment); + return 0; +} + +static int +get_extra(int argc, char *argv[]) { + zip_flags_t geflags; + zip_uint16_t id, eidx, eflen; + const zip_uint8_t *efdata; + zip_uint64_t idx; + /* get extra field data */ + idx = strtoull(argv[0], NULL, 10); + eidx = (zip_uint16_t)strtoull(argv[1], NULL, 10); + geflags = get_flags(argv[2]); + if ((efdata = zip_file_extra_field_get(za, idx, eidx, &id, &eflen, geflags)) == NULL) { + fprintf(stderr, "can't get extra field data for file at index %" PRIu64 ", extra field %d, flags %u: %s\n", idx, eidx, geflags, zip_strerror(za)); + return -1; + } + printf("Extra field 0x%04x: len %d", id, eflen); + if (eflen > 0) { + printf(", data "); + hexdump(efdata, eflen); + } + printf("\n"); + return 0; +} + +static int +get_extra_by_id(int argc, char *argv[]) { + zip_flags_t geflags; + zip_uint16_t eid, eidx, eflen; + const zip_uint8_t *efdata; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + eid = (zip_uint16_t)strtoull(argv[1], NULL, 10); + eidx = (zip_uint16_t)strtoull(argv[2], NULL, 10); + geflags = get_flags(argv[3]); + if ((efdata = zip_file_extra_field_get_by_id(za, idx, eid, eidx, &eflen, geflags)) == NULL) { + fprintf(stderr, "can't get extra field data for file at index %" PRIu64 ", extra field id %d, ef index %d, flags %u: %s\n", idx, eid, eidx, geflags, zip_strerror(za)); + return -1; + } + printf("Extra field 0x%04x: len %d", eid, eflen); + if (eflen > 0) { + printf(", data "); + hexdump(efdata, eflen); + } + printf("\n"); + return 0; +} + +static int +get_file_comment(int argc, char *argv[]) { + const char *comment; + int len; + zip_uint64_t idx; + /* get file comment */ + idx = strtoull(argv[0], NULL, 10); + if ((comment = zip_get_file_comment(za, idx, &len, 0)) == NULL) { + fprintf(stderr, "can't get comment for '%s': %s\n", zip_get_name(za, idx, 0), zip_strerror(za)); + return -1; + } + else if (len == 0) + printf("No comment for '%s'\n", zip_get_name(za, idx, 0)); + else + printf("File comment for '%s': %.*s\n", zip_get_name(za, idx, 0), len, comment); + return 0; +} + +static int +get_num_entries(int argc, char *argv[]) { + zip_int64_t count; + zip_flags_t flags; + /* get number of entries in archive */ + flags = get_flags(argv[0]); + count = zip_get_num_entries(za, flags); + printf("%" PRId64 " entr%s in archive\n", count, count == 1 ? "y" : "ies"); + return 0; +} + +static int +name_locate(int argc, char *argv[]) { + zip_flags_t flags; + zip_int64_t idx; + flags = get_flags(argv[1]); + + if ((idx = zip_name_locate(za, argv[0], flags)) < 0) { + fprintf(stderr, "can't find entry with name '%s' using flags '%s'\n", argv[0], argv[1]); + } + else { + printf("name '%s' using flags '%s' found at index %" PRId64 "\n", argv[0], argv[1], idx); + } + + return 0; +} + +static void +progress_callback(zip_t *archive, double percentage, void *ud) { + printf("%.1lf%% done\n", percentage * 100); +} + +static int +print_progress(int argc, char *argv[]) { + zip_register_progress_callback_with_state(za, 0.001, progress_callback, NULL, NULL); + return 0; +} + +static int +zrename(int argc, char *argv[]) { + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + if (zip_rename(za, idx, argv[1]) < 0) { + fprintf(stderr, "can't rename file at index '%" PRIu64 "' to '%s': %s\n", idx, argv[1], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +replace_file_contents(int argc, char *argv[]) { + /* replace file contents with data from command line */ + const char *content; + zip_source_t *s; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + content = argv[1]; + if ((s = zip_source_buffer(za, content, strlen(content), 0)) == NULL || zip_file_replace(za, idx, s, 0) < 0) { + zip_source_free(s); + fprintf(stderr, "error replacing file data: %s\n", zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_extra(int argc, char *argv[]) { + zip_flags_t geflags; + zip_uint16_t eid, eidx; + const zip_uint8_t *efdata; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + eid = (zip_uint16_t)strtoull(argv[1], NULL, 10); + eidx = (zip_uint16_t)strtoull(argv[2], NULL, 10); + geflags = get_flags(argv[3]); + efdata = (zip_uint8_t *)argv[4]; + if ((zip_file_extra_field_set(za, idx, eid, eidx, efdata, (zip_uint16_t)strlen((const char *)efdata), geflags)) < 0) { + fprintf(stderr, "can't set extra field data for file at index '%" PRIu64 "', extra field id '%d', index '%d': %s\n", idx, eid, eidx, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_archive_comment(int argc, char *argv[]) { + if (zip_set_archive_comment(za, argv[0], (zip_uint16_t)strlen(argv[0])) < 0) { + fprintf(stderr, "can't set archive comment to '%s': %s\n", argv[0], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_file_comment(int argc, char *argv[]) { + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + if (zip_file_set_comment(za, idx, argv[1], (zip_uint16_t)strlen(argv[1]), 0) < 0) { + fprintf(stderr, "can't set file comment at index '%" PRIu64 "' to '%s': %s\n", idx, argv[1], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_file_compression(int argc, char *argv[]) { + zip_int32_t method; + zip_uint32_t flags; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + method = get_compression_method(argv[1]); + flags = (zip_uint32_t)strtoull(argv[2], NULL, 10); + if (zip_set_file_compression(za, idx, method, flags) < 0) { + fprintf(stderr, "can't set file compression method at index '%" PRIu64 "' to '%s', flags '%d': %s\n", idx, argv[1], flags, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_file_encryption(int argc, char *argv[]) { + zip_uint16_t method; + zip_uint64_t idx; + char *password; + idx = strtoull(argv[0], NULL, 10); + method = get_encryption_method(argv[1]); + password = argv[2]; + if (strlen(password) == 0) { + password = NULL; + } + if (zip_file_set_encryption(za, idx, method, password) < 0) { + fprintf(stderr, "can't set file encryption method at index '%" PRIu64 "' to '%s': %s\n", idx, argv[1], zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_file_mtime(int argc, char *argv[]) { + /* set file last modification time (mtime) */ + time_t mtime; + zip_uint64_t idx; + idx = strtoull(argv[0], NULL, 10); + mtime = (time_t)strtoull(argv[1], NULL, 10); + if (zip_file_set_mtime(za, idx, mtime, 0) < 0) { + fprintf(stderr, "can't set file mtime at index '%" PRIu64 "' to '%ld': %s\n", idx, mtime, zip_strerror(za)); + return -1; + } + return 0; +} + +static int +set_file_mtime_all(int argc, char *argv[]) { + /* set last modification time (mtime) for all files */ + time_t mtime; + zip_int64_t num_entries; + zip_uint64_t idx; + mtime = (time_t)strtoull(argv[0], NULL, 10); + + if ((num_entries = zip_get_num_entries(za, 0)) < 0) { + fprintf(stderr, "can't get number of entries: %s\n", zip_strerror(za)); + return -1; + } + for (idx = 0; idx < (zip_uint64_t)num_entries; idx++) { + if (zip_file_set_mtime(za, idx, mtime, 0) < 0) { + fprintf(stderr, "can't set file mtime at index '%" PRIu64 "' to '%ld': %s\n", idx, mtime, zip_strerror(za)); + return -1; + } + } + return 0; +} + +static int +set_password(int argc, char *argv[]) { + /* set default password */ + if (zip_set_default_password(za, argv[0]) < 0) { + fprintf(stderr, "can't set default password to '%s'\n", argv[0]); + return -1; + } + return 0; +} + +static int +zstat(int argc, char *argv[]) { + zip_uint64_t idx; + char buf[100]; + struct zip_stat sb; + idx = strtoull(argv[0], NULL, 10); + + if (zip_stat_index(za, idx, stat_flags, &sb) < 0) { + fprintf(stderr, "zip_stat_index failed on '%" PRIu64 "' failed: %s\n", idx, zip_strerror(za)); + return -1; + } + + if (sb.valid & ZIP_STAT_NAME) + printf("name: '%s'\n", sb.name); + if (sb.valid & ZIP_STAT_INDEX) + printf("index: '%" PRIu64 "'\n", sb.index); + if (sb.valid & ZIP_STAT_SIZE) + printf("size: '%" PRIu64 "'\n", sb.size); + if (sb.valid & ZIP_STAT_COMP_SIZE) + printf("compressed size: '%" PRIu64 "'\n", sb.comp_size); + if (sb.valid & ZIP_STAT_MTIME) { + struct tm *tpm; + tpm = localtime(&sb.mtime); + if (tpm == NULL) { + printf("mtime: \n"); + } else { + strftime(buf, sizeof(buf), "%a %b %d %Y %H:%M:%S", tpm); + printf("mtime: '%s'\n", buf); + } + } + if (sb.valid & ZIP_STAT_CRC) + printf("crc: '%0x'\n", sb.crc); + if (sb.valid & ZIP_STAT_COMP_METHOD) + printf("compression method: '%d'\n", sb.comp_method); + if (sb.valid & ZIP_STAT_ENCRYPTION_METHOD) + printf("encryption method: '%d'\n", sb.encryption_method); + if (sb.valid & ZIP_STAT_FLAGS) + printf("flags: '%ld'\n", (long)sb.flags); + printf("\n"); + + return 0; +} + +static zip_flags_t +get_flags(const char *arg) { + zip_flags_t flags = 0; + if (strchr(arg, 'C') != NULL) + flags |= ZIP_FL_NOCASE; + if (strchr(arg, 'c') != NULL) + flags |= ZIP_FL_CENTRAL; + if (strchr(arg, 'd') != NULL) + flags |= ZIP_FL_NODIR; + if (strchr(arg, 'l') != NULL) + flags |= ZIP_FL_LOCAL; + if (strchr(arg, 'u') != NULL) + flags |= ZIP_FL_UNCHANGED; + return flags; +} + +static zip_int32_t +get_compression_method(const char *arg) { + if (strcmp(arg, "default") == 0) + return ZIP_CM_DEFAULT; + else if (strcmp(arg, "store") == 0) + return ZIP_CM_STORE; + else if (strcmp(arg, "deflate") == 0) + return ZIP_CM_DEFLATE; +#if defined(HAVE_LIBBZ2) + else if (strcmp(arg, "bzip2") == 0) + return ZIP_CM_BZIP2; +#endif + else if (strcmp(arg, "unknown") == 0) + return 100; + return 0; /* TODO: error handling */ +} + +static zip_uint16_t +get_encryption_method(const char *arg) { + if (strcmp(arg, "none") == 0) + return ZIP_EM_NONE; + else if (strcmp(arg, "AES-128") == 0) + return ZIP_EM_AES_128; + else if (strcmp(arg, "AES-192") == 0) + return ZIP_EM_AES_192; + else if (strcmp(arg, "AES-256") == 0) + return ZIP_EM_AES_256; + else if (strcmp(arg, "unknown") == 0) + return 100; + return (zip_uint16_t)-1; /* TODO: error handling */ +} + +static void +hexdump(const zip_uint8_t *data, zip_uint16_t len) { + zip_uint16_t i; + + if (len <= 0) + return; + + printf("0x"); + + for (i = 0; i < len; i++) + printf("%02x", data[i]); + + return; +} + + +static zip_t * +read_from_file(const char *archive, int flags, zip_error_t *error, zip_uint64_t offset, zip_uint64_t length) { + zip_t *zaa; + zip_source_t *source; + int err; + + if (offset == 0 && length == 0) { + if (strcmp(archive, "/dev/stdin") == 0) { + zaa = zip_fdopen(STDIN_FILENO, flags & ~ZIP_CREATE, &err); + } + else { + zaa = zip_open(archive, flags, &err); + } + if (zaa == NULL) { + zip_error_set(error, err, errno); + return NULL; + } + } + else { + if (length > ZIP_INT64_MAX) { + zip_error_set(error, ZIP_ER_INVAL, 0); + return NULL; + } + if ((source = zip_source_file_create(archive, offset, (zip_int64_t)length, error)) == NULL || (zaa = zip_open_from_source(source, flags, error)) == NULL) { + zip_source_free(source); + return NULL; + } + } + + return zaa; +} + +dispatch_table_t dispatch_table[] = {{"add", 2, "name content", "add file called name using content", add}, + {"add_dir", 1, "name", "add directory", add_dir}, + {"add_file", 4, "name file_to_add offset len", "add file to archive, len bytes starting from offset", add_file}, + {"add_from_zip", 5, "name archivename index offset len", "add file from another archive, len bytes starting from offset", add_from_zip}, + {"cat", 1, "index", "output file contents to stdout", cat}, + {"count_extra", 2, "index flags", "show number of extra fields for archive entry", count_extra}, + {"count_extra_by_id", 3, "index extra_id flags", "show number of extra fields of type extra_id for archive entry", count_extra_by_id}, + {"delete", 1, "index", "remove entry", delete}, + {"delete_extra", 3, "index extra_idx flags", "remove extra field", delete_extra}, + {"delete_extra_by_id", 4, "index extra_id extra_index flags", "remove extra field of type extra_id", delete_extra_by_id}, + {"get_archive_comment", 0, "", "show archive comment", get_archive_comment}, + {"get_extra", 3, "index extra_index flags", "show extra field", get_extra}, + {"get_extra_by_id", 4, "index extra_id extra_index flags", "show extra field of type extra_id", get_extra_by_id}, + {"get_file_comment", 1, "index", "get file comment", get_file_comment}, + {"get_num_entries", 1, "flags", "get number of entries in archive", get_num_entries}, + {"name_locate", 2, "name flags", "find entry in archive", name_locate}, + {"print_progress", 0, "", "print progress during zip_close()", print_progress}, + {"rename", 2, "index name", "rename entry", zrename}, + {"replace_file_contents", 2, "index data", "replace entry with data", replace_file_contents}, + {"set_archive_comment", 1, "comment", "set archive comment", set_archive_comment}, + {"set_extra", 5, "index extra_id extra_index flags value", "set extra field", set_extra}, + {"set_file_comment", 2, "index comment", "set file comment", set_file_comment}, + {"set_file_compression", 3, "index method compression_flags", "set file compression method", set_file_compression}, + {"set_file_encryption", 3, "index method password", "set file encryption method", set_file_encryption}, + {"set_file_mtime", 2, "index timestamp", "set file modification time", set_file_mtime}, + {"set_file_mtime_all", 1, "timestamp", "set file modification time for all files", set_file_mtime_all}, + {"set_password", 1, "password", "set default password for encryption", set_password}, + {"stat", 1, "index", "print information about entry", zstat} +#ifdef DISPATCH_REGRESS + , + DISPATCH_REGRESS +#endif +}; + +static int +dispatch(int argc, char *argv[]) { + unsigned int i; + for (i = 0; i < sizeof(dispatch_table) / sizeof(dispatch_table_t); i++) { + if (strcmp(dispatch_table[i].cmdline_name, argv[0]) == 0) { + argc--; + argv++; + /* 1 for the command, argument_count for the arguments */ + if (argc < dispatch_table[i].argument_count) { + fprintf(stderr, "not enough arguments for command '%s': %d available, %d needed\n", dispatch_table[i].cmdline_name, argc, dispatch_table[i].argument_count); + return -1; + } + if (dispatch_table[i].function(argc, argv) == 0) + return 1 + dispatch_table[i].argument_count; + return -1; + } + } + + fprintf(stderr, "unknown command '%s'\n", argv[0]); + return -1; +} + + +static void +usage(const char *progname, const char *reason) { + unsigned int i; + FILE *out; + if (reason == NULL) + out = stdout; + else + out = stderr; + fprintf(out, "usage: %s [-ceghnrst]" USAGE_REGRESS " [-l len] [-o offset] archive command1 [args] [command2 [args] ...]\n", progname); + if (reason != NULL) { + fprintf(out, "%s\n", reason); + exit(1); + } + + fprintf(out, "\nSupported options are:\n" + "\t-c\t\tcheck consistency\n" + "\t-e\t\terror if archive already exists (only useful with -n)\n" +#ifdef FOR_REGRESS + "\t-F size\t\tfragment size for in memory archive\n" +#endif + "\t-g\t\tguess file name encoding (for stat)\n" +#ifdef FOR_REGRESS + "\t-H\t\twrite files with holes compactly\n" +#endif + "\t-h\t\tdisplay this usage\n" + "\t-l len\t\tonly use len bytes of file\n" +#ifdef FOR_REGRESS + "\t-m\t\tread archive into memory, and modify there; write out at end\n" +#endif + "\t-n\t\tcreate archive if it doesn't exist\n" + "\t-o offset\tstart reading file at offset\n" + "\t-r\t\tprint raw file name encoding without translation (for stat)\n" + "\t-s\t\tfollow file name convention strictly (for stat)\n" + "\t-t\t\tdisregard current archive contents, if any\n"); + fprintf(out, "\nSupported commands and arguments are:\n"); + for (i = 0; i < sizeof(dispatch_table) / sizeof(dispatch_table_t); i++) { + fprintf(out, "\t%s %s\n\t %s\n\n", dispatch_table[i].cmdline_name, dispatch_table[i].arg_names, dispatch_table[i].description); + } + fprintf(out, "\nSupported flags are:\n" + "\t0\t(no flags)\n" + "\tC\tZIP_FL_NOCASE\n" + "\tc\tZIP_FL_CENTRAL\n" + "\td\tZIP_FL_NODIR\n" + "\tl\tZIP_FL_LOCAL\n" + "\tu\tZIP_FL_UNCHANGED\n"); + fprintf(out, "\nSupported compression methods are:\n" + "\tdefault\n" +#if defined(HAVE_LIBBZ2) + "\tbzip2\n" +#endif + "\tdeflate\n" + "\tstore\n"); + fprintf(out, "\nSupported compression methods are:\n" + "\tnone\n" + "\tAES-128\n" + "\tAES-192\n" + "\tAES-256\n"); + fprintf(out, "\nThe index is zero-based.\n"); + exit(0); +} + +#ifndef FOR_REGRESS +#define ziptool_open read_from_file +int +ziptool_post_close(const char *archive) { + return 0; +} +#endif + +int +main(int argc, char *argv[]) { + const char *archive; + unsigned int i; + int c, arg, err, flags; + const char *prg; + zip_uint64_t len = 0, offset = 0; + zip_error_t error; + + flags = 0; + prg = argv[0]; + + while ((c = getopt(argc, argv, "ceghl:no:rst" OPTIONS_REGRESS)) != -1) { + switch (c) { + case 'c': + flags |= ZIP_CHECKCONS; + break; + case 'e': + flags |= ZIP_EXCL; + break; + case 'g': + stat_flags = ZIP_FL_ENC_GUESS; + break; + case 'h': + usage(prg, NULL); + break; + case 'l': + len = strtoull(optarg, NULL, 10); + break; + case 'n': + flags |= ZIP_CREATE; + break; + case 'o': + offset = strtoull(optarg, NULL, 10); + break; + case 'r': + stat_flags = ZIP_FL_ENC_RAW; + break; + case 's': + stat_flags = ZIP_FL_ENC_STRICT; + break; + case 't': + flags |= ZIP_TRUNCATE; + break; +#ifdef GETOPT_REGRESS + GETOPT_REGRESS +#endif + + default: { + char reason[128]; + snprintf(reason, sizeof(reason), "invalid option -%c", optopt); + usage(prg, reason); + } + } + } + + if (optind >= argc - 1) + usage(prg, "too few arguments"); + + arg = optind; + + archive = argv[arg++]; + + if (flags == 0) + flags = ZIP_CREATE; + + zip_error_init(&error); + za = ziptool_open(archive, flags, &error, offset, len); + if (za == NULL) { + fprintf(stderr, "can't open zip archive '%s': %s\n", archive, zip_error_strerror(&error)); + zip_error_fini(&error); + return 1; + } + zip_error_fini(&error); + + err = 0; + while (arg < argc) { + int ret; + ret = dispatch(argc - arg, argv + arg); + if (ret > 0) { + arg += ret; + } + else { + err = 1; + break; + } + } + + if (zip_close(za) == -1) { + fprintf(stderr, "can't close zip archive '%s': %s\n", archive, zip_strerror(za)); + return 1; + } + if (ziptool_post_close(archive) < 0) { + err = 1; + } + + for (i = 0; i < z_in_count; i++) { + if (zip_close(z_in[i]) < 0) { + err = 1; + } + } + + return err; +} diff --git a/third_party/zlib/v1_2_11/CMakeLists.txt b/third_party/zlib/v1_2_11/CMakeLists.txt new file mode 100644 index 0000000..0fe939d --- /dev/null +++ b/third_party/zlib/v1_2_11/CMakeLists.txt @@ -0,0 +1,249 @@ +cmake_minimum_required(VERSION 2.4.4) +set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON) + +project(zlib C) + +set(VERSION "1.2.11") + +option(ASM686 "Enable building i686 assembly implementation") +option(AMD64 "Enable building amd64 assembly implementation") + +set(INSTALL_BIN_DIR "${CMAKE_INSTALL_PREFIX}/bin" CACHE PATH "Installation directory for executables") +set(INSTALL_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib" CACHE PATH "Installation directory for libraries") +set(INSTALL_INC_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "Installation directory for headers") +set(INSTALL_MAN_DIR "${CMAKE_INSTALL_PREFIX}/share/man" CACHE PATH "Installation directory for manual pages") +set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files") + +include(CheckTypeSize) +include(CheckFunctionExists) +include(CheckIncludeFile) +include(CheckCSourceCompiles) +enable_testing() + +check_include_file(sys/types.h HAVE_SYS_TYPES_H) +check_include_file(stdint.h HAVE_STDINT_H) +check_include_file(stddef.h HAVE_STDDEF_H) + +# +# Check to see if we have large file support +# +set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1) +# We add these other definitions here because CheckTypeSize.cmake +# in CMake 2.4.x does not automatically do so and we want +# compatibility with CMake 2.4.x. +if(HAVE_SYS_TYPES_H) + list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H) +endif() +if(HAVE_STDINT_H) + list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H) +endif() +if(HAVE_STDDEF_H) + list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H) +endif() +check_type_size(off64_t OFF64_T) +if(HAVE_OFF64_T) + add_definitions(-D_LARGEFILE64_SOURCE=1) +endif() +set(CMAKE_REQUIRED_DEFINITIONS) # clear variable + +# +# Check for fseeko +# +check_function_exists(fseeko HAVE_FSEEKO) +if(NOT HAVE_FSEEKO) + add_definitions(-DNO_FSEEKO) +endif() + +# +# Check for unistd.h +# +check_include_file(unistd.h Z_HAVE_UNISTD_H) + +if(MSVC) + set(CMAKE_DEBUG_POSTFIX "d") + add_definitions(-D_CRT_SECURE_NO_DEPRECATE) + add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR) + # If we're doing an out of source build and the user has a zconf.h + # in their source tree... + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h) + message(STATUS "Renaming") + message(STATUS " ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h") + message(STATUS "to 'zconf.h.included' because this file is included with zlib") + message(STATUS "but CMake generates it automatically in the build directory.") + file(RENAME ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.included) + endif() +endif() + +set(ZLIB_PC ${CMAKE_CURRENT_BINARY_DIR}/zlib.pc) +configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zlib.pc.cmakein + ${ZLIB_PC} @ONLY) +configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.cmakein + ${CMAKE_CURRENT_BINARY_DIR}/zconf.h @ONLY) +include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}) + + +#============================================================================ +# zlib +#============================================================================ + +set(ZLIB_PUBLIC_HDRS + ${CMAKE_CURRENT_BINARY_DIR}/zconf.h + zlib.h +) +set(ZLIB_PRIVATE_HDRS + crc32.h + deflate.h + gzguts.h + inffast.h + inffixed.h + inflate.h + inftrees.h + trees.h + zutil.h +) +set(ZLIB_SRCS + adler32.c + compress.c + crc32.c + deflate.c + gzclose.c + gzlib.c + gzread.c + gzwrite.c + inflate.c + infback.c + inftrees.c + inffast.c + trees.c + uncompr.c + zutil.c +) + +if(NOT MINGW) + set(ZLIB_DLL_SRCS + win32/zlib1.rc # If present will override custom build rule below. + ) +endif() + +if(CMAKE_COMPILER_IS_GNUCC) + if(ASM686) + set(ZLIB_ASMS contrib/asm686/match.S) + elseif (AMD64) + set(ZLIB_ASMS contrib/amd64/amd64-match.S) + endif () + + if(ZLIB_ASMS) + add_definitions(-DASMV) + set_source_files_properties(${ZLIB_ASMS} PROPERTIES LANGUAGE C COMPILE_FLAGS -DNO_UNDERLINE) + endif() +endif() + +if(MSVC) + if(ASM686) + ENABLE_LANGUAGE(ASM_MASM) + set(ZLIB_ASMS + contrib/masmx86/inffas32.asm + contrib/masmx86/match686.asm + ) + elseif (AMD64) + ENABLE_LANGUAGE(ASM_MASM) + set(ZLIB_ASMS + contrib/masmx64/gvmat64.asm + contrib/masmx64/inffasx64.asm + ) + endif() + + if(ZLIB_ASMS) + add_definitions(-DASMV -DASMINF) + endif() +endif() + +# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION +file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents) +string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([-0-9A-Za-z.]+)\".*" + "\\1" ZLIB_FULL_VERSION ${_zlib_h_contents}) + +if(MINGW) + # This gets us DLL resource information when compiling on MinGW. + if(NOT CMAKE_RC_COMPILER) + set(CMAKE_RC_COMPILER windres.exe) + endif() + + add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj + COMMAND ${CMAKE_RC_COMPILER} + -D GCC_WINDRES + -I ${CMAKE_CURRENT_SOURCE_DIR} + -I ${CMAKE_CURRENT_BINARY_DIR} + -o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj + -i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc) + set(ZLIB_DLL_SRCS ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj) +endif(MINGW) + +add_library(zlib SHARED ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_DLL_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) +add_library(zlibstatic STATIC ${ZLIB_SRCS} ${ZLIB_ASMS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS}) +set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL) +set_target_properties(zlib PROPERTIES SOVERSION 1) + +if(NOT CYGWIN) + # This property causes shared libraries on Linux to have the full version + # encoded into their final filename. We disable this on Cygwin because + # it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll + # seems to be the default. + # + # This has no effect with MSVC, on that platform the version info for + # the DLL comes from the resource file win32/zlib1.rc + set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION}) +endif() + +if(UNIX) + # On unix-like platforms the library is almost always called libz + set_target_properties(zlib zlibstatic PROPERTIES OUTPUT_NAME z) + if(NOT APPLE) + set_target_properties(zlib PROPERTIES LINK_FLAGS "-Wl,--version-script,\"${CMAKE_CURRENT_SOURCE_DIR}/zlib.map\"") + endif() +elseif(BUILD_SHARED_LIBS AND WIN32) + # Creates zlib1.dll when building shared library version + set_target_properties(zlib PROPERTIES SUFFIX "1.dll") +endif() + +if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL ) + install(TARGETS zlib zlibstatic + RUNTIME DESTINATION "${INSTALL_BIN_DIR}" + ARCHIVE DESTINATION "${INSTALL_LIB_DIR}" + LIBRARY DESTINATION "${INSTALL_LIB_DIR}" ) +endif() +if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL ) + install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION "${INSTALL_INC_DIR}") +endif() +if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) + install(FILES zlib.3 DESTINATION "${INSTALL_MAN_DIR}/man3") +endif() +if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL ) + install(FILES ${ZLIB_PC} DESTINATION "${INSTALL_PKGCONFIG_DIR}") +endif() + +#============================================================================ +# Example binaries +#============================================================================ + +add_executable(example test/example.c) +target_link_libraries(example zlib) +add_test(example example) + +add_executable(minigzip test/minigzip.c) +target_link_libraries(minigzip zlib) + +if(HAVE_OFF64_T) + add_executable(example64 test/example.c) + target_link_libraries(example64 zlib) + set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") + add_test(example64 example64) + + add_executable(minigzip64 test/minigzip.c) + target_link_libraries(minigzip64 zlib) + set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64") +endif() diff --git a/third_party/zlib/v1_2_11/ChangeLog b/third_party/zlib/v1_2_11/ChangeLog new file mode 100644 index 0000000..30199a6 --- /dev/null +++ b/third_party/zlib/v1_2_11/ChangeLog @@ -0,0 +1,1515 @@ + + ChangeLog file for zlib + +Changes in 1.2.11 (15 Jan 2017) +- Fix deflate stored bug when pulling last block from window +- Permit immediate deflateParams changes before any deflate input + +Changes in 1.2.10 (2 Jan 2017) +- Avoid warnings on snprintf() return value +- Fix bug in deflate_stored() for zero-length input +- Fix bug in gzwrite.c that produced corrupt gzip files +- Remove files to be installed before copying them in Makefile.in +- Add warnings when compiling with assembler code + +Changes in 1.2.9 (31 Dec 2016) +- Fix contrib/minizip to permit unzipping with desktop API [Zouzou] +- Improve contrib/blast to return unused bytes +- Assure that gzoffset() is correct when appending +- Improve compress() and uncompress() to support large lengths +- Fix bug in test/example.c where error code not saved +- Remedy Coverity warning [Randers-Pehrson] +- Improve speed of gzprintf() in transparent mode +- Fix inflateInit2() bug when windowBits is 16 or 32 +- Change DEBUG macro to ZLIB_DEBUG +- Avoid uninitialized access by gzclose_w() +- Allow building zlib outside of the source directory +- Fix bug that accepted invalid zlib header when windowBits is zero +- Fix gzseek() problem on MinGW due to buggy _lseeki64 there +- Loop on write() calls in gzwrite.c in case of non-blocking I/O +- Add --warn (-w) option to ./configure for more compiler warnings +- Reject a window size of 256 bytes if not using the zlib wrapper +- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE +- Add --debug (-d) option to ./configure to define ZLIB_DEBUG +- Fix bugs in creating a very large gzip header +- Add uncompress2() function, which returns the input size used +- Assure that deflateParams() will not switch functions mid-block +- Dramatically speed up deflation for level 0 (storing) +- Add gzfread(), duplicating the interface of fread() +- Add gzfwrite(), duplicating the interface of fwrite() +- Add deflateGetDictionary() function +- Use snprintf() for later versions of Microsoft C +- Fix *Init macros to use z_ prefix when requested +- Replace as400 with os400 for OS/400 support [Monnerat] +- Add crc32_z() and adler32_z() functions with size_t lengths +- Update Visual Studio project files [AraHaan] + +Changes in 1.2.8 (28 Apr 2013) +- Update contrib/minizip/iowin32.c for Windows RT [Vollant] +- Do not force Z_CONST for C++ +- Clean up contrib/vstudio [Roß] +- Correct spelling error in zlib.h +- Fix mixed line endings in contrib/vstudio + +Changes in 1.2.7.3 (13 Apr 2013) +- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc + +Changes in 1.2.7.2 (13 Apr 2013) +- Change check for a four-byte type back to hexadecimal +- Fix typo in win32/Makefile.msc +- Add casts in gzwrite.c for pointer differences + +Changes in 1.2.7.1 (24 Mar 2013) +- Replace use of unsafe string functions with snprintf if available +- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink] +- Fix gzgetc undefine when Z_PREFIX set [Turk] +- Eliminate use of mktemp in Makefile (not always available) +- Fix bug in 'F' mode for gzopen() +- Add inflateGetDictionary() function +- Correct comment in deflate.h +- Use _snprintf for snprintf in Microsoft C +- On Darwin, only use /usr/bin/libtool if libtool is not Apple +- Delete "--version" file if created by "ar --version" [Richard G.] +- Fix configure check for veracity of compiler error return codes +- Fix CMake compilation of static lib for MSVC2010 x64 +- Remove unused variable in infback9.c +- Fix argument checks in gzlog_compress() and gzlog_write() +- Clean up the usage of z_const and respect const usage within zlib +- Clean up examples/gzlog.[ch] comparisons of different types +- Avoid shift equal to bits in type (caused endless loop) +- Fix uninitialized value bug in gzputc() introduced by const patches +- Fix memory allocation error in examples/zran.c [Nor] +- Fix bug where gzopen(), gzclose() would write an empty file +- Fix bug in gzclose() when gzwrite() runs out of memory +- Check for input buffer malloc failure in examples/gzappend.c +- Add note to contrib/blast to use binary mode in stdio +- Fix comparisons of differently signed integers in contrib/blast +- Check for invalid code length codes in contrib/puff +- Fix serious but very rare decompression bug in inftrees.c +- Update inflateBack() comments, since inflate() can be faster +- Use underscored I/O function names for WINAPI_FAMILY +- Add _tr_flush_bits to the external symbols prefixed by --zprefix +- Add contrib/vstudio/vc10 pre-build step for static only +- Quote --version-script argument in CMakeLists.txt +- Don't specify --version-script on Apple platforms in CMakeLists.txt +- Fix casting error in contrib/testzlib/testzlib.c +- Fix types in contrib/minizip to match result of get_crc_table() +- Simplify contrib/vstudio/vc10 with 'd' suffix +- Add TOP support to win32/Makefile.msc +- Suport i686 and amd64 assembler builds in CMakeLists.txt +- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h +- Add vc11 and vc12 build files to contrib/vstudio +- Add gzvprintf() as an undocumented function in zlib +- Fix configure for Sun shell +- Remove runtime check in configure for four-byte integer type +- Add casts and consts to ease user conversion to C++ +- Add man pages for minizip and miniunzip +- In Makefile uninstall, don't rm if preceding cd fails +- Do not return Z_BUF_ERROR if deflateParam() has nothing to write + +Changes in 1.2.7 (2 May 2012) +- Replace use of memmove() with a simple copy for portability +- Test for existence of strerror +- Restore gzgetc_ for backward compatibility with 1.2.6 +- Fix build with non-GNU make on Solaris +- Require gcc 4.0 or later on Mac OS X to use the hidden attribute +- Include unistd.h for Watcom C +- Use __WATCOMC__ instead of __WATCOM__ +- Do not use the visibility attribute if NO_VIZ defined +- Improve the detection of no hidden visibility attribute +- Avoid using __int64 for gcc or solo compilation +- Cast to char * in gzprintf to avoid warnings [Zinser] +- Fix make_vms.com for VAX [Zinser] +- Don't use library or built-in byte swaps +- Simplify test and use of gcc hidden attribute +- Fix bug in gzclose_w() when gzwrite() fails to allocate memory +- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen() +- Fix bug in test/minigzip.c for configure --solo +- Fix contrib/vstudio project link errors [Mohanathas] +- Add ability to choose the builder in make_vms.com [Schweda] +- Add DESTDIR support to mingw32 win32/Makefile.gcc +- Fix comments in win32/Makefile.gcc for proper usage +- Allow overriding the default install locations for cmake +- Generate and install the pkg-config file with cmake +- Build both a static and a shared version of zlib with cmake +- Include version symbols for cmake builds +- If using cmake with MSVC, add the source directory to the includes +- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta] +- Move obsolete emx makefile to old [Truta] +- Allow the use of -Wundef when compiling or using zlib +- Avoid the use of the -u option with mktemp +- Improve inflate() documentation on the use of Z_FINISH +- Recognize clang as gcc +- Add gzopen_w() in Windows for wide character path names +- Rename zconf.h in CMakeLists.txt to move it out of the way +- Add source directory in CMakeLists.txt for building examples +- Look in build directory for zlib.pc in CMakeLists.txt +- Remove gzflags from zlibvc.def in vc9 and vc10 +- Fix contrib/minizip compilation in the MinGW environment +- Update ./configure for Solaris, support --64 [Mooney] +- Remove -R. from Solaris shared build (possible security issue) +- Avoid race condition for parallel make (-j) running example +- Fix type mismatch between get_crc_table() and crc_table +- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler] +- Fix the path to zlib.map in CMakeLists.txt +- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe] +- Add instructions to win32/Makefile.gcc for shared install [Torri] + +Changes in 1.2.6.1 (12 Feb 2012) +- Avoid the use of the Objective-C reserved name "id" +- Include io.h in gzguts.h for Microsoft compilers +- Fix problem with ./configure --prefix and gzgetc macro +- Include gz_header definition when compiling zlib solo +- Put gzflags() functionality back in zutil.c +- Avoid library header include in crc32.c for Z_SOLO +- Use name in GCC_CLASSIC as C compiler for coverage testing, if set +- Minor cleanup in contrib/minizip/zip.c [Vollant] +- Update make_vms.com [Zinser] +- Remove unnecessary gzgetc_ function +- Use optimized byte swap operations for Microsoft and GNU [Snyder] +- Fix minor typo in zlib.h comments [Rzesniowiecki] + +Changes in 1.2.6 (29 Jan 2012) +- Update the Pascal interface in contrib/pascal +- Fix function numbers for gzgetc_ in zlibvc.def files +- Fix configure.ac for contrib/minizip [Schiffer] +- Fix large-entry detection in minizip on 64-bit systems [Schiffer] +- Have ./configure use the compiler return code for error indication +- Fix CMakeLists.txt for cross compilation [McClure] +- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes] +- Fix compilation of contrib/minizip on FreeBSD [Marquez] +- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath] +- Include io.h for Turbo C / Borland C on all platforms [Truta] +- Make version explicit in contrib/minizip/configure.ac [Bosmans] +- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant] +- Minor cleanup up contrib/minizip/unzip.c [Vollant] +- Fix bug when compiling minizip with C++ [Vollant] +- Protect for long name and extra fields in contrib/minizip [Vollant] +- Avoid some warnings in contrib/minizip [Vollant] +- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip +- Add missing libs to minizip linker command +- Add support for VPATH builds in contrib/minizip +- Add an --enable-demos option to contrib/minizip/configure +- Add the generation of configure.log by ./configure +- Exit when required parameters not provided to win32/Makefile.gcc +- Have gzputc return the character written instead of the argument +- Use the -m option on ldconfig for BSD systems [Tobias] +- Correct in zlib.map when deflateResetKeep was added + +Changes in 1.2.5.3 (15 Jan 2012) +- Restore gzgetc function for binary compatibility +- Do not use _lseeki64 under Borland C++ [Truta] +- Update win32/Makefile.msc to build test/*.c [Truta] +- Remove old/visualc6 given CMakefile and other alternatives +- Update AS400 build files and documentation [Monnerat] +- Update win32/Makefile.gcc to build test/*.c [Truta] +- Permit stronger flushes after Z_BLOCK flushes +- Avoid extraneous empty blocks when doing empty flushes +- Permit Z_NULL arguments to deflatePending +- Allow deflatePrime() to insert bits in the middle of a stream +- Remove second empty static block for Z_PARTIAL_FLUSH +- Write out all of the available bits when using Z_BLOCK +- Insert the first two strings in the hash table after a flush + +Changes in 1.2.5.2 (17 Dec 2011) +- fix ld error: unable to find version dependency 'ZLIB_1.2.5' +- use relative symlinks for shared libs +- Avoid searching past window for Z_RLE strategy +- Assure that high-water mark initialization is always applied in deflate +- Add assertions to fill_window() in deflate.c to match comments +- Update python link in README +- Correct spelling error in gzread.c +- Fix bug in gzgets() for a concatenated empty gzip stream +- Correct error in comment for gz_make() +- Change gzread() and related to ignore junk after gzip streams +- Allow gzread() and related to continue after gzclearerr() +- Allow gzrewind() and gzseek() after a premature end-of-file +- Simplify gzseek() now that raw after gzip is ignored +- Change gzgetc() to a macro for speed (~40% speedup in testing) +- Fix gzclose() to return the actual error last encountered +- Always add large file support for windows +- Include zconf.h for windows large file support +- Include zconf.h.cmakein for windows large file support +- Update zconf.h.cmakein on make distclean +- Merge vestigial vsnprintf determination from zutil.h to gzguts.h +- Clarify how gzopen() appends in zlib.h comments +- Correct documentation of gzdirect() since junk at end now ignored +- Add a transparent write mode to gzopen() when 'T' is in the mode +- Update python link in zlib man page +- Get inffixed.h and MAKEFIXED result to match +- Add a ./config --solo option to make zlib subset with no library use +- Add undocumented inflateResetKeep() function for CAB file decoding +- Add --cover option to ./configure for gcc coverage testing +- Add #define ZLIB_CONST option to use const in the z_stream interface +- Add comment to gzdopen() in zlib.h to use dup() when using fileno() +- Note behavior of uncompress() to provide as much data as it can +- Add files in contrib/minizip to aid in building libminizip +- Split off AR options in Makefile.in and configure +- Change ON macro to Z_ARG to avoid application conflicts +- Facilitate compilation with Borland C++ for pragmas and vsnprintf +- Include io.h for Turbo C / Borland C++ +- Move example.c and minigzip.c to test/ +- Simplify incomplete code table filling in inflate_table() +- Remove code from inflate.c and infback.c that is impossible to execute +- Test the inflate code with full coverage +- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw) +- Add deflateResetKeep and fix inflateResetKeep to retain dictionary +- Fix gzwrite.c to accommodate reduced memory zlib compilation +- Have inflate() with Z_FINISH avoid the allocation of a window +- Do not set strm->adler when doing raw inflate +- Fix gzeof() to behave just like feof() when read is not past end of file +- Fix bug in gzread.c when end-of-file is reached +- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF +- Document gzread() capability to read concurrently written files +- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo] + +Changes in 1.2.5.1 (10 Sep 2011) +- Update FAQ entry on shared builds (#13) +- Avoid symbolic argument to chmod in Makefile.in +- Fix bug and add consts in contrib/puff [Oberhumer] +- Update contrib/puff/zeros.raw test file to have all block types +- Add full coverage test for puff in contrib/puff/Makefile +- Fix static-only-build install in Makefile.in +- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno] +- Add libz.a dependency to shared in Makefile.in for parallel builds +- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out +- Replace $(...) with `...` in configure for non-bash sh [Bowler] +- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen] +- Add solaris* to Linux* in configure to allow gcc use [Groffen] +- Add *bsd* to Linux* case in configure [Bar-Lev] +- Add inffast.obj to dependencies in win32/Makefile.msc +- Correct spelling error in deflate.h [Kohler] +- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc +- Add test to configure for GNU C looking for gcc in output of $cc -v +- Add zlib.pc generation to win32/Makefile.gcc [Weigelt] +- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not +- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense +- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser) +- Make stronger test in zconf.h to include unistd.h for LFS +- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack] +- Fix zlib.h LFS support when Z_PREFIX used +- Add updated as400 support (removed from old) [Monnerat] +- Avoid deflate sensitivity to volatile input data +- Avoid division in adler32_combine for NO_DIVIDE +- Clarify the use of Z_FINISH with deflateBound() amount of space +- Set binary for output file in puff.c +- Use u4 type for crc_table to avoid conversion warnings +- Apply casts in zlib.h to avoid conversion warnings +- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller] +- Improve inflateSync() documentation to note indeterminancy +- Add deflatePending() function to return the amount of pending output +- Correct the spelling of "specification" in FAQ [Randers-Pehrson] +- Add a check in configure for stdarg.h, use for gzprintf() +- Check that pointers fit in ints when gzprint() compiled old style +- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler] +- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt] +- Add debug records in assmebler code [Londer] +- Update RFC references to use http://tools.ietf.org/html/... [Li] +- Add --archs option, use of libtool to configure for Mac OS X [Borstel] + +Changes in 1.2.5 (19 Apr 2010) +- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] +- Default to libdir as sharedlibdir in configure [Nieder] +- Update copyright dates on modified source files +- Update trees.c to be able to generate modified trees.h +- Exit configure for MinGW, suggesting win32/Makefile.gcc +- Check for NULL path in gz_open [Homurlu] + +Changes in 1.2.4.5 (18 Apr 2010) +- Set sharedlibdir in configure [Torok] +- Set LDFLAGS in Makefile.in [Bar-Lev] +- Avoid mkdir objs race condition in Makefile.in [Bowler] +- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays +- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C +- Don't use hidden attribute when it is a warning generator (e.g. Solaris) + +Changes in 1.2.4.4 (18 Apr 2010) +- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] +- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty +- Try to use bash or ksh regardless of functionality of /bin/sh +- Fix configure incompatibility with NetBSD sh +- Remove attempt to run under bash or ksh since have better NetBSD fix +- Fix win32/Makefile.gcc for MinGW [Bar-Lev] +- Add diagnostic messages when using CROSS_PREFIX in configure +- Added --sharedlibdir option to configure [Weigelt] +- Use hidden visibility attribute when available [Frysinger] + +Changes in 1.2.4.3 (10 Apr 2010) +- Only use CROSS_PREFIX in configure for ar and ranlib if they exist +- Use CROSS_PREFIX for nm [Bar-Lev] +- Assume _LARGEFILE64_SOURCE defined is equivalent to true +- Avoid use of undefined symbols in #if with && and || +- Make *64 prototypes in gzguts.h consistent with functions +- Add -shared load option for MinGW in configure [Bowler] +- Move z_off64_t to public interface, use instead of off64_t +- Remove ! from shell test in configure (not portable to Solaris) +- Change +0 macro tests to -0 for possibly increased portability + +Changes in 1.2.4.2 (9 Apr 2010) +- Add consistent carriage returns to readme.txt's in masmx86 and masmx64 +- Really provide prototypes for *64 functions when building without LFS +- Only define unlink() in minigzip.c if unistd.h not included +- Update README to point to contrib/vstudio project files +- Move projects/vc6 to old/ and remove projects/ +- Include stdlib.h in minigzip.c for setmode() definition under WinCE +- Clean up assembler builds in win32/Makefile.msc [Rowe] +- Include sys/types.h for Microsoft for off_t definition +- Fix memory leak on error in gz_open() +- Symbolize nm as $NM in configure [Weigelt] +- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] +- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined +- Fix bug in gzeof() to take into account unused input data +- Avoid initialization of structures with variables in puff.c +- Updated win32/README-WIN32.txt [Rowe] + +Changes in 1.2.4.1 (28 Mar 2010) +- Remove the use of [a-z] constructs for sed in configure [gentoo 310225] +- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] +- Restore "for debugging" comment on sprintf() in gzlib.c +- Remove fdopen for MVS from gzguts.h +- Put new README-WIN32.txt in win32 [Rowe] +- Add check for shell to configure and invoke another shell if needed +- Fix big fat stinking bug in gzseek() on uncompressed files +- Remove vestigial F_OPEN64 define in zutil.h +- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE +- Avoid errors on non-LFS systems when applications define LFS macros +- Set EXE to ".exe" in configure for MINGW [Kahle] +- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] +- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] +- Add DLL install in win32/makefile.gcc [Bar-Lev] +- Allow Linux* or linux* from uname in configure [Bar-Lev] +- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] +- Add cross-compilation prefixes to configure [Bar-Lev] +- Match type exactly in gz_load() invocation in gzread.c +- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func +- Provide prototypes for *64 functions when building zlib without LFS +- Don't use -lc when linking shared library on MinGW +- Remove errno.h check in configure and vestigial errno code in zutil.h + +Changes in 1.2.4 (14 Mar 2010) +- Fix VER3 extraction in configure for no fourth subversion +- Update zlib.3, add docs to Makefile.in to make .pdf out of it +- Add zlib.3.pdf to distribution +- Don't set error code in gzerror() if passed pointer is NULL +- Apply destination directory fixes to CMakeLists.txt [Lowman] +- Move #cmakedefine's to a new zconf.in.cmakein +- Restore zconf.h for builds that don't use configure or cmake +- Add distclean to dummy Makefile for convenience +- Update and improve INDEX, README, and FAQ +- Update CMakeLists.txt for the return of zconf.h [Lowman] +- Update contrib/vstudio/vc9 and vc10 [Vollant] +- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc +- Apply license and readme changes to contrib/asm686 [Raiter] +- Check file name lengths and add -c option in minigzip.c [Li] +- Update contrib/amd64 and contrib/masmx86/ [Vollant] +- Avoid use of "eof" parameter in trees.c to not shadow library variable +- Update make_vms.com for removal of zlibdefs.h [Zinser] +- Update assembler code and vstudio projects in contrib [Vollant] +- Remove outdated assembler code contrib/masm686 and contrib/asm586 +- Remove old vc7 and vc8 from contrib/vstudio +- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] +- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() +- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] +- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) +- Fix bug in void-returning vsprintf() case in gzwrite.c +- Fix name change from inflate.h in contrib/inflate86/inffas86.c +- Check if temporary file exists before removing in make_vms.com [Zinser] +- Fix make install and uninstall for --static option +- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] +- Update readme.txt in contrib/masmx64 and masmx86 to assemble + +Changes in 1.2.3.9 (21 Feb 2010) +- Expunge gzio.c +- Move as400 build information to old +- Fix updates in contrib/minizip and contrib/vstudio +- Add const to vsnprintf test in configure to avoid warnings [Weigelt] +- Delete zconf.h (made by configure) [Weigelt] +- Change zconf.in.h to zconf.h.in per convention [Weigelt] +- Check for NULL buf in gzgets() +- Return empty string for gzgets() with len == 1 (like fgets()) +- Fix description of gzgets() in zlib.h for end-of-file, NULL return +- Update minizip to 1.1 [Vollant] +- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c +- Note in zlib.h that gzerror() should be used to distinguish from EOF +- Remove use of snprintf() from gzlib.c +- Fix bug in gzseek() +- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] +- Fix zconf.h generation in CMakeLists.txt [Lowman] +- Improve comments in zconf.h where modified by configure + +Changes in 1.2.3.8 (13 Feb 2010) +- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] +- Use z_off64_t in gz_zero() and gz_skip() to match state->skip +- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) +- Revert to Makefile.in from 1.2.3.6 (live with the clutter) +- Fix missing error return in gzflush(), add zlib.h note +- Add *64 functions to zlib.map [Levin] +- Fix signed/unsigned comparison in gz_comp() +- Use SFLAGS when testing shared linking in configure +- Add --64 option to ./configure to use -m64 with gcc +- Fix ./configure --help to correctly name options +- Have make fail if a test fails [Levin] +- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] +- Remove assembler object files from contrib + +Changes in 1.2.3.7 (24 Jan 2010) +- Always gzopen() with O_LARGEFILE if available +- Fix gzdirect() to work immediately after gzopen() or gzdopen() +- Make gzdirect() more precise when the state changes while reading +- Improve zlib.h documentation in many places +- Catch memory allocation failure in gz_open() +- Complete close operation if seek forward in gzclose_w() fails +- Return Z_ERRNO from gzclose_r() if close() fails +- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL +- Return zero for gzwrite() errors to match zlib.h description +- Return -1 on gzputs() error to match zlib.h description +- Add zconf.in.h to allow recovery from configure modification [Weigelt] +- Fix static library permissions in Makefile.in [Weigelt] +- Avoid warnings in configure tests that hide functionality [Weigelt] +- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] +- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] +- Avoid access of uninitialized data for first inflateReset2 call [Gomes] +- Keep object files in subdirectories to reduce the clutter somewhat +- Remove default Makefile and zlibdefs.h, add dummy Makefile +- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ +- Remove zlibdefs.h completely -- modify zconf.h instead + +Changes in 1.2.3.6 (17 Jan 2010) +- Avoid void * arithmetic in gzread.c and gzwrite.c +- Make compilers happier with const char * for gz_error message +- Avoid unused parameter warning in inflate.c +- Avoid signed-unsigned comparison warning in inflate.c +- Indent #pragma's for traditional C +- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() +- Correct email address in configure for system options +- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] +- Update zlib.map [Brown] +- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] +- Apply various fixes to CMakeLists.txt [Lowman] +- Add checks on len in gzread() and gzwrite() +- Add error message for no more room for gzungetc() +- Remove zlib version check in gzwrite() +- Defer compression of gzprintf() result until need to +- Use snprintf() in gzdopen() if available +- Remove USE_MMAP configuration determination (only used by minigzip) +- Remove examples/pigz.c (available separately) +- Update examples/gun.c to 1.6 + +Changes in 1.2.3.5 (8 Jan 2010) +- Add space after #if in zutil.h for some compilers +- Fix relatively harmless bug in deflate_fast() [Exarevsky] +- Fix same problem in deflate_slow() +- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] +- Add deflate_rle() for faster Z_RLE strategy run-length encoding +- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding +- Change name of "write" variable in inffast.c to avoid library collisions +- Fix premature EOF from gzread() in gzio.c [Brown] +- Use zlib header window size if windowBits is 0 in inflateInit2() +- Remove compressBound() call in deflate.c to avoid linking compress.o +- Replace use of errno in gz* with functions, support WinCE [Alves] +- Provide alternative to perror() in minigzip.c for WinCE [Alves] +- Don't use _vsnprintf on later versions of MSVC [Lowman] +- Add CMake build script and input file [Lowman] +- Update contrib/minizip to 1.1 [Svensson, Vollant] +- Moved nintendods directory from contrib to . +- Replace gzio.c with a new set of routines with the same functionality +- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above +- Update contrib/minizip to 1.1b +- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h + +Changes in 1.2.3.4 (21 Dec 2009) +- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility +- Update comments in configure and Makefile.in for default --shared +- Fix test -z's in configure [Marquess] +- Build examplesh and minigzipsh when not testing +- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h +- Import LDFLAGS from the environment in configure +- Fix configure to populate SFLAGS with discovered CFLAGS options +- Adapt make_vms.com to the new Makefile.in [Zinser] +- Add zlib2ansi script for C++ compilation [Marquess] +- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) +- Add AMD64 assembler code for longest match to contrib [Teterin] +- Include options from $SFLAGS when doing $LDSHARED +- Simplify 64-bit file support by introducing z_off64_t type +- Make shared object files in objs directory to work around old Sun cc +- Use only three-part version number for Darwin shared compiles +- Add rc option to ar in Makefile.in for when ./configure not run +- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* +- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile +- Protect against _FILE_OFFSET_BITS being defined when compiling zlib +- Rename Makefile.in targets allstatic to static and allshared to shared +- Fix static and shared Makefile.in targets to be independent +- Correct error return bug in gz_open() by setting state [Brown] +- Put spaces before ;;'s in configure for better sh compatibility +- Add pigz.c (parallel implementation of gzip) to examples/ +- Correct constant in crc32.c to UL [Leventhal] +- Reject negative lengths in crc32_combine() +- Add inflateReset2() function to work like inflateEnd()/inflateInit2() +- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] +- Correct typo in doc/algorithm.txt [Janik] +- Fix bug in adler32_combine() [Zhu] +- Catch missing-end-of-block-code error in all inflates and in puff + Assures that random input to inflate eventually results in an error +- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ +- Update ENOUGH and its usage to reflect discovered bounds +- Fix gzerror() error report on empty input file [Brown] +- Add ush casts in trees.c to avoid pedantic runtime errors +- Fix typo in zlib.h uncompress() description [Reiss] +- Correct inflate() comments with regard to automatic header detection +- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) +- Put new version of gzlog (2.0) in examples with interruption recovery +- Add puff compile option to permit invalid distance-too-far streams +- Add puff TEST command options, ability to read piped input +- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but + _LARGEFILE64_SOURCE not defined +- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart +- Fix deflateSetDictionary() to use all 32K for output consistency +- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) +- Clear bytes after deflate lookahead to avoid use of uninitialized data +- Change a limit in inftrees.c to be more transparent to Coverity Prevent +- Update win32/zlib.def with exported symbols from zlib.h +- Correct spelling errors in zlib.h [Willem, Sobrado] +- Allow Z_BLOCK for deflate() to force a new block +- Allow negative bits in inflatePrime() to delete existing bit buffer +- Add Z_TREES flush option to inflate() to return at end of trees +- Add inflateMark() to return current state information for random access +- Add Makefile for NintendoDS to contrib [Costa] +- Add -w in configure compile tests to avoid spurious warnings [Beucler] +- Fix typos in zlib.h comments for deflateSetDictionary() +- Fix EOF detection in transparent gzread() [Maier] + +Changes in 1.2.3.3 (2 October 2006) +- Make --shared the default for configure, add a --static option +- Add compile option to permit invalid distance-too-far streams +- Add inflateUndermine() function which is required to enable above +- Remove use of "this" variable name for C++ compatibility [Marquess] +- Add testing of shared library in make test, if shared library built +- Use ftello() and fseeko() if available instead of ftell() and fseek() +- Provide two versions of all functions that use the z_off_t type for + binary compatibility -- a normal version and a 64-bit offset version, + per the Large File Support Extension when _LARGEFILE64_SOURCE is + defined; use the 64-bit versions by default when _FILE_OFFSET_BITS + is defined to be 64 +- Add a --uname= option to configure to perhaps help with cross-compiling + +Changes in 1.2.3.2 (3 September 2006) +- Turn off silly Borland warnings [Hay] +- Use off64_t and define _LARGEFILE64_SOURCE when present +- Fix missing dependency on inffixed.h in Makefile.in +- Rig configure --shared to build both shared and static [Teredesai, Truta] +- Remove zconf.in.h and instead create a new zlibdefs.h file +- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] +- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] + +Changes in 1.2.3.1 (16 August 2006) +- Add watcom directory with OpenWatcom make files [Daniel] +- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] +- Update make_vms.com [Zinser] +- Use -fPIC for shared build in configure [Teredesai, Nicholson] +- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] +- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck] +- Add some FAQ entries about the contrib directory +- Update the MVS question in the FAQ +- Avoid extraneous reads after EOF in gzio.c [Brown] +- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] +- Add comments to zlib.h about gzerror() usage [Brown] +- Set extra flags in gzip header in gzopen() like deflate() does +- Make configure options more compatible with double-dash conventions + [Weigelt] +- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] +- Fix uninstall target in Makefile.in [Truta] +- Add pkgconfig support [Weigelt] +- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] +- Replace set_data_type() with a more accurate detect_data_type() in + trees.c, according to the txtvsbin.txt document [Truta] +- Swap the order of #include and #include "zlib.h" in + gzio.c, example.c and minigzip.c [Truta] +- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, + Truta] (where?) +- Fix target "clean" from win32/Makefile.bor [Truta] +- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] +- Update zlib www home address in win32/DLL_FAQ.txt [Truta] +- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] +- Enable browse info in the "Debug" and "ASM Debug" configurations in + the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] +- Add pkgconfig support [Weigelt] +- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, + for use in win32/zlib1.rc [Polushin, Rowe, Truta] +- Add a document that explains the new text detection scheme to + doc/txtvsbin.txt [Truta] +- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] +- Move algorithm.txt into doc/ [Truta] +- Synchronize FAQ with website +- Fix compressBound(), was low for some pathological cases [Fearnley] +- Take into account wrapper variations in deflateBound() +- Set examples/zpipe.c input and output to binary mode for Windows +- Update examples/zlib_how.html with new zpipe.c (also web site) +- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems + that gcc became pickier in 4.0) +- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain + un-versioned, the patch adds versioning only for symbols introduced in + zlib-1.2.0 or later. It also declares as local those symbols which are + not designed to be exported." [Levin] +- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure +- Do not initialize global static by default in trees.c, add a response + NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] +- Don't use strerror() in gzio.c under WinCE [Yakimov] +- Don't use errno.h in zutil.h under WinCE [Yakimov] +- Move arguments for AR to its usage to allow replacing ar [Marot] +- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] +- Improve inflateInit() and inflateInit2() documentation +- Fix structure size comment in inflate.h +- Change configure help option from --h* to --help [Santos] + +Changes in 1.2.3 (18 July 2005) +- Apply security vulnerability fixes to contrib/infback9 as well +- Clean up some text files (carriage returns, trailing space) +- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] + +Changes in 1.2.2.4 (11 July 2005) +- Add inflatePrime() function for starting inflation at bit boundary +- Avoid some Visual C warnings in deflate.c +- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit + compile +- Fix some spelling errors in comments [Betts] +- Correct inflateInit2() error return documentation in zlib.h +- Add zran.c example of compressed data random access to examples + directory, shows use of inflatePrime() +- Fix cast for assignments to strm->state in inflate.c and infback.c +- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] +- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] +- Add cast in trees.c t avoid a warning [Oberhumer] +- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] +- Update make_vms.com [Zinser] +- Initialize state->write in inflateReset() since copied in inflate_fast() +- Be more strict on incomplete code sets in inflate_table() and increase + ENOUGH and MAXD -- this repairs a possible security vulnerability for + invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for + discovering the vulnerability and providing test cases. +- Add ia64 support to configure for HP-UX [Smith] +- Add error return to gzread() for format or i/o error [Levin] +- Use malloc.h for OS/2 [Necasek] + +Changes in 1.2.2.3 (27 May 2005) +- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile +- Typecast fread() return values in gzio.c [Vollant] +- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) +- Fix crc check bug in gzread() after gzungetc() [Heiner] +- Add the deflateTune() function to adjust internal compression parameters +- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) +- Remove an incorrect assertion in examples/zpipe.c +- Add C++ wrapper in infback9.h [Donais] +- Fix bug in inflateCopy() when decoding fixed codes +- Note in zlib.h how much deflateSetDictionary() actually uses +- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) +- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] +- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] +- Add gzdirect() function to indicate transparent reads +- Update contrib/minizip [Vollant] +- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] +- Add casts in crc32.c to avoid warnings [Oberhumer] +- Add contrib/masmx64 [Vollant] +- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] + +Changes in 1.2.2.2 (30 December 2004) +- Replace structure assignments in deflate.c and inflate.c with zmemcpy to + avoid implicit memcpy calls (portability for no-library compilation) +- Increase sprintf() buffer size in gzdopen() to allow for large numbers +- Add INFLATE_STRICT to check distances against zlib header +- Improve WinCE errno handling and comments [Chang] +- Remove comment about no gzip header processing in FAQ +- Add Z_FIXED strategy option to deflateInit2() to force fixed trees +- Add updated make_vms.com [Coghlan], update README +- Create a new "examples" directory, move gzappend.c there, add zpipe.c, + fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. +- Add FAQ entry and comments in deflate.c on uninitialized memory access +- Add Solaris 9 make options in configure [Gilbert] +- Allow strerror() usage in gzio.c for STDC +- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] +- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] +- Use z_off_t for adler32_combine() and crc32_combine() lengths +- Make adler32() much faster for small len +- Use OS_CODE in deflate() default gzip header + +Changes in 1.2.2.1 (31 October 2004) +- Allow inflateSetDictionary() call for raw inflate +- Fix inflate header crc check bug for file names and comments +- Add deflateSetHeader() and gz_header structure for custom gzip headers +- Add inflateGetheader() to retrieve gzip headers +- Add crc32_combine() and adler32_combine() functions +- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list +- Use zstreamp consistently in zlib.h (inflate_back functions) +- Remove GUNZIP condition from definition of inflate_mode in inflate.h + and in contrib/inflate86/inffast.S [Truta, Anderson] +- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] +- Update projects/README.projects and projects/visualc6 [Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] +- Deprecate Z_ASCII; use Z_TEXT instead [Truta] +- Use a new algorithm for setting strm->data_type in trees.c [Truta] +- Do not define an exit() prototype in zutil.c unless DEBUG defined +- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] +- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() +- Fix Darwin build version identification [Peterson] + +Changes in 1.2.2 (3 October 2004) +- Update zlib.h comments on gzip in-memory processing +- Set adler to 1 in inflateReset() to support Java test suite [Walles] +- Add contrib/dotzlib [Ravn] +- Update win32/DLL_FAQ.txt [Truta] +- Update contrib/minizip [Vollant] +- Move contrib/visual-basic.txt to old/ [Truta] +- Fix assembler builds in projects/visualc6/ [Truta] + +Changes in 1.2.1.2 (9 September 2004) +- Update INDEX file +- Fix trees.c to update strm->data_type (no one ever noticed!) +- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] +- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) +- Add limited multitasking protection to DYNAMIC_CRC_TABLE +- Add NO_vsnprintf for VMS in zutil.h [Mozilla] +- Don't declare strerror() under VMS [Mozilla] +- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize +- Update contrib/ada [Anisimkov] +- Update contrib/minizip [Vollant] +- Fix configure to not hardcode directories for Darwin [Peterson] +- Fix gzio.c to not return error on empty files [Brown] +- Fix indentation; update version in contrib/delphi/ZLib.pas and + contrib/pascal/zlibpas.pas [Truta] +- Update mkasm.bat in contrib/masmx86 [Truta] +- Update contrib/untgz [Truta] +- Add projects/README.projects [Truta] +- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] +- Remove an unnecessary assignment to curr in inftrees.c [Truta] +- Add OS/2 to exe builds in configure [Poltorak] +- Remove err dummy parameter in zlib.h [Kientzle] + +Changes in 1.2.1.1 (9 January 2004) +- Update email address in README +- Several FAQ updates +- Fix a big fat bug in inftrees.c that prevented decoding valid + dynamic blocks with only literals and no distance codes -- + Thanks to "Hot Emu" for the bug report and sample file +- Add a note to puff.c on no distance codes case. + +Changes in 1.2.1 (17 November 2003) +- Remove a tab in contrib/gzappend/gzappend.c +- Update some interfaces in contrib for new zlib functions +- Update zlib version number in some contrib entries +- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] +- Support shared libraries on Hurd and KFreeBSD [Brown] +- Fix error in NO_DIVIDE option of adler32.c + +Changes in 1.2.0.8 (4 November 2003) +- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas +- Add experimental NO_DIVIDE #define in adler32.c + - Possibly faster on some processors (let me know if it is) +- Correct Z_BLOCK to not return on first inflate call if no wrap +- Fix strm->data_type on inflate() return to correctly indicate EOB +- Add deflatePrime() function for appending in the middle of a byte +- Add contrib/gzappend for an example of appending to a stream +- Update win32/DLL_FAQ.txt [Truta] +- Delete Turbo C comment in README [Truta] +- Improve some indentation in zconf.h [Truta] +- Fix infinite loop on bad input in configure script [Church] +- Fix gzeof() for concatenated gzip files [Johnson] +- Add example to contrib/visual-basic.txt [Michael B.] +- Add -p to mkdir's in Makefile.in [vda] +- Fix configure to properly detect presence or lack of printf functions +- Add AS400 support [Monnerat] +- Add a little Cygwin support [Wilson] + +Changes in 1.2.0.7 (21 September 2003) +- Correct some debug formats in contrib/infback9 +- Cast a type in a debug statement in trees.c +- Change search and replace delimiter in configure from % to # [Beebe] +- Update contrib/untgz to 0.2 with various fixes [Truta] +- Add build support for Amiga [Nikl] +- Remove some directories in old that have been updated to 1.2 +- Add dylib building for Mac OS X in configure and Makefile.in +- Remove old distribution stuff from Makefile +- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X +- Update links in README + +Changes in 1.2.0.6 (13 September 2003) +- Minor FAQ updates +- Update contrib/minizip to 1.00 [Vollant] +- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] +- Update POSTINC comment for 68060 [Nikl] +- Add contrib/infback9 with deflate64 decoding (unsupported) +- For MVS define NO_vsnprintf and undefine FAR [van Burik] +- Add pragma for fdopen on MVS [van Burik] + +Changes in 1.2.0.5 (8 September 2003) +- Add OF to inflateBackEnd() declaration in zlib.h +- Remember start when using gzdopen in the middle of a file +- Use internal off_t counters in gz* functions to properly handle seeks +- Perform more rigorous check for distance-too-far in inffast.c +- Add Z_BLOCK flush option to return from inflate at block boundary +- Set strm->data_type on return from inflate + - Indicate bits unused, if at block boundary, and if in last block +- Replace size_t with ptrdiff_t in crc32.c, and check for correct size +- Add condition so old NO_DEFLATE define still works for compatibility +- FAQ update regarding the Windows DLL [Truta] +- INDEX update: add qnx entry, remove aix entry [Truta] +- Install zlib.3 into mandir [Wilson] +- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] +- Adapt the zlib interface to the new DLL convention guidelines [Truta] +- Introduce ZLIB_WINAPI macro to allow the export of functions using + the WINAPI calling convention, for Visual Basic [Vollant, Truta] +- Update msdos and win32 scripts and makefiles [Truta] +- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] +- Add contrib/ada [Anisimkov] +- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] +- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] +- Add contrib/masm686 [Truta] +- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm + [Truta, Vollant] +- Update contrib/delphi; rename to contrib/pascal; add example [Truta] +- Remove contrib/delphi2; add a new contrib/delphi [Truta] +- Avoid inclusion of the nonstandard in contrib/iostream, + and fix some method prototypes [Truta] +- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip + [Truta] +- Avoid the use of backslash (\) in contrib/minizip [Vollant] +- Fix file time handling in contrib/untgz; update makefiles [Truta] +- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines + [Vollant] +- Remove contrib/vstudio/vc15_16 [Vollant] +- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] +- Update README.contrib [Truta] +- Invert the assignment order of match_head and s->prev[...] in + INSERT_STRING [Truta] +- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings + [Truta] +- Compare function pointers with 0, not with NULL or Z_NULL [Truta] +- Fix prototype of syncsearch in inflate.c [Truta] +- Introduce ASMINF macro to be enabled when using an ASM implementation + of inflate_fast [Truta] +- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] +- Modify test_gzio in example.c to take a single file name as a + parameter [Truta] +- Exit the example.c program if gzopen fails [Truta] +- Add type casts around strlen in example.c [Truta] +- Remove casting to sizeof in minigzip.c; give a proper type + to the variable compared with SUFFIX_LEN [Truta] +- Update definitions of STDC and STDC99 in zconf.h [Truta] +- Synchronize zconf.h with the new Windows DLL interface [Truta] +- Use SYS16BIT instead of __32BIT__ to distinguish between + 16- and 32-bit platforms [Truta] +- Use far memory allocators in small 16-bit memory models for + Turbo C [Truta] +- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in + zlibCompileFlags [Truta] +- Cygwin has vsnprintf [Wilson] +- In Windows16, OS_CODE is 0, as in MSDOS [Truta] +- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] + +Changes in 1.2.0.4 (10 August 2003) +- Minor FAQ updates +- Be more strict when checking inflateInit2's windowBits parameter +- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well +- Add gzip wrapper option to deflateInit2 using windowBits +- Add updated QNX rule in configure and qnx directory [Bonnefoy] +- Make inflate distance-too-far checks more rigorous +- Clean up FAR usage in inflate +- Add casting to sizeof() in gzio.c and minigzip.c + +Changes in 1.2.0.3 (19 July 2003) +- Fix silly error in gzungetc() implementation [Vollant] +- Update contrib/minizip and contrib/vstudio [Vollant] +- Fix printf format in example.c +- Correct cdecl support in zconf.in.h [Anisimkov] +- Minor FAQ updates + +Changes in 1.2.0.2 (13 July 2003) +- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons +- Attempt to avoid warnings in crc32.c for pointer-int conversion +- Add AIX to configure, remove aix directory [Bakker] +- Add some casts to minigzip.c +- Improve checking after insecure sprintf() or vsprintf() calls +- Remove #elif's from crc32.c +- Change leave label to inf_leave in inflate.c and infback.c to avoid + library conflicts +- Remove inflate gzip decoding by default--only enable gzip decoding by + special request for stricter backward compatibility +- Add zlibCompileFlags() function to return compilation information +- More typecasting in deflate.c to avoid warnings +- Remove leading underscore from _Capital #defines [Truta] +- Fix configure to link shared library when testing +- Add some Windows CE target adjustments [Mai] +- Remove #define ZLIB_DLL in zconf.h [Vollant] +- Add zlib.3 [Rodgers] +- Update RFC URL in deflate.c and algorithm.txt [Mai] +- Add zlib_dll_FAQ.txt to contrib [Truta] +- Add UL to some constants [Truta] +- Update minizip and vstudio [Vollant] +- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h +- Expand use of NO_DUMMY_DECL to avoid all dummy structures +- Added iostream3 to contrib [Schwardt] +- Replace rewind() with fseek() for WinCE [Truta] +- Improve setting of zlib format compression level flags + - Report 0 for huffman and rle strategies and for level == 0 or 1 + - Report 2 only for level == 6 +- Only deal with 64K limit when necessary at compile time [Truta] +- Allow TOO_FAR check to be turned off at compile time [Truta] +- Add gzclearerr() function [Souza] +- Add gzungetc() function + +Changes in 1.2.0.1 (17 March 2003) +- Add Z_RLE strategy for run-length encoding [Truta] + - When Z_RLE requested, restrict matches to distance one + - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE +- Correct FASTEST compilation to allow level == 0 +- Clean up what gets compiled for FASTEST +- Incorporate changes to zconf.in.h [Vollant] + - Refine detection of Turbo C need for dummy returns + - Refine ZLIB_DLL compilation + - Include additional header file on VMS for off_t typedef +- Try to use _vsnprintf where it supplants vsprintf [Vollant] +- Add some casts in inffast.c +- Enchance comments in zlib.h on what happens if gzprintf() tries to + write more than 4095 bytes before compression +- Remove unused state from inflateBackEnd() +- Remove exit(0) from minigzip.c, example.c +- Get rid of all those darn tabs +- Add "check" target to Makefile.in that does the same thing as "test" +- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in +- Update contrib/inflate86 [Anderson] +- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] +- Add msdos and win32 directories with makefiles [Truta] +- More additions and improvements to the FAQ + +Changes in 1.2.0 (9 March 2003) +- New and improved inflate code + - About 20% faster + - Does not allocate 32K window unless and until needed + - Automatically detects and decompresses gzip streams + - Raw inflate no longer needs an extra dummy byte at end + - Added inflateBack functions using a callback interface--even faster + than inflate, useful for file utilities (gzip, zip) + - Added inflateCopy() function to record state for random access on + externally generated deflate streams (e.g. in gzip files) + - More readable code (I hope) +- New and improved crc32() + - About 50% faster, thanks to suggestions from Rodney Brown +- Add deflateBound() and compressBound() functions +- Fix memory leak in deflateInit2() +- Permit setting dictionary for raw deflate (for parallel deflate) +- Fix const declaration for gzwrite() +- Check for some malloc() failures in gzio.c +- Fix bug in gzopen() on single-byte file 0x1f +- Fix bug in gzread() on concatenated file with 0x1f at end of buffer + and next buffer doesn't start with 0x8b +- Fix uncompress() to return Z_DATA_ERROR on truncated input +- Free memory at end of example.c +- Remove MAX #define in trees.c (conflicted with some libraries) +- Fix static const's in deflate.c, gzio.c, and zutil.[ch] +- Declare malloc() and free() in gzio.c if STDC not defined +- Use malloc() instead of calloc() in zutil.c if int big enough +- Define STDC for AIX +- Add aix/ with approach for compiling shared library on AIX +- Add HP-UX support for shared libraries in configure +- Add OpenUNIX support for shared libraries in configure +- Use $cc instead of gcc to build shared library +- Make prefix directory if needed when installing +- Correct Macintosh avoidance of typedef Byte in zconf.h +- Correct Turbo C memory allocation when under Linux +- Use libz.a instead of -lz in Makefile (assure use of compiled library) +- Update configure to check for snprintf or vsnprintf functions and their + return value, warn during make if using an insecure function +- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that + is lost when library is used--resolution is to build new zconf.h +- Documentation improvements (in zlib.h): + - Document raw deflate and inflate + - Update RFCs URL + - Point out that zlib and gzip formats are different + - Note that Z_BUF_ERROR is not fatal + - Document string limit for gzprintf() and possible buffer overflow + - Note requirement on avail_out when flushing + - Note permitted values of flush parameter of inflate() +- Add some FAQs (and even answers) to the FAQ +- Add contrib/inflate86/ for x86 faster inflate +- Add contrib/blast/ for PKWare Data Compression Library decompression +- Add contrib/puff/ simple inflate for deflate format description + +Changes in 1.1.4 (11 March 2002) +- ZFREE was repeated on same allocation on some error conditions. + This creates a security problem described in + http://www.zlib.org/advisory-2002-03-11.txt +- Returned incorrect error (Z_MEM_ERROR) on some invalid data +- Avoid accesses before window for invalid distances with inflate window + less than 32K. +- force windowBits > 8 to avoid a bug in the encoder for a window size + of 256 bytes. (A complete fix will be available in 1.1.5). + +Changes in 1.1.3 (9 July 1998) +- fix "an inflate input buffer bug that shows up on rare but persistent + occasions" (Mark) +- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) +- fix gzseek(..., SEEK_SET) in write mode +- fix crc check after a gzeek (Frank Faubert) +- fix miniunzip when the last entry in a zip file is itself a zip file + (J Lillge) +- add contrib/asm586 and contrib/asm686 (Brian Raiter) + See http://www.muppetlabs.com/~breadbox/software/assembly.html +- add support for Delphi 3 in contrib/delphi (Bob Dellaca) +- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) +- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) +- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) +- added a FAQ file + +- Support gzdopen on Mac with Metrowerks (Jason Linhart) +- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) +- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) +- avoid some warnings with Borland C (Tom Tanner) +- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) +- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) +- allow several arguments to configure (Tim Mooney, Frodo Looijaard) +- use libdir and includedir in Makefile.in (Tim Mooney) +- support shared libraries on OSF1 V4 (Tim Mooney) +- remove so_locations in "make clean" (Tim Mooney) +- fix maketree.c compilation error (Glenn, Mark) +- Python interface to zlib now in Python 1.5 (Jeremy Hylton) +- new Makefile.riscos (Rich Walker) +- initialize static descriptors in trees.c for embedded targets (Nick Smith) +- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) +- add the OS/2 files in Makefile.in too (Andrew Zabolotny) +- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) +- fix maketree.c to allow clean compilation of inffixed.h (Mark) +- fix parameter check in deflateCopy (Gunther Nikl) +- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) +- Many portability patches by Christian Spieler: + . zutil.c, zutil.h: added "const" for zmem* + . Make_vms.com: fixed some typos + . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists + . msdos/Makefile.msc: remove "default rtl link library" info from obj files + . msdos/Makefile.*: use model-dependent name for the built zlib library + . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: + new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) +- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) +- replace __far with _far for better portability (Christian Spieler, Tom Lane) +- fix test for errno.h in configure (Tim Newsham) + +Changes in 1.1.2 (19 March 98) +- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) + See http://www.winimage.com/zLibDll/unzip.html +- preinitialize the inflate tables for fixed codes, to make the code + completely thread safe (Mark) +- some simplifications and slight speed-up to the inflate code (Mark) +- fix gzeof on non-compressed files (Allan Schrum) +- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) +- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) +- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) +- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) +- do not wrap extern "C" around system includes (Tom Lane) +- mention zlib binding for TCL in README (Andreas Kupries) +- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) +- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) +- allow "configure --prefix $HOME" (Tim Mooney) +- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) +- move Makefile.sas to amiga/Makefile.sas + +Changes in 1.1.1 (27 Feb 98) +- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) +- remove block truncation heuristic which had very marginal effect for zlib + (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the + compression ratio on some files. This also allows inlining _tr_tally for + matches in deflate_slow. +- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) + +Changes in 1.1.0 (24 Feb 98) +- do not return STREAM_END prematurely in inflate (John Bowler) +- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) +- compile with -DFASTEST to get compression code optimized for speed only +- in minigzip, try mmap'ing the input file first (Miguel Albrecht) +- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain + on Sun but significant on HP) + +- add a pointer to experimental unzip library in README (Gilles Vollant) +- initialize variable gcc in configure (Chris Herborth) + +Changes in 1.0.9 (17 Feb 1998) +- added gzputs and gzgets functions +- do not clear eof flag in gzseek (Mark Diekhans) +- fix gzseek for files in transparent mode (Mark Diekhans) +- do not assume that vsprintf returns the number of bytes written (Jens Krinke) +- replace EXPORT with ZEXPORT to avoid conflict with other programs +- added compress2 in zconf.h, zlib.def, zlib.dnt +- new asm code from Gilles Vollant in contrib/asm386 +- simplify the inflate code (Mark): + . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() + . ZALLOC the length list in inflate_trees_fixed() instead of using stack + . ZALLOC the value area for huft_build() instead of using stack + . Simplify Z_FINISH check in inflate() + +- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 +- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) +- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with + the declaration of FAR (Gilles VOllant) +- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) +- read_buf buf parameter of type Bytef* instead of charf* +- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) +- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) +- fix check for presence of directories in "make install" (Ian Willis) + +Changes in 1.0.8 (27 Jan 1998) +- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) +- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) +- added compress2() to allow setting the compression level +- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) +- use constant arrays for the static trees in trees.c instead of computing + them at run time (thanks to Ken Raeburn for this suggestion). To create + trees.h, compile with GEN_TREES_H and run "make test". +- check return code of example in "make test" and display result +- pass minigzip command line options to file_compress +- simplifying code of inflateSync to avoid gcc 2.8 bug + +- support CC="gcc -Wall" in configure -s (QingLong) +- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) +- fix test for shared library support to avoid compiler warnings +- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) +- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) +- do not use fdopen for Metrowerks on Mac (Brad Pettit)) +- add checks for gzputc and gzputc in example.c +- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) +- use const for the CRC table (Ken Raeburn) +- fixed "make uninstall" for shared libraries +- use Tracev instead of Trace in infblock.c +- in example.c use correct compressed length for test_sync +- suppress +vnocompatwarnings in configure for HPUX (not always supported) + +Changes in 1.0.7 (20 Jan 1998) +- fix gzseek which was broken in write mode +- return error for gzseek to negative absolute position +- fix configure for Linux (Chun-Chung Chen) +- increase stack space for MSC (Tim Wegner) +- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) +- define EXPORTVA for gzprintf (Gilles Vollant) +- added man page zlib.3 (Rick Rodgers) +- for contrib/untgz, fix makedir() and improve Makefile + +- check gzseek in write mode in example.c +- allocate extra buffer for seeks only if gzseek is actually called +- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) +- add inflateSyncPoint in zconf.h +- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def + +Changes in 1.0.6 (19 Jan 1998) +- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and + gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) +- Fix a deflate bug occurring only with compression level 0 (thanks to + Andy Buckler for finding this one). +- In minigzip, pass transparently also the first byte for .Z files. +- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() +- check Z_FINISH in inflate (thanks to Marc Schluper) +- Implement deflateCopy (thanks to Adam Costello) +- make static libraries by default in configure, add --shared option. +- move MSDOS or Windows specific files to directory msdos +- suppress the notion of partial flush to simplify the interface + (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) +- suppress history buffer provided by application to simplify the interface + (this feature was not implemented anyway in 1.0.4) +- next_in and avail_in must be initialized before calling inflateInit or + inflateInit2 +- add EXPORT in all exported functions (for Windows DLL) +- added Makefile.nt (thanks to Stephen Williams) +- added the unsupported "contrib" directory: + contrib/asm386/ by Gilles Vollant + 386 asm code replacing longest_match(). + contrib/iostream/ by Kevin Ruland + A C++ I/O streams interface to the zlib gz* functions + contrib/iostream2/ by Tyge Løvset + Another C++ I/O streams interface + contrib/untgz/ by "Pedro A. Aranda Guti\irrez" + A very simple tar.gz file extractor using zlib + contrib/visual-basic.txt by Carlos Rios + How to use compress(), uncompress() and the gz* functions from VB. +- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression + level) in minigzip (thanks to Tom Lane) + +- use const for rommable constants in deflate +- added test for gzseek and gztell in example.c +- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) +- add undocumented function zError to convert error code to string + (for Tim Smithers) +- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. +- Use default memcpy for Symantec MSDOS compiler. +- Add EXPORT keyword for check_func (needed for Windows DLL) +- add current directory to LD_LIBRARY_PATH for "make test" +- create also a link for libz.so.1 +- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) +- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) +- added -soname for Linux in configure (Chun-Chung Chen, +- assign numbers to the exported functions in zlib.def (for Windows DLL) +- add advice in zlib.h for best usage of deflateSetDictionary +- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) +- allow compilation with ANSI keywords only enabled for TurboC in large model +- avoid "versionString"[0] (Borland bug) +- add NEED_DUMMY_RETURN for Borland +- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). +- allow compilation with CC +- defined STDC for OS/2 (David Charlap) +- limit external names to 8 chars for MVS (Thomas Lund) +- in minigzip.c, use static buffers only for 16-bit systems +- fix suffix check for "minigzip -d foo.gz" +- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) +- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) +- added makelcc.bat for lcc-win32 (Tom St Denis) +- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) +- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. +- check for unistd.h in configure (for off_t) +- remove useless check parameter in inflate_blocks_free +- avoid useless assignment of s->check to itself in inflate_blocks_new +- do not flush twice in gzclose (thanks to Ken Raeburn) +- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h +- use NO_ERRNO_H instead of enumeration of operating systems with errno.h +- work around buggy fclose on pipes for HP/UX +- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) +- fix configure if CC is already equal to gcc + +Changes in 1.0.5 (3 Jan 98) +- Fix inflate to terminate gracefully when fed corrupted or invalid data +- Use const for rommable constants in inflate +- Eliminate memory leaks on error conditions in inflate +- Removed some vestigial code in inflate +- Update web address in README + +Changes in 1.0.4 (24 Jul 96) +- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF + bit, so the decompressor could decompress all the correct data but went + on to attempt decompressing extra garbage data. This affected minigzip too. +- zlibVersion and gzerror return const char* (needed for DLL) +- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) +- use z_error only for DEBUG (avoid problem with DLLs) + +Changes in 1.0.3 (2 Jul 96) +- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS + small and medium models; this makes the library incompatible with previous + versions for these models. (No effect in large model or on other systems.) +- return OK instead of BUF_ERROR if previous deflate call returned with + avail_out as zero but there is nothing to do +- added memcmp for non STDC compilers +- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) +- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) +- better check for 16-bit mode MSC (avoids problem with Symantec) + +Changes in 1.0.2 (23 May 96) +- added Windows DLL support +- added a function zlibVersion (for the DLL support) +- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) +- Bytef is define's instead of typedef'd only for Borland C +- avoid reading uninitialized memory in example.c +- mention in README that the zlib format is now RFC1950 +- updated Makefile.dj2 +- added algorithm.doc + +Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] +- fix array overlay in deflate.c which sometimes caused bad compressed data +- fix inflate bug with empty stored block +- fix MSDOS medium model which was broken in 0.99 +- fix deflateParams() which could generate bad compressed data. +- Bytef is define'd instead of typedef'ed (work around Borland bug) +- added an INDEX file +- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), + Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) +- speed up adler32 for modern machines without auto-increment +- added -ansi for IRIX in configure +- static_init_done in trees.c is an int +- define unlink as delete for VMS +- fix configure for QNX +- add configure branch for SCO and HPUX +- avoid many warnings (unused variables, dead assignments, etc...) +- no fdopen for BeOS +- fix the Watcom fix for 32 bit mode (define FAR as empty) +- removed redefinition of Byte for MKWERKS +- work around an MWKERKS bug (incorrect merge of all .h files) + +Changes in 0.99 (27 Jan 96) +- allow preset dictionary shared between compressor and decompressor +- allow compression level 0 (no compression) +- add deflateParams in zlib.h: allow dynamic change of compression level + and compression strategy. +- test large buffers and deflateParams in example.c +- add optional "configure" to build zlib as a shared library +- suppress Makefile.qnx, use configure instead +- fixed deflate for 64-bit systems (detected on Cray) +- fixed inflate_blocks for 64-bit systems (detected on Alpha) +- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) +- always return Z_BUF_ERROR when deflate() has nothing to do +- deflateInit and inflateInit are now macros to allow version checking +- prefix all global functions and types with z_ with -DZ_PREFIX +- make falloc completely reentrant (inftrees.c) +- fixed very unlikely race condition in ct_static_init +- free in reverse order of allocation to help memory manager +- use zlib-1.0/* instead of zlib/* inside the tar.gz +- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith + -Wconversion -Wstrict-prototypes -Wmissing-prototypes" +- allow gzread on concatenated .gz files +- deflateEnd now returns Z_DATA_ERROR if it was premature +- deflate is finally (?) fully deterministic (no matches beyond end of input) +- Document Z_SYNC_FLUSH +- add uninstall in Makefile +- Check for __cpluplus in zlib.h +- Better test in ct_align for partial flush +- avoid harmless warnings for Borland C++ +- initialize hash_head in deflate.c +- avoid warning on fdopen (gzio.c) for HP cc -Aa +- include stdlib.h for STDC compilers +- include errno.h for Cray +- ignore error if ranlib doesn't exist +- call ranlib twice for NeXTSTEP +- use exec_prefix instead of prefix for libz.a +- renamed ct_* as _tr_* to avoid conflict with applications +- clear z->msg in inflateInit2 before any error return +- initialize opaque in example.c, gzio.c, deflate.c and inflate.c +- fixed typo in zconf.h (_GNUC__ => __GNUC__) +- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) +- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) +- in fcalloc, normalize pointer if size > 65520 bytes +- don't use special fcalloc for 32 bit Borland C++ +- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... +- use Z_BINARY instead of BINARY +- document that gzclose after gzdopen will close the file +- allow "a" as mode in gzopen. +- fix error checking in gzread +- allow skipping .gz extra-field on pipes +- added reference to Perl interface in README +- put the crc table in FAR data (I dislike more and more the medium model :) +- added get_crc_table +- added a dimension to all arrays (Borland C can't count). +- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast +- guard against multiple inclusion of *.h (for precompiled header on Mac) +- Watcom C pretends to be Microsoft C small model even in 32 bit mode. +- don't use unsized arrays to avoid silly warnings by Visual C++: + warning C4746: 'inflate_mask' : unsized array treated as '__far' + (what's wrong with far data in far model?). +- define enum out of inflate_blocks_state to allow compilation with C++ + +Changes in 0.95 (16 Aug 95) +- fix MSDOS small and medium model (now easier to adapt to any compiler) +- inlined send_bits +- fix the final (:-) bug for deflate with flush (output was correct but + not completely flushed in rare occasions). +- default window size is same for compression and decompression + (it's now sufficient to set MAX_WBITS in zconf.h). +- voidp -> voidpf and voidnp -> voidp (for consistency with other + typedefs and because voidnp was not near in large model). + +Changes in 0.94 (13 Aug 95) +- support MSDOS medium model +- fix deflate with flush (could sometimes generate bad output) +- fix deflateReset (zlib header was incorrectly suppressed) +- added support for VMS +- allow a compression level in gzopen() +- gzflush now calls fflush +- For deflate with flush, flush even if no more input is provided. +- rename libgz.a as libz.a +- avoid complex expression in infcodes.c triggering Turbo C bug +- work around a problem with gcc on Alpha (in INSERT_STRING) +- don't use inline functions (problem with some gcc versions) +- allow renaming of Byte, uInt, etc... with #define. +- avoid warning about (unused) pointer before start of array in deflate.c +- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c +- avoid reserved word 'new' in trees.c + +Changes in 0.93 (25 June 95) +- temporarily disable inline functions +- make deflate deterministic +- give enough lookahead for PARTIAL_FLUSH +- Set binary mode for stdin/stdout in minigzip.c for OS/2 +- don't even use signed char in inflate (not portable enough) +- fix inflate memory leak for segmented architectures + +Changes in 0.92 (3 May 95) +- don't assume that char is signed (problem on SGI) +- Clear bit buffer when starting a stored block +- no memcpy on Pyramid +- suppressed inftest.c +- optimized fill_window, put longest_match inline for gcc +- optimized inflate on stored blocks. +- untabify all sources to simplify patches + +Changes in 0.91 (2 May 95) +- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h +- Document the memory requirements in zconf.h +- added "make install" +- fix sync search logic in inflateSync +- deflate(Z_FULL_FLUSH) now works even if output buffer too short +- after inflateSync, don't scare people with just "lo world" +- added support for DJGPP + +Changes in 0.9 (1 May 95) +- don't assume that zalloc clears the allocated memory (the TurboC bug + was Mark's bug after all :) +- let again gzread copy uncompressed data unchanged (was working in 0.71) +- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented +- added a test of inflateSync in example.c +- moved MAX_WBITS to zconf.h because users might want to change that. +- document explicitly that zalloc(64K) on MSDOS must return a normalized + pointer (zero offset) +- added Makefiles for Microsoft C, Turbo C, Borland C++ +- faster crc32() + +Changes in 0.8 (29 April 95) +- added fast inflate (inffast.c) +- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this + is incompatible with previous versions of zlib which returned Z_OK. +- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) + (actually that was not a compiler bug, see 0.81 above) +- gzread no longer reads one extra byte in certain cases +- In gzio destroy(), don't reference a freed structure +- avoid many warnings for MSDOS +- avoid the ERROR symbol which is used by MS Windows + +Changes in 0.71 (14 April 95) +- Fixed more MSDOS compilation problems :( There is still a bug with + TurboC large model. + +Changes in 0.7 (14 April 95) +- Added full inflate support. +- Simplified the crc32() interface. The pre- and post-conditioning + (one's complement) is now done inside crc32(). WARNING: this is + incompatible with previous versions; see zlib.h for the new usage. + +Changes in 0.61 (12 April 95) +- workaround for a bug in TurboC. example and minigzip now work on MSDOS. + +Changes in 0.6 (11 April 95) +- added minigzip.c +- added gzdopen to reopen a file descriptor as gzFile +- added transparent reading of non-gziped files in gzread. +- fixed bug in gzread (don't read crc as data) +- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). +- don't allocate big arrays in the stack (for MSDOS) +- fix some MSDOS compilation problems + +Changes in 0.5: +- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but + not yet Z_FULL_FLUSH. +- support decompression but only in a single step (forced Z_FINISH) +- added opaque object for zalloc and zfree. +- added deflateReset and inflateReset +- added a variable zlib_version for consistency checking. +- renamed the 'filter' parameter of deflateInit2 as 'strategy'. + Added Z_FILTERED and Z_HUFFMAN_ONLY constants. + +Changes in 0.4: +- avoid "zip" everywhere, use zlib instead of ziplib. +- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush + if compression method == 8. +- added adler32 and crc32 +- renamed deflateOptions as deflateInit2, call one or the other but not both +- added the method parameter for deflateInit2. +- added inflateInit2 +- simplied considerably deflateInit and inflateInit by not supporting + user-provided history buffer. This is supported only in deflateInit2 + and inflateInit2. + +Changes in 0.3: +- prefix all macro names with Z_ +- use Z_FINISH instead of deflateEnd to finish compression. +- added Z_HUFFMAN_ONLY +- added gzerror() diff --git a/third_party/zlib/v1_2_11/FAQ b/third_party/zlib/v1_2_11/FAQ new file mode 100644 index 0000000..99b7cf9 --- /dev/null +++ b/third_party/zlib/v1_2_11/FAQ @@ -0,0 +1,368 @@ + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://zlib.net/ which may have more recent information. +The lastest zlib FAQ is at http://zlib.net/zlib_faq.html + + + 1. Is zlib Y2K-compliant? + + Yes. zlib doesn't handle dates. + + 2. Where can I get a Windows DLL version? + + The zlib sources can be compiled without change to produce a DLL. See the + file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the + precompiled DLL are found in the zlib web site at http://zlib.net/ . + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://marknelson.us/1997/01/01/zlib-engine/ + * win32/DLL_FAQ.txt in the zlib distribution + + 4. compress() returns Z_BUF_ERROR. + + Make sure that before the call of compress(), the length of the compressed + buffer is equal to the available size of the compressed buffer and not + zero. For Visual Basic, check that this parameter is passed by reference + ("as any"), not by value ("as long"). + + 5. deflate() or inflate() returns Z_BUF_ERROR. + + Before making the call, make sure that avail_in and avail_out are not zero. + When setting the parameter flush equal to Z_FINISH, also make sure that + avail_out is big enough to allow processing all pending input. Note that a + Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be + made with more input or output space. A Z_BUF_ERROR may in fact be + unavoidable depending on how the functions are used, since it is not + possible to tell whether or not there is more output pending when + strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a + heavily annotated example. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h . Examples of zlib usage are in the files test/example.c + and test/minigzip.c, with more in examples/ . + + 7. Why don't you use GNU autoconf or libtool or ...? + + Because we would like to keep zlib as a very small and simple package. + zlib is rather portable and doesn't need much configuration. + + 8. I found a bug in zlib. + + Most of the time, such problems are due to an incorrect usage of zlib. + Please try to reproduce the problem with a small program and send the + corresponding source to us at zlib@gzip.org . Do not send multi-megabyte + data files without prior agreement. + + 9. Why do I get "undefined reference to gzputc"? + + If "make test" produces something like + + example.o(.text+0x154): undefined reference to `gzputc' + + check that you don't have old files libz.* in /usr/lib, /usr/local/lib or + /usr/X11R6/lib. Remove any old versions, then do "make install". + +10. I need a Delphi interface to zlib. + + See the contrib/delphi directory in the zlib distribution. + +11. Can zlib handle .zip archives? + + Not by itself, no. See the directory contrib/minizip in the zlib + distribution. + +12. Can zlib handle .Z files? + + No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt + the code of uncompress on your own. + +13. How can I make a Unix shared library? + + By default a shared (and a static) library is built for Unix. So: + + make distclean + ./configure + make + +14. How do I install a shared zlib library on Unix? + + After the above, then: + + make install + + However, many flavors of Unix come with a shared zlib already installed. + Before going to the trouble of compiling a shared version of zlib and + trying to install it, you may want to check if it's already there! If you + can #include , it's there. The -lz option will probably link to + it. You can check the version at the top of zlib.h or with the + ZLIB_VERSION symbol defined in zlib.h . + +15. I have a question about OttoPDF. + + We are not the authors of OttoPDF. The real author is on the OttoPDF web + site: Joel Hainley, jhainley@myndkryme.com. + +16. Can zlib decode Flate data in an Adobe PDF file? + + Yes. See http://www.pdflib.com/ . To modify PDF forms, see + http://sourceforge.net/projects/acroformtool/ . + +17. Why am I getting this "register_frame_info not found" error on Solaris? + + After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib + generates an error such as: + + ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: + symbol __register_frame_info: referenced symbol not found + + The symbol __register_frame_info is not part of zlib, it is generated by + the C compiler (cc or gcc). You must recompile applications using zlib + which have this problem. This problem is specific to Solaris. See + http://www.sunfreeware.com for Solaris versions of zlib and applications + using zlib. + +18. Why does gzip give an error on a file I make with compress/deflate? + + The compress and deflate functions produce data in the zlib format, which + is different and incompatible with the gzip format. The gz* functions in + zlib on the other hand use the gzip format. Both the zlib and gzip formats + use the same compressed data format internally, but have different headers + and trailers around the compressed data. + +19. Ok, so why are there two different formats? + + The gzip format was designed to retain the directory information about a + single file, such as the name and last modification date. The zlib format + on the other hand was designed for in-memory and communication channel + applications, and has a much more compact header and trailer and uses a + faster integrity check than gzip. + +20. Well that's nice, but how do I make a gzip file in memory? + + You can request that deflate write the gzip format instead of the zlib + format using deflateInit2(). You can also request that inflate decode the + gzip format using inflateInit2(). Read zlib.h for more details. + +21. Is zlib thread-safe? + + Yes. However any library routines that zlib uses and any application- + provided memory allocation routines must also be thread-safe. zlib's gz* + functions use stdio library routines, and most of zlib's functions use the + library memory allocation routines by default. zlib's *Init* functions + allow for the application to provide custom memory allocation routines. + + Of course, you should only operate on any given zlib or gzip stream from a + single thread at a time. + +22. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +23. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +24. The license says that altered source versions must be "plainly marked". So + what exactly do I need to do to meet that requirement? + + You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In + particular, the final version number needs to be changed to "f", and an + identification string should be appended to ZLIB_VERSION. Version numbers + x.x.x.f are reserved for modifications to zlib by others than the zlib + maintainers. For example, if the version of the base zlib you are altering + is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and + ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also + update the version strings in deflate.c and inftrees.c. + + For altered source distributions, you should also note the origin and + nature of the changes in zlib.h, as well as in ChangeLog and README, along + with the dates of the alterations. The origin should include at least your + name (or your company's name), and an email address to contact for help or + issues with the library. + + Note that distributing a compiled zlib library along with zlib.h and + zconf.h is also a source distribution, and so you should change + ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes + in zlib.h as you would for a full source distribution. + +25. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +26. Will zlib work on a 64-bit machine? + + Yes. It has been tested on 64-bit machines, and has no dependence on any + data types being limited to 32-bits in length. If you have any + difficulties, please provide a complete problem report to zlib@gzip.org + +27. Will zlib decompress data from the PKWare Data Compression Library? + + No. The PKWare DCL uses a completely different compressed data format than + does PKZIP and zlib. However, you can look in zlib's contrib/blast + directory for a possible solution to your problem. + +28. Can I access data randomly in a compressed stream? + + No, not without some preparation. If when compressing you periodically use + Z_FULL_FLUSH, carefully write all the pending data at those points, and + keep an index of those locations, then you can start decompression at those + points. You have to be careful to not use Z_FULL_FLUSH too often, since it + can significantly degrade compression. Alternatively, you can scan a + deflate stream once to generate an index, and then use that index for + random access. See examples/zran.c . + +29. Does zlib work on MVS, OS/390, CICS, etc.? + + It has in the past, but we have not heard of any recent evidence. There + were working ports of zlib 1.1.4 to MVS, but those links no longer work. + If you know of recent, successful applications of zlib on these operating + systems, please let us know. Thanks. + +30. Is there some simpler, easier to read version of inflate I can look at to + understand the deflate format? + + First off, you should read RFC 1951. Second, yes. Look in zlib's + contrib/puff directory. + +31. Does zlib infringe on any patents? + + As far as we know, no. In fact, that was originally the whole point behind + zlib. Look here for some more information: + + http://www.gzip.org/#faq11 + +32. Can zlib work with greater than 4 GB of data? + + Yes. inflate() and deflate() will process any amount of data correctly. + Each call of inflate() or deflate() is limited to input and output chunks + of the maximum value that can be stored in the compiler's "unsigned int" + type, but there is no limit to the number of chunks. Note however that the + strm.total_in and strm_total_out counters may be limited to 4 GB. These + counters are provided as a convenience and are not used internally by + inflate() or deflate(). The application can easily set up its own counters + updated after each call of inflate() or deflate() to count beyond 4 GB. + compress() and uncompress() may be limited to 4 GB, since they operate in a + single call. gzseek() and gztell() may be limited to 4 GB depending on how + zlib is compiled. See the zlibCompileFlags() function in zlib.h. + + The word "may" appears several times above since there is a 4 GB limit only + if the compiler's "long" type is 32 bits. If the compiler's "long" type is + 64 bits, then the limit is 16 exabytes. + +33. Does zlib have any security vulnerabilities? + + The only one that we are aware of is potentially in gzprintf(). If zlib is + compiled to use sprintf() or vsprintf(), then there is no protection + against a buffer overflow of an 8K string space (or other value as set by + gzbuffer()), other than the caller of gzprintf() assuring that the output + will not exceed 8K. On the other hand, if zlib is compiled to use + snprintf() or vsnprintf(), which should normally be the case, then there is + no vulnerability. The ./configure script will display warnings if an + insecure variation of sprintf() will be used by gzprintf(). Also the + zlibCompileFlags() function will return information on what variant of + sprintf() is used by gzprintf(). + + If you don't have snprintf() or vsnprintf() and would like one, you can + find a portable implementation here: + + http://www.ijs.si/software/snprintf/ + + Note that you should be using the most recent version of zlib. Versions + 1.1.3 and before were subject to a double-free vulnerability, and versions + 1.2.1 and 1.2.2 were subject to an access exception when decompressing + invalid compressed data. + +34. Is there a Java version of zlib? + + Probably what you want is to use zlib in Java. zlib is already included + as part of the Java SDK in the java.util.zip package. If you really want + a version of zlib written in the Java language, look on the zlib home + page for links: http://zlib.net/ . + +35. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pedantic. Can't you guys write proper code? + + Many years ago, we gave up attempting to avoid warnings on every compiler + in the universe. It just got to be a waste of time, and some compilers + were downright silly as well as contradicted each other. So now, we simply + make sure that the code always works. + +36. Valgrind (or some similar memory access checker) says that deflate is + performing a conditional jump that depends on an uninitialized value. + Isn't that a bug? + + No. That is intentional for performance reasons, and the output of deflate + is not affected. This only started showing up recently since zlib 1.2.x + uses malloc() by default for allocations, whereas earlier versions used + calloc(), which zeros out the allocated memory. Even though the code was + correct, versions 1.2.4 and later was changed to not stimulate these + checkers. + +37. Will zlib read the (insert any ancient or arcane format here) compressed + data format? + + Probably not. Look in the comp.compression FAQ for pointers to various + formats and associated software. + +38. How can I encrypt/decrypt zip files with zlib? + + zlib doesn't support encryption. The original PKZIP encryption is very + weak and can be broken with freely available programs. To get strong + encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib + compression. For PKZIP compatible "encryption", look at + http://www.info-zip.org/ + +39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? + + "gzip" is the gzip format, and "deflate" is the zlib format. They should + probably have called the second one "zlib" instead to avoid confusion with + the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 + correctly points to the zlib specification in RFC 1950 for the "deflate" + transfer encoding, there have been reports of servers and browsers that + incorrectly produce or expect raw deflate data per the deflate + specification in RFC 1951, most notably Microsoft. So even though the + "deflate" transfer encoding using the zlib format would be the more + efficient approach (and in fact exactly what the zlib format was designed + for), using the "gzip" transfer encoding is probably more reliable due to + an unfortunate choice of name on the part of the HTTP 1.1 authors. + + Bottom line: use the gzip format for HTTP 1.1 encoding. + +40. Does zlib support the new "Deflate64" format introduced by PKWare? + + No. PKWare has apparently decided to keep that format proprietary, since + they have not documented it as they have previous compression formats. In + any case, the compression improvements are so modest compared to other more + modern approaches, that it's not worth the effort to implement. + +41. I'm having a problem with the zip functions in zlib, can you help? + + There are no zip functions in zlib. You are probably using minizip by + Giles Vollant, which is found in the contrib directory of zlib. It is not + part of zlib. In fact none of the stuff in contrib is part of zlib. The + files in there are not supported by the zlib authors. You need to contact + the authors of the respective contribution for help. + +42. The match.asm code in contrib is under the GNU General Public License. + Since it's part of zlib, doesn't that mean that all of zlib falls under the + GNU GPL? + + No. The files in contrib are not part of zlib. They were contributed by + other authors and are provided as a convenience to the user within the zlib + distribution. Each item in contrib has its own license. + +43. Is zlib subject to export controls? What is its ECCN? + + zlib is not subject to export controls, and so is classified as EAR99. + +44. Can you please sign these lengthy legal documents and fax them back to us + so that we can use your software in our product? + + No. Go away. Shoo. diff --git a/third_party/zlib/v1_2_11/INDEX b/third_party/zlib/v1_2_11/INDEX new file mode 100644 index 0000000..2ba0641 --- /dev/null +++ b/third_party/zlib/v1_2_11/INDEX @@ -0,0 +1,68 @@ +CMakeLists.txt cmake build file +ChangeLog history of changes +FAQ Frequently Asked Questions about zlib +INDEX this file +Makefile dummy Makefile that tells you to ./configure +Makefile.in template for Unix Makefile +README guess what +configure configure script for Unix +make_vms.com makefile for VMS +test/example.c zlib usages examples for build testing +test/minigzip.c minimal gzip-like functionality for build testing +test/infcover.c inf*.c code coverage for build coverage testing +treebuild.xml XML description of source file dependencies +zconf.h.cmakein zconf.h template for cmake +zconf.h.in zconf.h template for configure +zlib.3 Man page for zlib +zlib.3.pdf Man page in PDF format +zlib.map Linux symbol information +zlib.pc.in Template for pkg-config descriptor +zlib.pc.cmakein zlib.pc template for cmake +zlib2ansi perl script to convert source files for C++ compilation + +amiga/ makefiles for Amiga SAS C +as400/ makefiles for AS/400 +doc/ documentation for formats and algorithms +msdos/ makefiles for MSDOS +nintendods/ makefile for Nintendo DS +old/ makefiles for various architectures and zlib documentation + files that have not yet been updated for zlib 1.2.x +qnx/ makefiles for QNX +watcom/ makefiles for OpenWatcom +win32/ makefiles for Windows + + zlib public header files (required for library use): +zconf.h +zlib.h + + private source files used to build the zlib library: +adler32.c +compress.c +crc32.c +crc32.h +deflate.c +deflate.h +gzclose.c +gzguts.h +gzlib.c +gzread.c +gzwrite.c +infback.c +inffast.c +inffast.h +inffixed.h +inflate.c +inflate.h +inftrees.c +inftrees.h +trees.c +trees.h +uncompr.c +zutil.c +zutil.h + + source files for sample programs +See examples/README.examples + + unsupported contributions by third parties +See contrib/README.contrib diff --git a/third_party/zlib/v1_2_11/Makefile b/third_party/zlib/v1_2_11/Makefile new file mode 100644 index 0000000..6bba86c --- /dev/null +++ b/third_party/zlib/v1_2_11/Makefile @@ -0,0 +1,5 @@ +all: + -@echo "Please use ./configure first. Thank you." + +distclean: + make -f Makefile.in distclean diff --git a/third_party/zlib/v1_2_11/Makefile.in b/third_party/zlib/v1_2_11/Makefile.in new file mode 100644 index 0000000..5a77949 --- /dev/null +++ b/third_party/zlib/v1_2_11/Makefile.in @@ -0,0 +1,410 @@ +# Makefile for zlib +# Copyright (C) 1995-2017 Jean-loup Gailly, Mark Adler +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile and test, type: +# ./configure; make test +# Normally configure builds both a static and a shared library. +# If you want to build just a static library, use: ./configure --static + +# To use the asm code, type: +# cp contrib/asm?86/match.S ./match.S +# make LOC=-DASMV OBJA=match.o + +# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type: +# make install +# To install in $HOME instead of /usr/local, use: +# make install prefix=$HOME + +CC=cc + +CFLAGS=-O +#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 +#CFLAGS=-g -DZLIB_DEBUG +#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ +# -Wstrict-prototypes -Wmissing-prototypes + +SFLAGS=-O +LDFLAGS= +TEST_LDFLAGS=-L. libz.a +LDSHARED=$(CC) +CPP=$(CC) -E + +STATICLIB=libz.a +SHAREDLIB=libz.so +SHAREDLIBV=libz.so.1.2.11 +SHAREDLIBM=libz.so.1 +LIBS=$(STATICLIB) $(SHAREDLIBV) + +AR=ar +ARFLAGS=rc +RANLIB=ranlib +LDCONFIG=ldconfig +LDSHAREDLIBC=-lc +TAR=tar +SHELL=/bin/sh +EXE= + +prefix = /usr/local +exec_prefix = ${prefix} +libdir = ${exec_prefix}/lib +sharedlibdir = ${libdir} +includedir = ${prefix}/include +mandir = ${prefix}/share/man +man3dir = ${mandir}/man3 +pkgconfigdir = ${libdir}/pkgconfig +SRCDIR= +ZINC= +ZINCOUT=-I. + +OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o +OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o +OBJC = $(OBJZ) $(OBJG) + +PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo +PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo +PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG) + +# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo +OBJA = +PIC_OBJA = + +OBJS = $(OBJC) $(OBJA) + +PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA) + +all: static shared + +static: example$(EXE) minigzip$(EXE) + +shared: examplesh$(EXE) minigzipsh$(EXE) + +all64: example64$(EXE) minigzip64$(EXE) + +check: test + +test: all teststatic testshared + +teststatic: static + @TMPST=tmpst_$$; \ + if echo hello world | ./minigzip | ./minigzip -d && ./example $$TMPST ; then \ + echo ' *** zlib test OK ***'; \ + else \ + echo ' *** zlib test FAILED ***'; false; \ + fi; \ + rm -f $$TMPST + +testshared: shared + @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ + LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \ + DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \ + SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \ + TMPSH=tmpsh_$$; \ + if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh $$TMPSH; then \ + echo ' *** zlib shared test OK ***'; \ + else \ + echo ' *** zlib shared test FAILED ***'; false; \ + fi; \ + rm -f $$TMPSH + +test64: all64 + @TMP64=tmp64_$$; \ + if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64 $$TMP64; then \ + echo ' *** zlib 64-bit test OK ***'; \ + else \ + echo ' *** zlib 64-bit test FAILED ***'; false; \ + fi; \ + rm -f $$TMP64 + +infcover.o: $(SRCDIR)test/infcover.c $(SRCDIR)zlib.h zconf.h + $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/infcover.c + +infcover: infcover.o libz.a + $(CC) $(CFLAGS) -o $@ infcover.o libz.a + +cover: infcover + rm -f *.gcda + ./infcover + gcov inf*.c + +libz.a: $(OBJS) + $(AR) $(ARFLAGS) $@ $(OBJS) + -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 + +match.o: match.S + $(CPP) match.S > _match.s + $(CC) -c _match.s + mv _match.o match.o + rm -f _match.s + +match.lo: match.S + $(CPP) match.S > _match.s + $(CC) -c -fPIC _match.s + mv _match.o match.lo + rm -f _match.s + +example.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h + $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/example.c + +minigzip.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h + $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/minigzip.c + +example64.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h + $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/example.c + +minigzip64.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h + $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/minigzip.c + + +adler32.o: $(SRCDIR)adler32.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)adler32.c + +crc32.o: $(SRCDIR)crc32.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)crc32.c + +deflate.o: $(SRCDIR)deflate.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)deflate.c + +infback.o: $(SRCDIR)infback.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)infback.c + +inffast.o: $(SRCDIR)inffast.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inffast.c + +inflate.o: $(SRCDIR)inflate.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inflate.c + +inftrees.o: $(SRCDIR)inftrees.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inftrees.c + +trees.o: $(SRCDIR)trees.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)trees.c + +zutil.o: $(SRCDIR)zutil.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)zutil.c + +compress.o: $(SRCDIR)compress.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)compress.c + +uncompr.o: $(SRCDIR)uncompr.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)uncompr.c + +gzclose.o: $(SRCDIR)gzclose.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzclose.c + +gzlib.o: $(SRCDIR)gzlib.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzlib.c + +gzread.o: $(SRCDIR)gzread.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzread.c + +gzwrite.o: $(SRCDIR)gzwrite.c + $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzwrite.c + + +adler32.lo: $(SRCDIR)adler32.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/adler32.o $(SRCDIR)adler32.c + -@mv objs/adler32.o $@ + +crc32.lo: $(SRCDIR)crc32.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/crc32.o $(SRCDIR)crc32.c + -@mv objs/crc32.o $@ + +deflate.lo: $(SRCDIR)deflate.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/deflate.o $(SRCDIR)deflate.c + -@mv objs/deflate.o $@ + +infback.lo: $(SRCDIR)infback.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/infback.o $(SRCDIR)infback.c + -@mv objs/infback.o $@ + +inffast.lo: $(SRCDIR)inffast.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inffast.o $(SRCDIR)inffast.c + -@mv objs/inffast.o $@ + +inflate.lo: $(SRCDIR)inflate.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inflate.o $(SRCDIR)inflate.c + -@mv objs/inflate.o $@ + +inftrees.lo: $(SRCDIR)inftrees.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/inftrees.o $(SRCDIR)inftrees.c + -@mv objs/inftrees.o $@ + +trees.lo: $(SRCDIR)trees.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/trees.o $(SRCDIR)trees.c + -@mv objs/trees.o $@ + +zutil.lo: $(SRCDIR)zutil.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/zutil.o $(SRCDIR)zutil.c + -@mv objs/zutil.o $@ + +compress.lo: $(SRCDIR)compress.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/compress.o $(SRCDIR)compress.c + -@mv objs/compress.o $@ + +uncompr.lo: $(SRCDIR)uncompr.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/uncompr.o $(SRCDIR)uncompr.c + -@mv objs/uncompr.o $@ + +gzclose.lo: $(SRCDIR)gzclose.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzclose.o $(SRCDIR)gzclose.c + -@mv objs/gzclose.o $@ + +gzlib.lo: $(SRCDIR)gzlib.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzlib.o $(SRCDIR)gzlib.c + -@mv objs/gzlib.o $@ + +gzread.lo: $(SRCDIR)gzread.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzread.o $(SRCDIR)gzread.c + -@mv objs/gzread.o $@ + +gzwrite.lo: $(SRCDIR)gzwrite.c + -@mkdir objs 2>/dev/null || test -d objs + $(CC) $(SFLAGS) $(ZINC) -DPIC -c -o objs/gzwrite.o $(SRCDIR)gzwrite.c + -@mv objs/gzwrite.o $@ + + +placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a + $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS) + rm -f $(SHAREDLIB) $(SHAREDLIBM) + ln -s $@ $(SHAREDLIB) + ln -s $@ $(SHAREDLIBM) + -@rmdir objs + +example$(EXE): example.o $(STATICLIB) + $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS) + +minigzip$(EXE): minigzip.o $(STATICLIB) + $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS) + +examplesh$(EXE): example.o $(SHAREDLIBV) + $(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV) + +minigzipsh$(EXE): minigzip.o $(SHAREDLIBV) + $(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV) + +example64$(EXE): example64.o $(STATICLIB) + $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS) + +minigzip64$(EXE): minigzip64.o $(STATICLIB) + $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS) + +install-libs: $(LIBS) + -@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi + -@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi + -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi + -@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi + -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi + rm -f $(DESTDIR)$(libdir)/$(STATICLIB) + cp $(STATICLIB) $(DESTDIR)$(libdir) + chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB) + -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1 + -@if test -n "$(SHAREDLIBV)"; then \ + rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ + cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \ + echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \ + chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \ + echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \ + rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ + ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \ + ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \ + ($(LDCONFIG) || true) >/dev/null 2>&1; \ + fi + rm -f $(DESTDIR)$(man3dir)/zlib.3 + cp $(SRCDIR)zlib.3 $(DESTDIR)$(man3dir) + chmod 644 $(DESTDIR)$(man3dir)/zlib.3 + rm -f $(DESTDIR)$(pkgconfigdir)/zlib.pc + cp zlib.pc $(DESTDIR)$(pkgconfigdir) + chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc +# The ranlib in install is needed on NeXTSTEP which checks file times +# ldconfig is for Linux + +install: install-libs + -@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi + rm -f $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h + cp $(SRCDIR)zlib.h zconf.h $(DESTDIR)$(includedir) + chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h + +uninstall: + cd $(DESTDIR)$(includedir) && rm -f zlib.h zconf.h + cd $(DESTDIR)$(libdir) && rm -f libz.a; \ + if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \ + rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \ + fi + cd $(DESTDIR)$(man3dir) && rm -f zlib.3 + cd $(DESTDIR)$(pkgconfigdir) && rm -f zlib.pc + +docs: zlib.3.pdf + +zlib.3.pdf: $(SRCDIR)zlib.3 + groff -mandoc -f H -T ps $(SRCDIR)zlib.3 | ps2pdf - $@ + +zconf.h.cmakein: $(SRCDIR)zconf.h.in + -@ TEMPFILE=zconfh_$$; \ + echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\ + sed -f $$TEMPFILE $(SRCDIR)zconf.h.in > $@ &&\ + touch -r $(SRCDIR)zconf.h.in $@ &&\ + rm $$TEMPFILE + +zconf: $(SRCDIR)zconf.h.in + cp -p $(SRCDIR)zconf.h.in zconf.h + +mostlyclean: clean +clean: + rm -f *.o *.lo *~ \ + example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \ + example64$(EXE) minigzip64$(EXE) \ + infcover \ + libz.* foo.gz so_locations \ + _match.s maketree contrib/infback9/*.o + rm -rf objs + rm -f *.gcda *.gcno *.gcov + rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov + +maintainer-clean: distclean +distclean: clean zconf zconf.h.cmakein docs + rm -f Makefile zlib.pc configure.log + -@rm -f .DS_Store + @if [ -f Makefile.in ]; then \ + printf 'all:\n\t-@echo "Please use ./configure first. Thank you."\n' > Makefile ; \ + printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile ; \ + touch -r $(SRCDIR)Makefile.in Makefile ; fi + @if [ ! -f zconf.h.in ]; then rm -f zconf.h zconf.h.cmakein ; fi + @if [ ! -f zlib.3 ]; then rm -f zlib.3.pdf ; fi + +tags: + etags $(SRCDIR)*.[ch] + +adler32.o zutil.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h +gzclose.o gzlib.o gzread.o gzwrite.o: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h +compress.o example.o minigzip.o uncompr.o: $(SRCDIR)zlib.h zconf.h +crc32.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h +deflate.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h +infback.o inflate.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h +inffast.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h +inftrees.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h +trees.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h + +adler32.lo zutil.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h +gzclose.lo gzlib.lo gzread.lo gzwrite.lo: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h +compress.lo example.lo minigzip.lo uncompr.lo: $(SRCDIR)zlib.h zconf.h +crc32.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h +deflate.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h +infback.lo inflate.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h +inffast.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h +inftrees.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h +trees.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h diff --git a/third_party/zlib/v1_2_11/README b/third_party/zlib/v1_2_11/README new file mode 100644 index 0000000..51106de --- /dev/null +++ b/third_party/zlib/v1_2_11/README @@ -0,0 +1,115 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.11 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +rfc1952 (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file test/example.c which also tests that +the library is working correctly. Another example is given in the file +test/minigzip.c. The compression library itself is composed of all source +files in the root directory. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile.in. In short "./configure; make test", and if that goes +well, "make install" should work for most flavors of Unix. For Windows, use +one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use +make_vms.com. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available at +http://marknelson.us/1997/01/01/zlib-engine/ . + +The changes made in version 1.2.11 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory contrib/ . + +zlib is available in Java using the java.util.zip package, documented at +http://java.sun.com/developer/technicalArticles/Programming/compression/ . + +A Perl interface to zlib written by Paul Marquess is available +at CPAN (Comprehensive Perl Archive Network) sites, including +http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://docs.python.org/library/zlib.html . + +zlib is built into tcl: http://wiki.tcl.tk/4610 . + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS or BEOS. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/third_party/zlib/v1_2_11/adler32.c b/third_party/zlib/v1_2_11/adler32.c new file mode 100644 index 0000000..d0be438 --- /dev/null +++ b/third_party/zlib/v1_2_11/adler32.c @@ -0,0 +1,186 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521U /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32_z(adler, buf, len) + uLong adler; + const Bytef *buf; + z_size_t len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + return adler32_z(adler, buf, len); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/third_party/zlib/v1_2_11/amiga/Makefile.pup b/third_party/zlib/v1_2_11/amiga/Makefile.pup new file mode 100644 index 0000000..8940c12 --- /dev/null +++ b/third_party/zlib/v1_2_11/amiga/Makefile.pup @@ -0,0 +1,69 @@ +# Amiga powerUP (TM) Makefile +# makefile for libpng and SAS C V6.58/7.00 PPC compiler +# Copyright (C) 1998 by Andreas R. Kleinert + +LIBNAME = libzip.a + +CC = scppc +CFLAGS = NOSTKCHK NOSINT OPTIMIZE OPTGO OPTPEEP OPTINLOCAL OPTINL \ + OPTLOOP OPTRDEP=8 OPTDEP=8 OPTCOMP=8 NOVER +AR = ppc-amigaos-ar cr +RANLIB = ppc-amigaos-ranlib +LD = ppc-amigaos-ld -r +LDFLAGS = -o +LDLIBS = LIB:scppc.a LIB:end.o +RM = delete quiet + +OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ + uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o + +TEST_OBJS = example.o minigzip.o + +all: example minigzip + +check: test +test: all + example + echo hello world | minigzip | minigzip -d + +$(LIBNAME): $(OBJS) + $(AR) $@ $(OBJS) + -$(RANLIB) $@ + +example: example.o $(LIBNAME) + $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) + +minigzip: minigzip.o $(LIBNAME) + $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS) + +mostlyclean: clean +clean: + $(RM) *.o example minigzip $(LIBNAME) foo.gz + +zip: + zip -ul9 zlib README ChangeLog Makefile Make????.??? Makefile.?? \ + descrip.mms *.[ch] + +tgz: + cd ..; tar cfz zlib/zlib.tgz zlib/README zlib/ChangeLog zlib/Makefile \ + zlib/Make????.??? zlib/Makefile.?? zlib/descrip.mms zlib/*.[ch] + +# DO NOT DELETE THIS LINE -- make depend depends on it. + +adler32.o: zlib.h zconf.h +compress.o: zlib.h zconf.h +crc32.o: crc32.h zlib.h zconf.h +deflate.o: deflate.h zutil.h zlib.h zconf.h +example.o: zlib.h zconf.h +gzclose.o: zlib.h zconf.h gzguts.h +gzlib.o: zlib.h zconf.h gzguts.h +gzread.o: zlib.h zconf.h gzguts.h +gzwrite.o: zlib.h zconf.h gzguts.h +inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +inftrees.o: zutil.h zlib.h zconf.h inftrees.h +minigzip.o: zlib.h zconf.h +trees.o: deflate.h zutil.h zlib.h zconf.h trees.h +uncompr.o: zlib.h zconf.h +zutil.o: zutil.h zlib.h zconf.h diff --git a/third_party/zlib/v1_2_11/amiga/Makefile.sas b/third_party/zlib/v1_2_11/amiga/Makefile.sas new file mode 100644 index 0000000..749e291 --- /dev/null +++ b/third_party/zlib/v1_2_11/amiga/Makefile.sas @@ -0,0 +1,68 @@ +# SMakefile for zlib +# Modified from the standard UNIX Makefile Copyright Jean-loup Gailly +# Osma Ahvenlampi +# Amiga, SAS/C 6.56 & Smake + +CC=sc +CFLAGS=OPT +#CFLAGS=OPT CPU=68030 +#CFLAGS=DEBUG=LINE +LDFLAGS=LIB z.lib + +SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \ + NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \ + DEF=POSTINC + +OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ + uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o + +TEST_OBJS = example.o minigzip.o + +all: SCOPTIONS example minigzip + +check: test +test: all + example + echo hello world | minigzip | minigzip -d + +install: z.lib + copy clone zlib.h zconf.h INCLUDE: + copy clone z.lib LIB: + +z.lib: $(OBJS) + oml z.lib r $(OBJS) + +example: example.o z.lib + $(CC) $(CFLAGS) LINK TO $@ example.o $(LDFLAGS) + +minigzip: minigzip.o z.lib + $(CC) $(CFLAGS) LINK TO $@ minigzip.o $(LDFLAGS) + +mostlyclean: clean +clean: + -delete force quiet example minigzip *.o z.lib foo.gz *.lnk SCOPTIONS + +SCOPTIONS: Makefile.sas + copy to $@ (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen; + sourceLen -= stream.avail_in; + } + err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH); + } while (err == Z_OK); + + *destLen = stream.total_out; + deflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/third_party/zlib/v1_2_11/configure b/third_party/zlib/v1_2_11/configure new file mode 100644 index 0000000..e974d1f --- /dev/null +++ b/third_party/zlib/v1_2_11/configure @@ -0,0 +1,921 @@ +#!/bin/sh +# configure script for zlib. +# +# Normally configure builds both a static and a shared library. +# If you want to build just a static library, use: ./configure --static +# +# To impose specific compiler or flags or install directory, use for example: +# prefix=$HOME CC=cc CFLAGS="-O4" ./configure +# or for csh/tcsh users: +# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure) + +# Incorrect settings of CC or CFLAGS may prevent creating a shared library. +# If you have problems, try without defining CC and CFLAGS before reporting +# an error. + +# start off configure.log +echo -------------------- >> configure.log +echo $0 $* >> configure.log +date >> configure.log + +# get source directory +SRCDIR=`dirname $0` +if test $SRCDIR = "."; then + ZINC="" + ZINCOUT="-I." + SRCDIR="" +else + ZINC='-include zconf.h' + ZINCOUT='-I. -I$(SRCDIR)' + SRCDIR="$SRCDIR/" +fi + +# set command prefix for cross-compilation +if [ -n "${CHOST}" ]; then + uname="`echo "${CHOST}" | sed -e 's/^[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)$/\1/' -e 's/^[^-]*-[^-]*-\([^-]*\)-.*$/\1/'`" + CROSS_PREFIX="${CHOST}-" +fi + +# destination name for static library +STATICLIB=libz.a + +# extract zlib version numbers from zlib.h +VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < ${SRCDIR}zlib.h` +VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < ${SRCDIR}zlib.h` +VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` +VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h` + +# establish commands for library building +if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then + AR=${AR-"${CROSS_PREFIX}ar"} + test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log +else + AR=${AR-"ar"} + test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log +fi +ARFLAGS=${ARFLAGS-"rc"} +if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then + RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"} + test -n "${CROSS_PREFIX}" && echo Using ${RANLIB} | tee -a configure.log +else + RANLIB=${RANLIB-"ranlib"} +fi +if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then + NM=${NM-"${CROSS_PREFIX}nm"} + test -n "${CROSS_PREFIX}" && echo Using ${NM} | tee -a configure.log +else + NM=${NM-"nm"} +fi + +# set defaults before processing command line options +LDCONFIG=${LDCONFIG-"ldconfig"} +LDSHAREDLIBC="${LDSHAREDLIBC--lc}" +ARCHS= +prefix=${prefix-/usr/local} +exec_prefix=${exec_prefix-'${prefix}'} +libdir=${libdir-'${exec_prefix}/lib'} +sharedlibdir=${sharedlibdir-'${libdir}'} +includedir=${includedir-'${prefix}/include'} +mandir=${mandir-'${prefix}/share/man'} +shared_ext='.so' +shared=1 +solo=0 +cover=0 +zprefix=0 +zconst=0 +build64=0 +gcc=0 +warn=0 +debug=0 +old_cc="$CC" +old_cflags="$CFLAGS" +OBJC='$(OBJZ) $(OBJG)' +PIC_OBJC='$(PIC_OBJZ) $(PIC_OBJG)' + +# leave this script, optionally in a bad way +leave() +{ + if test "$*" != "0"; then + echo "** $0 aborting." | tee -a configure.log + fi + rm -f $test.[co] $test $test$shared_ext $test.gcno ./--version + echo -------------------- >> configure.log + echo >> configure.log + echo >> configure.log + exit $1 +} + +# process command line options +while test $# -ge 1 +do +case "$1" in + -h* | --help) + echo 'usage:' | tee -a configure.log + echo ' configure [--const] [--zprefix] [--prefix=PREFIX] [--eprefix=EXPREFIX]' | tee -a configure.log + echo ' [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]' | tee -a configure.log + echo ' [--includedir=INCLUDEDIR] [--archs="-arch i386 -arch x86_64"]' | tee -a configure.log + exit 0 ;; + -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;; + -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;; + -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;; + --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;; + -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;; + -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;; + -p* | --prefix) prefix="$2"; shift; shift ;; + -e* | --eprefix) exec_prefix="$2"; shift; shift ;; + -l* | --libdir) libdir="$2"; shift; shift ;; + -i* | --includedir) includedir="$2"; shift; shift ;; + -s* | --shared | --enable-shared) shared=1; shift ;; + -t | --static) shared=0; shift ;; + --solo) solo=1; shift ;; + --cover) cover=1; shift ;; + -z* | --zprefix) zprefix=1; shift ;; + -6* | --64) build64=1; shift ;; + -a*=* | --archs=*) ARCHS=`echo $1 | sed 's/.*=//'`; shift ;; + --sysconfdir=*) echo "ignored option: --sysconfdir" | tee -a configure.log; shift ;; + --localstatedir=*) echo "ignored option: --localstatedir" | tee -a configure.log; shift ;; + -c* | --const) zconst=1; shift ;; + -w* | --warn) warn=1; shift ;; + -d* | --debug) debug=1; shift ;; + *) + echo "unknown option: $1" | tee -a configure.log + echo "$0 --help for help" | tee -a configure.log + leave 1;; + esac +done + +# temporary file name +test=ztest$$ + +# put arguments in log, also put test file in log if used in arguments +show() +{ + case "$*" in + *$test.c*) + echo === $test.c === >> configure.log + cat $test.c >> configure.log + echo === >> configure.log;; + esac + echo $* >> configure.log +} + +# check for gcc vs. cc and set compile and link flags based on the system identified by uname +cat > $test.c <&1` in + *gcc*) gcc=1 ;; + *clang*) gcc=1 ;; +esac + +show $cc -c $test.c +if test "$gcc" -eq 1 && ($cc -c $test.c) >> configure.log 2>&1; then + echo ... using gcc >> configure.log + CC="$cc" + CFLAGS="${CFLAGS--O3}" + SFLAGS="${CFLAGS--O3} -fPIC" + if test "$ARCHS"; then + CFLAGS="${CFLAGS} ${ARCHS}" + LDFLAGS="${LDFLAGS} ${ARCHS}" + fi + if test $build64 -eq 1; then + CFLAGS="${CFLAGS} -m64" + SFLAGS="${SFLAGS} -m64" + fi + if test "$warn" -eq 1; then + if test "$zconst" -eq 1; then + CFLAGS="${CFLAGS} -Wall -Wextra -Wcast-qual -pedantic -DZLIB_CONST" + else + CFLAGS="${CFLAGS} -Wall -Wextra -pedantic" + fi + fi + if test $debug -eq 1; then + CFLAGS="${CFLAGS} -DZLIB_DEBUG" + SFLAGS="${SFLAGS} -DZLIB_DEBUG" + fi + if test -z "$uname"; then + uname=`(uname -s || echo unknown) 2>/dev/null` + fi + case "$uname" in + Linux* | linux* | GNU | GNU/* | solaris*) + LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} ;; + *BSD | *bsd* | DragonFly) + LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} + LDCONFIG="ldconfig -m" ;; + CYGWIN* | Cygwin* | cygwin* | OS/2*) + EXE='.exe' ;; + MINGW* | mingw*) +# temporary bypass + rm -f $test.[co] $test $test$shared_ext + echo "Please use win32/Makefile.gcc instead." | tee -a configure.log + leave 1 + LDSHARED=${LDSHARED-"$cc -shared"} + LDSHAREDLIBC="" + EXE='.exe' ;; + QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4 + # (alain.bonnefoy@icbt.com) + LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;; + HP-UX*) + LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"} + case `(uname -m || echo unknown) 2>/dev/null` in + ia64) + shared_ext='.so' + SHAREDLIB='libz.so' ;; + *) + shared_ext='.sl' + SHAREDLIB='libz.sl' ;; + esac ;; + Darwin* | darwin*) + shared_ext='.dylib' + SHAREDLIB=libz$shared_ext + SHAREDLIBV=libz.$VER$shared_ext + SHAREDLIBM=libz.$VER1$shared_ext + LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"} + if libtool -V 2>&1 | grep Apple > /dev/null; then + AR="libtool" + else + AR="/usr/bin/libtool" + fi + ARFLAGS="-o" ;; + *) LDSHARED=${LDSHARED-"$cc -shared"} ;; + esac +else + # find system name and corresponding cc options + CC=${CC-cc} + gcc=0 + echo ... using $CC >> configure.log + if test -z "$uname"; then + uname=`(uname -sr || echo unknown) 2>/dev/null` + fi + case "$uname" in + HP-UX*) SFLAGS=${CFLAGS-"-O +z"} + CFLAGS=${CFLAGS-"-O"} +# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"} + LDSHARED=${LDSHARED-"ld -b"} + case `(uname -m || echo unknown) 2>/dev/null` in + ia64) + shared_ext='.so' + SHAREDLIB='libz.so' ;; + *) + shared_ext='.sl' + SHAREDLIB='libz.sl' ;; + esac ;; + IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."} + CFLAGS=${CFLAGS-"-ansi -O2"} + LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; + OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"} + CFLAGS=${CFLAGS-"-O -std1"} + LDFLAGS="${LDFLAGS} -Wl,-rpath,." + LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;; + OSF1*) SFLAGS=${CFLAGS-"-O -std1"} + CFLAGS=${CFLAGS-"-O -std1"} + LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;; + QNX*) SFLAGS=${CFLAGS-"-4 -O"} + CFLAGS=${CFLAGS-"-4 -O"} + LDSHARED=${LDSHARED-"cc"} + RANLIB=${RANLIB-"true"} + AR="cc" + ARFLAGS="-A" ;; + SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "} + CFLAGS=${CFLAGS-"-O3"} + LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;; + SunOS\ 5* | solaris*) + LDSHARED=${LDSHARED-"cc -G -h libz$shared_ext.$VER1"} + SFLAGS=${CFLAGS-"-fast -KPIC"} + CFLAGS=${CFLAGS-"-fast"} + if test $build64 -eq 1; then + # old versions of SunPRO/Workshop/Studio don't support -m64, + # but newer ones do. Check for it. + flag64=`$CC -flags | egrep -- '^-m64'` + if test x"$flag64" != x"" ; then + CFLAGS="${CFLAGS} -m64" + SFLAGS="${SFLAGS} -m64" + else + case `(uname -m || echo unknown) 2>/dev/null` in + i86*) + SFLAGS="$SFLAGS -xarch=amd64" + CFLAGS="$CFLAGS -xarch=amd64" ;; + *) + SFLAGS="$SFLAGS -xarch=v9" + CFLAGS="$CFLAGS -xarch=v9" ;; + esac + fi + fi + if test -n "$ZINC"; then + ZINC='-I- -I. -I$(SRCDIR)' + fi + ;; + SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"} + CFLAGS=${CFLAGS-"-O2"} + LDSHARED=${LDSHARED-"ld"} ;; + SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"} + CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"} + LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;; + UNIX_System_V\ 4.2.0) + SFLAGS=${CFLAGS-"-KPIC -O"} + CFLAGS=${CFLAGS-"-O"} + LDSHARED=${LDSHARED-"cc -G"} ;; + UNIX_SV\ 4.2MP) + SFLAGS=${CFLAGS-"-Kconform_pic -O"} + CFLAGS=${CFLAGS-"-O"} + LDSHARED=${LDSHARED-"cc -G"} ;; + OpenUNIX\ 5) + SFLAGS=${CFLAGS-"-KPIC -O"} + CFLAGS=${CFLAGS-"-O"} + LDSHARED=${LDSHARED-"cc -G"} ;; + AIX*) # Courtesy of dbakker@arrayasolutions.com + SFLAGS=${CFLAGS-"-O -qmaxmem=8192"} + CFLAGS=${CFLAGS-"-O -qmaxmem=8192"} + LDSHARED=${LDSHARED-"xlc -G"} ;; + # send working options for other systems to zlib@gzip.org + *) SFLAGS=${CFLAGS-"-O"} + CFLAGS=${CFLAGS-"-O"} + LDSHARED=${LDSHARED-"cc -shared"} ;; + esac +fi + +# destination names for shared library if not defined above +SHAREDLIB=${SHAREDLIB-"libz$shared_ext"} +SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"} +SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"} + +echo >> configure.log + +# define functions for testing compiler and library characteristics and logging the results + +cat > $test.c </dev/null; then + try() + { + show $* + test "`( $* ) 2>&1 | tee -a configure.log`" = "" + } + echo - using any output from compiler to indicate an error >> configure.log +else + try() + { + show $* + ( $* ) >> configure.log 2>&1 + ret=$? + if test $ret -ne 0; then + echo "(exit code "$ret")" >> configure.log + fi + return $ret + } +fi + +tryboth() +{ + show $* + got=`( $* ) 2>&1` + ret=$? + printf %s "$got" >> configure.log + if test $ret -ne 0; then + return $ret + fi + test "$got" = "" +} + +cat > $test.c << EOF +int foo() { return 0; } +EOF +echo "Checking for obsessive-compulsive compiler options..." >> configure.log +if try $CC -c $CFLAGS $test.c; then + : +else + echo "Compiler error reporting is too harsh for $0 (perhaps remove -Werror)." | tee -a configure.log + leave 1 +fi + +echo >> configure.log + +# see if shared library build supported +cat > $test.c <> configure.log + show "$NM $test.o | grep _hello" + if test "`$NM $test.o | grep _hello | tee -a configure.log`" = ""; then + CPP="$CPP -DNO_UNDERLINE" + echo Checking for underline in external names... No. | tee -a configure.log + else + echo Checking for underline in external names... Yes. | tee -a configure.log + fi ;; +esac + +echo >> configure.log + +# check for size_t +cat > $test.c < +#include +size_t dummy = 0; +EOF +if try $CC -c $CFLAGS $test.c; then + echo "Checking for size_t... Yes." | tee -a configure.log + need_sizet=0 +else + echo "Checking for size_t... No." | tee -a configure.log + need_sizet=1 +fi + +echo >> configure.log + +# find the size_t integer type, if needed +if test $need_sizet -eq 1; then + cat > $test.c < $test.c < +int main(void) { + if (sizeof(void *) <= sizeof(int)) puts("int"); + else if (sizeof(void *) <= sizeof(long)) puts("long"); + else puts("z_longlong"); + return 0; +} +EOF + else + echo "Checking for long long... No." | tee -a configure.log + cat > $test.c < +int main(void) { + if (sizeof(void *) <= sizeof(int)) puts("int"); + else puts("long"); + return 0; +} +EOF + fi + if try $CC $CFLAGS -o $test $test.c; then + sizet=`./$test` + echo "Checking for a pointer-size integer type..." $sizet"." | tee -a configure.log + else + echo "Failed to find a pointer-size integer type." | tee -a configure.log + leave 1 + fi +fi + +if test $need_sizet -eq 1; then + CFLAGS="${CFLAGS} -DNO_SIZE_T=${sizet}" + SFLAGS="${SFLAGS} -DNO_SIZE_T=${sizet}" +fi + +echo >> configure.log + +# check for large file support, and if none, check for fseeko() +cat > $test.c < +off64_t dummy = 0; +EOF +if try $CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c; then + CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1" + SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1" + ALL="${ALL} all64" + TEST="${TEST} test64" + echo "Checking for off64_t... Yes." | tee -a configure.log + echo "Checking for fseeko... Yes." | tee -a configure.log +else + echo "Checking for off64_t... No." | tee -a configure.log + echo >> configure.log + cat > $test.c < +int main(void) { + fseeko(NULL, 0, 0); + return 0; +} +EOF + if try $CC $CFLAGS -o $test $test.c; then + echo "Checking for fseeko... Yes." | tee -a configure.log + else + CFLAGS="${CFLAGS} -DNO_FSEEKO" + SFLAGS="${SFLAGS} -DNO_FSEEKO" + echo "Checking for fseeko... No." | tee -a configure.log + fi +fi + +echo >> configure.log + +# check for strerror() for use by gz* functions +cat > $test.c < +#include +int main() { return strlen(strerror(errno)); } +EOF +if try $CC $CFLAGS -o $test $test.c; then + echo "Checking for strerror... Yes." | tee -a configure.log +else + CFLAGS="${CFLAGS} -DNO_STRERROR" + SFLAGS="${SFLAGS} -DNO_STRERROR" + echo "Checking for strerror... No." | tee -a configure.log +fi + +# copy clean zconf.h for subsequent edits +cp -p ${SRCDIR}zconf.h.in zconf.h + +echo >> configure.log + +# check for unistd.h and save result in zconf.h +cat > $test.c < +int main() { return 0; } +EOF +if try $CC -c $CFLAGS $test.c; then + sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h + mv zconf.temp.h zconf.h + echo "Checking for unistd.h... Yes." | tee -a configure.log +else + echo "Checking for unistd.h... No." | tee -a configure.log +fi + +echo >> configure.log + +# check for stdarg.h and save result in zconf.h +cat > $test.c < +int main() { return 0; } +EOF +if try $CC -c $CFLAGS $test.c; then + sed < zconf.h "/^#ifdef HAVE_STDARG_H.* may be/s/def HAVE_STDARG_H\(.*\) may be/ 1\1 was/" > zconf.temp.h + mv zconf.temp.h zconf.h + echo "Checking for stdarg.h... Yes." | tee -a configure.log +else + echo "Checking for stdarg.h... No." | tee -a configure.log +fi + +# if the z_ prefix was requested, save that in zconf.h +if test $zprefix -eq 1; then + sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h + mv zconf.temp.h zconf.h + echo >> configure.log + echo "Using z_ prefix on all symbols." | tee -a configure.log +fi + +# if --solo compilation was requested, save that in zconf.h and remove gz stuff from object lists +if test $solo -eq 1; then + sed '/#define ZCONF_H/a\ +#define Z_SOLO + +' < zconf.h > zconf.temp.h + mv zconf.temp.h zconf.h +OBJC='$(OBJZ)' +PIC_OBJC='$(PIC_OBJZ)' +fi + +# if code coverage testing was requested, use older gcc if defined, e.g. "gcc-4.2" on Mac OS X +if test $cover -eq 1; then + CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage" + if test -n "$GCC_CLASSIC"; then + CC=$GCC_CLASSIC + fi +fi + +echo >> configure.log + +# conduct a series of tests to resolve eight possible cases of using "vs" or "s" printf functions +# (using stdarg or not), with or without "n" (proving size of buffer), and with or without a +# return value. The most secure result is vsnprintf() with a return value. snprintf() with a +# return value is secure as well, but then gzprintf() will be limited to 20 arguments. +cat > $test.c < +#include +#include "zconf.h" +int main() +{ +#ifndef STDC + choke me +#endif + return 0; +} +EOF +if try $CC -c $CFLAGS $test.c; then + echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()." | tee -a configure.log + + echo >> configure.log + cat > $test.c < +#include +int mytest(const char *fmt, ...) +{ + char buf[20]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return 0; +} +int main() +{ + return (mytest("Hello%d\n", 1)); +} +EOF + if try $CC $CFLAGS -o $test $test.c; then + echo "Checking for vsnprintf() in stdio.h... Yes." | tee -a configure.log + + echo >> configure.log + cat >$test.c < +#include +int mytest(const char *fmt, ...) +{ + int n; + char buf[20]; + va_list ap; + va_start(ap, fmt); + n = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return n; +} +int main() +{ + return (mytest("Hello%d\n", 1)); +} +EOF + + if try $CC -c $CFLAGS $test.c; then + echo "Checking for return value of vsnprintf()... Yes." | tee -a configure.log + else + CFLAGS="$CFLAGS -DHAS_vsnprintf_void" + SFLAGS="$SFLAGS -DHAS_vsnprintf_void" + echo "Checking for return value of vsnprintf()... No." | tee -a configure.log + echo " WARNING: apparently vsnprintf() does not return a value. zlib" | tee -a configure.log + echo " can build but will be open to possible string-format security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + fi + else + CFLAGS="$CFLAGS -DNO_vsnprintf" + SFLAGS="$SFLAGS -DNO_vsnprintf" + echo "Checking for vsnprintf() in stdio.h... No." | tee -a configure.log + echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" | tee -a configure.log + echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + + echo >> configure.log + cat >$test.c < +#include +int mytest(const char *fmt, ...) +{ + int n; + char buf[20]; + va_list ap; + va_start(ap, fmt); + n = vsprintf(buf, fmt, ap); + va_end(ap); + return n; +} +int main() +{ + return (mytest("Hello%d\n", 1)); +} +EOF + + if try $CC -c $CFLAGS $test.c; then + echo "Checking for return value of vsprintf()... Yes." | tee -a configure.log + else + CFLAGS="$CFLAGS -DHAS_vsprintf_void" + SFLAGS="$SFLAGS -DHAS_vsprintf_void" + echo "Checking for return value of vsprintf()... No." | tee -a configure.log + echo " WARNING: apparently vsprintf() does not return a value. zlib" | tee -a configure.log + echo " can build but will be open to possible string-format security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + fi + fi +else + echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()." | tee -a configure.log + + echo >> configure.log + cat >$test.c < +int mytest() +{ + char buf[20]; + snprintf(buf, sizeof(buf), "%s", "foo"); + return 0; +} +int main() +{ + return (mytest()); +} +EOF + + if try $CC $CFLAGS -o $test $test.c; then + echo "Checking for snprintf() in stdio.h... Yes." | tee -a configure.log + + echo >> configure.log + cat >$test.c < +int mytest() +{ + char buf[20]; + return snprintf(buf, sizeof(buf), "%s", "foo"); +} +int main() +{ + return (mytest()); +} +EOF + + if try $CC -c $CFLAGS $test.c; then + echo "Checking for return value of snprintf()... Yes." | tee -a configure.log + else + CFLAGS="$CFLAGS -DHAS_snprintf_void" + SFLAGS="$SFLAGS -DHAS_snprintf_void" + echo "Checking for return value of snprintf()... No." | tee -a configure.log + echo " WARNING: apparently snprintf() does not return a value. zlib" | tee -a configure.log + echo " can build but will be open to possible string-format security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + fi + else + CFLAGS="$CFLAGS -DNO_snprintf" + SFLAGS="$SFLAGS -DNO_snprintf" + echo "Checking for snprintf() in stdio.h... No." | tee -a configure.log + echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" | tee -a configure.log + echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + + echo >> configure.log + cat >$test.c < +int mytest() +{ + char buf[20]; + return sprintf(buf, "%s", "foo"); +} +int main() +{ + return (mytest()); +} +EOF + + if try $CC -c $CFLAGS $test.c; then + echo "Checking for return value of sprintf()... Yes." | tee -a configure.log + else + CFLAGS="$CFLAGS -DHAS_sprintf_void" + SFLAGS="$SFLAGS -DHAS_sprintf_void" + echo "Checking for return value of sprintf()... No." | tee -a configure.log + echo " WARNING: apparently sprintf() does not return a value. zlib" | tee -a configure.log + echo " can build but will be open to possible string-format security" | tee -a configure.log + echo " vulnerabilities." | tee -a configure.log + fi + fi +fi + +# see if we can hide zlib internal symbols that are linked between separate source files +if test "$gcc" -eq 1; then + echo >> configure.log + cat > $test.c <> configure.log +echo ALL = $ALL >> configure.log +echo AR = $AR >> configure.log +echo ARFLAGS = $ARFLAGS >> configure.log +echo CC = $CC >> configure.log +echo CFLAGS = $CFLAGS >> configure.log +echo CPP = $CPP >> configure.log +echo EXE = $EXE >> configure.log +echo LDCONFIG = $LDCONFIG >> configure.log +echo LDFLAGS = $LDFLAGS >> configure.log +echo LDSHARED = $LDSHARED >> configure.log +echo LDSHAREDLIBC = $LDSHAREDLIBC >> configure.log +echo OBJC = $OBJC >> configure.log +echo PIC_OBJC = $PIC_OBJC >> configure.log +echo RANLIB = $RANLIB >> configure.log +echo SFLAGS = $SFLAGS >> configure.log +echo SHAREDLIB = $SHAREDLIB >> configure.log +echo SHAREDLIBM = $SHAREDLIBM >> configure.log +echo SHAREDLIBV = $SHAREDLIBV >> configure.log +echo STATICLIB = $STATICLIB >> configure.log +echo TEST = $TEST >> configure.log +echo VER = $VER >> configure.log +echo Z_U4 = $Z_U4 >> configure.log +echo SRCDIR = $SRCDIR >> configure.log +echo exec_prefix = $exec_prefix >> configure.log +echo includedir = $includedir >> configure.log +echo libdir = $libdir >> configure.log +echo mandir = $mandir >> configure.log +echo prefix = $prefix >> configure.log +echo sharedlibdir = $sharedlibdir >> configure.log +echo uname = $uname >> configure.log + +# udpate Makefile with the configure results +sed < ${SRCDIR}Makefile.in " +/^CC *=/s#=.*#=$CC# +/^CFLAGS *=/s#=.*#=$CFLAGS# +/^SFLAGS *=/s#=.*#=$SFLAGS# +/^LDFLAGS *=/s#=.*#=$LDFLAGS# +/^LDSHARED *=/s#=.*#=$LDSHARED# +/^CPP *=/s#=.*#=$CPP# +/^STATICLIB *=/s#=.*#=$STATICLIB# +/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# +/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# +/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# +/^AR *=/s#=.*#=$AR# +/^ARFLAGS *=/s#=.*#=$ARFLAGS# +/^RANLIB *=/s#=.*#=$RANLIB# +/^LDCONFIG *=/s#=.*#=$LDCONFIG# +/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC# +/^EXE *=/s#=.*#=$EXE# +/^SRCDIR *=/s#=.*#=$SRCDIR# +/^ZINC *=/s#=.*#=$ZINC# +/^ZINCOUT *=/s#=.*#=$ZINCOUT# +/^prefix *=/s#=.*#=$prefix# +/^exec_prefix *=/s#=.*#=$exec_prefix# +/^libdir *=/s#=.*#=$libdir# +/^sharedlibdir *=/s#=.*#=$sharedlibdir# +/^includedir *=/s#=.*#=$includedir# +/^mandir *=/s#=.*#=$mandir# +/^OBJC *=/s#=.*#= $OBJC# +/^PIC_OBJC *=/s#=.*#= $PIC_OBJC# +/^all: */s#:.*#: $ALL# +/^test: */s#:.*#: $TEST# +" > Makefile + +# create zlib.pc with the configure results +sed < ${SRCDIR}zlib.pc.in " +/^CC *=/s#=.*#=$CC# +/^CFLAGS *=/s#=.*#=$CFLAGS# +/^CPP *=/s#=.*#=$CPP# +/^LDSHARED *=/s#=.*#=$LDSHARED# +/^STATICLIB *=/s#=.*#=$STATICLIB# +/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# +/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# +/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# +/^AR *=/s#=.*#=$AR# +/^ARFLAGS *=/s#=.*#=$ARFLAGS# +/^RANLIB *=/s#=.*#=$RANLIB# +/^EXE *=/s#=.*#=$EXE# +/^prefix *=/s#=.*#=$prefix# +/^exec_prefix *=/s#=.*#=$exec_prefix# +/^libdir *=/s#=.*#=$libdir# +/^sharedlibdir *=/s#=.*#=$sharedlibdir# +/^includedir *=/s#=.*#=$includedir# +/^mandir *=/s#=.*#=$mandir# +/^LDFLAGS *=/s#=.*#=$LDFLAGS# +" | sed -e " +s/\@VERSION\@/$VER/g; +" > zlib.pc + +# done +leave 0 diff --git a/third_party/zlib/v1_2_11/contrib/README.contrib b/third_party/zlib/v1_2_11/contrib/README.contrib new file mode 100644 index 0000000..a411d5c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/README.contrib @@ -0,0 +1,78 @@ +All files under this contrib directory are UNSUPPORTED. There were +provided by users of zlib and were not tested by the authors of zlib. +Use at your own risk. Please contact the authors of the contributions +for help about these, not the zlib authors. Thanks. + + +ada/ by Dmitriy Anisimkov + Support for Ada + See http://zlib-ada.sourceforge.net/ + +amd64/ by Mikhail Teterin + asm code for AMD64 + See patch at http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/96393 + +asm686/ by Brian Raiter + asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax + See http://www.muppetlabs.com/~breadbox/software/assembly.html + +blast/ by Mark Adler + Decompressor for output of PKWare Data Compression Library (DCL) + +delphi/ by Cosmin Truta + Support for Delphi and C++ Builder + +dotzlib/ by Henrik Ravn + Support for Microsoft .Net and Visual C++ .Net + +gcc_gvmat64/by Gilles Vollant + GCC Version of x86 64-bit (AMD64 and Intel EM64t) code for x64 + assembler to replace longest_match() and inflate_fast() + +infback9/ by Mark Adler + Unsupported diffs to infback to decode the deflate64 format + +inflate86/ by Chris Anderson + Tuned x86 gcc asm code to replace inflate_fast() + +iostream/ by Kevin Ruland + A C++ I/O streams interface to the zlib gz* functions + +iostream2/ by Tyge Løvset + Another C++ I/O streams interface + +iostream3/ by Ludwig Schwardt + and Kevin Ruland + Yet another C++ I/O streams interface + +masmx64/ by Gilles Vollant + x86 64-bit (AMD64 and Intel EM64t) code for x64 assembler to + replace longest_match() and inflate_fast(), also masm x86 + 64-bits translation of Chris Anderson inflate_fast() + +masmx86/ by Gilles Vollant + x86 asm code to replace longest_match() and inflate_fast(), + for Visual C++ and MASM (32 bits). + Based on Brian Raiter (asm686) and Chris Anderson (inflate86) + +minizip/ by Gilles Vollant + Mini zip and unzip based on zlib + Includes Zip64 support by Mathias Svensson + See http://www.winimage.com/zLibDll/minizip.html + +pascal/ by Bob Dellaca et al. + Support for Pascal + +puff/ by Mark Adler + Small, low memory usage inflate. Also serves to provide an + unambiguous description of the deflate format. + +testzlib/ by Gilles Vollant + Example of the use of zlib + +untgz/ by Pedro A. Aranda Gutierrez + A very simple tar.gz file extractor using zlib + +vstudio/ by Gilles Vollant + Building a minizip-enhanced zlib with Microsoft Visual Studio + Includes vc11 from kreuzerkrieg and vc12 from davispuh diff --git a/third_party/zlib/v1_2_11/contrib/ada/buffer_demo.adb b/third_party/zlib/v1_2_11/contrib/ada/buffer_demo.adb new file mode 100644 index 0000000..46b8638 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/buffer_demo.adb @@ -0,0 +1,106 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2004 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- +-- +-- $Id: buffer_demo.adb,v 1.3 2004/09/06 06:55:35 vagul Exp $ + +-- This demo program provided by Dr Steve Sangwine +-- +-- Demonstration of a problem with Zlib-Ada (already fixed) when a buffer +-- of exactly the correct size is used for decompressed data, and the last +-- few bytes passed in to Zlib are checksum bytes. + +-- This program compresses a string of text, and then decompresses the +-- compressed text into a buffer of the same size as the original text. + +with Ada.Streams; use Ada.Streams; +with Ada.Text_IO; + +with ZLib; use ZLib; + +procedure Buffer_Demo is + EOL : Character renames ASCII.LF; + Text : constant String + := "Four score and seven years ago our fathers brought forth," & EOL & + "upon this continent, a new nation, conceived in liberty," & EOL & + "and dedicated to the proposition that `all men are created equal'."; + + Source : Stream_Element_Array (1 .. Text'Length); + for Source'Address use Text'Address; + +begin + Ada.Text_IO.Put (Text); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line + ("Uncompressed size : " & Positive'Image (Text'Length) & " bytes"); + + declare + Compressed_Data : Stream_Element_Array (1 .. Text'Length); + L : Stream_Element_Offset; + begin + Compress : declare + Compressor : Filter_Type; + I : Stream_Element_Offset; + begin + Deflate_Init (Compressor); + + -- Compress the whole of T at once. + + Translate (Compressor, Source, I, Compressed_Data, L, Finish); + pragma Assert (I = Source'Last); + + Close (Compressor); + + Ada.Text_IO.Put_Line + ("Compressed size : " + & Stream_Element_Offset'Image (L) & " bytes"); + end Compress; + + -- Now we decompress the data, passing short blocks of data to Zlib + -- (because this demonstrates the problem - the last block passed will + -- contain checksum information and there will be no output, only a + -- check inside Zlib that the checksum is correct). + + Decompress : declare + Decompressor : Filter_Type; + + Uncompressed_Data : Stream_Element_Array (1 .. Text'Length); + + Block_Size : constant := 4; + -- This makes sure that the last block contains + -- only Adler checksum data. + + P : Stream_Element_Offset := Compressed_Data'First - 1; + O : Stream_Element_Offset; + begin + Inflate_Init (Decompressor); + + loop + Translate + (Decompressor, + Compressed_Data + (P + 1 .. Stream_Element_Offset'Min (P + Block_Size, L)), + P, + Uncompressed_Data + (Total_Out (Decompressor) + 1 .. Uncompressed_Data'Last), + O, + No_Flush); + + Ada.Text_IO.Put_Line + ("Total in : " & Count'Image (Total_In (Decompressor)) & + ", out : " & Count'Image (Total_Out (Decompressor))); + + exit when P = L; + end loop; + + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line + ("Decompressed text matches original text : " + & Boolean'Image (Uncompressed_Data = Source)); + end Decompress; + end; +end Buffer_Demo; diff --git a/third_party/zlib/v1_2_11/contrib/ada/mtest.adb b/third_party/zlib/v1_2_11/contrib/ada/mtest.adb new file mode 100644 index 0000000..c4dfd08 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/mtest.adb @@ -0,0 +1,156 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- +-- Continuous test for ZLib multithreading. If the test would fail +-- we should provide thread safe allocation routines for the Z_Stream. +-- +-- $Id: mtest.adb,v 1.4 2004/07/23 07:49:54 vagul Exp $ + +with ZLib; +with Ada.Streams; +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; +with Ada.Exceptions; +with Ada.Task_Identification; + +procedure MTest is + use Ada.Streams; + use ZLib; + + Stop : Boolean := False; + + pragma Atomic (Stop); + + subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; + + package Random_Elements is + new Ada.Numerics.Discrete_Random (Visible_Symbols); + + task type Test_Task; + + task body Test_Task is + Buffer : Stream_Element_Array (1 .. 100_000); + Gen : Random_Elements.Generator; + + Buffer_First : Stream_Element_Offset; + Compare_First : Stream_Element_Offset; + + Deflate : Filter_Type; + Inflate : Filter_Type; + + procedure Further (Item : in Stream_Element_Array); + + procedure Read_Buffer + (Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset); + + ------------- + -- Further -- + ------------- + + procedure Further (Item : in Stream_Element_Array) is + + procedure Compare (Item : in Stream_Element_Array); + + ------------- + -- Compare -- + ------------- + + procedure Compare (Item : in Stream_Element_Array) is + Next_First : Stream_Element_Offset := Compare_First + Item'Length; + begin + if Buffer (Compare_First .. Next_First - 1) /= Item then + raise Program_Error; + end if; + + Compare_First := Next_First; + end Compare; + + procedure Compare_Write is new ZLib.Write (Write => Compare); + begin + Compare_Write (Inflate, Item, No_Flush); + end Further; + + ----------------- + -- Read_Buffer -- + ----------------- + + procedure Read_Buffer + (Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset) + is + Buff_Diff : Stream_Element_Offset := Buffer'Last - Buffer_First; + Next_First : Stream_Element_Offset; + begin + if Item'Length <= Buff_Diff then + Last := Item'Last; + + Next_First := Buffer_First + Item'Length; + + Item := Buffer (Buffer_First .. Next_First - 1); + + Buffer_First := Next_First; + else + Last := Item'First + Buff_Diff; + Item (Item'First .. Last) := Buffer (Buffer_First .. Buffer'Last); + Buffer_First := Buffer'Last + 1; + end if; + end Read_Buffer; + + procedure Translate is new Generic_Translate + (Data_In => Read_Buffer, + Data_Out => Further); + + begin + Random_Elements.Reset (Gen); + + Buffer := (others => 20); + + Main : loop + for J in Buffer'Range loop + Buffer (J) := Random_Elements.Random (Gen); + + Deflate_Init (Deflate); + Inflate_Init (Inflate); + + Buffer_First := Buffer'First; + Compare_First := Buffer'First; + + Translate (Deflate); + + if Compare_First /= Buffer'Last + 1 then + raise Program_Error; + end if; + + Ada.Text_IO.Put_Line + (Ada.Task_Identification.Image + (Ada.Task_Identification.Current_Task) + & Stream_Element_Offset'Image (J) + & ZLib.Count'Image (Total_Out (Deflate))); + + Close (Deflate); + Close (Inflate); + + exit Main when Stop; + end loop; + end loop Main; + exception + when E : others => + Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E)); + Stop := True; + end Test_Task; + + Test : array (1 .. 4) of Test_Task; + + pragma Unreferenced (Test); + + Dummy : Character; + +begin + Ada.Text_IO.Get_Immediate (Dummy); + Stop := True; +end MTest; diff --git a/third_party/zlib/v1_2_11/contrib/ada/read.adb b/third_party/zlib/v1_2_11/contrib/ada/read.adb new file mode 100644 index 0000000..1f2efbf --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/read.adb @@ -0,0 +1,156 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: read.adb,v 1.8 2004/05/31 10:53:40 vagul Exp $ + +-- Test/demo program for the generic read interface. + +with Ada.Numerics.Discrete_Random; +with Ada.Streams; +with Ada.Text_IO; + +with ZLib; + +procedure Read is + + use Ada.Streams; + + ------------------------------------ + -- Test configuration parameters -- + ------------------------------------ + + File_Size : Stream_Element_Offset := 100_000; + + Continuous : constant Boolean := False; + -- If this constant is True, the test would be repeated again and again, + -- with increment File_Size for every iteration. + + Header : constant ZLib.Header_Type := ZLib.Default; + -- Do not use Header other than Default in ZLib versions 1.1.4 and older. + + Init_Random : constant := 8; + -- We are using the same random sequence, in case of we catch bug, + -- so we would be able to reproduce it. + + -- End -- + + Pack_Size : Stream_Element_Offset; + Offset : Stream_Element_Offset; + + Filter : ZLib.Filter_Type; + + subtype Visible_Symbols + is Stream_Element range 16#20# .. 16#7E#; + + package Random_Elements is new + Ada.Numerics.Discrete_Random (Visible_Symbols); + + Gen : Random_Elements.Generator; + Period : constant Stream_Element_Offset := 200; + -- Period constant variable for random generator not to be very random. + -- Bigger period, harder random. + + Read_Buffer : Stream_Element_Array (1 .. 2048); + Read_First : Stream_Element_Offset; + Read_Last : Stream_Element_Offset; + + procedure Reset; + + procedure Read + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset); + -- this procedure is for generic instantiation of + -- ZLib.Read + -- reading data from the File_In. + + procedure Read is new ZLib.Read + (Read, + Read_Buffer, + Rest_First => Read_First, + Rest_Last => Read_Last); + + ---------- + -- Read -- + ---------- + + procedure Read + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset) is + begin + Last := Stream_Element_Offset'Min + (Item'Last, + Item'First + File_Size - Offset); + + for J in Item'First .. Last loop + if J < Item'First + Period then + Item (J) := Random_Elements.Random (Gen); + else + Item (J) := Item (J - Period); + end if; + + Offset := Offset + 1; + end loop; + end Read; + + ----------- + -- Reset -- + ----------- + + procedure Reset is + begin + Random_Elements.Reset (Gen, Init_Random); + Pack_Size := 0; + Offset := 1; + Read_First := Read_Buffer'Last + 1; + Read_Last := Read_Buffer'Last; + end Reset; + +begin + Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); + + loop + for Level in ZLib.Compression_Level'Range loop + + Ada.Text_IO.Put ("Level =" + & ZLib.Compression_Level'Image (Level)); + + -- Deflate using generic instantiation. + + ZLib.Deflate_Init + (Filter, + Level, + Header => Header); + + Reset; + + Ada.Text_IO.Put + (Stream_Element_Offset'Image (File_Size) & " ->"); + + loop + declare + Buffer : Stream_Element_Array (1 .. 1024); + Last : Stream_Element_Offset; + begin + Read (Filter, Buffer, Last); + + Pack_Size := Pack_Size + Last - Buffer'First + 1; + + exit when Last < Buffer'Last; + end; + end loop; + + Ada.Text_IO.Put_Line (Stream_Element_Offset'Image (Pack_Size)); + + ZLib.Close (Filter); + end loop; + + exit when not Continuous; + + File_Size := File_Size + 1; + end loop; +end Read; diff --git a/third_party/zlib/v1_2_11/contrib/ada/readme.txt b/third_party/zlib/v1_2_11/contrib/ada/readme.txt new file mode 100644 index 0000000..ce4d2ca --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/readme.txt @@ -0,0 +1,65 @@ + ZLib for Ada thick binding (ZLib.Ada) + Release 1.3 + +ZLib.Ada is a thick binding interface to the popular ZLib data +compression library, available at http://www.gzip.org/zlib/. +It provides Ada-style access to the ZLib C library. + + + Here are the main changes since ZLib.Ada 1.2: + +- Attension: ZLib.Read generic routine have a initialization requirement + for Read_Last parameter now. It is a bit incompartible with previous version, + but extends functionality, we could use new parameters Allow_Read_Some and + Flush now. + +- Added Is_Open routines to ZLib and ZLib.Streams packages. + +- Add pragma Assert to check Stream_Element is 8 bit. + +- Fix extraction to buffer with exact known decompressed size. Error reported by + Steve Sangwine. + +- Fix definition of ULong (changed to unsigned_long), fix regression on 64 bits + computers. Patch provided by Pascal Obry. + +- Add Status_Error exception definition. + +- Add pragma Assertion that Ada.Streams.Stream_Element size is 8 bit. + + + How to build ZLib.Ada under GNAT + +You should have the ZLib library already build on your computer, before +building ZLib.Ada. Make the directory of ZLib.Ada sources current and +issue the command: + + gnatmake test -largs -L -lz + +Or use the GNAT project file build for GNAT 3.15 or later: + + gnatmake -Pzlib.gpr -L + + + How to build ZLib.Ada under Aonix ObjectAda for Win32 7.2.2 + +1. Make a project with all *.ads and *.adb files from the distribution. +2. Build the libz.a library from the ZLib C sources. +3. Rename libz.a to z.lib. +4. Add the library z.lib to the project. +5. Add the libc.lib library from the ObjectAda distribution to the project. +6. Build the executable using test.adb as a main procedure. + + + How to use ZLib.Ada + +The source files test.adb and read.adb are small demo programs that show +the main functionality of ZLib.Ada. + +The routines from the package specifications are commented. + + +Homepage: http://zlib-ada.sourceforge.net/ +Author: Dmitriy Anisimkov + +Contributors: Pascal Obry , Steve Sangwine diff --git a/third_party/zlib/v1_2_11/contrib/ada/test.adb b/third_party/zlib/v1_2_11/contrib/ada/test.adb new file mode 100644 index 0000000..90773ac --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/test.adb @@ -0,0 +1,463 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: test.adb,v 1.17 2003/08/12 12:13:30 vagul Exp $ + +-- The program has a few aims. +-- 1. Test ZLib.Ada95 thick binding functionality. +-- 2. Show the example of use main functionality of the ZLib.Ada95 binding. +-- 3. Build this program automatically compile all ZLib.Ada95 packages under +-- GNAT Ada95 compiler. + +with ZLib.Streams; +with Ada.Streams.Stream_IO; +with Ada.Numerics.Discrete_Random; + +with Ada.Text_IO; + +with Ada.Calendar; + +procedure Test is + + use Ada.Streams; + use Stream_IO; + + ------------------------------------ + -- Test configuration parameters -- + ------------------------------------ + + File_Size : Count := 100_000; + Continuous : constant Boolean := False; + + Header : constant ZLib.Header_Type := ZLib.Default; + -- ZLib.None; + -- ZLib.Auto; + -- ZLib.GZip; + -- Do not use Header other then Default in ZLib versions 1.1.4 + -- and older. + + Strategy : constant ZLib.Strategy_Type := ZLib.Default_Strategy; + Init_Random : constant := 10; + + -- End -- + + In_File_Name : constant String := "testzlib.in"; + -- Name of the input file + + Z_File_Name : constant String := "testzlib.zlb"; + -- Name of the compressed file. + + Out_File_Name : constant String := "testzlib.out"; + -- Name of the decompressed file. + + File_In : File_Type; + File_Out : File_Type; + File_Back : File_Type; + File_Z : ZLib.Streams.Stream_Type; + + Filter : ZLib.Filter_Type; + + Time_Stamp : Ada.Calendar.Time; + + procedure Generate_File; + -- Generate file of spetsified size with some random data. + -- The random data is repeatable, for the good compression. + + procedure Compare_Streams + (Left, Right : in out Root_Stream_Type'Class); + -- The procedure compearing data in 2 streams. + -- It is for compare data before and after compression/decompression. + + procedure Compare_Files (Left, Right : String); + -- Compare files. Based on the Compare_Streams. + + procedure Copy_Streams + (Source, Target : in out Root_Stream_Type'Class; + Buffer_Size : in Stream_Element_Offset := 1024); + -- Copying data from one stream to another. It is for test stream + -- interface of the library. + + procedure Data_In + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset); + -- this procedure is for generic instantiation of + -- ZLib.Generic_Translate. + -- reading data from the File_In. + + procedure Data_Out (Item : in Stream_Element_Array); + -- this procedure is for generic instantiation of + -- ZLib.Generic_Translate. + -- writing data to the File_Out. + + procedure Stamp; + -- Store the timestamp to the local variable. + + procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count); + -- Print the time statistic with the message. + + procedure Translate is new ZLib.Generic_Translate + (Data_In => Data_In, + Data_Out => Data_Out); + -- This procedure is moving data from File_In to File_Out + -- with compression or decompression, depend on initialization of + -- Filter parameter. + + ------------------- + -- Compare_Files -- + ------------------- + + procedure Compare_Files (Left, Right : String) is + Left_File, Right_File : File_Type; + begin + Open (Left_File, In_File, Left); + Open (Right_File, In_File, Right); + Compare_Streams (Stream (Left_File).all, Stream (Right_File).all); + Close (Left_File); + Close (Right_File); + end Compare_Files; + + --------------------- + -- Compare_Streams -- + --------------------- + + procedure Compare_Streams + (Left, Right : in out Ada.Streams.Root_Stream_Type'Class) + is + Left_Buffer, Right_Buffer : Stream_Element_Array (0 .. 16#FFF#); + Left_Last, Right_Last : Stream_Element_Offset; + begin + loop + Read (Left, Left_Buffer, Left_Last); + Read (Right, Right_Buffer, Right_Last); + + if Left_Last /= Right_Last then + Ada.Text_IO.Put_Line ("Compare error :" + & Stream_Element_Offset'Image (Left_Last) + & " /= " + & Stream_Element_Offset'Image (Right_Last)); + + raise Constraint_Error; + + elsif Left_Buffer (0 .. Left_Last) + /= Right_Buffer (0 .. Right_Last) + then + Ada.Text_IO.Put_Line ("ERROR: IN and OUT files is not equal."); + raise Constraint_Error; + + end if; + + exit when Left_Last < Left_Buffer'Last; + end loop; + end Compare_Streams; + + ------------------ + -- Copy_Streams -- + ------------------ + + procedure Copy_Streams + (Source, Target : in out Ada.Streams.Root_Stream_Type'Class; + Buffer_Size : in Stream_Element_Offset := 1024) + is + Buffer : Stream_Element_Array (1 .. Buffer_Size); + Last : Stream_Element_Offset; + begin + loop + Read (Source, Buffer, Last); + Write (Target, Buffer (1 .. Last)); + + exit when Last < Buffer'Last; + end loop; + end Copy_Streams; + + ------------- + -- Data_In -- + ------------- + + procedure Data_In + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset) is + begin + Read (File_In, Item, Last); + end Data_In; + + -------------- + -- Data_Out -- + -------------- + + procedure Data_Out (Item : in Stream_Element_Array) is + begin + Write (File_Out, Item); + end Data_Out; + + ------------------- + -- Generate_File -- + ------------------- + + procedure Generate_File is + subtype Visible_Symbols is Stream_Element range 16#20# .. 16#7E#; + + package Random_Elements is + new Ada.Numerics.Discrete_Random (Visible_Symbols); + + Gen : Random_Elements.Generator; + Buffer : Stream_Element_Array := (1 .. 77 => 16#20#) & 10; + + Buffer_Count : constant Count := File_Size / Buffer'Length; + -- Number of same buffers in the packet. + + Density : constant Count := 30; -- from 0 to Buffer'Length - 2; + + procedure Fill_Buffer (J, D : in Count); + -- Change the part of the buffer. + + ----------------- + -- Fill_Buffer -- + ----------------- + + procedure Fill_Buffer (J, D : in Count) is + begin + for K in 0 .. D loop + Buffer + (Stream_Element_Offset ((J + K) mod (Buffer'Length - 1) + 1)) + := Random_Elements.Random (Gen); + + end loop; + end Fill_Buffer; + + begin + Random_Elements.Reset (Gen, Init_Random); + + Create (File_In, Out_File, In_File_Name); + + Fill_Buffer (1, Buffer'Length - 2); + + for J in 1 .. Buffer_Count loop + Write (File_In, Buffer); + + Fill_Buffer (J, Density); + end loop; + + -- fill remain size. + + Write + (File_In, + Buffer + (1 .. Stream_Element_Offset + (File_Size - Buffer'Length * Buffer_Count))); + + Flush (File_In); + Close (File_In); + end Generate_File; + + --------------------- + -- Print_Statistic -- + --------------------- + + procedure Print_Statistic (Msg : String; Data_Size : ZLib.Count) is + use Ada.Calendar; + use Ada.Text_IO; + + package Count_IO is new Integer_IO (ZLib.Count); + + Curr_Dur : Duration := Clock - Time_Stamp; + begin + Put (Msg); + + Set_Col (20); + Ada.Text_IO.Put ("size ="); + + Count_IO.Put + (Data_Size, + Width => Stream_IO.Count'Image (File_Size)'Length); + + Put_Line (" duration =" & Duration'Image (Curr_Dur)); + end Print_Statistic; + + ----------- + -- Stamp -- + ----------- + + procedure Stamp is + begin + Time_Stamp := Ada.Calendar.Clock; + end Stamp; + +begin + Ada.Text_IO.Put_Line ("ZLib " & ZLib.Version); + + loop + Generate_File; + + for Level in ZLib.Compression_Level'Range loop + + Ada.Text_IO.Put_Line ("Level =" + & ZLib.Compression_Level'Image (Level)); + + -- Test generic interface. + Open (File_In, In_File, In_File_Name); + Create (File_Out, Out_File, Z_File_Name); + + Stamp; + + -- Deflate using generic instantiation. + + ZLib.Deflate_Init + (Filter => Filter, + Level => Level, + Strategy => Strategy, + Header => Header); + + Translate (Filter); + Print_Statistic ("Generic compress", ZLib.Total_Out (Filter)); + ZLib.Close (Filter); + + Close (File_In); + Close (File_Out); + + Open (File_In, In_File, Z_File_Name); + Create (File_Out, Out_File, Out_File_Name); + + Stamp; + + -- Inflate using generic instantiation. + + ZLib.Inflate_Init (Filter, Header => Header); + + Translate (Filter); + Print_Statistic ("Generic decompress", ZLib.Total_Out (Filter)); + + ZLib.Close (Filter); + + Close (File_In); + Close (File_Out); + + Compare_Files (In_File_Name, Out_File_Name); + + -- Test stream interface. + + -- Compress to the back stream. + + Open (File_In, In_File, In_File_Name); + Create (File_Back, Out_File, Z_File_Name); + + Stamp; + + ZLib.Streams.Create + (Stream => File_Z, + Mode => ZLib.Streams.Out_Stream, + Back => ZLib.Streams.Stream_Access + (Stream (File_Back)), + Back_Compressed => True, + Level => Level, + Strategy => Strategy, + Header => Header); + + Copy_Streams + (Source => Stream (File_In).all, + Target => File_Z); + + -- Flushing internal buffers to the back stream. + + ZLib.Streams.Flush (File_Z, ZLib.Finish); + + Print_Statistic ("Write compress", + ZLib.Streams.Write_Total_Out (File_Z)); + + ZLib.Streams.Close (File_Z); + + Close (File_In); + Close (File_Back); + + -- Compare reading from original file and from + -- decompression stream. + + Open (File_In, In_File, In_File_Name); + Open (File_Back, In_File, Z_File_Name); + + ZLib.Streams.Create + (Stream => File_Z, + Mode => ZLib.Streams.In_Stream, + Back => ZLib.Streams.Stream_Access + (Stream (File_Back)), + Back_Compressed => True, + Header => Header); + + Stamp; + Compare_Streams (Stream (File_In).all, File_Z); + + Print_Statistic ("Read decompress", + ZLib.Streams.Read_Total_Out (File_Z)); + + ZLib.Streams.Close (File_Z); + Close (File_In); + Close (File_Back); + + -- Compress by reading from compression stream. + + Open (File_Back, In_File, In_File_Name); + Create (File_Out, Out_File, Z_File_Name); + + ZLib.Streams.Create + (Stream => File_Z, + Mode => ZLib.Streams.In_Stream, + Back => ZLib.Streams.Stream_Access + (Stream (File_Back)), + Back_Compressed => False, + Level => Level, + Strategy => Strategy, + Header => Header); + + Stamp; + Copy_Streams + (Source => File_Z, + Target => Stream (File_Out).all); + + Print_Statistic ("Read compress", + ZLib.Streams.Read_Total_Out (File_Z)); + + ZLib.Streams.Close (File_Z); + + Close (File_Out); + Close (File_Back); + + -- Decompress to decompression stream. + + Open (File_In, In_File, Z_File_Name); + Create (File_Back, Out_File, Out_File_Name); + + ZLib.Streams.Create + (Stream => File_Z, + Mode => ZLib.Streams.Out_Stream, + Back => ZLib.Streams.Stream_Access + (Stream (File_Back)), + Back_Compressed => False, + Header => Header); + + Stamp; + + Copy_Streams + (Source => Stream (File_In).all, + Target => File_Z); + + Print_Statistic ("Write decompress", + ZLib.Streams.Write_Total_Out (File_Z)); + + ZLib.Streams.Close (File_Z); + Close (File_In); + Close (File_Back); + + Compare_Files (In_File_Name, Out_File_Name); + end loop; + + Ada.Text_IO.Put_Line (Count'Image (File_Size) & " Ok."); + + exit when not Continuous; + + File_Size := File_Size + 1; + end loop; +end Test; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.adb b/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.adb new file mode 100644 index 0000000..b6497ba --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.adb @@ -0,0 +1,225 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: zlib-streams.adb,v 1.10 2004/05/31 10:53:40 vagul Exp $ + +with Ada.Unchecked_Deallocation; + +package body ZLib.Streams is + + ----------- + -- Close -- + ----------- + + procedure Close (Stream : in out Stream_Type) is + procedure Free is new Ada.Unchecked_Deallocation + (Stream_Element_Array, Buffer_Access); + begin + if Stream.Mode = Out_Stream or Stream.Mode = Duplex then + -- We should flush the data written by the writer. + + Flush (Stream, Finish); + + Close (Stream.Writer); + end if; + + if Stream.Mode = In_Stream or Stream.Mode = Duplex then + Close (Stream.Reader); + Free (Stream.Buffer); + end if; + end Close; + + ------------ + -- Create -- + ------------ + + procedure Create + (Stream : out Stream_Type; + Mode : in Stream_Mode; + Back : in Stream_Access; + Back_Compressed : in Boolean; + Level : in Compression_Level := Default_Compression; + Strategy : in Strategy_Type := Default_Strategy; + Header : in Header_Type := Default; + Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset + := Default_Buffer_Size; + Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset + := Default_Buffer_Size) + is + + subtype Buffer_Subtype is Stream_Element_Array (1 .. Read_Buffer_Size); + + procedure Init_Filter + (Filter : in out Filter_Type; + Compress : in Boolean); + + ----------------- + -- Init_Filter -- + ----------------- + + procedure Init_Filter + (Filter : in out Filter_Type; + Compress : in Boolean) is + begin + if Compress then + Deflate_Init + (Filter, Level, Strategy, Header => Header); + else + Inflate_Init (Filter, Header => Header); + end if; + end Init_Filter; + + begin + Stream.Back := Back; + Stream.Mode := Mode; + + if Mode = Out_Stream or Mode = Duplex then + Init_Filter (Stream.Writer, Back_Compressed); + Stream.Buffer_Size := Write_Buffer_Size; + else + Stream.Buffer_Size := 0; + end if; + + if Mode = In_Stream or Mode = Duplex then + Init_Filter (Stream.Reader, not Back_Compressed); + + Stream.Buffer := new Buffer_Subtype; + Stream.Rest_First := Stream.Buffer'Last + 1; + Stream.Rest_Last := Stream.Buffer'Last; + end if; + end Create; + + ----------- + -- Flush -- + ----------- + + procedure Flush + (Stream : in out Stream_Type; + Mode : in Flush_Mode := Sync_Flush) + is + Buffer : Stream_Element_Array (1 .. Stream.Buffer_Size); + Last : Stream_Element_Offset; + begin + loop + Flush (Stream.Writer, Buffer, Last, Mode); + + Ada.Streams.Write (Stream.Back.all, Buffer (1 .. Last)); + + exit when Last < Buffer'Last; + end loop; + end Flush; + + ------------- + -- Is_Open -- + ------------- + + function Is_Open (Stream : Stream_Type) return Boolean is + begin + return Is_Open (Stream.Reader) or else Is_Open (Stream.Writer); + end Is_Open; + + ---------- + -- Read -- + ---------- + + procedure Read + (Stream : in out Stream_Type; + Item : out Stream_Element_Array; + Last : out Stream_Element_Offset) + is + + procedure Read + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset); + + ---------- + -- Read -- + ---------- + + procedure Read + (Item : out Stream_Element_Array; + Last : out Stream_Element_Offset) is + begin + Ada.Streams.Read (Stream.Back.all, Item, Last); + end Read; + + procedure Read is new ZLib.Read + (Read => Read, + Buffer => Stream.Buffer.all, + Rest_First => Stream.Rest_First, + Rest_Last => Stream.Rest_Last); + + begin + Read (Stream.Reader, Item, Last); + end Read; + + ------------------- + -- Read_Total_In -- + ------------------- + + function Read_Total_In (Stream : in Stream_Type) return Count is + begin + return Total_In (Stream.Reader); + end Read_Total_In; + + -------------------- + -- Read_Total_Out -- + -------------------- + + function Read_Total_Out (Stream : in Stream_Type) return Count is + begin + return Total_Out (Stream.Reader); + end Read_Total_Out; + + ----------- + -- Write -- + ----------- + + procedure Write + (Stream : in out Stream_Type; + Item : in Stream_Element_Array) + is + + procedure Write (Item : in Stream_Element_Array); + + ----------- + -- Write -- + ----------- + + procedure Write (Item : in Stream_Element_Array) is + begin + Ada.Streams.Write (Stream.Back.all, Item); + end Write; + + procedure Write is new ZLib.Write + (Write => Write, + Buffer_Size => Stream.Buffer_Size); + + begin + Write (Stream.Writer, Item, No_Flush); + end Write; + + -------------------- + -- Write_Total_In -- + -------------------- + + function Write_Total_In (Stream : in Stream_Type) return Count is + begin + return Total_In (Stream.Writer); + end Write_Total_In; + + --------------------- + -- Write_Total_Out -- + --------------------- + + function Write_Total_Out (Stream : in Stream_Type) return Count is + begin + return Total_Out (Stream.Writer); + end Write_Total_Out; + +end ZLib.Streams; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.ads b/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.ads new file mode 100644 index 0000000..8e26cd4 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib-streams.ads @@ -0,0 +1,114 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: zlib-streams.ads,v 1.12 2004/05/31 10:53:40 vagul Exp $ + +package ZLib.Streams is + + type Stream_Mode is (In_Stream, Out_Stream, Duplex); + + type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class; + + type Stream_Type is + new Ada.Streams.Root_Stream_Type with private; + + procedure Read + (Stream : in out Stream_Type; + Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset); + + procedure Write + (Stream : in out Stream_Type; + Item : in Ada.Streams.Stream_Element_Array); + + procedure Flush + (Stream : in out Stream_Type; + Mode : in Flush_Mode := Sync_Flush); + -- Flush the written data to the back stream, + -- all data placed to the compressor is flushing to the Back stream. + -- Should not be used until necessary, because it is decreasing + -- compression. + + function Read_Total_In (Stream : in Stream_Type) return Count; + pragma Inline (Read_Total_In); + -- Return total number of bytes read from back stream so far. + + function Read_Total_Out (Stream : in Stream_Type) return Count; + pragma Inline (Read_Total_Out); + -- Return total number of bytes read so far. + + function Write_Total_In (Stream : in Stream_Type) return Count; + pragma Inline (Write_Total_In); + -- Return total number of bytes written so far. + + function Write_Total_Out (Stream : in Stream_Type) return Count; + pragma Inline (Write_Total_Out); + -- Return total number of bytes written to the back stream. + + procedure Create + (Stream : out Stream_Type; + Mode : in Stream_Mode; + Back : in Stream_Access; + Back_Compressed : in Boolean; + Level : in Compression_Level := Default_Compression; + Strategy : in Strategy_Type := Default_Strategy; + Header : in Header_Type := Default; + Read_Buffer_Size : in Ada.Streams.Stream_Element_Offset + := Default_Buffer_Size; + Write_Buffer_Size : in Ada.Streams.Stream_Element_Offset + := Default_Buffer_Size); + -- Create the Comression/Decompression stream. + -- If mode is In_Stream then Write operation is disabled. + -- If mode is Out_Stream then Read operation is disabled. + + -- If Back_Compressed is true then + -- Data written to the Stream is compressing to the Back stream + -- and data read from the Stream is decompressed data from the Back stream. + + -- If Back_Compressed is false then + -- Data written to the Stream is decompressing to the Back stream + -- and data read from the Stream is compressed data from the Back stream. + + -- !!! When the Need_Header is False ZLib-Ada is using undocumented + -- ZLib 1.1.4 functionality to do not create/wait for ZLib headers. + + function Is_Open (Stream : Stream_Type) return Boolean; + + procedure Close (Stream : in out Stream_Type); + +private + + use Ada.Streams; + + type Buffer_Access is access all Stream_Element_Array; + + type Stream_Type + is new Root_Stream_Type with + record + Mode : Stream_Mode; + + Buffer : Buffer_Access; + Rest_First : Stream_Element_Offset; + Rest_Last : Stream_Element_Offset; + -- Buffer for Read operation. + -- We need to have this buffer in the record + -- because not all read data from back stream + -- could be processed during the read operation. + + Buffer_Size : Stream_Element_Offset; + -- Buffer size for write operation. + -- We do not need to have this buffer + -- in the record because all data could be + -- processed in the write operation. + + Back : Stream_Access; + Reader : Filter_Type; + Writer : Filter_Type; + end record; + +end ZLib.Streams; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.adb b/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.adb new file mode 100644 index 0000000..0ca4a71 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.adb @@ -0,0 +1,141 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: zlib-thin.adb,v 1.8 2003/12/14 18:27:31 vagul Exp $ + +package body ZLib.Thin is + + ZLIB_VERSION : constant Chars_Ptr := zlibVersion; + + Z_Stream_Size : constant Int := Z_Stream'Size / System.Storage_Unit; + + -------------- + -- Avail_In -- + -------------- + + function Avail_In (Strm : in Z_Stream) return UInt is + begin + return Strm.Avail_In; + end Avail_In; + + --------------- + -- Avail_Out -- + --------------- + + function Avail_Out (Strm : in Z_Stream) return UInt is + begin + return Strm.Avail_Out; + end Avail_Out; + + ------------------ + -- Deflate_Init -- + ------------------ + + function Deflate_Init + (strm : Z_Streamp; + level : Int; + method : Int; + windowBits : Int; + memLevel : Int; + strategy : Int) + return Int is + begin + return deflateInit2 + (strm, + level, + method, + windowBits, + memLevel, + strategy, + ZLIB_VERSION, + Z_Stream_Size); + end Deflate_Init; + + ------------------ + -- Inflate_Init -- + ------------------ + + function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int is + begin + return inflateInit2 (strm, windowBits, ZLIB_VERSION, Z_Stream_Size); + end Inflate_Init; + + ------------------------ + -- Last_Error_Message -- + ------------------------ + + function Last_Error_Message (Strm : in Z_Stream) return String is + use Interfaces.C.Strings; + begin + if Strm.msg = Null_Ptr then + return ""; + else + return Value (Strm.msg); + end if; + end Last_Error_Message; + + ------------ + -- Set_In -- + ------------ + + procedure Set_In + (Strm : in out Z_Stream; + Buffer : in Voidp; + Size : in UInt) is + begin + Strm.Next_In := Buffer; + Strm.Avail_In := Size; + end Set_In; + + ------------------ + -- Set_Mem_Func -- + ------------------ + + procedure Set_Mem_Func + (Strm : in out Z_Stream; + Opaque : in Voidp; + Alloc : in alloc_func; + Free : in free_func) is + begin + Strm.opaque := Opaque; + Strm.zalloc := Alloc; + Strm.zfree := Free; + end Set_Mem_Func; + + ------------- + -- Set_Out -- + ------------- + + procedure Set_Out + (Strm : in out Z_Stream; + Buffer : in Voidp; + Size : in UInt) is + begin + Strm.Next_Out := Buffer; + Strm.Avail_Out := Size; + end Set_Out; + + -------------- + -- Total_In -- + -------------- + + function Total_In (Strm : in Z_Stream) return ULong is + begin + return Strm.Total_In; + end Total_In; + + --------------- + -- Total_Out -- + --------------- + + function Total_Out (Strm : in Z_Stream) return ULong is + begin + return Strm.Total_Out; + end Total_Out; + +end ZLib.Thin; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.ads b/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.ads new file mode 100644 index 0000000..810173c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib-thin.ads @@ -0,0 +1,450 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2003 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: zlib-thin.ads,v 1.11 2004/07/23 06:33:11 vagul Exp $ + +with Interfaces.C.Strings; + +with System; + +private package ZLib.Thin is + + -- From zconf.h + + MAX_MEM_LEVEL : constant := 9; -- zconf.h:105 + -- zconf.h:105 + MAX_WBITS : constant := 15; -- zconf.h:115 + -- 32K LZ77 window + -- zconf.h:115 + SEEK_SET : constant := 8#0000#; -- zconf.h:244 + -- Seek from beginning of file. + -- zconf.h:244 + SEEK_CUR : constant := 1; -- zconf.h:245 + -- Seek from current position. + -- zconf.h:245 + SEEK_END : constant := 2; -- zconf.h:246 + -- Set file pointer to EOF plus "offset" + -- zconf.h:246 + + type Byte is new Interfaces.C.unsigned_char; -- 8 bits + -- zconf.h:214 + type UInt is new Interfaces.C.unsigned; -- 16 bits or more + -- zconf.h:216 + type Int is new Interfaces.C.int; + + type ULong is new Interfaces.C.unsigned_long; -- 32 bits or more + -- zconf.h:217 + subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; + + type ULong_Access is access ULong; + type Int_Access is access Int; + + subtype Voidp is System.Address; -- zconf.h:232 + + subtype Byte_Access is Voidp; + + Nul : constant Voidp := System.Null_Address; + -- end from zconf + + Z_NO_FLUSH : constant := 8#0000#; -- zlib.h:125 + -- zlib.h:125 + Z_PARTIAL_FLUSH : constant := 1; -- zlib.h:126 + -- will be removed, use + -- Z_SYNC_FLUSH instead + -- zlib.h:126 + Z_SYNC_FLUSH : constant := 2; -- zlib.h:127 + -- zlib.h:127 + Z_FULL_FLUSH : constant := 3; -- zlib.h:128 + -- zlib.h:128 + Z_FINISH : constant := 4; -- zlib.h:129 + -- zlib.h:129 + Z_OK : constant := 8#0000#; -- zlib.h:132 + -- zlib.h:132 + Z_STREAM_END : constant := 1; -- zlib.h:133 + -- zlib.h:133 + Z_NEED_DICT : constant := 2; -- zlib.h:134 + -- zlib.h:134 + Z_ERRNO : constant := -1; -- zlib.h:135 + -- zlib.h:135 + Z_STREAM_ERROR : constant := -2; -- zlib.h:136 + -- zlib.h:136 + Z_DATA_ERROR : constant := -3; -- zlib.h:137 + -- zlib.h:137 + Z_MEM_ERROR : constant := -4; -- zlib.h:138 + -- zlib.h:138 + Z_BUF_ERROR : constant := -5; -- zlib.h:139 + -- zlib.h:139 + Z_VERSION_ERROR : constant := -6; -- zlib.h:140 + -- zlib.h:140 + Z_NO_COMPRESSION : constant := 8#0000#; -- zlib.h:145 + -- zlib.h:145 + Z_BEST_SPEED : constant := 1; -- zlib.h:146 + -- zlib.h:146 + Z_BEST_COMPRESSION : constant := 9; -- zlib.h:147 + -- zlib.h:147 + Z_DEFAULT_COMPRESSION : constant := -1; -- zlib.h:148 + -- zlib.h:148 + Z_FILTERED : constant := 1; -- zlib.h:151 + -- zlib.h:151 + Z_HUFFMAN_ONLY : constant := 2; -- zlib.h:152 + -- zlib.h:152 + Z_DEFAULT_STRATEGY : constant := 8#0000#; -- zlib.h:153 + -- zlib.h:153 + Z_BINARY : constant := 8#0000#; -- zlib.h:156 + -- zlib.h:156 + Z_ASCII : constant := 1; -- zlib.h:157 + -- zlib.h:157 + Z_UNKNOWN : constant := 2; -- zlib.h:158 + -- zlib.h:158 + Z_DEFLATED : constant := 8; -- zlib.h:161 + -- zlib.h:161 + Z_NULL : constant := 8#0000#; -- zlib.h:164 + -- for initializing zalloc, zfree, opaque + -- zlib.h:164 + type gzFile is new Voidp; -- zlib.h:646 + + type Z_Stream is private; + + type Z_Streamp is access all Z_Stream; -- zlib.h:89 + + type alloc_func is access function + (Opaque : Voidp; + Items : UInt; + Size : UInt) + return Voidp; -- zlib.h:63 + + type free_func is access procedure (opaque : Voidp; address : Voidp); + + function zlibVersion return Chars_Ptr; + + function Deflate (strm : Z_Streamp; flush : Int) return Int; + + function DeflateEnd (strm : Z_Streamp) return Int; + + function Inflate (strm : Z_Streamp; flush : Int) return Int; + + function InflateEnd (strm : Z_Streamp) return Int; + + function deflateSetDictionary + (strm : Z_Streamp; + dictionary : Byte_Access; + dictLength : UInt) + return Int; + + function deflateCopy (dest : Z_Streamp; source : Z_Streamp) return Int; + -- zlib.h:478 + + function deflateReset (strm : Z_Streamp) return Int; -- zlib.h:495 + + function deflateParams + (strm : Z_Streamp; + level : Int; + strategy : Int) + return Int; -- zlib.h:506 + + function inflateSetDictionary + (strm : Z_Streamp; + dictionary : Byte_Access; + dictLength : UInt) + return Int; -- zlib.h:548 + + function inflateSync (strm : Z_Streamp) return Int; -- zlib.h:565 + + function inflateReset (strm : Z_Streamp) return Int; -- zlib.h:580 + + function compress + (dest : Byte_Access; + destLen : ULong_Access; + source : Byte_Access; + sourceLen : ULong) + return Int; -- zlib.h:601 + + function compress2 + (dest : Byte_Access; + destLen : ULong_Access; + source : Byte_Access; + sourceLen : ULong; + level : Int) + return Int; -- zlib.h:615 + + function uncompress + (dest : Byte_Access; + destLen : ULong_Access; + source : Byte_Access; + sourceLen : ULong) + return Int; + + function gzopen (path : Chars_Ptr; mode : Chars_Ptr) return gzFile; + + function gzdopen (fd : Int; mode : Chars_Ptr) return gzFile; + + function gzsetparams + (file : gzFile; + level : Int; + strategy : Int) + return Int; + + function gzread + (file : gzFile; + buf : Voidp; + len : UInt) + return Int; + + function gzwrite + (file : in gzFile; + buf : in Voidp; + len : in UInt) + return Int; + + function gzprintf (file : in gzFile; format : in Chars_Ptr) return Int; + + function gzputs (file : in gzFile; s : in Chars_Ptr) return Int; + + function gzgets + (file : gzFile; + buf : Chars_Ptr; + len : Int) + return Chars_Ptr; + + function gzputc (file : gzFile; char : Int) return Int; + + function gzgetc (file : gzFile) return Int; + + function gzflush (file : gzFile; flush : Int) return Int; + + function gzseek + (file : gzFile; + offset : Int; + whence : Int) + return Int; + + function gzrewind (file : gzFile) return Int; + + function gztell (file : gzFile) return Int; + + function gzeof (file : gzFile) return Int; + + function gzclose (file : gzFile) return Int; + + function gzerror (file : gzFile; errnum : Int_Access) return Chars_Ptr; + + function adler32 + (adler : ULong; + buf : Byte_Access; + len : UInt) + return ULong; + + function crc32 + (crc : ULong; + buf : Byte_Access; + len : UInt) + return ULong; + + function deflateInit + (strm : Z_Streamp; + level : Int; + version : Chars_Ptr; + stream_size : Int) + return Int; + + function deflateInit2 + (strm : Z_Streamp; + level : Int; + method : Int; + windowBits : Int; + memLevel : Int; + strategy : Int; + version : Chars_Ptr; + stream_size : Int) + return Int; + + function Deflate_Init + (strm : Z_Streamp; + level : Int; + method : Int; + windowBits : Int; + memLevel : Int; + strategy : Int) + return Int; + pragma Inline (Deflate_Init); + + function inflateInit + (strm : Z_Streamp; + version : Chars_Ptr; + stream_size : Int) + return Int; + + function inflateInit2 + (strm : in Z_Streamp; + windowBits : in Int; + version : in Chars_Ptr; + stream_size : in Int) + return Int; + + function inflateBackInit + (strm : in Z_Streamp; + windowBits : in Int; + window : in Byte_Access; + version : in Chars_Ptr; + stream_size : in Int) + return Int; + -- Size of window have to be 2**windowBits. + + function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int; + pragma Inline (Inflate_Init); + + function zError (err : Int) return Chars_Ptr; + + function inflateSyncPoint (z : Z_Streamp) return Int; + + function get_crc_table return ULong_Access; + + -- Interface to the available fields of the z_stream structure. + -- The application must update next_in and avail_in when avail_in has + -- dropped to zero. It must update next_out and avail_out when avail_out + -- has dropped to zero. The application must initialize zalloc, zfree and + -- opaque before calling the init function. + + procedure Set_In + (Strm : in out Z_Stream; + Buffer : in Voidp; + Size : in UInt); + pragma Inline (Set_In); + + procedure Set_Out + (Strm : in out Z_Stream; + Buffer : in Voidp; + Size : in UInt); + pragma Inline (Set_Out); + + procedure Set_Mem_Func + (Strm : in out Z_Stream; + Opaque : in Voidp; + Alloc : in alloc_func; + Free : in free_func); + pragma Inline (Set_Mem_Func); + + function Last_Error_Message (Strm : in Z_Stream) return String; + pragma Inline (Last_Error_Message); + + function Avail_Out (Strm : in Z_Stream) return UInt; + pragma Inline (Avail_Out); + + function Avail_In (Strm : in Z_Stream) return UInt; + pragma Inline (Avail_In); + + function Total_In (Strm : in Z_Stream) return ULong; + pragma Inline (Total_In); + + function Total_Out (Strm : in Z_Stream) return ULong; + pragma Inline (Total_Out); + + function inflateCopy + (dest : in Z_Streamp; + Source : in Z_Streamp) + return Int; + + function compressBound (Source_Len : in ULong) return ULong; + + function deflateBound + (Strm : in Z_Streamp; + Source_Len : in ULong) + return ULong; + + function gzungetc (C : in Int; File : in gzFile) return Int; + + function zlibCompileFlags return ULong; + +private + + type Z_Stream is record -- zlib.h:68 + Next_In : Voidp := Nul; -- next input byte + Avail_In : UInt := 0; -- number of bytes available at next_in + Total_In : ULong := 0; -- total nb of input bytes read so far + Next_Out : Voidp := Nul; -- next output byte should be put there + Avail_Out : UInt := 0; -- remaining free space at next_out + Total_Out : ULong := 0; -- total nb of bytes output so far + msg : Chars_Ptr; -- last error message, NULL if no error + state : Voidp; -- not visible by applications + zalloc : alloc_func := null; -- used to allocate the internal state + zfree : free_func := null; -- used to free the internal state + opaque : Voidp; -- private data object passed to + -- zalloc and zfree + data_type : Int; -- best guess about the data type: + -- ascii or binary + adler : ULong; -- adler32 value of the uncompressed + -- data + reserved : ULong; -- reserved for future use + end record; + + pragma Convention (C, Z_Stream); + + pragma Import (C, zlibVersion, "zlibVersion"); + pragma Import (C, Deflate, "deflate"); + pragma Import (C, DeflateEnd, "deflateEnd"); + pragma Import (C, Inflate, "inflate"); + pragma Import (C, InflateEnd, "inflateEnd"); + pragma Import (C, deflateSetDictionary, "deflateSetDictionary"); + pragma Import (C, deflateCopy, "deflateCopy"); + pragma Import (C, deflateReset, "deflateReset"); + pragma Import (C, deflateParams, "deflateParams"); + pragma Import (C, inflateSetDictionary, "inflateSetDictionary"); + pragma Import (C, inflateSync, "inflateSync"); + pragma Import (C, inflateReset, "inflateReset"); + pragma Import (C, compress, "compress"); + pragma Import (C, compress2, "compress2"); + pragma Import (C, uncompress, "uncompress"); + pragma Import (C, gzopen, "gzopen"); + pragma Import (C, gzdopen, "gzdopen"); + pragma Import (C, gzsetparams, "gzsetparams"); + pragma Import (C, gzread, "gzread"); + pragma Import (C, gzwrite, "gzwrite"); + pragma Import (C, gzprintf, "gzprintf"); + pragma Import (C, gzputs, "gzputs"); + pragma Import (C, gzgets, "gzgets"); + pragma Import (C, gzputc, "gzputc"); + pragma Import (C, gzgetc, "gzgetc"); + pragma Import (C, gzflush, "gzflush"); + pragma Import (C, gzseek, "gzseek"); + pragma Import (C, gzrewind, "gzrewind"); + pragma Import (C, gztell, "gztell"); + pragma Import (C, gzeof, "gzeof"); + pragma Import (C, gzclose, "gzclose"); + pragma Import (C, gzerror, "gzerror"); + pragma Import (C, adler32, "adler32"); + pragma Import (C, crc32, "crc32"); + pragma Import (C, deflateInit, "deflateInit_"); + pragma Import (C, inflateInit, "inflateInit_"); + pragma Import (C, deflateInit2, "deflateInit2_"); + pragma Import (C, inflateInit2, "inflateInit2_"); + pragma Import (C, zError, "zError"); + pragma Import (C, inflateSyncPoint, "inflateSyncPoint"); + pragma Import (C, get_crc_table, "get_crc_table"); + + -- since zlib 1.2.0: + + pragma Import (C, inflateCopy, "inflateCopy"); + pragma Import (C, compressBound, "compressBound"); + pragma Import (C, deflateBound, "deflateBound"); + pragma Import (C, gzungetc, "gzungetc"); + pragma Import (C, zlibCompileFlags, "zlibCompileFlags"); + + pragma Import (C, inflateBackInit, "inflateBackInit_"); + + -- I stopped binding the inflateBack routines, because realize that + -- it does not support zlib and gzip headers for now, and have no + -- symmetric deflateBack routines. + -- ZLib-Ada is symmetric regarding deflate/inflate data transformation + -- and has a similar generic callback interface for the + -- deflate/inflate transformation based on the regular Deflate/Inflate + -- routines. + + -- pragma Import (C, inflateBack, "inflateBack"); + -- pragma Import (C, inflateBackEnd, "inflateBackEnd"); + +end ZLib.Thin; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib.adb b/third_party/zlib/v1_2_11/contrib/ada/zlib.adb new file mode 100644 index 0000000..8b6fd68 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib.adb @@ -0,0 +1,701 @@ +---------------------------------------------------------------- +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2004 Dmitriy Anisimkov -- +-- -- +-- Open source license information is in the zlib.ads file. -- +---------------------------------------------------------------- + +-- $Id: zlib.adb,v 1.31 2004/09/06 06:53:19 vagul Exp $ + +with Ada.Exceptions; +with Ada.Unchecked_Conversion; +with Ada.Unchecked_Deallocation; + +with Interfaces.C.Strings; + +with ZLib.Thin; + +package body ZLib is + + use type Thin.Int; + + type Z_Stream is new Thin.Z_Stream; + + type Return_Code_Enum is + (OK, + STREAM_END, + NEED_DICT, + ERRNO, + STREAM_ERROR, + DATA_ERROR, + MEM_ERROR, + BUF_ERROR, + VERSION_ERROR); + + type Flate_Step_Function is access + function (Strm : in Thin.Z_Streamp; Flush : in Thin.Int) return Thin.Int; + pragma Convention (C, Flate_Step_Function); + + type Flate_End_Function is access + function (Ctrm : in Thin.Z_Streamp) return Thin.Int; + pragma Convention (C, Flate_End_Function); + + type Flate_Type is record + Step : Flate_Step_Function; + Done : Flate_End_Function; + end record; + + subtype Footer_Array is Stream_Element_Array (1 .. 8); + + Simple_GZip_Header : constant Stream_Element_Array (1 .. 10) + := (16#1f#, 16#8b#, -- Magic header + 16#08#, -- Z_DEFLATED + 16#00#, -- Flags + 16#00#, 16#00#, 16#00#, 16#00#, -- Time + 16#00#, -- XFlags + 16#03# -- OS code + ); + -- The simplest gzip header is not for informational, but just for + -- gzip format compatibility. + -- Note that some code below is using assumption + -- Simple_GZip_Header'Last > Footer_Array'Last, so do not make + -- Simple_GZip_Header'Last <= Footer_Array'Last. + + Return_Code : constant array (Thin.Int range <>) of Return_Code_Enum + := (0 => OK, + 1 => STREAM_END, + 2 => NEED_DICT, + -1 => ERRNO, + -2 => STREAM_ERROR, + -3 => DATA_ERROR, + -4 => MEM_ERROR, + -5 => BUF_ERROR, + -6 => VERSION_ERROR); + + Flate : constant array (Boolean) of Flate_Type + := (True => (Step => Thin.Deflate'Access, + Done => Thin.DeflateEnd'Access), + False => (Step => Thin.Inflate'Access, + Done => Thin.InflateEnd'Access)); + + Flush_Finish : constant array (Boolean) of Flush_Mode + := (True => Finish, False => No_Flush); + + procedure Raise_Error (Stream : in Z_Stream); + pragma Inline (Raise_Error); + + procedure Raise_Error (Message : in String); + pragma Inline (Raise_Error); + + procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int); + + procedure Free is new Ada.Unchecked_Deallocation + (Z_Stream, Z_Stream_Access); + + function To_Thin_Access is new Ada.Unchecked_Conversion + (Z_Stream_Access, Thin.Z_Streamp); + + procedure Translate_GZip + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode); + -- Separate translate routine for make gzip header. + + procedure Translate_Auto + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode); + -- translate routine without additional headers. + + ----------------- + -- Check_Error -- + ----------------- + + procedure Check_Error (Stream : in Z_Stream; Code : in Thin.Int) is + use type Thin.Int; + begin + if Code /= Thin.Z_OK then + Raise_Error + (Return_Code_Enum'Image (Return_Code (Code)) + & ": " & Last_Error_Message (Stream)); + end if; + end Check_Error; + + ----------- + -- Close -- + ----------- + + procedure Close + (Filter : in out Filter_Type; + Ignore_Error : in Boolean := False) + is + Code : Thin.Int; + begin + if not Ignore_Error and then not Is_Open (Filter) then + raise Status_Error; + end if; + + Code := Flate (Filter.Compression).Done (To_Thin_Access (Filter.Strm)); + + if Ignore_Error or else Code = Thin.Z_OK then + Free (Filter.Strm); + else + declare + Error_Message : constant String + := Last_Error_Message (Filter.Strm.all); + begin + Free (Filter.Strm); + Ada.Exceptions.Raise_Exception + (ZLib_Error'Identity, + Return_Code_Enum'Image (Return_Code (Code)) + & ": " & Error_Message); + end; + end if; + end Close; + + ----------- + -- CRC32 -- + ----------- + + function CRC32 + (CRC : in Unsigned_32; + Data : in Ada.Streams.Stream_Element_Array) + return Unsigned_32 + is + use Thin; + begin + return Unsigned_32 (crc32 (ULong (CRC), + Data'Address, + Data'Length)); + end CRC32; + + procedure CRC32 + (CRC : in out Unsigned_32; + Data : in Ada.Streams.Stream_Element_Array) is + begin + CRC := CRC32 (CRC, Data); + end CRC32; + + ------------------ + -- Deflate_Init -- + ------------------ + + procedure Deflate_Init + (Filter : in out Filter_Type; + Level : in Compression_Level := Default_Compression; + Strategy : in Strategy_Type := Default_Strategy; + Method : in Compression_Method := Deflated; + Window_Bits : in Window_Bits_Type := Default_Window_Bits; + Memory_Level : in Memory_Level_Type := Default_Memory_Level; + Header : in Header_Type := Default) + is + use type Thin.Int; + Win_Bits : Thin.Int := Thin.Int (Window_Bits); + begin + if Is_Open (Filter) then + raise Status_Error; + end if; + + -- We allow ZLib to make header only in case of default header type. + -- Otherwise we would either do header by ourselfs, or do not do + -- header at all. + + if Header = None or else Header = GZip then + Win_Bits := -Win_Bits; + end if; + + -- For the GZip CRC calculation and make headers. + + if Header = GZip then + Filter.CRC := 0; + Filter.Offset := Simple_GZip_Header'First; + else + Filter.Offset := Simple_GZip_Header'Last + 1; + end if; + + Filter.Strm := new Z_Stream; + Filter.Compression := True; + Filter.Stream_End := False; + Filter.Header := Header; + + if Thin.Deflate_Init + (To_Thin_Access (Filter.Strm), + Level => Thin.Int (Level), + method => Thin.Int (Method), + windowBits => Win_Bits, + memLevel => Thin.Int (Memory_Level), + strategy => Thin.Int (Strategy)) /= Thin.Z_OK + then + Raise_Error (Filter.Strm.all); + end if; + end Deflate_Init; + + ----------- + -- Flush -- + ----------- + + procedure Flush + (Filter : in out Filter_Type; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode) + is + No_Data : Stream_Element_Array := (1 .. 0 => 0); + Last : Stream_Element_Offset; + begin + Translate (Filter, No_Data, Last, Out_Data, Out_Last, Flush); + end Flush; + + ----------------------- + -- Generic_Translate -- + ----------------------- + + procedure Generic_Translate + (Filter : in out ZLib.Filter_Type; + In_Buffer_Size : in Integer := Default_Buffer_Size; + Out_Buffer_Size : in Integer := Default_Buffer_Size) + is + In_Buffer : Stream_Element_Array + (1 .. Stream_Element_Offset (In_Buffer_Size)); + Out_Buffer : Stream_Element_Array + (1 .. Stream_Element_Offset (Out_Buffer_Size)); + Last : Stream_Element_Offset; + In_Last : Stream_Element_Offset; + In_First : Stream_Element_Offset; + Out_Last : Stream_Element_Offset; + begin + Main : loop + Data_In (In_Buffer, Last); + + In_First := In_Buffer'First; + + loop + Translate + (Filter => Filter, + In_Data => In_Buffer (In_First .. Last), + In_Last => In_Last, + Out_Data => Out_Buffer, + Out_Last => Out_Last, + Flush => Flush_Finish (Last < In_Buffer'First)); + + if Out_Buffer'First <= Out_Last then + Data_Out (Out_Buffer (Out_Buffer'First .. Out_Last)); + end if; + + exit Main when Stream_End (Filter); + + -- The end of in buffer. + + exit when In_Last = Last; + + In_First := In_Last + 1; + end loop; + end loop Main; + + end Generic_Translate; + + ------------------ + -- Inflate_Init -- + ------------------ + + procedure Inflate_Init + (Filter : in out Filter_Type; + Window_Bits : in Window_Bits_Type := Default_Window_Bits; + Header : in Header_Type := Default) + is + use type Thin.Int; + Win_Bits : Thin.Int := Thin.Int (Window_Bits); + + procedure Check_Version; + -- Check the latest header types compatibility. + + procedure Check_Version is + begin + if Version <= "1.1.4" then + Raise_Error + ("Inflate header type " & Header_Type'Image (Header) + & " incompatible with ZLib version " & Version); + end if; + end Check_Version; + + begin + if Is_Open (Filter) then + raise Status_Error; + end if; + + case Header is + when None => + Check_Version; + + -- Inflate data without headers determined + -- by negative Win_Bits. + + Win_Bits := -Win_Bits; + when GZip => + Check_Version; + + -- Inflate gzip data defined by flag 16. + + Win_Bits := Win_Bits + 16; + when Auto => + Check_Version; + + -- Inflate with automatic detection + -- of gzip or native header defined by flag 32. + + Win_Bits := Win_Bits + 32; + when Default => null; + end case; + + Filter.Strm := new Z_Stream; + Filter.Compression := False; + Filter.Stream_End := False; + Filter.Header := Header; + + if Thin.Inflate_Init + (To_Thin_Access (Filter.Strm), Win_Bits) /= Thin.Z_OK + then + Raise_Error (Filter.Strm.all); + end if; + end Inflate_Init; + + ------------- + -- Is_Open -- + ------------- + + function Is_Open (Filter : in Filter_Type) return Boolean is + begin + return Filter.Strm /= null; + end Is_Open; + + ----------------- + -- Raise_Error -- + ----------------- + + procedure Raise_Error (Message : in String) is + begin + Ada.Exceptions.Raise_Exception (ZLib_Error'Identity, Message); + end Raise_Error; + + procedure Raise_Error (Stream : in Z_Stream) is + begin + Raise_Error (Last_Error_Message (Stream)); + end Raise_Error; + + ---------- + -- Read -- + ---------- + + procedure Read + (Filter : in out Filter_Type; + Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode := No_Flush) + is + In_Last : Stream_Element_Offset; + Item_First : Ada.Streams.Stream_Element_Offset := Item'First; + V_Flush : Flush_Mode := Flush; + + begin + pragma Assert (Rest_First in Buffer'First .. Buffer'Last + 1); + pragma Assert (Rest_Last in Buffer'First - 1 .. Buffer'Last); + + loop + if Rest_Last = Buffer'First - 1 then + V_Flush := Finish; + + elsif Rest_First > Rest_Last then + Read (Buffer, Rest_Last); + Rest_First := Buffer'First; + + if Rest_Last < Buffer'First then + V_Flush := Finish; + end if; + end if; + + Translate + (Filter => Filter, + In_Data => Buffer (Rest_First .. Rest_Last), + In_Last => In_Last, + Out_Data => Item (Item_First .. Item'Last), + Out_Last => Last, + Flush => V_Flush); + + Rest_First := In_Last + 1; + + exit when Stream_End (Filter) + or else Last = Item'Last + or else (Last >= Item'First and then Allow_Read_Some); + + Item_First := Last + 1; + end loop; + end Read; + + ---------------- + -- Stream_End -- + ---------------- + + function Stream_End (Filter : in Filter_Type) return Boolean is + begin + if Filter.Header = GZip and Filter.Compression then + return Filter.Stream_End + and then Filter.Offset = Footer_Array'Last + 1; + else + return Filter.Stream_End; + end if; + end Stream_End; + + -------------- + -- Total_In -- + -------------- + + function Total_In (Filter : in Filter_Type) return Count is + begin + return Count (Thin.Total_In (To_Thin_Access (Filter.Strm).all)); + end Total_In; + + --------------- + -- Total_Out -- + --------------- + + function Total_Out (Filter : in Filter_Type) return Count is + begin + return Count (Thin.Total_Out (To_Thin_Access (Filter.Strm).all)); + end Total_Out; + + --------------- + -- Translate -- + --------------- + + procedure Translate + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode) is + begin + if Filter.Header = GZip and then Filter.Compression then + Translate_GZip + (Filter => Filter, + In_Data => In_Data, + In_Last => In_Last, + Out_Data => Out_Data, + Out_Last => Out_Last, + Flush => Flush); + else + Translate_Auto + (Filter => Filter, + In_Data => In_Data, + In_Last => In_Last, + Out_Data => Out_Data, + Out_Last => Out_Last, + Flush => Flush); + end if; + end Translate; + + -------------------- + -- Translate_Auto -- + -------------------- + + procedure Translate_Auto + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode) + is + use type Thin.Int; + Code : Thin.Int; + + begin + if not Is_Open (Filter) then + raise Status_Error; + end if; + + if Out_Data'Length = 0 and then In_Data'Length = 0 then + raise Constraint_Error; + end if; + + Set_Out (Filter.Strm.all, Out_Data'Address, Out_Data'Length); + Set_In (Filter.Strm.all, In_Data'Address, In_Data'Length); + + Code := Flate (Filter.Compression).Step + (To_Thin_Access (Filter.Strm), + Thin.Int (Flush)); + + if Code = Thin.Z_STREAM_END then + Filter.Stream_End := True; + else + Check_Error (Filter.Strm.all, Code); + end if; + + In_Last := In_Data'Last + - Stream_Element_Offset (Avail_In (Filter.Strm.all)); + Out_Last := Out_Data'Last + - Stream_Element_Offset (Avail_Out (Filter.Strm.all)); + end Translate_Auto; + + -------------------- + -- Translate_GZip -- + -------------------- + + procedure Translate_GZip + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode) + is + Out_First : Stream_Element_Offset; + + procedure Add_Data (Data : in Stream_Element_Array); + -- Add data to stream from the Filter.Offset till necessary, + -- used for add gzip headr/footer. + + procedure Put_32 + (Item : in out Stream_Element_Array; + Data : in Unsigned_32); + pragma Inline (Put_32); + + -------------- + -- Add_Data -- + -------------- + + procedure Add_Data (Data : in Stream_Element_Array) is + Data_First : Stream_Element_Offset renames Filter.Offset; + Data_Last : Stream_Element_Offset; + Data_Len : Stream_Element_Offset; -- -1 + Out_Len : Stream_Element_Offset; -- -1 + begin + Out_First := Out_Last + 1; + + if Data_First > Data'Last then + return; + end if; + + Data_Len := Data'Last - Data_First; + Out_Len := Out_Data'Last - Out_First; + + if Data_Len <= Out_Len then + Out_Last := Out_First + Data_Len; + Data_Last := Data'Last; + else + Out_Last := Out_Data'Last; + Data_Last := Data_First + Out_Len; + end if; + + Out_Data (Out_First .. Out_Last) := Data (Data_First .. Data_Last); + + Data_First := Data_Last + 1; + Out_First := Out_Last + 1; + end Add_Data; + + ------------ + -- Put_32 -- + ------------ + + procedure Put_32 + (Item : in out Stream_Element_Array; + Data : in Unsigned_32) + is + D : Unsigned_32 := Data; + begin + for J in Item'First .. Item'First + 3 loop + Item (J) := Stream_Element (D and 16#FF#); + D := Shift_Right (D, 8); + end loop; + end Put_32; + + begin + Out_Last := Out_Data'First - 1; + + if not Filter.Stream_End then + Add_Data (Simple_GZip_Header); + + Translate_Auto + (Filter => Filter, + In_Data => In_Data, + In_Last => In_Last, + Out_Data => Out_Data (Out_First .. Out_Data'Last), + Out_Last => Out_Last, + Flush => Flush); + + CRC32 (Filter.CRC, In_Data (In_Data'First .. In_Last)); + end if; + + if Filter.Stream_End and then Out_Last <= Out_Data'Last then + -- This detection method would work only when + -- Simple_GZip_Header'Last > Footer_Array'Last + + if Filter.Offset = Simple_GZip_Header'Last + 1 then + Filter.Offset := Footer_Array'First; + end if; + + declare + Footer : Footer_Array; + begin + Put_32 (Footer, Filter.CRC); + Put_32 (Footer (Footer'First + 4 .. Footer'Last), + Unsigned_32 (Total_In (Filter))); + Add_Data (Footer); + end; + end if; + end Translate_GZip; + + ------------- + -- Version -- + ------------- + + function Version return String is + begin + return Interfaces.C.Strings.Value (Thin.zlibVersion); + end Version; + + ----------- + -- Write -- + ----------- + + procedure Write + (Filter : in out Filter_Type; + Item : in Ada.Streams.Stream_Element_Array; + Flush : in Flush_Mode := No_Flush) + is + Buffer : Stream_Element_Array (1 .. Buffer_Size); + In_Last : Stream_Element_Offset; + Out_Last : Stream_Element_Offset; + In_First : Stream_Element_Offset := Item'First; + begin + if Item'Length = 0 and Flush = No_Flush then + return; + end if; + + loop + Translate + (Filter => Filter, + In_Data => Item (In_First .. Item'Last), + In_Last => In_Last, + Out_Data => Buffer, + Out_Last => Out_Last, + Flush => Flush); + + if Out_Last >= Buffer'First then + Write (Buffer (1 .. Out_Last)); + end if; + + exit when In_Last = Item'Last or Stream_End (Filter); + + In_First := In_Last + 1; + end loop; + end Write; + +end ZLib; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib.ads b/third_party/zlib/v1_2_11/contrib/ada/zlib.ads new file mode 100644 index 0000000..79ffc40 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib.ads @@ -0,0 +1,328 @@ +------------------------------------------------------------------------------ +-- ZLib for Ada thick binding. -- +-- -- +-- Copyright (C) 2002-2004 Dmitriy Anisimkov -- +-- -- +-- This library is free software; you can redistribute it and/or modify -- +-- it under the terms of the GNU General Public License as published by -- +-- the Free Software Foundation; either version 2 of the License, or (at -- +-- your option) any later version. -- +-- -- +-- This library is distributed in the hope that it will be useful, but -- +-- WITHOUT ANY WARRANTY; without even the implied warranty of -- +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- +-- General Public License for more details. -- +-- -- +-- You should have received a copy of the GNU General Public License -- +-- along with this library; if not, write to the Free Software Foundation, -- +-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- +-- -- +-- As a special exception, if other files instantiate generics from this -- +-- unit, or you link this unit with other files to produce an executable, -- +-- this unit does not by itself cause the resulting executable to be -- +-- covered by the GNU General Public License. This exception does not -- +-- however invalidate any other reasons why the executable file might be -- +-- covered by the GNU Public License. -- +------------------------------------------------------------------------------ + +-- $Id: zlib.ads,v 1.26 2004/09/06 06:53:19 vagul Exp $ + +with Ada.Streams; + +with Interfaces; + +package ZLib is + + ZLib_Error : exception; + Status_Error : exception; + + type Compression_Level is new Integer range -1 .. 9; + + type Flush_Mode is private; + + type Compression_Method is private; + + type Window_Bits_Type is new Integer range 8 .. 15; + + type Memory_Level_Type is new Integer range 1 .. 9; + + type Unsigned_32 is new Interfaces.Unsigned_32; + + type Strategy_Type is private; + + type Header_Type is (None, Auto, Default, GZip); + -- Header type usage have a some limitation for inflate. + -- See comment for Inflate_Init. + + subtype Count is Ada.Streams.Stream_Element_Count; + + Default_Memory_Level : constant Memory_Level_Type := 8; + Default_Window_Bits : constant Window_Bits_Type := 15; + + ---------------------------------- + -- Compression method constants -- + ---------------------------------- + + Deflated : constant Compression_Method; + -- Only one method allowed in this ZLib version + + --------------------------------- + -- Compression level constants -- + --------------------------------- + + No_Compression : constant Compression_Level := 0; + Best_Speed : constant Compression_Level := 1; + Best_Compression : constant Compression_Level := 9; + Default_Compression : constant Compression_Level := -1; + + -------------------------- + -- Flush mode constants -- + -------------------------- + + No_Flush : constant Flush_Mode; + -- Regular way for compression, no flush + + Partial_Flush : constant Flush_Mode; + -- Will be removed, use Z_SYNC_FLUSH instead + + Sync_Flush : constant Flush_Mode; + -- All pending output is flushed to the output buffer and the output + -- is aligned on a byte boundary, so that the decompressor can get all + -- input data available so far. (In particular avail_in is zero after the + -- call if enough output space has been provided before the call.) + -- Flushing may degrade compression for some compression algorithms and so + -- it should be used only when necessary. + + Block_Flush : constant Flush_Mode; + -- Z_BLOCK requests that inflate() stop + -- if and when it get to the next deflate block boundary. When decoding the + -- zlib or gzip format, this will cause inflate() to return immediately + -- after the header and before the first block. When doing a raw inflate, + -- inflate() will go ahead and process the first block, and will return + -- when it gets to the end of that block, or when it runs out of data. + + Full_Flush : constant Flush_Mode; + -- All output is flushed as with SYNC_FLUSH, and the compression state + -- is reset so that decompression can restart from this point if previous + -- compressed data has been damaged or if random access is desired. Using + -- Full_Flush too often can seriously degrade the compression. + + Finish : constant Flush_Mode; + -- Just for tell the compressor that input data is complete. + + ------------------------------------ + -- Compression strategy constants -- + ------------------------------------ + + -- RLE stategy could be used only in version 1.2.0 and later. + + Filtered : constant Strategy_Type; + Huffman_Only : constant Strategy_Type; + RLE : constant Strategy_Type; + Default_Strategy : constant Strategy_Type; + + Default_Buffer_Size : constant := 4096; + + type Filter_Type is tagged limited private; + -- The filter is for compression and for decompression. + -- The usage of the type is depend of its initialization. + + function Version return String; + pragma Inline (Version); + -- Return string representation of the ZLib version. + + procedure Deflate_Init + (Filter : in out Filter_Type; + Level : in Compression_Level := Default_Compression; + Strategy : in Strategy_Type := Default_Strategy; + Method : in Compression_Method := Deflated; + Window_Bits : in Window_Bits_Type := Default_Window_Bits; + Memory_Level : in Memory_Level_Type := Default_Memory_Level; + Header : in Header_Type := Default); + -- Compressor initialization. + -- When Header parameter is Auto or Default, then default zlib header + -- would be provided for compressed data. + -- When Header is GZip, then gzip header would be set instead of + -- default header. + -- When Header is None, no header would be set for compressed data. + + procedure Inflate_Init + (Filter : in out Filter_Type; + Window_Bits : in Window_Bits_Type := Default_Window_Bits; + Header : in Header_Type := Default); + -- Decompressor initialization. + -- Default header type mean that ZLib default header is expecting in the + -- input compressed stream. + -- Header type None mean that no header is expecting in the input stream. + -- GZip header type mean that GZip header is expecting in the + -- input compressed stream. + -- Auto header type mean that header type (GZip or Native) would be + -- detected automatically in the input stream. + -- Note that header types parameter values None, GZip and Auto are + -- supported for inflate routine only in ZLib versions 1.2.0.2 and later. + -- Deflate_Init is supporting all header types. + + function Is_Open (Filter : in Filter_Type) return Boolean; + pragma Inline (Is_Open); + -- Is the filter opened for compression or decompression. + + procedure Close + (Filter : in out Filter_Type; + Ignore_Error : in Boolean := False); + -- Closing the compression or decompressor. + -- If stream is closing before the complete and Ignore_Error is False, + -- The exception would be raised. + + generic + with procedure Data_In + (Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset); + with procedure Data_Out + (Item : in Ada.Streams.Stream_Element_Array); + procedure Generic_Translate + (Filter : in out Filter_Type; + In_Buffer_Size : in Integer := Default_Buffer_Size; + Out_Buffer_Size : in Integer := Default_Buffer_Size); + -- Compress/decompress data fetch from Data_In routine and pass the result + -- to the Data_Out routine. User should provide Data_In and Data_Out + -- for compression/decompression data flow. + -- Compression or decompression depend on Filter initialization. + + function Total_In (Filter : in Filter_Type) return Count; + pragma Inline (Total_In); + -- Returns total number of input bytes read so far + + function Total_Out (Filter : in Filter_Type) return Count; + pragma Inline (Total_Out); + -- Returns total number of bytes output so far + + function CRC32 + (CRC : in Unsigned_32; + Data : in Ada.Streams.Stream_Element_Array) + return Unsigned_32; + pragma Inline (CRC32); + -- Compute CRC32, it could be necessary for make gzip format + + procedure CRC32 + (CRC : in out Unsigned_32; + Data : in Ada.Streams.Stream_Element_Array); + pragma Inline (CRC32); + -- Compute CRC32, it could be necessary for make gzip format + + ------------------------------------------------- + -- Below is more complex low level routines. -- + ------------------------------------------------- + + procedure Translate + (Filter : in out Filter_Type; + In_Data : in Ada.Streams.Stream_Element_Array; + In_Last : out Ada.Streams.Stream_Element_Offset; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode); + -- Compress/decompress the In_Data buffer and place the result into + -- Out_Data. In_Last is the index of last element from In_Data accepted by + -- the Filter. Out_Last is the last element of the received data from + -- Filter. To tell the filter that incoming data are complete put the + -- Flush parameter to Finish. + + function Stream_End (Filter : in Filter_Type) return Boolean; + pragma Inline (Stream_End); + -- Return the true when the stream is complete. + + procedure Flush + (Filter : in out Filter_Type; + Out_Data : out Ada.Streams.Stream_Element_Array; + Out_Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode); + pragma Inline (Flush); + -- Flushing the data from the compressor. + + generic + with procedure Write + (Item : in Ada.Streams.Stream_Element_Array); + -- User should provide this routine for accept + -- compressed/decompressed data. + + Buffer_Size : in Ada.Streams.Stream_Element_Offset + := Default_Buffer_Size; + -- Buffer size for Write user routine. + + procedure Write + (Filter : in out Filter_Type; + Item : in Ada.Streams.Stream_Element_Array; + Flush : in Flush_Mode := No_Flush); + -- Compress/Decompress data from Item to the generic parameter procedure + -- Write. Output buffer size could be set in Buffer_Size generic parameter. + + generic + with procedure Read + (Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset); + -- User should provide data for compression/decompression + -- thru this routine. + + Buffer : in out Ada.Streams.Stream_Element_Array; + -- Buffer for keep remaining data from the previous + -- back read. + + Rest_First, Rest_Last : in out Ada.Streams.Stream_Element_Offset; + -- Rest_First have to be initialized to Buffer'Last + 1 + -- Rest_Last have to be initialized to Buffer'Last + -- before usage. + + Allow_Read_Some : in Boolean := False; + -- Is it allowed to return Last < Item'Last before end of data. + + procedure Read + (Filter : in out Filter_Type; + Item : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset; + Flush : in Flush_Mode := No_Flush); + -- Compress/Decompress data from generic parameter procedure Read to the + -- Item. User should provide Buffer and initialized Rest_First, Rest_Last + -- indicators. If Allow_Read_Some is True, Read routines could return + -- Last < Item'Last only at end of stream. + +private + + use Ada.Streams; + + pragma Assert (Ada.Streams.Stream_Element'Size = 8); + pragma Assert (Ada.Streams.Stream_Element'Modulus = 2**8); + + type Flush_Mode is new Integer range 0 .. 5; + + type Compression_Method is new Integer range 8 .. 8; + + type Strategy_Type is new Integer range 0 .. 3; + + No_Flush : constant Flush_Mode := 0; + Partial_Flush : constant Flush_Mode := 1; + Sync_Flush : constant Flush_Mode := 2; + Full_Flush : constant Flush_Mode := 3; + Finish : constant Flush_Mode := 4; + Block_Flush : constant Flush_Mode := 5; + + Filtered : constant Strategy_Type := 1; + Huffman_Only : constant Strategy_Type := 2; + RLE : constant Strategy_Type := 3; + Default_Strategy : constant Strategy_Type := 0; + + Deflated : constant Compression_Method := 8; + + type Z_Stream; + + type Z_Stream_Access is access all Z_Stream; + + type Filter_Type is tagged limited record + Strm : Z_Stream_Access; + Compression : Boolean; + Stream_End : Boolean; + Header : Header_Type; + CRC : Unsigned_32; + Offset : Stream_Element_Offset; + -- Offset for gzip header/footer output. + end record; + +end ZLib; diff --git a/third_party/zlib/v1_2_11/contrib/ada/zlib.gpr b/third_party/zlib/v1_2_11/contrib/ada/zlib.gpr new file mode 100644 index 0000000..296b22a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/ada/zlib.gpr @@ -0,0 +1,20 @@ +project Zlib is + + for Languages use ("Ada"); + for Source_Dirs use ("."); + for Object_Dir use "."; + for Main use ("test.adb", "mtest.adb", "read.adb", "buffer_demo"); + + package Compiler is + for Default_Switches ("ada") use ("-gnatwcfilopru", "-gnatVcdfimorst", "-gnatyabcefhiklmnoprst"); + end Compiler; + + package Linker is + for Default_Switches ("ada") use ("-lz"); + end Linker; + + package Builder is + for Default_Switches ("ada") use ("-s", "-gnatQ"); + end Builder; + +end Zlib; diff --git a/third_party/zlib/v1_2_11/contrib/amd64/amd64-match.S b/third_party/zlib/v1_2_11/contrib/amd64/amd64-match.S new file mode 100644 index 0000000..81d4a1c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/amd64/amd64-match.S @@ -0,0 +1,452 @@ +/* + * match.S -- optimized version of longest_match() + * based on the similar work by Gilles Vollant, and Brian Raiter, written 1998 + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the BSD License. Use by owners of Che Guevarra + * parafernalia is prohibited, where possible, and highly discouraged + * elsewhere. + */ + +#ifndef NO_UNDERLINE +# define match_init _match_init +# define longest_match _longest_match +#endif + +#define scanend ebx +#define scanendw bx +#define chainlenwmask edx /* high word: current chain len low word: s->wmask */ +#define curmatch rsi +#define curmatchd esi +#define windowbestlen r8 +#define scanalign r9 +#define scanalignd r9d +#define window r10 +#define bestlen r11 +#define bestlend r11d +#define scanstart r12d +#define scanstartw r12w +#define scan r13 +#define nicematch r14d +#define limit r15 +#define limitd r15d +#define prev rcx + +/* + * The 258 is a "magic number, not a parameter -- changing it + * breaks the hell loose + */ +#define MAX_MATCH (258) +#define MIN_MATCH (3) +#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) +#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) + +/* stack frame offsets */ +#define LocalVarsSize (112) +#define _chainlenwmask ( 8-LocalVarsSize)(%rsp) +#define _windowbestlen (16-LocalVarsSize)(%rsp) +#define save_r14 (24-LocalVarsSize)(%rsp) +#define save_rsi (32-LocalVarsSize)(%rsp) +#define save_rbx (40-LocalVarsSize)(%rsp) +#define save_r12 (56-LocalVarsSize)(%rsp) +#define save_r13 (64-LocalVarsSize)(%rsp) +#define save_r15 (80-LocalVarsSize)(%rsp) + + +.globl match_init, longest_match + +/* + * On AMD64 the first argument of a function (in our case -- the pointer to + * deflate_state structure) is passed in %rdi, hence our offsets below are + * all off of that. + */ + +/* you can check the structure offset by running + +#include +#include +#include "deflate.h" + +void print_depl() +{ +deflate_state ds; +deflate_state *s=&ds; +printf("size pointer=%u\n",(int)sizeof(void*)); + +printf("#define dsWSize (%3u)(%%rdi)\n",(int)(((char*)&(s->w_size))-((char*)s))); +printf("#define dsWMask (%3u)(%%rdi)\n",(int)(((char*)&(s->w_mask))-((char*)s))); +printf("#define dsWindow (%3u)(%%rdi)\n",(int)(((char*)&(s->window))-((char*)s))); +printf("#define dsPrev (%3u)(%%rdi)\n",(int)(((char*)&(s->prev))-((char*)s))); +printf("#define dsMatchLen (%3u)(%%rdi)\n",(int)(((char*)&(s->match_length))-((char*)s))); +printf("#define dsPrevMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_match))-((char*)s))); +printf("#define dsStrStart (%3u)(%%rdi)\n",(int)(((char*)&(s->strstart))-((char*)s))); +printf("#define dsMatchStart (%3u)(%%rdi)\n",(int)(((char*)&(s->match_start))-((char*)s))); +printf("#define dsLookahead (%3u)(%%rdi)\n",(int)(((char*)&(s->lookahead))-((char*)s))); +printf("#define dsPrevLen (%3u)(%%rdi)\n",(int)(((char*)&(s->prev_length))-((char*)s))); +printf("#define dsMaxChainLen (%3u)(%%rdi)\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); +printf("#define dsGoodMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->good_match))-((char*)s))); +printf("#define dsNiceMatch (%3u)(%%rdi)\n",(int)(((char*)&(s->nice_match))-((char*)s))); +} + +*/ + + +/* + to compile for XCode 3.2 on MacOSX x86_64 + - run "gcc -g -c -DXCODE_MAC_X64_STRUCTURE amd64-match.S" + */ + + +#ifndef CURRENT_LINX_XCODE_MAC_X64_STRUCTURE +#define dsWSize ( 68)(%rdi) +#define dsWMask ( 76)(%rdi) +#define dsWindow ( 80)(%rdi) +#define dsPrev ( 96)(%rdi) +#define dsMatchLen (144)(%rdi) +#define dsPrevMatch (148)(%rdi) +#define dsStrStart (156)(%rdi) +#define dsMatchStart (160)(%rdi) +#define dsLookahead (164)(%rdi) +#define dsPrevLen (168)(%rdi) +#define dsMaxChainLen (172)(%rdi) +#define dsGoodMatch (188)(%rdi) +#define dsNiceMatch (192)(%rdi) + +#else + +#ifndef STRUCT_OFFSET +# define STRUCT_OFFSET (0) +#endif + + +#define dsWSize ( 56 + STRUCT_OFFSET)(%rdi) +#define dsWMask ( 64 + STRUCT_OFFSET)(%rdi) +#define dsWindow ( 72 + STRUCT_OFFSET)(%rdi) +#define dsPrev ( 88 + STRUCT_OFFSET)(%rdi) +#define dsMatchLen (136 + STRUCT_OFFSET)(%rdi) +#define dsPrevMatch (140 + STRUCT_OFFSET)(%rdi) +#define dsStrStart (148 + STRUCT_OFFSET)(%rdi) +#define dsMatchStart (152 + STRUCT_OFFSET)(%rdi) +#define dsLookahead (156 + STRUCT_OFFSET)(%rdi) +#define dsPrevLen (160 + STRUCT_OFFSET)(%rdi) +#define dsMaxChainLen (164 + STRUCT_OFFSET)(%rdi) +#define dsGoodMatch (180 + STRUCT_OFFSET)(%rdi) +#define dsNiceMatch (184 + STRUCT_OFFSET)(%rdi) + +#endif + + + + +.text + +/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ + +longest_match: +/* + * Retrieve the function arguments. %curmatch will hold cur_match + * throughout the entire function (passed via rsi on amd64). + * rdi will hold the pointer to the deflate_state (first arg on amd64) + */ + mov %rsi, save_rsi + mov %rbx, save_rbx + mov %r12, save_r12 + mov %r13, save_r13 + mov %r14, save_r14 + mov %r15, save_r15 + +/* uInt wmask = s->w_mask; */ +/* unsigned chain_length = s->max_chain_length; */ +/* if (s->prev_length >= s->good_match) { */ +/* chain_length >>= 2; */ +/* } */ + + movl dsPrevLen, %eax + movl dsGoodMatch, %ebx + cmpl %ebx, %eax + movl dsWMask, %eax + movl dsMaxChainLen, %chainlenwmask + jl LastMatchGood + shrl $2, %chainlenwmask +LastMatchGood: + +/* chainlen is decremented once beforehand so that the function can */ +/* use the sign flag instead of the zero flag for the exit test. */ +/* It is then shifted into the high word, to make room for the wmask */ +/* value, which it will always accompany. */ + + decl %chainlenwmask + shll $16, %chainlenwmask + orl %eax, %chainlenwmask + +/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ + + movl dsNiceMatch, %eax + movl dsLookahead, %ebx + cmpl %eax, %ebx + jl LookaheadLess + movl %eax, %ebx +LookaheadLess: movl %ebx, %nicematch + +/* register Bytef *scan = s->window + s->strstart; */ + + mov dsWindow, %window + movl dsStrStart, %limitd + lea (%limit, %window), %scan + +/* Determine how many bytes the scan ptr is off from being */ +/* dword-aligned. */ + + mov %scan, %scanalign + negl %scanalignd + andl $3, %scanalignd + +/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ +/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ + + movl dsWSize, %eax + subl $MIN_LOOKAHEAD, %eax + xorl %ecx, %ecx + subl %eax, %limitd + cmovng %ecx, %limitd + +/* int best_len = s->prev_length; */ + + movl dsPrevLen, %bestlend + +/* Store the sum of s->window + best_len in %windowbestlen locally, and in memory. */ + + lea (%window, %bestlen), %windowbestlen + mov %windowbestlen, _windowbestlen + +/* register ush scan_start = *(ushf*)scan; */ +/* register ush scan_end = *(ushf*)(scan+best_len-1); */ +/* Posf *prev = s->prev; */ + + movzwl (%scan), %scanstart + movzwl -1(%scan, %bestlen), %scanend + mov dsPrev, %prev + +/* Jump into the main loop. */ + + movl %chainlenwmask, _chainlenwmask + jmp LoopEntry + +.balign 16 + +/* do { + * match = s->window + cur_match; + * if (*(ushf*)(match+best_len-1) != scan_end || + * *(ushf*)match != scan_start) continue; + * [...] + * } while ((cur_match = prev[cur_match & wmask]) > limit + * && --chain_length != 0); + * + * Here is the inner loop of the function. The function will spend the + * majority of its time in this loop, and majority of that time will + * be spent in the first ten instructions. + */ +LookupLoop: + andl %chainlenwmask, %curmatchd + movzwl (%prev, %curmatch, 2), %curmatchd + cmpl %limitd, %curmatchd + jbe LeaveNow + subl $0x00010000, %chainlenwmask + js LeaveNow +LoopEntry: cmpw -1(%windowbestlen, %curmatch), %scanendw + jne LookupLoop + cmpw %scanstartw, (%window, %curmatch) + jne LookupLoop + +/* Store the current value of chainlen. */ + movl %chainlenwmask, _chainlenwmask + +/* %scan is the string under scrutiny, and %prev to the string we */ +/* are hoping to match it up with. In actuality, %esi and %edi are */ +/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ +/* initialized to -(MAX_MATCH_8 - scanalign). */ + + mov $(-MAX_MATCH_8), %rdx + lea (%curmatch, %window), %windowbestlen + lea MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen + lea MAX_MATCH_8(%scan, %scanalign), %prev + +/* the prefetching below makes very little difference... */ + prefetcht1 (%windowbestlen, %rdx) + prefetcht1 (%prev, %rdx) + +/* + * Test the strings for equality, 8 bytes at a time. At the end, + * adjust %rdx so that it is offset to the exact byte that mismatched. + * + * It should be confessed that this loop usually does not represent + * much of the total running time. Replacing it with a more + * straightforward "rep cmpsb" would not drastically degrade + * performance -- unrolling it, for example, makes no difference. + */ + +#undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */ + +LoopCmps: +#ifdef USE_SSE + /* Preload the SSE registers */ + movdqu (%windowbestlen, %rdx), %xmm1 + movdqu (%prev, %rdx), %xmm2 + pcmpeqb %xmm2, %xmm1 + movdqu 16(%windowbestlen, %rdx), %xmm3 + movdqu 16(%prev, %rdx), %xmm4 + pcmpeqb %xmm4, %xmm3 + movdqu 32(%windowbestlen, %rdx), %xmm5 + movdqu 32(%prev, %rdx), %xmm6 + pcmpeqb %xmm6, %xmm5 + movdqu 48(%windowbestlen, %rdx), %xmm7 + movdqu 48(%prev, %rdx), %xmm8 + pcmpeqb %xmm8, %xmm7 + + /* Check the comparisions' results */ + pmovmskb %xmm1, %rax + notw %ax + bsfw %ax, %ax + jnz LeaveLoopCmps + + /* this is the only iteration of the loop with a possibility of having + incremented rdx by 0x108 (each loop iteration add 16*4 = 0x40 + and (0x40*4)+8=0x108 */ + add $8, %rdx + jz LenMaximum + add $8, %rdx + + + pmovmskb %xmm3, %rax + notw %ax + bsfw %ax, %ax + jnz LeaveLoopCmps + + + add $16, %rdx + + + pmovmskb %xmm5, %rax + notw %ax + bsfw %ax, %ax + jnz LeaveLoopCmps + + add $16, %rdx + + + pmovmskb %xmm7, %rax + notw %ax + bsfw %ax, %ax + jnz LeaveLoopCmps + + add $16, %rdx + + jmp LoopCmps +LeaveLoopCmps: add %rax, %rdx +#else + mov (%windowbestlen, %rdx), %rax + xor (%prev, %rdx), %rax + jnz LeaveLoopCmps + + mov 8(%windowbestlen, %rdx), %rax + xor 8(%prev, %rdx), %rax + jnz LeaveLoopCmps8 + + mov 16(%windowbestlen, %rdx), %rax + xor 16(%prev, %rdx), %rax + jnz LeaveLoopCmps16 + + add $24, %rdx + jnz LoopCmps + jmp LenMaximum +# if 0 +/* + * This three-liner is tantalizingly simple, but bsf is a slow instruction, + * and the complicated alternative down below is quite a bit faster. Sad... + */ + +LeaveLoopCmps: bsf %rax, %rax /* find the first non-zero bit */ + shrl $3, %eax /* divide by 8 to get the byte */ + add %rax, %rdx +# else +LeaveLoopCmps16: + add $8, %rdx +LeaveLoopCmps8: + add $8, %rdx +LeaveLoopCmps: testl $0xFFFFFFFF, %eax /* Check the first 4 bytes */ + jnz Check16 + add $4, %rdx + shr $32, %rax +Check16: testw $0xFFFF, %ax + jnz LenLower + add $2, %rdx + shrl $16, %eax +LenLower: subb $1, %al + adc $0, %rdx +# endif +#endif + +/* Calculate the length of the match. If it is longer than MAX_MATCH, */ +/* then automatically accept it as the best possible match and leave. */ + + lea (%prev, %rdx), %rax + sub %scan, %rax + cmpl $MAX_MATCH, %eax + jge LenMaximum + +/* If the length of the match is not longer than the best match we */ +/* have so far, then forget it and return to the lookup loop. */ + + cmpl %bestlend, %eax + jg LongerMatch + mov _windowbestlen, %windowbestlen + mov dsPrev, %prev + movl _chainlenwmask, %edx + jmp LookupLoop + +/* s->match_start = cur_match; */ +/* best_len = len; */ +/* if (len >= nice_match) break; */ +/* scan_end = *(ushf*)(scan+best_len-1); */ + +LongerMatch: + movl %eax, %bestlend + movl %curmatchd, dsMatchStart + cmpl %nicematch, %eax + jge LeaveNow + + lea (%window, %bestlen), %windowbestlen + mov %windowbestlen, _windowbestlen + + movzwl -1(%scan, %rax), %scanend + mov dsPrev, %prev + movl _chainlenwmask, %chainlenwmask + jmp LookupLoop + +/* Accept the current string, with the maximum possible length. */ + +LenMaximum: + movl $MAX_MATCH, %bestlend + movl %curmatchd, dsMatchStart + +/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ +/* return s->lookahead; */ + +LeaveNow: + movl dsLookahead, %eax + cmpl %eax, %bestlend + cmovngl %bestlend, %eax +LookaheadRet: + +/* Restore the registers and return from whence we came. */ + + mov save_rsi, %rsi + mov save_rbx, %rbx + mov save_r12, %r12 + mov save_r13, %r13 + mov save_r14, %r14 + mov save_r15, %r15 + + ret + +match_init: ret diff --git a/third_party/zlib/v1_2_11/contrib/asm686/README.686 b/third_party/zlib/v1_2_11/contrib/asm686/README.686 new file mode 100644 index 0000000..a0bf3be --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/asm686/README.686 @@ -0,0 +1,51 @@ +This is a patched version of zlib, modified to use +Pentium-Pro-optimized assembly code in the deflation algorithm. The +files changed/added by this patch are: + +README.686 +match.S + +The speedup that this patch provides varies, depending on whether the +compiler used to build the original version of zlib falls afoul of the +PPro's speed traps. My own tests show a speedup of around 10-20% at +the default compression level, and 20-30% using -9, against a version +compiled using gcc 2.7.2.3. Your mileage may vary. + +Note that this code has been tailored for the PPro/PII in particular, +and will not perform particuarly well on a Pentium. + +If you are using an assembler other than GNU as, you will have to +translate match.S to use your assembler's syntax. (Have fun.) + +Brian Raiter +breadbox@muppetlabs.com +April, 1998 + + +Added for zlib 1.1.3: + +The patches come from +http://www.muppetlabs.com/~breadbox/software/assembly.html + +To compile zlib with this asm file, copy match.S to the zlib directory +then do: + +CFLAGS="-O3 -DASMV" ./configure +make OBJA=match.o + + +Update: + +I've been ignoring these assembly routines for years, believing that +gcc's generated code had caught up with it sometime around gcc 2.95 +and the major rearchitecting of the Pentium 4. However, I recently +learned that, despite what I believed, this code still has some life +in it. On the Pentium 4 and AMD64 chips, it continues to run about 8% +faster than the code produced by gcc 4.1. + +In acknowledgement of its continuing usefulness, I've altered the +license to match that of the rest of zlib. Share and Enjoy! + +Brian Raiter +breadbox@muppetlabs.com +April, 2007 diff --git a/third_party/zlib/v1_2_11/contrib/asm686/match.S b/third_party/zlib/v1_2_11/contrib/asm686/match.S new file mode 100644 index 0000000..fa42109 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/asm686/match.S @@ -0,0 +1,357 @@ +/* match.S -- x86 assembly version of the zlib longest_match() function. + * Optimized for the Intel 686 chips (PPro and later). + * + * Copyright (C) 1998, 2007 Brian Raiter + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the author be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#ifndef NO_UNDERLINE +#define match_init _match_init +#define longest_match _longest_match +#endif + +#define MAX_MATCH (258) +#define MIN_MATCH (3) +#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1) +#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7) + +/* stack frame offsets */ + +#define chainlenwmask 0 /* high word: current chain len */ + /* low word: s->wmask */ +#define window 4 /* local copy of s->window */ +#define windowbestlen 8 /* s->window + bestlen */ +#define scanstart 16 /* first two bytes of string */ +#define scanend 12 /* last two bytes of string */ +#define scanalign 20 /* dword-misalignment of string */ +#define nicematch 24 /* a good enough match size */ +#define bestlen 28 /* size of best match so far */ +#define scan 32 /* ptr to string wanting match */ + +#define LocalVarsSize (36) +/* saved ebx 36 */ +/* saved edi 40 */ +/* saved esi 44 */ +/* saved ebp 48 */ +/* return address 52 */ +#define deflatestate 56 /* the function arguments */ +#define curmatch 60 + +/* All the +zlib1222add offsets are due to the addition of fields + * in zlib in the deflate_state structure since the asm code was first written + * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). + * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). + * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). + */ + +#define zlib1222add (8) + +#define dsWSize (36+zlib1222add) +#define dsWMask (44+zlib1222add) +#define dsWindow (48+zlib1222add) +#define dsPrev (56+zlib1222add) +#define dsMatchLen (88+zlib1222add) +#define dsPrevMatch (92+zlib1222add) +#define dsStrStart (100+zlib1222add) +#define dsMatchStart (104+zlib1222add) +#define dsLookahead (108+zlib1222add) +#define dsPrevLen (112+zlib1222add) +#define dsMaxChainLen (116+zlib1222add) +#define dsGoodMatch (132+zlib1222add) +#define dsNiceMatch (136+zlib1222add) + + +.file "match.S" + +.globl match_init, longest_match + +.text + +/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */ +.cfi_sections .debug_frame + +longest_match: + +.cfi_startproc +/* Save registers that the compiler may be using, and adjust %esp to */ +/* make room for our stack frame. */ + + pushl %ebp + .cfi_def_cfa_offset 8 + .cfi_offset ebp, -8 + pushl %edi + .cfi_def_cfa_offset 12 + pushl %esi + .cfi_def_cfa_offset 16 + pushl %ebx + .cfi_def_cfa_offset 20 + subl $LocalVarsSize, %esp + .cfi_def_cfa_offset LocalVarsSize+20 + +/* Retrieve the function arguments. %ecx will hold cur_match */ +/* throughout the entire function. %edx will hold the pointer to the */ +/* deflate_state structure during the function's setup (before */ +/* entering the main loop). */ + + movl deflatestate(%esp), %edx + movl curmatch(%esp), %ecx + +/* uInt wmask = s->w_mask; */ +/* unsigned chain_length = s->max_chain_length; */ +/* if (s->prev_length >= s->good_match) { */ +/* chain_length >>= 2; */ +/* } */ + + movl dsPrevLen(%edx), %eax + movl dsGoodMatch(%edx), %ebx + cmpl %ebx, %eax + movl dsWMask(%edx), %eax + movl dsMaxChainLen(%edx), %ebx + jl LastMatchGood + shrl $2, %ebx +LastMatchGood: + +/* chainlen is decremented once beforehand so that the function can */ +/* use the sign flag instead of the zero flag for the exit test. */ +/* It is then shifted into the high word, to make room for the wmask */ +/* value, which it will always accompany. */ + + decl %ebx + shll $16, %ebx + orl %eax, %ebx + movl %ebx, chainlenwmask(%esp) + +/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */ + + movl dsNiceMatch(%edx), %eax + movl dsLookahead(%edx), %ebx + cmpl %eax, %ebx + jl LookaheadLess + movl %eax, %ebx +LookaheadLess: movl %ebx, nicematch(%esp) + +/* register Bytef *scan = s->window + s->strstart; */ + + movl dsWindow(%edx), %esi + movl %esi, window(%esp) + movl dsStrStart(%edx), %ebp + lea (%esi,%ebp), %edi + movl %edi, scan(%esp) + +/* Determine how many bytes the scan ptr is off from being */ +/* dword-aligned. */ + + movl %edi, %eax + negl %eax + andl $3, %eax + movl %eax, scanalign(%esp) + +/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */ +/* s->strstart - (IPos)MAX_DIST(s) : NIL; */ + + movl dsWSize(%edx), %eax + subl $MIN_LOOKAHEAD, %eax + subl %eax, %ebp + jg LimitPositive + xorl %ebp, %ebp +LimitPositive: + +/* int best_len = s->prev_length; */ + + movl dsPrevLen(%edx), %eax + movl %eax, bestlen(%esp) + +/* Store the sum of s->window + best_len in %esi locally, and in %esi. */ + + addl %eax, %esi + movl %esi, windowbestlen(%esp) + +/* register ush scan_start = *(ushf*)scan; */ +/* register ush scan_end = *(ushf*)(scan+best_len-1); */ +/* Posf *prev = s->prev; */ + + movzwl (%edi), %ebx + movl %ebx, scanstart(%esp) + movzwl -1(%edi,%eax), %ebx + movl %ebx, scanend(%esp) + movl dsPrev(%edx), %edi + +/* Jump into the main loop. */ + + movl chainlenwmask(%esp), %edx + jmp LoopEntry + +.balign 16 + +/* do { + * match = s->window + cur_match; + * if (*(ushf*)(match+best_len-1) != scan_end || + * *(ushf*)match != scan_start) continue; + * [...] + * } while ((cur_match = prev[cur_match & wmask]) > limit + * && --chain_length != 0); + * + * Here is the inner loop of the function. The function will spend the + * majority of its time in this loop, and majority of that time will + * be spent in the first ten instructions. + * + * Within this loop: + * %ebx = scanend + * %ecx = curmatch + * %edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) + * %esi = windowbestlen - i.e., (window + bestlen) + * %edi = prev + * %ebp = limit + */ +LookupLoop: + andl %edx, %ecx + movzwl (%edi,%ecx,2), %ecx + cmpl %ebp, %ecx + jbe LeaveNow + subl $0x00010000, %edx + js LeaveNow +LoopEntry: movzwl -1(%esi,%ecx), %eax + cmpl %ebx, %eax + jnz LookupLoop + movl window(%esp), %eax + movzwl (%eax,%ecx), %eax + cmpl scanstart(%esp), %eax + jnz LookupLoop + +/* Store the current value of chainlen. */ + + movl %edx, chainlenwmask(%esp) + +/* Point %edi to the string under scrutiny, and %esi to the string we */ +/* are hoping to match it up with. In actuality, %esi and %edi are */ +/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */ +/* initialized to -(MAX_MATCH_8 - scanalign). */ + + movl window(%esp), %esi + movl scan(%esp), %edi + addl %ecx, %esi + movl scanalign(%esp), %eax + movl $(-MAX_MATCH_8), %edx + lea MAX_MATCH_8(%edi,%eax), %edi + lea MAX_MATCH_8(%esi,%eax), %esi + +/* Test the strings for equality, 8 bytes at a time. At the end, + * adjust %edx so that it is offset to the exact byte that mismatched. + * + * We already know at this point that the first three bytes of the + * strings match each other, and they can be safely passed over before + * starting the compare loop. So what this code does is skip over 0-3 + * bytes, as much as necessary in order to dword-align the %edi + * pointer. (%esi will still be misaligned three times out of four.) + * + * It should be confessed that this loop usually does not represent + * much of the total running time. Replacing it with a more + * straightforward "rep cmpsb" would not drastically degrade + * performance. + */ +LoopCmps: + movl (%esi,%edx), %eax + xorl (%edi,%edx), %eax + jnz LeaveLoopCmps + movl 4(%esi,%edx), %eax + xorl 4(%edi,%edx), %eax + jnz LeaveLoopCmps4 + addl $8, %edx + jnz LoopCmps + jmp LenMaximum +LeaveLoopCmps4: addl $4, %edx +LeaveLoopCmps: testl $0x0000FFFF, %eax + jnz LenLower + addl $2, %edx + shrl $16, %eax +LenLower: subb $1, %al + adcl $0, %edx + +/* Calculate the length of the match. If it is longer than MAX_MATCH, */ +/* then automatically accept it as the best possible match and leave. */ + + lea (%edi,%edx), %eax + movl scan(%esp), %edi + subl %edi, %eax + cmpl $MAX_MATCH, %eax + jge LenMaximum + +/* If the length of the match is not longer than the best match we */ +/* have so far, then forget it and return to the lookup loop. */ + + movl deflatestate(%esp), %edx + movl bestlen(%esp), %ebx + cmpl %ebx, %eax + jg LongerMatch + movl windowbestlen(%esp), %esi + movl dsPrev(%edx), %edi + movl scanend(%esp), %ebx + movl chainlenwmask(%esp), %edx + jmp LookupLoop + +/* s->match_start = cur_match; */ +/* best_len = len; */ +/* if (len >= nice_match) break; */ +/* scan_end = *(ushf*)(scan+best_len-1); */ + +LongerMatch: movl nicematch(%esp), %ebx + movl %eax, bestlen(%esp) + movl %ecx, dsMatchStart(%edx) + cmpl %ebx, %eax + jge LeaveNow + movl window(%esp), %esi + addl %eax, %esi + movl %esi, windowbestlen(%esp) + movzwl -1(%edi,%eax), %ebx + movl dsPrev(%edx), %edi + movl %ebx, scanend(%esp) + movl chainlenwmask(%esp), %edx + jmp LookupLoop + +/* Accept the current string, with the maximum possible length. */ + +LenMaximum: movl deflatestate(%esp), %edx + movl $MAX_MATCH, bestlen(%esp) + movl %ecx, dsMatchStart(%edx) + +/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */ +/* return s->lookahead; */ + +LeaveNow: + movl deflatestate(%esp), %edx + movl bestlen(%esp), %ebx + movl dsLookahead(%edx), %eax + cmpl %eax, %ebx + jg LookaheadRet + movl %ebx, %eax +LookaheadRet: + +/* Restore the stack and return from whence we came. */ + + addl $LocalVarsSize, %esp + .cfi_def_cfa_offset 20 + popl %ebx + .cfi_def_cfa_offset 16 + popl %esi + .cfi_def_cfa_offset 12 + popl %edi + .cfi_def_cfa_offset 8 + popl %ebp + .cfi_def_cfa_offset 4 +.cfi_endproc +match_init: ret diff --git a/third_party/zlib/v1_2_11/contrib/blast/Makefile b/third_party/zlib/v1_2_11/contrib/blast/Makefile new file mode 100644 index 0000000..9be80ba --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/blast/Makefile @@ -0,0 +1,8 @@ +blast: blast.c blast.h + cc -DTEST -o blast blast.c + +test: blast + blast < test.pk | cmp - test.txt + +clean: + rm -f blast blast.o diff --git a/third_party/zlib/v1_2_11/contrib/blast/README b/third_party/zlib/v1_2_11/contrib/blast/README new file mode 100644 index 0000000..e3a60b3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/blast/README @@ -0,0 +1,4 @@ +Read blast.h for purpose and usage. + +Mark Adler +madler@alumni.caltech.edu diff --git a/third_party/zlib/v1_2_11/contrib/blast/blast.c b/third_party/zlib/v1_2_11/contrib/blast/blast.c new file mode 100644 index 0000000..e6e6590 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/blast/blast.c @@ -0,0 +1,466 @@ +/* blast.c + * Copyright (C) 2003, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in blast.h + * version 1.3, 24 Aug 2013 + * + * blast.c decompresses data compressed by the PKWare Compression Library. + * This function provides functionality similar to the explode() function of + * the PKWare library, hence the name "blast". + * + * This decompressor is based on the excellent format description provided by + * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the + * example Ben provided in the post is incorrect. The distance 110001 should + * instead be 111000. When corrected, the example byte stream becomes: + * + * 00 04 82 24 25 8f 80 7f + * + * which decompresses to "AIAIAIAIAIAIA" (without the quotes). + */ + +/* + * Change history: + * + * 1.0 12 Feb 2003 - First version + * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data + * 1.2 24 Oct 2012 - Add note about using binary mode in stdio + * - Fix comparisons of differently signed integers + * 1.3 24 Aug 2013 - Return unused input from blast() + * - Fix test code to correctly report unused input + * - Enable the provision of initial input to blast() + */ + +#include /* for NULL */ +#include /* for setjmp(), longjmp(), and jmp_buf */ +#include "blast.h" /* prototype for blast() */ + +#define local static /* for local function definitions */ +#define MAXBITS 13 /* maximum code length */ +#define MAXWIN 4096 /* maximum window size */ + +/* input and output state */ +struct state { + /* input state */ + blast_in infun; /* input function provided by user */ + void *inhow; /* opaque information passed to infun() */ + unsigned char *in; /* next input location */ + unsigned left; /* available input at in */ + int bitbuf; /* bit buffer */ + int bitcnt; /* number of bits in bit buffer */ + + /* input limit error return state for bits() and decode() */ + jmp_buf env; + + /* output state */ + blast_out outfun; /* output function provided by user */ + void *outhow; /* opaque information passed to outfun() */ + unsigned next; /* index of next write location in out[] */ + int first; /* true to check distances (for first 4K) */ + unsigned char out[MAXWIN]; /* output buffer and sliding window */ +}; + +/* + * Return need bits from the input stream. This always leaves less than + * eight bits in the buffer. bits() works properly for need == 0. + * + * Format notes: + * + * - Bits are stored in bytes from the least significant bit to the most + * significant bit. Therefore bits are dropped from the bottom of the bit + * buffer, using shift right, and new bytes are appended to the top of the + * bit buffer, using shift left. + */ +local int bits(struct state *s, int need) +{ + int val; /* bit accumulator */ + + /* load at least need bits into val */ + val = s->bitbuf; + while (s->bitcnt < need) { + if (s->left == 0) { + s->left = s->infun(s->inhow, &(s->in)); + if (s->left == 0) longjmp(s->env, 1); /* out of input */ + } + val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */ + s->left--; + s->bitcnt += 8; + } + + /* drop need bits and update buffer, always zero to seven bits left */ + s->bitbuf = val >> need; + s->bitcnt -= need; + + /* return need bits, zeroing the bits above that */ + return val & ((1 << need) - 1); +} + +/* + * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of + * each length, which for a canonical code are stepped through in order. + * symbol[] are the symbol values in canonical order, where the number of + * entries is the sum of the counts in count[]. The decoding process can be + * seen in the function decode() below. + */ +struct huffman { + short *count; /* number of symbols of each length */ + short *symbol; /* canonically ordered symbols */ +}; + +/* + * Decode a code from the stream s using huffman table h. Return the symbol or + * a negative value if there is an error. If all of the lengths are zero, i.e. + * an empty code, or if the code is incomplete and an invalid code is received, + * then -9 is returned after reading MAXBITS bits. + * + * Format notes: + * + * - The codes as stored in the compressed data are bit-reversed relative to + * a simple integer ordering of codes of the same lengths. Hence below the + * bits are pulled from the compressed data one at a time and used to + * build the code value reversed from what is in the stream in order to + * permit simple integer comparisons for decoding. + * + * - The first code for the shortest length is all ones. Subsequent codes of + * the same length are simply integer decrements of the previous code. When + * moving up a length, a one bit is appended to the code. For a complete + * code, the last code of the longest length will be all zeros. To support + * this ordering, the bits pulled during decoding are inverted to apply the + * more "natural" ordering starting with all zeros and incrementing. + */ +local int decode(struct state *s, struct huffman *h) +{ + int len; /* current number of bits in code */ + int code; /* len bits being decoded */ + int first; /* first code of length len */ + int count; /* number of codes of length len */ + int index; /* index of first code of length len in symbol table */ + int bitbuf; /* bits from stream */ + int left; /* bits left in next or left to process */ + short *next; /* next number of codes */ + + bitbuf = s->bitbuf; + left = s->bitcnt; + code = first = index = 0; + len = 1; + next = h->count + 1; + while (1) { + while (left--) { + code |= (bitbuf & 1) ^ 1; /* invert code */ + bitbuf >>= 1; + count = *next++; + if (code < first + count) { /* if length len, return symbol */ + s->bitbuf = bitbuf; + s->bitcnt = (s->bitcnt - len) & 7; + return h->symbol[index + (code - first)]; + } + index += count; /* else update for next length */ + first += count; + first <<= 1; + code <<= 1; + len++; + } + left = (MAXBITS+1) - len; + if (left == 0) break; + if (s->left == 0) { + s->left = s->infun(s->inhow, &(s->in)); + if (s->left == 0) longjmp(s->env, 1); /* out of input */ + } + bitbuf = *(s->in)++; + s->left--; + if (left > 8) left = 8; + } + return -9; /* ran out of codes */ +} + +/* + * Given a list of repeated code lengths rep[0..n-1], where each byte is a + * count (high four bits + 1) and a code length (low four bits), generate the + * list of code lengths. This compaction reduces the size of the object code. + * Then given the list of code lengths length[0..n-1] representing a canonical + * Huffman code for n symbols, construct the tables required to decode those + * codes. Those tables are the number of codes of each length, and the symbols + * sorted by length, retaining their original order within each length. The + * return value is zero for a complete code set, negative for an over- + * subscribed code set, and positive for an incomplete code set. The tables + * can be used if the return value is zero or positive, but they cannot be used + * if the return value is negative. If the return value is zero, it is not + * possible for decode() using that table to return an error--any stream of + * enough bits will resolve to a symbol. If the return value is positive, then + * it is possible for decode() using that table to return an error for received + * codes past the end of the incomplete lengths. + */ +local int construct(struct huffman *h, const unsigned char *rep, int n) +{ + int symbol; /* current symbol when stepping through length[] */ + int len; /* current length when stepping through h->count[] */ + int left; /* number of possible codes left of current length */ + short offs[MAXBITS+1]; /* offsets in symbol table for each length */ + short length[256]; /* code lengths */ + + /* convert compact repeat counts into symbol bit length list */ + symbol = 0; + do { + len = *rep++; + left = (len >> 4) + 1; + len &= 15; + do { + length[symbol++] = len; + } while (--left); + } while (--n); + n = symbol; + + /* count number of codes of each length */ + for (len = 0; len <= MAXBITS; len++) + h->count[len] = 0; + for (symbol = 0; symbol < n; symbol++) + (h->count[length[symbol]])++; /* assumes lengths are within bounds */ + if (h->count[0] == n) /* no codes! */ + return 0; /* complete, but decode() will fail */ + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; /* one possible code of zero length */ + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; /* one more bit, double codes left */ + left -= h->count[len]; /* deduct count from possible codes */ + if (left < 0) return left; /* over-subscribed--return negative */ + } /* left > 0 means incomplete */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + h->count[len]; + + /* + * put symbols in table sorted by length, by symbol order within each + * length + */ + for (symbol = 0; symbol < n; symbol++) + if (length[symbol] != 0) + h->symbol[offs[length[symbol]]++] = symbol; + + /* return zero for complete set, positive for incomplete set */ + return left; +} + +/* + * Decode PKWare Compression Library stream. + * + * Format notes: + * + * - First byte is 0 if literals are uncoded or 1 if they are coded. Second + * byte is 4, 5, or 6 for the number of extra bits in the distance code. + * This is the base-2 logarithm of the dictionary size minus six. + * + * - Compressed data is a combination of literals and length/distance pairs + * terminated by an end code. Literals are either Huffman coded or + * uncoded bytes. A length/distance pair is a coded length followed by a + * coded distance to represent a string that occurs earlier in the + * uncompressed data that occurs again at the current location. + * + * - A bit preceding a literal or length/distance pair indicates which comes + * next, 0 for literals, 1 for length/distance. + * + * - If literals are uncoded, then the next eight bits are the literal, in the + * normal bit order in the stream, i.e. no bit-reversal is needed. Similarly, + * no bit reversal is needed for either the length extra bits or the distance + * extra bits. + * + * - Literal bytes are simply written to the output. A length/distance pair is + * an instruction to copy previously uncompressed bytes to the output. The + * copy is from distance bytes back in the output stream, copying for length + * bytes. + * + * - Distances pointing before the beginning of the output data are not + * permitted. + * + * - Overlapped copies, where the length is greater than the distance, are + * allowed and common. For example, a distance of one and a length of 518 + * simply copies the last byte 518 times. A distance of four and a length of + * twelve copies the last four bytes three times. A simple forward copy + * ignoring whether the length is greater than the distance or not implements + * this correctly. + */ +local int decomp(struct state *s) +{ + int lit; /* true if literals are coded */ + int dict; /* log2(dictionary size) - 6 */ + int symbol; /* decoded symbol, extra bits for distance */ + int len; /* length for copy */ + unsigned dist; /* distance for copy */ + int copy; /* copy counter */ + unsigned char *from, *to; /* copy pointers */ + static int virgin = 1; /* build tables once */ + static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */ + static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */ + static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */ + static struct huffman litcode = {litcnt, litsym}; /* length code */ + static struct huffman lencode = {lencnt, lensym}; /* length code */ + static struct huffman distcode = {distcnt, distsym};/* distance code */ + /* bit lengths of literal codes */ + static const unsigned char litlen[] = { + 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, + 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, + 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, + 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, + 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, + 44, 173}; + /* bit lengths of length codes 0..15 */ + static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23}; + /* bit lengths of distance codes 0..63 */ + static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248}; + static const short base[16] = { /* base for length codes */ + 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264}; + static const char extra[16] = { /* extra bits for length codes */ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8}; + + /* set up decoding tables (once--might not be thread-safe) */ + if (virgin) { + construct(&litcode, litlen, sizeof(litlen)); + construct(&lencode, lenlen, sizeof(lenlen)); + construct(&distcode, distlen, sizeof(distlen)); + virgin = 0; + } + + /* read header */ + lit = bits(s, 8); + if (lit > 1) return -1; + dict = bits(s, 8); + if (dict < 4 || dict > 6) return -2; + + /* decode literals and length/distance pairs */ + do { + if (bits(s, 1)) { + /* get length */ + symbol = decode(s, &lencode); + len = base[symbol] + bits(s, extra[symbol]); + if (len == 519) break; /* end code */ + + /* get distance */ + symbol = len == 2 ? 2 : dict; + dist = decode(s, &distcode) << symbol; + dist += bits(s, symbol); + dist++; + if (s->first && dist > s->next) + return -3; /* distance too far back */ + + /* copy length bytes from distance bytes back */ + do { + to = s->out + s->next; + from = to - dist; + copy = MAXWIN; + if (s->next < dist) { + from += copy; + copy = dist; + } + copy -= s->next; + if (copy > len) copy = len; + len -= copy; + s->next += copy; + do { + *to++ = *from++; + } while (--copy); + if (s->next == MAXWIN) { + if (s->outfun(s->outhow, s->out, s->next)) return 1; + s->next = 0; + s->first = 0; + } + } while (len != 0); + } + else { + /* get literal and write it */ + symbol = lit ? decode(s, &litcode) : bits(s, 8); + s->out[s->next++] = symbol; + if (s->next == MAXWIN) { + if (s->outfun(s->outhow, s->out, s->next)) return 1; + s->next = 0; + s->first = 0; + } + } + } while (1); + return 0; +} + +/* See comments in blast.h */ +int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, + unsigned *left, unsigned char **in) +{ + struct state s; /* input/output state */ + int err; /* return value */ + + /* initialize input state */ + s.infun = infun; + s.inhow = inhow; + if (left != NULL && *left) { + s.left = *left; + s.in = *in; + } + else + s.left = 0; + s.bitbuf = 0; + s.bitcnt = 0; + + /* initialize output state */ + s.outfun = outfun; + s.outhow = outhow; + s.next = 0; + s.first = 1; + + /* return if bits() or decode() tries to read past available input */ + if (setjmp(s.env) != 0) /* if came back here via longjmp(), */ + err = 2; /* then skip decomp(), return error */ + else + err = decomp(&s); /* decompress */ + + /* return unused input */ + if (left != NULL) + *left = s.left; + if (in != NULL) + *in = s.left ? s.in : NULL; + + /* write any leftover output and update the error code if needed */ + if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) + err = 1; + return err; +} + +#ifdef TEST +/* Example of how to use blast() */ +#include +#include + +#define CHUNK 16384 + +local unsigned inf(void *how, unsigned char **buf) +{ + static unsigned char hold[CHUNK]; + + *buf = hold; + return fread(hold, 1, CHUNK, (FILE *)how); +} + +local int outf(void *how, unsigned char *buf, unsigned len) +{ + return fwrite(buf, 1, len, (FILE *)how) != len; +} + +/* Decompress a PKWare Compression Library stream from stdin to stdout */ +int main(void) +{ + int ret; + unsigned left; + + /* decompress to stdout */ + left = 0; + ret = blast(inf, stdin, outf, stdout, &left, NULL); + if (ret != 0) + fprintf(stderr, "blast error: %d\n", ret); + + /* count any leftover bytes */ + while (getchar() != EOF) + left++; + if (left) + fprintf(stderr, "blast warning: %u unused bytes of input\n", left); + + /* return blast() error code */ + return ret; +} +#endif diff --git a/third_party/zlib/v1_2_11/contrib/blast/blast.h b/third_party/zlib/v1_2_11/contrib/blast/blast.h new file mode 100644 index 0000000..6cf65ed --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/blast/blast.h @@ -0,0 +1,83 @@ +/* blast.h -- interface for blast.c + Copyright (C) 2003, 2012, 2013 Mark Adler + version 1.3, 24 Aug 2013 + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Mark Adler madler@alumni.caltech.edu + */ + + +/* + * blast() decompresses the PKWare Data Compression Library (DCL) compressed + * format. It provides the same functionality as the explode() function in + * that library. (Note: PKWare overused the "implode" verb, and the format + * used by their library implode() function is completely different and + * incompatible with the implode compression method supported by PKZIP.) + * + * The binary mode for stdio functions should be used to assure that the + * compressed data is not corrupted when read or written. For example: + * fopen(..., "rb") and fopen(..., "wb"). + */ + + +typedef unsigned (*blast_in)(void *how, unsigned char **buf); +typedef int (*blast_out)(void *how, unsigned char *buf, unsigned len); +/* Definitions for input/output functions passed to blast(). See below for + * what the provided functions need to do. + */ + + +int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow, + unsigned *left, unsigned char **in); +/* Decompress input to output using the provided infun() and outfun() calls. + * On success, the return value of blast() is zero. If there is an error in + * the source data, i.e. it is not in the proper format, then a negative value + * is returned. If there is not enough input available or there is not enough + * output space, then a positive error is returned. + * + * The input function is invoked: len = infun(how, &buf), where buf is set by + * infun() to point to the input buffer, and infun() returns the number of + * available bytes there. If infun() returns zero, then blast() returns with + * an input error. (blast() only asks for input if it needs it.) inhow is for + * use by the application to pass an input descriptor to infun(), if desired. + * + * If left and in are not NULL and *left is not zero when blast() is called, + * then the *left bytes are *in are consumed for input before infun() is used. + * + * The output function is invoked: err = outfun(how, buf, len), where the bytes + * to be written are buf[0..len-1]. If err is not zero, then blast() returns + * with an output error. outfun() is always called with len <= 4096. outhow + * is for use by the application to pass an output descriptor to outfun(), if + * desired. + * + * If there is any unused input, *left is set to the number of bytes that were + * read and *in points to them. Otherwise *left is set to zero and *in is set + * to NULL. If left or in are NULL, then they are not set. + * + * The return codes are: + * + * 2: ran out of input before completing decompression + * 1: output error before completing decompression + * 0: successful decompression + * -1: literal flag not zero or one + * -2: dictionary size not in 4..6 + * -3: distance is too far back + * + * At the bottom of blast.c is an example program that uses blast() that can be + * compiled to produce a command-line decompression filter by defining TEST. + */ diff --git a/third_party/zlib/v1_2_11/contrib/blast/test.pk b/third_party/zlib/v1_2_11/contrib/blast/test.pk new file mode 100644 index 0000000..be10b2b Binary files /dev/null and b/third_party/zlib/v1_2_11/contrib/blast/test.pk differ diff --git a/third_party/zlib/v1_2_11/contrib/blast/test.txt b/third_party/zlib/v1_2_11/contrib/blast/test.txt new file mode 100644 index 0000000..bfdf1c5 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/blast/test.txt @@ -0,0 +1 @@ +AIAIAIAIAIAIA \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/delphi/ZLib.pas b/third_party/zlib/v1_2_11/contrib/delphi/ZLib.pas new file mode 100644 index 0000000..060e199 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/delphi/ZLib.pas @@ -0,0 +1,557 @@ +{*******************************************************} +{ } +{ Borland Delphi Supplemental Components } +{ ZLIB Data Compression Interface Unit } +{ } +{ Copyright (c) 1997,99 Borland Corporation } +{ } +{*******************************************************} + +{ Updated for zlib 1.2.x by Cosmin Truta } + +unit ZLib; + +interface + +uses SysUtils, Classes; + +type + TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl; + TFree = procedure (AppData, Block: Pointer); cdecl; + + // Internal structure. Ignore. + TZStreamRec = packed record + next_in: PChar; // next input byte + avail_in: Integer; // number of bytes available at next_in + total_in: Longint; // total nb of input bytes read so far + + next_out: PChar; // next output byte should be put here + avail_out: Integer; // remaining free space at next_out + total_out: Longint; // total nb of bytes output so far + + msg: PChar; // last error message, NULL if no error + internal: Pointer; // not visible by applications + + zalloc: TAlloc; // used to allocate the internal state + zfree: TFree; // used to free the internal state + AppData: Pointer; // private data object passed to zalloc and zfree + + data_type: Integer; // best guess about the data type: ascii or binary + adler: Longint; // adler32 value of the uncompressed data + reserved: Longint; // reserved for future use + end; + + // Abstract ancestor class + TCustomZlibStream = class(TStream) + private + FStrm: TStream; + FStrmPos: Integer; + FOnProgress: TNotifyEvent; + FZRec: TZStreamRec; + FBuffer: array [Word] of Char; + protected + procedure Progress(Sender: TObject); dynamic; + property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; + constructor Create(Strm: TStream); + end; + +{ TCompressionStream compresses data on the fly as data is written to it, and + stores the compressed data to another stream. + + TCompressionStream is write-only and strictly sequential. Reading from the + stream will raise an exception. Using Seek to move the stream pointer + will raise an exception. + + Output data is cached internally, written to the output stream only when + the internal output buffer is full. All pending output data is flushed + when the stream is destroyed. + + The Position property returns the number of uncompressed bytes of + data that have been written to the stream so far. + + CompressionRate returns the on-the-fly percentage by which the original + data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100 + If raw data size = 100 and compressed data size = 25, the CompressionRate + is 75% + + The OnProgress event is called each time the output buffer is filled and + written to the output stream. This is useful for updating a progress + indicator when you are writing a large chunk of data to the compression + stream in a single call.} + + + TCompressionLevel = (clNone, clFastest, clDefault, clMax); + + TCompressionStream = class(TCustomZlibStream) + private + function GetCompressionRate: Single; + public + constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream); + destructor Destroy; override; + function Read(var Buffer; Count: Longint): Longint; override; + function Write(const Buffer; Count: Longint): Longint; override; + function Seek(Offset: Longint; Origin: Word): Longint; override; + property CompressionRate: Single read GetCompressionRate; + property OnProgress; + end; + +{ TDecompressionStream decompresses data on the fly as data is read from it. + + Compressed data comes from a separate source stream. TDecompressionStream + is read-only and unidirectional; you can seek forward in the stream, but not + backwards. The special case of setting the stream position to zero is + allowed. Seeking forward decompresses data until the requested position in + the uncompressed data has been reached. Seeking backwards, seeking relative + to the end of the stream, requesting the size of the stream, and writing to + the stream will raise an exception. + + The Position property returns the number of bytes of uncompressed data that + have been read from the stream so far. + + The OnProgress event is called each time the internal input buffer of + compressed data is exhausted and the next block is read from the input stream. + This is useful for updating a progress indicator when you are reading a + large chunk of data from the decompression stream in a single call.} + + TDecompressionStream = class(TCustomZlibStream) + public + constructor Create(Source: TStream); + destructor Destroy; override; + function Read(var Buffer; Count: Longint): Longint; override; + function Write(const Buffer; Count: Longint): Longint; override; + function Seek(Offset: Longint; Origin: Word): Longint; override; + property OnProgress; + end; + + + +{ CompressBuf compresses data, buffer to buffer, in one call. + In: InBuf = ptr to compressed data + InBytes = number of bytes in InBuf + Out: OutBuf = ptr to newly allocated buffer containing decompressed data + OutBytes = number of bytes in OutBuf } +procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; + out OutBuf: Pointer; out OutBytes: Integer); + + +{ DecompressBuf decompresses data, buffer to buffer, in one call. + In: InBuf = ptr to compressed data + InBytes = number of bytes in InBuf + OutEstimate = zero, or est. size of the decompressed data + Out: OutBuf = ptr to newly allocated buffer containing decompressed data + OutBytes = number of bytes in OutBuf } +procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; + OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); + +{ DecompressToUserBuf decompresses data, buffer to buffer, in one call. + In: InBuf = ptr to compressed data + InBytes = number of bytes in InBuf + Out: OutBuf = ptr to user-allocated buffer to contain decompressed data + BufSize = number of bytes in OutBuf } +procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; + const OutBuf: Pointer; BufSize: Integer); + +const + zlib_version = '1.2.11'; + +type + EZlibError = class(Exception); + ECompressionError = class(EZlibError); + EDecompressionError = class(EZlibError); + +implementation + +uses ZLibConst; + +const + Z_NO_FLUSH = 0; + Z_PARTIAL_FLUSH = 1; + Z_SYNC_FLUSH = 2; + Z_FULL_FLUSH = 3; + Z_FINISH = 4; + + Z_OK = 0; + Z_STREAM_END = 1; + Z_NEED_DICT = 2; + Z_ERRNO = (-1); + Z_STREAM_ERROR = (-2); + Z_DATA_ERROR = (-3); + Z_MEM_ERROR = (-4); + Z_BUF_ERROR = (-5); + Z_VERSION_ERROR = (-6); + + Z_NO_COMPRESSION = 0; + Z_BEST_SPEED = 1; + Z_BEST_COMPRESSION = 9; + Z_DEFAULT_COMPRESSION = (-1); + + Z_FILTERED = 1; + Z_HUFFMAN_ONLY = 2; + Z_RLE = 3; + Z_DEFAULT_STRATEGY = 0; + + Z_BINARY = 0; + Z_ASCII = 1; + Z_UNKNOWN = 2; + + Z_DEFLATED = 8; + + +{$L adler32.obj} +{$L compress.obj} +{$L crc32.obj} +{$L deflate.obj} +{$L infback.obj} +{$L inffast.obj} +{$L inflate.obj} +{$L inftrees.obj} +{$L trees.obj} +{$L uncompr.obj} +{$L zutil.obj} + +procedure adler32; external; +procedure compressBound; external; +procedure crc32; external; +procedure deflateInit2_; external; +procedure deflateParams; external; + +function _malloc(Size: Integer): Pointer; cdecl; +begin + Result := AllocMem(Size); +end; + +procedure _free(Block: Pointer); cdecl; +begin + FreeMem(Block); +end; + +procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; +begin + FillChar(P^, count, B); +end; + +procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; +begin + Move(source^, dest^, count); +end; + + + +// deflate compresses data +function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar; + recsize: Integer): Integer; external; +function deflate(var strm: TZStreamRec; flush: Integer): Integer; external; +function deflateEnd(var strm: TZStreamRec): Integer; external; + +// inflate decompresses data +function inflateInit_(var strm: TZStreamRec; version: PChar; + recsize: Integer): Integer; external; +function inflate(var strm: TZStreamRec; flush: Integer): Integer; external; +function inflateEnd(var strm: TZStreamRec): Integer; external; +function inflateReset(var strm: TZStreamRec): Integer; external; + + +function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl; +begin +// GetMem(Result, Items*Size); + Result := AllocMem(Items * Size); +end; + +procedure zlibFreeMem(AppData, Block: Pointer); cdecl; +begin + FreeMem(Block); +end; + +{function zlibCheck(code: Integer): Integer; +begin + Result := code; + if code < 0 then + raise EZlibError.Create('error'); //!! +end;} + +function CCheck(code: Integer): Integer; +begin + Result := code; + if code < 0 then + raise ECompressionError.Create('error'); //!! +end; + +function DCheck(code: Integer): Integer; +begin + Result := code; + if code < 0 then + raise EDecompressionError.Create('error'); //!! +end; + +procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; + out OutBuf: Pointer; out OutBytes: Integer); +var + strm: TZStreamRec; + P: Pointer; +begin + FillChar(strm, sizeof(strm), 0); + strm.zalloc := zlibAllocMem; + strm.zfree := zlibFreeMem; + OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255; + GetMem(OutBuf, OutBytes); + try + strm.next_in := InBuf; + strm.avail_in := InBytes; + strm.next_out := OutBuf; + strm.avail_out := OutBytes; + CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm))); + try + while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do + begin + P := OutBuf; + Inc(OutBytes, 256); + ReallocMem(OutBuf, OutBytes); + strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); + strm.avail_out := 256; + end; + finally + CCheck(deflateEnd(strm)); + end; + ReallocMem(OutBuf, strm.total_out); + OutBytes := strm.total_out; + except + FreeMem(OutBuf); + raise + end; +end; + + +procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; + OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); +var + strm: TZStreamRec; + P: Pointer; + BufInc: Integer; +begin + FillChar(strm, sizeof(strm), 0); + strm.zalloc := zlibAllocMem; + strm.zfree := zlibFreeMem; + BufInc := (InBytes + 255) and not 255; + if OutEstimate = 0 then + OutBytes := BufInc + else + OutBytes := OutEstimate; + GetMem(OutBuf, OutBytes); + try + strm.next_in := InBuf; + strm.avail_in := InBytes; + strm.next_out := OutBuf; + strm.avail_out := OutBytes; + DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); + try + while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do + begin + P := OutBuf; + Inc(OutBytes, BufInc); + ReallocMem(OutBuf, OutBytes); + strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); + strm.avail_out := BufInc; + end; + finally + DCheck(inflateEnd(strm)); + end; + ReallocMem(OutBuf, strm.total_out); + OutBytes := strm.total_out; + except + FreeMem(OutBuf); + raise + end; +end; + +procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; + const OutBuf: Pointer; BufSize: Integer); +var + strm: TZStreamRec; +begin + FillChar(strm, sizeof(strm), 0); + strm.zalloc := zlibAllocMem; + strm.zfree := zlibFreeMem; + strm.next_in := InBuf; + strm.avail_in := InBytes; + strm.next_out := OutBuf; + strm.avail_out := BufSize; + DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); + try + if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then + raise EZlibError.CreateRes(@sTargetBufferTooSmall); + finally + DCheck(inflateEnd(strm)); + end; +end; + +// TCustomZlibStream + +constructor TCustomZLibStream.Create(Strm: TStream); +begin + inherited Create; + FStrm := Strm; + FStrmPos := Strm.Position; + FZRec.zalloc := zlibAllocMem; + FZRec.zfree := zlibFreeMem; +end; + +procedure TCustomZLibStream.Progress(Sender: TObject); +begin + if Assigned(FOnProgress) then FOnProgress(Sender); +end; + + +// TCompressionStream + +constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; + Dest: TStream); +const + Levels: array [TCompressionLevel] of ShortInt = + (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); +begin + inherited Create(Dest); + FZRec.next_out := FBuffer; + FZRec.avail_out := sizeof(FBuffer); + CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); +end; + +destructor TCompressionStream.Destroy; +begin + FZRec.next_in := nil; + FZRec.avail_in := 0; + try + if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; + while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) + and (FZRec.avail_out = 0) do + begin + FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); + FZRec.next_out := FBuffer; + FZRec.avail_out := sizeof(FBuffer); + end; + if FZRec.avail_out < sizeof(FBuffer) then + FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); + finally + deflateEnd(FZRec); + end; + inherited Destroy; +end; + +function TCompressionStream.Read(var Buffer; Count: Longint): Longint; +begin + raise ECompressionError.CreateRes(@sInvalidStreamOp); +end; + +function TCompressionStream.Write(const Buffer; Count: Longint): Longint; +begin + FZRec.next_in := @Buffer; + FZRec.avail_in := Count; + if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; + while (FZRec.avail_in > 0) do + begin + CCheck(deflate(FZRec, 0)); + if FZRec.avail_out = 0 then + begin + FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); + FZRec.next_out := FBuffer; + FZRec.avail_out := sizeof(FBuffer); + FStrmPos := FStrm.Position; + Progress(Self); + end; + end; + Result := Count; +end; + +function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; +begin + if (Offset = 0) and (Origin = soFromCurrent) then + Result := FZRec.total_in + else + raise ECompressionError.CreateRes(@sInvalidStreamOp); +end; + +function TCompressionStream.GetCompressionRate: Single; +begin + if FZRec.total_in = 0 then + Result := 0 + else + Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; +end; + + +// TDecompressionStream + +constructor TDecompressionStream.Create(Source: TStream); +begin + inherited Create(Source); + FZRec.next_in := FBuffer; + FZRec.avail_in := 0; + DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); +end; + +destructor TDecompressionStream.Destroy; +begin + FStrm.Seek(-FZRec.avail_in, 1); + inflateEnd(FZRec); + inherited Destroy; +end; + +function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; +begin + FZRec.next_out := @Buffer; + FZRec.avail_out := Count; + if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos; + while (FZRec.avail_out > 0) do + begin + if FZRec.avail_in = 0 then + begin + FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer)); + if FZRec.avail_in = 0 then + begin + Result := Count - FZRec.avail_out; + Exit; + end; + FZRec.next_in := FBuffer; + FStrmPos := FStrm.Position; + Progress(Self); + end; + CCheck(inflate(FZRec, 0)); + end; + Result := Count; +end; + +function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; +begin + raise EDecompressionError.CreateRes(@sInvalidStreamOp); +end; + +function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; +var + I: Integer; + Buf: array [0..4095] of Char; +begin + if (Offset = 0) and (Origin = soFromBeginning) then + begin + DCheck(inflateReset(FZRec)); + FZRec.next_in := FBuffer; + FZRec.avail_in := 0; + FStrm.Position := 0; + FStrmPos := 0; + end + else if ( (Offset >= 0) and (Origin = soFromCurrent)) or + ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then + begin + if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); + if Offset > 0 then + begin + for I := 1 to Offset div sizeof(Buf) do + ReadBuffer(Buf, sizeof(Buf)); + ReadBuffer(Buf, Offset mod sizeof(Buf)); + end; + end + else + raise EDecompressionError.CreateRes(@sInvalidStreamOp); + Result := FZRec.total_out; +end; + + +end. diff --git a/third_party/zlib/v1_2_11/contrib/delphi/ZLibConst.pas b/third_party/zlib/v1_2_11/contrib/delphi/ZLibConst.pas new file mode 100644 index 0000000..cdfe136 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/delphi/ZLibConst.pas @@ -0,0 +1,11 @@ +unit ZLibConst; + +interface + +resourcestring + sTargetBufferTooSmall = 'ZLib error: target buffer may be too small'; + sInvalidStreamOp = 'Invalid stream operation'; + +implementation + +end. diff --git a/third_party/zlib/v1_2_11/contrib/delphi/readme.txt b/third_party/zlib/v1_2_11/contrib/delphi/readme.txt new file mode 100644 index 0000000..2dc9a8b --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/delphi/readme.txt @@ -0,0 +1,76 @@ + +Overview +======== + +This directory contains an update to the ZLib interface unit, +distributed by Borland as a Delphi supplemental component. + +The original ZLib unit is Copyright (c) 1997,99 Borland Corp., +and is based on zlib version 1.0.4. There are a series of bugs +and security problems associated with that old zlib version, and +we recommend the users to update their ZLib unit. + + +Summary of modifications +======================== + +- Improved makefile, adapted to zlib version 1.2.1. + +- Some field types from TZStreamRec are changed from Integer to + Longint, for consistency with the zlib.h header, and for 64-bit + readiness. + +- The zlib_version constant is updated. + +- The new Z_RLE strategy has its corresponding symbolic constant. + +- The allocation and deallocation functions and function types + (TAlloc, TFree, zlibAllocMem and zlibFreeMem) are now cdecl, + and _malloc and _free are added as C RTL stubs. As a result, + the original C sources of zlib can be compiled out of the box, + and linked to the ZLib unit. + + +Suggestions for improvements +============================ + +Currently, the ZLib unit provides only a limited wrapper around +the zlib library, and much of the original zlib functionality is +missing. Handling compressed file formats like ZIP/GZIP or PNG +cannot be implemented without having this functionality. +Applications that handle these formats are either using their own, +duplicated code, or not using the ZLib unit at all. + +Here are a few suggestions: + +- Checksum class wrappers around adler32() and crc32(), similar + to the Java classes that implement the java.util.zip.Checksum + interface. + +- The ability to read and write raw deflate streams, without the + zlib stream header and trailer. Raw deflate streams are used + in the ZIP file format. + +- The ability to read and write gzip streams, used in the GZIP + file format, and normally produced by the gzip program. + +- The ability to select a different compression strategy, useful + to PNG and MNG image compression, and to multimedia compression + in general. Besides the compression level + + TCompressionLevel = (clNone, clFastest, clDefault, clMax); + + which, in fact, could have used the 'z' prefix and avoided + TColor-like symbols + + TCompressionLevel = (zcNone, zcFastest, zcDefault, zcMax); + + there could be a compression strategy + + TCompressionStrategy = (zsDefault, zsFiltered, zsHuffmanOnly, zsRle); + +- ZIP and GZIP stream handling via TStreams. + + +-- +Cosmin Truta diff --git a/third_party/zlib/v1_2_11/contrib/delphi/zlibd32.mak b/third_party/zlib/v1_2_11/contrib/delphi/zlibd32.mak new file mode 100644 index 0000000..9bb00b7 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/delphi/zlibd32.mak @@ -0,0 +1,99 @@ +# Makefile for zlib +# For use with Delphi and C++ Builder under Win32 +# Updated for zlib 1.2.x by Cosmin Truta + +# ------------ Borland C++ ------------ + +# This project uses the Delphi (fastcall/register) calling convention: +LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl + +CC = bcc32 +LD = bcc32 +AR = tlib +# do not use "-pr" in CFLAGS +CFLAGS = -a -d -k- -O2 $(LOC) +LDFLAGS = + + +# variables +ZLIB_LIB = zlib.lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj +OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj +OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(CFLAGS) $*.c + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + +minigzip.obj: test/minigzip.c zlib.h zconf.h + + +# For the sake of the old Borland make, +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) + -del $(ZLIB_LIB) + $(AR) $(ZLIB_LIB) $(OBJP1) + $(AR) $(ZLIB_LIB) $(OBJP2) + + +# testing +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) + + +# cleanup +clean: + -del *.obj + -del *.exe + -del *.lib + -del *.tds + -del zlib.bak + -del foo.gz + diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.build b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.build new file mode 100644 index 0000000..7f90d6b --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.build @@ -0,0 +1,33 @@ + + + A .Net wrapper library around ZLib1.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.chm b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.chm new file mode 100644 index 0000000..f214a44 Binary files /dev/null and b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.chm differ diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.sln b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.sln new file mode 100644 index 0000000..ac45ca0 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 8.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotZLib", "DotZLib\DotZLib.csproj", "{BB1EE0B1-1808-46CB-B786-949D91117FC5}" + ProjectSection(ProjectDependencies) = postProject + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfiguration) = preSolution + Debug = Debug + Release = Release + EndGlobalSection + GlobalSection(ProjectConfiguration) = postSolution + {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.ActiveCfg = Debug|.NET + {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.Build.0 = Debug|.NET + {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.ActiveCfg = Release|.NET + {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.Build.0 = Release|.NET + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + EndGlobalSection + GlobalSection(ExtensibilityAddIns) = postSolution + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/AssemblyInfo.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/AssemblyInfo.cs new file mode 100644 index 0000000..0491bfc --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/AssemblyInfo.cs @@ -0,0 +1,58 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +// +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +// +[assembly: AssemblyTitle("DotZLib")] +[assembly: AssemblyDescription(".Net bindings for ZLib compression dll 1.2.x")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Henrik Ravn")] +[assembly: AssemblyProduct("")] +[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly: AssemblyVersion("1.0.*")] + +// +// In order to sign your assembly you must specify a key to use. Refer to the +// Microsoft .NET Framework documentation for more information on assembly signing. +// +// Use the attributes below to control which key is used for signing. +// +// Notes: +// (*) If no key is specified, the assembly is not signed. +// (*) KeyName refers to a key that has been installed in the Crypto Service +// Provider (CSP) on your machine. KeyFile refers to a file which contains +// a key. +// (*) If the KeyFile and the KeyName values are both specified, the +// following processing occurs: +// (1) If the KeyName can be found in the CSP, that key is used. +// (2) If the KeyName does not exist and the KeyFile does exist, the key +// in the KeyFile is installed into the CSP and used. +// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. +// When specifying the KeyFile, the location of the KeyFile should be +// relative to the project output directory which is +// %Project Directory%\obj\. For example, if your KeyFile is +// located in the project directory, you would specify the AssemblyKeyFile +// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] +// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework +// documentation for more information on this. +// +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile("")] +[assembly: AssemblyKeyName("")] diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/ChecksumImpl.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/ChecksumImpl.cs new file mode 100644 index 0000000..788b2fc --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/ChecksumImpl.cs @@ -0,0 +1,202 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Runtime.InteropServices; +using System.Text; + + +namespace DotZLib +{ + #region ChecksumGeneratorBase + /// + /// Implements the common functionality needed for all s + /// + /// + public abstract class ChecksumGeneratorBase : ChecksumGenerator + { + /// + /// The value of the current checksum + /// + protected uint _current; + + /// + /// Initializes a new instance of the checksum generator base - the current checksum is + /// set to zero + /// + public ChecksumGeneratorBase() + { + _current = 0; + } + + /// + /// Initializes a new instance of the checksum generator basewith a specified value + /// + /// The value to set the current checksum to + public ChecksumGeneratorBase(uint initialValue) + { + _current = initialValue; + } + + /// + /// Resets the current checksum to zero + /// + public void Reset() { _current = 0; } + + /// + /// Gets the current checksum value + /// + public uint Value { get { return _current; } } + + /// + /// Updates the current checksum with part of an array of bytes + /// + /// The data to update the checksum with + /// Where in data to start updating + /// The number of bytes from data to use + /// The sum of offset and count is larger than the length of data + /// data is a null reference + /// Offset or count is negative. + /// All the other Update methods are implmeneted in terms of this one. + /// This is therefore the only method a derived class has to implement + public abstract void Update(byte[] data, int offset, int count); + + /// + /// Updates the current checksum with an array of bytes. + /// + /// The data to update the checksum with + public void Update(byte[] data) + { + Update(data, 0, data.Length); + } + + /// + /// Updates the current checksum with the data from a string + /// + /// The string to update the checksum with + /// The characters in the string are converted by the UTF-8 encoding + public void Update(string data) + { + Update(Encoding.UTF8.GetBytes(data)); + } + + /// + /// Updates the current checksum with the data from a string, using a specific encoding + /// + /// The string to update the checksum with + /// The encoding to use + public void Update(string data, Encoding encoding) + { + Update(encoding.GetBytes(data)); + } + + } + #endregion + + #region CRC32 + /// + /// Implements a CRC32 checksum generator + /// + public sealed class CRC32Checksum : ChecksumGeneratorBase + { + #region DLL imports + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern uint crc32(uint crc, int data, uint length); + + #endregion + + /// + /// Initializes a new instance of the CRC32 checksum generator + /// + public CRC32Checksum() : base() {} + + /// + /// Initializes a new instance of the CRC32 checksum generator with a specified value + /// + /// The value to set the current checksum to + public CRC32Checksum(uint initialValue) : base(initialValue) {} + + /// + /// Updates the current checksum with part of an array of bytes + /// + /// The data to update the checksum with + /// Where in data to start updating + /// The number of bytes from data to use + /// The sum of offset and count is larger than the length of data + /// data is a null reference + /// Offset or count is negative. + public override void Update(byte[] data, int offset, int count) + { + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > data.Length) throw new ArgumentException(); + GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); + try + { + _current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); + } + finally + { + hData.Free(); + } + } + + } + #endregion + + #region Adler + /// + /// Implements a checksum generator that computes the Adler checksum on data + /// + public sealed class AdlerChecksum : ChecksumGeneratorBase + { + #region DLL imports + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern uint adler32(uint adler, int data, uint length); + + #endregion + + /// + /// Initializes a new instance of the Adler checksum generator + /// + public AdlerChecksum() : base() {} + + /// + /// Initializes a new instance of the Adler checksum generator with a specified value + /// + /// The value to set the current checksum to + public AdlerChecksum(uint initialValue) : base(initialValue) {} + + /// + /// Updates the current checksum with part of an array of bytes + /// + /// The data to update the checksum with + /// Where in data to start updating + /// The number of bytes from data to use + /// The sum of offset and count is larger than the length of data + /// data is a null reference + /// Offset or count is negative. + public override void Update(byte[] data, int offset, int count) + { + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > data.Length) throw new ArgumentException(); + GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned); + try + { + _current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count); + } + finally + { + hData.Free(); + } + } + + } + #endregion + +} \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CircularBuffer.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CircularBuffer.cs new file mode 100644 index 0000000..c1cab3a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CircularBuffer.cs @@ -0,0 +1,83 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Diagnostics; + +namespace DotZLib +{ + + /// + /// This class implements a circular buffer + /// + internal class CircularBuffer + { + #region Private data + private int _capacity; + private int _head; + private int _tail; + private int _size; + private byte[] _buffer; + #endregion + + public CircularBuffer(int capacity) + { + Debug.Assert( capacity > 0 ); + _buffer = new byte[capacity]; + _capacity = capacity; + _head = 0; + _tail = 0; + _size = 0; + } + + public int Size { get { return _size; } } + + public int Put(byte[] source, int offset, int count) + { + Debug.Assert( count > 0 ); + int trueCount = Math.Min(count, _capacity - Size); + for (int i = 0; i < trueCount; ++i) + _buffer[(_tail+i) % _capacity] = source[offset+i]; + _tail += trueCount; + _tail %= _capacity; + _size += trueCount; + return trueCount; + } + + public bool Put(byte b) + { + if (Size == _capacity) // no room + return false; + _buffer[_tail++] = b; + _tail %= _capacity; + ++_size; + return true; + } + + public int Get(byte[] destination, int offset, int count) + { + int trueCount = Math.Min(count,Size); + for (int i = 0; i < trueCount; ++i) + destination[offset + i] = _buffer[(_head+i) % _capacity]; + _head += trueCount; + _head %= _capacity; + _size -= trueCount; + return trueCount; + } + + public int Get() + { + if (Size == 0) + return -1; + + int result = (int)_buffer[_head++ % _capacity]; + --_size; + return result; + } + + } +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CodecBase.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CodecBase.cs new file mode 100644 index 0000000..42e6da3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/CodecBase.cs @@ -0,0 +1,198 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Runtime.InteropServices; + +namespace DotZLib +{ + /// + /// Implements the common functionality needed for all s + /// + public abstract class CodecBase : Codec, IDisposable + { + + #region Data members + + /// + /// Instance of the internal zlib buffer structure that is + /// passed to all functions in the zlib dll + /// + internal ZStream _ztream = new ZStream(); + + /// + /// True if the object instance has been disposed, false otherwise + /// + protected bool _isDisposed = false; + + /// + /// The size of the internal buffers + /// + protected const int kBufferSize = 16384; + + private byte[] _outBuffer = new byte[kBufferSize]; + private byte[] _inBuffer = new byte[kBufferSize]; + + private GCHandle _hInput; + private GCHandle _hOutput; + + private uint _checksum = 0; + + #endregion + + /// + /// Initializes a new instance of the CodeBase class. + /// + public CodecBase() + { + try + { + _hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned); + _hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned); + } + catch (Exception) + { + CleanUp(false); + throw; + } + } + + + #region Codec Members + + /// + /// Occurs when more processed data are available. + /// + public event DataAvailableHandler DataAvailable; + + /// + /// Fires the event + /// + protected void OnDataAvailable() + { + if (_ztream.total_out > 0) + { + if (DataAvailable != null) + DataAvailable( _outBuffer, 0, (int)_ztream.total_out); + resetOutput(); + } + } + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// Adding data may, or may not, raise the DataAvailable event + public void Add(byte[] data) + { + Add(data,0,data.Length); + } + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// The index of the first byte to add from data + /// The number of bytes to add + /// Adding data may, or may not, raise the DataAvailable event + /// This must be implemented by a derived class + public abstract void Add(byte[] data, int offset, int count); + + /// + /// Finishes up any pending data that needs to be processed and handled. + /// + /// This must be implemented by a derived class + public abstract void Finish(); + + /// + /// Gets the checksum of the data that has been added so far + /// + public uint Checksum { get { return _checksum; } } + + #endregion + + #region Destructor & IDisposable stuff + + /// + /// Destroys this instance + /// + ~CodecBase() + { + CleanUp(false); + } + + /// + /// Releases any unmanaged resources and calls the method of the derived class + /// + public void Dispose() + { + CleanUp(true); + } + + /// + /// Performs any codec specific cleanup + /// + /// This must be implemented by a derived class + protected abstract void CleanUp(); + + // performs the release of the handles and calls the dereived CleanUp() + private void CleanUp(bool isDisposing) + { + if (!_isDisposed) + { + CleanUp(); + if (_hInput.IsAllocated) + _hInput.Free(); + if (_hOutput.IsAllocated) + _hOutput.Free(); + + _isDisposed = true; + } + } + + + #endregion + + #region Helper methods + + /// + /// Copies a number of bytes to the internal codec buffer - ready for proccesing + /// + /// The byte array that contains the data to copy + /// The index of the first byte to copy + /// The number of bytes to copy from data + protected void copyInput(byte[] data, int startIndex, int count) + { + Array.Copy(data, startIndex, _inBuffer,0, count); + _ztream.next_in = _hInput.AddrOfPinnedObject(); + _ztream.total_in = 0; + _ztream.avail_in = (uint)count; + + } + + /// + /// Resets the internal output buffers to a known state - ready for processing + /// + protected void resetOutput() + { + _ztream.total_out = 0; + _ztream.avail_out = kBufferSize; + _ztream.next_out = _hOutput.AddrOfPinnedObject(); + } + + /// + /// Updates the running checksum property + /// + /// The new checksum value + protected void setChecksum(uint newSum) + { + _checksum = newSum; + } + #endregion + + } +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Deflater.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Deflater.cs new file mode 100644 index 0000000..c247792 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Deflater.cs @@ -0,0 +1,106 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace DotZLib +{ + + /// + /// Implements a data compressor, using the deflate algorithm in the ZLib dll + /// + public sealed class Deflater : CodecBase + { + #region Dll imports + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] + private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int deflate(ref ZStream sz, int flush); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int deflateReset(ref ZStream sz); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int deflateEnd(ref ZStream sz); + #endregion + + /// + /// Constructs an new instance of the Deflater + /// + /// The compression level to use for this Deflater + public Deflater(CompressLevel level) : base() + { + int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream)); + if (retval != 0) + throw new ZLibException(retval, "Could not initialize deflater"); + + resetOutput(); + } + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// The index of the first byte to add from data + /// The number of bytes to add + /// Adding data may, or may not, raise the DataAvailable event + public override void Add(byte[] data, int offset, int count) + { + if (data == null) throw new ArgumentNullException(); + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > data.Length) throw new ArgumentException(); + + int total = count; + int inputIndex = offset; + int err = 0; + + while (err >= 0 && inputIndex < total) + { + copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); + while (err >= 0 && _ztream.avail_in > 0) + { + err = deflate(ref _ztream, (int)FlushTypes.None); + if (err == 0) + while (_ztream.avail_out == 0) + { + OnDataAvailable(); + err = deflate(ref _ztream, (int)FlushTypes.None); + } + inputIndex += (int)_ztream.total_in; + } + } + setChecksum( _ztream.adler ); + } + + + /// + /// Finishes up any pending data that needs to be processed and handled. + /// + public override void Finish() + { + int err; + do + { + err = deflate(ref _ztream, (int)FlushTypes.Finish); + OnDataAvailable(); + } + while (err == 0); + setChecksum( _ztream.adler ); + deflateReset(ref _ztream); + resetOutput(); + } + + /// + /// Closes the internal zlib deflate stream + /// + protected override void CleanUp() { deflateEnd(ref _ztream); } + + } +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.cs new file mode 100644 index 0000000..be184b4 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.cs @@ -0,0 +1,288 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + + +namespace DotZLib +{ + + #region Internal types + + /// + /// Defines constants for the various flush types used with zlib + /// + internal enum FlushTypes + { + None, Partial, Sync, Full, Finish, Block + } + + #region ZStream structure + // internal mapping of the zlib zstream structure for marshalling + [StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)] + internal struct ZStream + { + public IntPtr next_in; + public uint avail_in; + public uint total_in; + + public IntPtr next_out; + public uint avail_out; + public uint total_out; + + [MarshalAs(UnmanagedType.LPStr)] + string msg; + uint state; + + uint zalloc; + uint zfree; + uint opaque; + + int data_type; + public uint adler; + uint reserved; + } + + #endregion + + #endregion + + #region Public enums + /// + /// Defines constants for the available compression levels in zlib + /// + public enum CompressLevel : int + { + /// + /// The default compression level with a reasonable compromise between compression and speed + /// + Default = -1, + /// + /// No compression at all. The data are passed straight through. + /// + None = 0, + /// + /// The maximum compression rate available. + /// + Best = 9, + /// + /// The fastest available compression level. + /// + Fastest = 1 + } + #endregion + + #region Exception classes + /// + /// The exception that is thrown when an error occurs on the zlib dll + /// + public class ZLibException : ApplicationException + { + /// + /// Initializes a new instance of the class with a specified + /// error message and error code + /// + /// The zlib error code that caused the exception + /// A message that (hopefully) describes the error + public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg)) + { + } + + /// + /// Initializes a new instance of the class with a specified + /// error code + /// + /// The zlib error code that caused the exception + public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode)) + { + } + } + #endregion + + #region Interfaces + + /// + /// Declares methods and properties that enables a running checksum to be calculated + /// + public interface ChecksumGenerator + { + /// + /// Gets the current value of the checksum + /// + uint Value { get; } + + /// + /// Clears the current checksum to 0 + /// + void Reset(); + + /// + /// Updates the current checksum with an array of bytes + /// + /// The data to update the checksum with + void Update(byte[] data); + + /// + /// Updates the current checksum with part of an array of bytes + /// + /// The data to update the checksum with + /// Where in data to start updating + /// The number of bytes from data to use + /// The sum of offset and count is larger than the length of data + /// data is a null reference + /// Offset or count is negative. + void Update(byte[] data, int offset, int count); + + /// + /// Updates the current checksum with the data from a string + /// + /// The string to update the checksum with + /// The characters in the string are converted by the UTF-8 encoding + void Update(string data); + + /// + /// Updates the current checksum with the data from a string, using a specific encoding + /// + /// The string to update the checksum with + /// The encoding to use + void Update(string data, Encoding encoding); + } + + + /// + /// Represents the method that will be called from a codec when new data + /// are available. + /// + /// The byte array containing the processed data + /// The index of the first processed byte in data + /// The number of processed bytes available + /// On return from this method, the data may be overwritten, so grab it while you can. + /// You cannot assume that startIndex will be zero. + /// + public delegate void DataAvailableHandler(byte[] data, int startIndex, int count); + + /// + /// Declares methods and events for implementing compressors/decompressors + /// + public interface Codec + { + /// + /// Occurs when more processed data are available. + /// + event DataAvailableHandler DataAvailable; + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// Adding data may, or may not, raise the DataAvailable event + void Add(byte[] data); + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// The index of the first byte to add from data + /// The number of bytes to add + /// Adding data may, or may not, raise the DataAvailable event + void Add(byte[] data, int offset, int count); + + /// + /// Finishes up any pending data that needs to be processed and handled. + /// + void Finish(); + + /// + /// Gets the checksum of the data that has been added so far + /// + uint Checksum { get; } + + + } + + #endregion + + #region Classes + /// + /// Encapsulates general information about the ZLib library + /// + public class Info + { + #region DLL imports + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern uint zlibCompileFlags(); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern string zlibVersion(); + #endregion + + #region Private stuff + private uint _flags; + + // helper function that unpacks a bitsize mask + private static int bitSize(uint bits) + { + switch (bits) + { + case 0: return 16; + case 1: return 32; + case 2: return 64; + } + return -1; + } + #endregion + + /// + /// Constructs an instance of the Info class. + /// + public Info() + { + _flags = zlibCompileFlags(); + } + + /// + /// True if the library is compiled with debug info + /// + public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } } + + /// + /// True if the library is compiled with assembly optimizations + /// + public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } } + + /// + /// Gets the size of the unsigned int that was compiled into Zlib + /// + public int SizeOfUInt { get { return bitSize(_flags & 3); } } + + /// + /// Gets the size of the unsigned long that was compiled into Zlib + /// + public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } } + + /// + /// Gets the size of the pointers that were compiled into Zlib + /// + public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } } + + /// + /// Gets the size of the z_off_t type that was compiled into Zlib + /// + public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } } + + /// + /// Gets the version of ZLib as a string, e.g. "1.2.1" + /// + public static string Version { get { return zlibVersion(); } } + } + + #endregion + +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.csproj b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.csproj new file mode 100644 index 0000000..71eeb85 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/DotZLib.csproj @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/GZipStream.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/GZipStream.cs new file mode 100644 index 0000000..b161300 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/GZipStream.cs @@ -0,0 +1,301 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace DotZLib +{ + /// + /// Implements a compressed , in GZip (.gz) format. + /// + public class GZipStream : Stream, IDisposable + { + #region Dll Imports + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] + private static extern IntPtr gzopen(string name, string mode); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int gzclose(IntPtr gzFile); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int gzwrite(IntPtr gzFile, int data, int length); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int gzread(IntPtr gzFile, int data, int length); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int gzgetc(IntPtr gzFile); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int gzputc(IntPtr gzFile, int c); + + #endregion + + #region Private data + private IntPtr _gzFile; + private bool _isDisposed = false; + private bool _isWriting; + #endregion + + #region Constructors + /// + /// Creates a new file as a writeable GZipStream + /// + /// The name of the compressed file to create + /// The compression level to use when adding data + /// If an error occurred in the internal zlib function + public GZipStream(string fileName, CompressLevel level) + { + _isWriting = true; + _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level)); + if (_gzFile == IntPtr.Zero) + throw new ZLibException(-1, "Could not open " + fileName); + } + + /// + /// Opens an existing file as a readable GZipStream + /// + /// The name of the file to open + /// If an error occurred in the internal zlib function + public GZipStream(string fileName) + { + _isWriting = false; + _gzFile = gzopen(fileName, "rb"); + if (_gzFile == IntPtr.Zero) + throw new ZLibException(-1, "Could not open " + fileName); + + } + #endregion + + #region Access properties + /// + /// Returns true of this stream can be read from, false otherwise + /// + public override bool CanRead + { + get + { + return !_isWriting; + } + } + + + /// + /// Returns false. + /// + public override bool CanSeek + { + get + { + return false; + } + } + + /// + /// Returns true if this tsream is writeable, false otherwise + /// + public override bool CanWrite + { + get + { + return _isWriting; + } + } + #endregion + + #region Destructor & IDispose stuff + + /// + /// Destroys this instance + /// + ~GZipStream() + { + cleanUp(false); + } + + /// + /// Closes the external file handle + /// + public void Dispose() + { + cleanUp(true); + } + + // Does the actual closing of the file handle. + private void cleanUp(bool isDisposing) + { + if (!_isDisposed) + { + gzclose(_gzFile); + _isDisposed = true; + } + } + #endregion + + #region Basic reading and writing + /// + /// Attempts to read a number of bytes from the stream. + /// + /// The destination data buffer + /// The index of the first destination byte in buffer + /// The number of bytes requested + /// The number of bytes read + /// If buffer is null + /// If count or offset are negative + /// If offset + count is > buffer.Length + /// If this stream is not readable. + /// If this stream has been disposed. + public override int Read(byte[] buffer, int offset, int count) + { + if (!CanRead) throw new NotSupportedException(); + if (buffer == null) throw new ArgumentNullException(); + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > buffer.Length) throw new ArgumentException(); + if (_isDisposed) throw new ObjectDisposedException("GZipStream"); + + GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); + int result; + try + { + result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); + if (result < 0) + throw new IOException(); + } + finally + { + h.Free(); + } + return result; + } + + /// + /// Attempts to read a single byte from the stream. + /// + /// The byte that was read, or -1 in case of error or End-Of-File + public override int ReadByte() + { + if (!CanRead) throw new NotSupportedException(); + if (_isDisposed) throw new ObjectDisposedException("GZipStream"); + return gzgetc(_gzFile); + } + + /// + /// Writes a number of bytes to the stream + /// + /// + /// + /// + /// If buffer is null + /// If count or offset are negative + /// If offset + count is > buffer.Length + /// If this stream is not writeable. + /// If this stream has been disposed. + public override void Write(byte[] buffer, int offset, int count) + { + if (!CanWrite) throw new NotSupportedException(); + if (buffer == null) throw new ArgumentNullException(); + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > buffer.Length) throw new ArgumentException(); + if (_isDisposed) throw new ObjectDisposedException("GZipStream"); + + GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned); + try + { + int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count); + if (result < 0) + throw new IOException(); + } + finally + { + h.Free(); + } + } + + /// + /// Writes a single byte to the stream + /// + /// The byte to add to the stream. + /// If this stream is not writeable. + /// If this stream has been disposed. + public override void WriteByte(byte value) + { + if (!CanWrite) throw new NotSupportedException(); + if (_isDisposed) throw new ObjectDisposedException("GZipStream"); + + int result = gzputc(_gzFile, (int)value); + if (result < 0) + throw new IOException(); + } + #endregion + + #region Position & length stuff + /// + /// Not supported. + /// + /// + /// Always thrown + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + /// + /// Not suppported. + /// + /// + /// + /// + /// Always thrown + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + /// + /// Flushes the GZipStream. + /// + /// In this implementation, this method does nothing. This is because excessive + /// flushing may degrade the achievable compression rates. + public override void Flush() + { + // left empty on purpose + } + + /// + /// Gets/sets the current position in the GZipStream. Not suppported. + /// + /// In this implementation this property is not supported + /// Always thrown + public override long Position + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + + /// + /// Gets the size of the stream. Not suppported. + /// + /// In this implementation this property is not supported + /// Always thrown + public override long Length + { + get + { + throw new NotSupportedException(); + } + } + #endregion + } +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Inflater.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Inflater.cs new file mode 100644 index 0000000..8ed5451 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/Inflater.cs @@ -0,0 +1,105 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace DotZLib +{ + + /// + /// Implements a data decompressor, using the inflate algorithm in the ZLib dll + /// + public class Inflater : CodecBase + { + #region Dll imports + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] + private static extern int inflateInit_(ref ZStream sz, string vs, int size); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int inflate(ref ZStream sz, int flush); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int inflateReset(ref ZStream sz); + + [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)] + private static extern int inflateEnd(ref ZStream sz); + #endregion + + /// + /// Constructs an new instance of the Inflater + /// + public Inflater() : base() + { + int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream)); + if (retval != 0) + throw new ZLibException(retval, "Could not initialize inflater"); + + resetOutput(); + } + + + /// + /// Adds more data to the codec to be processed. + /// + /// Byte array containing the data to be added to the codec + /// The index of the first byte to add from data + /// The number of bytes to add + /// Adding data may, or may not, raise the DataAvailable event + public override void Add(byte[] data, int offset, int count) + { + if (data == null) throw new ArgumentNullException(); + if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); + if ((offset+count) > data.Length) throw new ArgumentException(); + + int total = count; + int inputIndex = offset; + int err = 0; + + while (err >= 0 && inputIndex < total) + { + copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize)); + err = inflate(ref _ztream, (int)FlushTypes.None); + if (err == 0) + while (_ztream.avail_out == 0) + { + OnDataAvailable(); + err = inflate(ref _ztream, (int)FlushTypes.None); + } + + inputIndex += (int)_ztream.total_in; + } + setChecksum( _ztream.adler ); + } + + + /// + /// Finishes up any pending data that needs to be processed and handled. + /// + public override void Finish() + { + int err; + do + { + err = inflate(ref _ztream, (int)FlushTypes.Finish); + OnDataAvailable(); + } + while (err == 0); + setChecksum( _ztream.adler ); + inflateReset(ref _ztream); + resetOutput(); + } + + /// + /// Closes the internal zlib inflate stream + /// + protected override void CleanUp() { inflateEnd(ref _ztream); } + + + } +} diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/UnitTests.cs b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/UnitTests.cs new file mode 100644 index 0000000..44f7633 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/DotZLib/UnitTests.cs @@ -0,0 +1,274 @@ +// +// © Copyright Henrik Ravn 2004 +// +// Use, modification and distribution are subject to the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +using System; +using System.Collections; +using System.IO; + +// uncomment the define below to include unit tests +//#define nunit +#if nunit +using NUnit.Framework; + +// Unit tests for the DotZLib class library +// ---------------------------------------- +// +// Use this with NUnit 2 from http://www.nunit.org +// + +namespace DotZLibTests +{ + using DotZLib; + + // helper methods + internal class Utils + { + public static bool byteArrEqual( byte[] lhs, byte[] rhs ) + { + if (lhs.Length != rhs.Length) + return false; + for (int i = lhs.Length-1; i >= 0; --i) + if (lhs[i] != rhs[i]) + return false; + return true; + } + + } + + + [TestFixture] + public class CircBufferTests + { + #region Circular buffer tests + [Test] + public void SinglePutGet() + { + CircularBuffer buf = new CircularBuffer(10); + Assert.AreEqual( 0, buf.Size ); + Assert.AreEqual( -1, buf.Get() ); + + Assert.IsTrue(buf.Put( 1 )); + Assert.AreEqual( 1, buf.Size ); + Assert.AreEqual( 1, buf.Get() ); + Assert.AreEqual( 0, buf.Size ); + Assert.AreEqual( -1, buf.Get() ); + } + + [Test] + public void BlockPutGet() + { + CircularBuffer buf = new CircularBuffer(10); + byte[] arr = {1,2,3,4,5,6,7,8,9,10}; + Assert.AreEqual( 10, buf.Put(arr,0,10) ); + Assert.AreEqual( 10, buf.Size ); + Assert.IsFalse( buf.Put(11) ); + Assert.AreEqual( 1, buf.Get() ); + Assert.IsTrue( buf.Put(11) ); + + byte[] arr2 = (byte[])arr.Clone(); + Assert.AreEqual( 9, buf.Get(arr2,1,9) ); + Assert.IsTrue( Utils.byteArrEqual(arr,arr2) ); + } + + #endregion + } + + [TestFixture] + public class ChecksumTests + { + #region CRC32 Tests + [Test] + public void CRC32_Null() + { + CRC32Checksum crc32 = new CRC32Checksum(); + Assert.AreEqual( 0, crc32.Value ); + + crc32 = new CRC32Checksum(1); + Assert.AreEqual( 1, crc32.Value ); + + crc32 = new CRC32Checksum(556); + Assert.AreEqual( 556, crc32.Value ); + } + + [Test] + public void CRC32_Data() + { + CRC32Checksum crc32 = new CRC32Checksum(); + byte[] data = { 1,2,3,4,5,6,7 }; + crc32.Update(data); + Assert.AreEqual( 0x70e46888, crc32.Value ); + + crc32 = new CRC32Checksum(); + crc32.Update("penguin"); + Assert.AreEqual( 0x0e5c1a120, crc32.Value ); + + crc32 = new CRC32Checksum(1); + crc32.Update("penguin"); + Assert.AreEqual(0x43b6aa94, crc32.Value); + + } + #endregion + + #region Adler tests + + [Test] + public void Adler_Null() + { + AdlerChecksum adler = new AdlerChecksum(); + Assert.AreEqual(0, adler.Value); + + adler = new AdlerChecksum(1); + Assert.AreEqual( 1, adler.Value ); + + adler = new AdlerChecksum(556); + Assert.AreEqual( 556, adler.Value ); + } + + [Test] + public void Adler_Data() + { + AdlerChecksum adler = new AdlerChecksum(1); + byte[] data = { 1,2,3,4,5,6,7 }; + adler.Update(data); + Assert.AreEqual( 0x5b001d, adler.Value ); + + adler = new AdlerChecksum(); + adler.Update("penguin"); + Assert.AreEqual(0x0bcf02f6, adler.Value ); + + adler = new AdlerChecksum(1); + adler.Update("penguin"); + Assert.AreEqual(0x0bd602f7, adler.Value); + + } + #endregion + } + + [TestFixture] + public class InfoTests + { + #region Info tests + [Test] + public void Info_Version() + { + Info info = new Info(); + Assert.AreEqual("1.2.11", Info.Version); + Assert.AreEqual(32, info.SizeOfUInt); + Assert.AreEqual(32, info.SizeOfULong); + Assert.AreEqual(32, info.SizeOfPointer); + Assert.AreEqual(32, info.SizeOfOffset); + } + #endregion + } + + [TestFixture] + public class DeflateInflateTests + { + #region Deflate tests + [Test] + public void Deflate_Init() + { + using (Deflater def = new Deflater(CompressLevel.Default)) + { + } + } + + private ArrayList compressedData = new ArrayList(); + private uint adler1; + + private ArrayList uncompressedData = new ArrayList(); + private uint adler2; + + public void CDataAvail(byte[] data, int startIndex, int count) + { + for (int i = 0; i < count; ++i) + compressedData.Add(data[i+startIndex]); + } + + [Test] + public void Deflate_Compress() + { + compressedData.Clear(); + + byte[] testData = new byte[35000]; + for (int i = 0; i < testData.Length; ++i) + testData[i] = 5; + + using (Deflater def = new Deflater((CompressLevel)5)) + { + def.DataAvailable += new DataAvailableHandler(CDataAvail); + def.Add(testData); + def.Finish(); + adler1 = def.Checksum; + } + } + #endregion + + #region Inflate tests + [Test] + public void Inflate_Init() + { + using (Inflater inf = new Inflater()) + { + } + } + + private void DDataAvail(byte[] data, int startIndex, int count) + { + for (int i = 0; i < count; ++i) + uncompressedData.Add(data[i+startIndex]); + } + + [Test] + public void Inflate_Expand() + { + uncompressedData.Clear(); + + using (Inflater inf = new Inflater()) + { + inf.DataAvailable += new DataAvailableHandler(DDataAvail); + inf.Add((byte[])compressedData.ToArray(typeof(byte))); + inf.Finish(); + adler2 = inf.Checksum; + } + Assert.AreEqual( adler1, adler2 ); + } + #endregion + } + + [TestFixture] + public class GZipStreamTests + { + #region GZipStream test + [Test] + public void GZipStream_WriteRead() + { + using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best)) + { + BinaryWriter writer = new BinaryWriter(gzOut); + writer.Write("hi there"); + writer.Write(Math.PI); + writer.Write(42); + } + + using (GZipStream gzIn = new GZipStream("gzstream.gz")) + { + BinaryReader reader = new BinaryReader(gzIn); + string s = reader.ReadString(); + Assert.AreEqual("hi there",s); + double d = reader.ReadDouble(); + Assert.AreEqual(Math.PI, d); + int i = reader.ReadInt32(); + Assert.AreEqual(42,i); + } + + } + #endregion + } +} + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/LICENSE_1_0.txt b/third_party/zlib/v1_2_11/contrib/dotzlib/LICENSE_1_0.txt new file mode 100644 index 0000000..30aac2c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/LICENSE_1_0.txt @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/dotzlib/readme.txt b/third_party/zlib/v1_2_11/contrib/dotzlib/readme.txt new file mode 100644 index 0000000..b239572 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/dotzlib/readme.txt @@ -0,0 +1,58 @@ +This directory contains a .Net wrapper class library for the ZLib1.dll + +The wrapper includes support for inflating/deflating memory buffers, +.Net streaming wrappers for the gz streams part of zlib, and wrappers +for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples. + +Directory structure: +-------------------- + +LICENSE_1_0.txt - License file. +readme.txt - This file. +DotZLib.chm - Class library documentation +DotZLib.build - NAnt build file +DotZLib.sln - Microsoft Visual Studio 2003 solution file + +DotZLib\*.cs - Source files for the class library + +Unit tests: +----------- +The file DotZLib/UnitTests.cs contains unit tests for use with NUnit 2.1 or higher. +To include unit tests in the build, define nunit before building. + + +Build instructions: +------------------- + +1. Using Visual Studio.Net 2003: + Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll) + will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on + you are building the release or debug version of the library. Check + DotZLib/UnitTests.cs for instructions on how to include unit tests in the + build. + +2. Using NAnt: + Open a command prompt with access to the build environment and run nant + in the same directory as the DotZLib.build file. + You can define 2 properties on the nant command-line to control the build: + debug={true|false} to toggle between release/debug builds (default=true). + nunit={true|false} to include or esclude unit tests (default=true). + Also the target clean will remove binaries. + Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release + or ./DotZLib/bin/debug, depending on whether you are building the release + or debug version of the library. + + Examples: + nant -D:debug=false -D:nunit=false + will build a release mode version of the library without unit tests. + nant + will build a debug version of the library with unit tests + nant clean + will remove all previously built files. + + +--------------------------------- +Copyright (c) Henrik Ravn 2004 + +Use, modification and distribution are subject to the Boost Software License, Version 1.0. +(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) diff --git a/third_party/zlib/v1_2_11/contrib/gcc_gvmat64/gvmat64.S b/third_party/zlib/v1_2_11/contrib/gcc_gvmat64/gvmat64.S new file mode 100644 index 0000000..dd858dd --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/gcc_gvmat64/gvmat64.S @@ -0,0 +1,574 @@ +/* +;uInt longest_match_x64( +; deflate_state *s, +; IPos cur_match); // current match + +; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64 +; (AMD64 on Athlon 64, Opteron, Phenom +; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) +; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode) +; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. +; +; File written by Gilles Vollant, by converting to assembly the longest_match +; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. +; and by taking inspiration on asm686 with masm, optimised assembly code +; from Brian Raiter, written 1998 +; +; This software is provided 'as-is', without any express or implied +; warranty. In no event will the authors be held liable for any damages +; arising from the use of this software. +; +; Permission is granted to anyone to use this software for any purpose, +; including commercial applications, and to alter it and redistribute it +; freely, subject to the following restrictions: +; +; 1. The origin of this software must not be misrepresented; you must not +; claim that you wrote the original software. If you use this software +; in a product, an acknowledgment in the product documentation would be +; appreciated but is not required. +; 2. Altered source versions must be plainly marked as such, and must not be +; misrepresented as being the original software +; 3. This notice may not be removed or altered from any source distribution. +; +; http://www.zlib.net +; http://www.winimage.com/zLibDll +; http://www.muppetlabs.com/~breadbox/software/assembly.html +; +; to compile this file for zLib, I use option: +; gcc -c -arch x86_64 gvmat64.S + + +;uInt longest_match(s, cur_match) +; deflate_state *s; +; IPos cur_match; // current match / +; +; with XCode for Mac, I had strange error with some jump on intel syntax +; this is why BEFORE_JMP and AFTER_JMP are used + */ + + +#define BEFORE_JMP .att_syntax +#define AFTER_JMP .intel_syntax noprefix + +#ifndef NO_UNDERLINE +# define match_init _match_init +# define longest_match _longest_match +#endif + +.intel_syntax noprefix + +.globl match_init, longest_match +.text +longest_match: + + + +#define LocalVarsSize 96 +/* +; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 +; free register : r14,r15 +; register can be saved : rsp +*/ + +#define chainlenwmask (rsp + 8 - LocalVarsSize) +#define nicematch (rsp + 16 - LocalVarsSize) + +#define save_rdi (rsp + 24 - LocalVarsSize) +#define save_rsi (rsp + 32 - LocalVarsSize) +#define save_rbx (rsp + 40 - LocalVarsSize) +#define save_rbp (rsp + 48 - LocalVarsSize) +#define save_r12 (rsp + 56 - LocalVarsSize) +#define save_r13 (rsp + 64 - LocalVarsSize) +#define save_r14 (rsp + 72 - LocalVarsSize) +#define save_r15 (rsp + 80 - LocalVarsSize) + + +/* +; all the +4 offsets are due to the addition of pending_buf_size (in zlib +; in the deflate_state structure since the asm code was first written +; (if you compile with zlib 1.0.4 or older, remove the +4). +; Note : these value are good with a 8 bytes boundary pack structure +*/ + +#define MAX_MATCH 258 +#define MIN_MATCH 3 +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) + +/* +;;; Offsets for fields in the deflate_state structure. These numbers +;;; are calculated from the definition of deflate_state, with the +;;; assumption that the compiler will dword-align the fields. (Thus, +;;; changing the definition of deflate_state could easily cause this +;;; program to crash horribly, without so much as a warning at +;;; compile time. Sigh.) + +; all the +zlib1222add offsets are due to the addition of fields +; in zlib in the deflate_state structure since the asm code was first written +; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). +; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). +; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). +*/ + + + +/* you can check the structure offset by running + +#include +#include +#include "deflate.h" + +void print_depl() +{ +deflate_state ds; +deflate_state *s=&ds; +printf("size pointer=%u\n",(int)sizeof(void*)); + +printf("#define dsWSize %u\n",(int)(((char*)&(s->w_size))-((char*)s))); +printf("#define dsWMask %u\n",(int)(((char*)&(s->w_mask))-((char*)s))); +printf("#define dsWindow %u\n",(int)(((char*)&(s->window))-((char*)s))); +printf("#define dsPrev %u\n",(int)(((char*)&(s->prev))-((char*)s))); +printf("#define dsMatchLen %u\n",(int)(((char*)&(s->match_length))-((char*)s))); +printf("#define dsPrevMatch %u\n",(int)(((char*)&(s->prev_match))-((char*)s))); +printf("#define dsStrStart %u\n",(int)(((char*)&(s->strstart))-((char*)s))); +printf("#define dsMatchStart %u\n",(int)(((char*)&(s->match_start))-((char*)s))); +printf("#define dsLookahead %u\n",(int)(((char*)&(s->lookahead))-((char*)s))); +printf("#define dsPrevLen %u\n",(int)(((char*)&(s->prev_length))-((char*)s))); +printf("#define dsMaxChainLen %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s))); +printf("#define dsGoodMatch %u\n",(int)(((char*)&(s->good_match))-((char*)s))); +printf("#define dsNiceMatch %u\n",(int)(((char*)&(s->nice_match))-((char*)s))); +} +*/ + +#define dsWSize 68 +#define dsWMask 76 +#define dsWindow 80 +#define dsPrev 96 +#define dsMatchLen 144 +#define dsPrevMatch 148 +#define dsStrStart 156 +#define dsMatchStart 160 +#define dsLookahead 164 +#define dsPrevLen 168 +#define dsMaxChainLen 172 +#define dsGoodMatch 188 +#define dsNiceMatch 192 + +#define window_size [ rcx + dsWSize] +#define WMask [ rcx + dsWMask] +#define window_ad [ rcx + dsWindow] +#define prev_ad [ rcx + dsPrev] +#define strstart [ rcx + dsStrStart] +#define match_start [ rcx + dsMatchStart] +#define Lookahead [ rcx + dsLookahead] //; 0ffffffffh on infozip +#define prev_length [ rcx + dsPrevLen] +#define max_chain_length [ rcx + dsMaxChainLen] +#define good_match [ rcx + dsGoodMatch] +#define nice_match [ rcx + dsNiceMatch] + +/* +; windows: +; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match) + +; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and +; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp +; +; All registers must be preserved across the call, except for +; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. + +; +; gcc on macosx-linux: +; see http://www.x86-64.org/documentation/abi-0.99.pdf +; param 1 in rdi, param 2 in rsi +; rbx, rsp, rbp, r12 to r15 must be preserved + +;;; Save registers that the compiler may be using, and adjust esp to +;;; make room for our stack frame. + + +;;; Retrieve the function arguments. r8d will hold cur_match +;;; throughout the entire function. edx will hold the pointer to the +;;; deflate_state structure during the function's setup (before +;;; entering the main loop. + +; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) +; mac: param 1 in rdi, param 2 rsi +; this clear high 32 bits of r8, which can be garbage in both r8 and rdx +*/ + mov [save_rbx],rbx + mov [save_rbp],rbp + + + mov rcx,rdi + + mov r8d,esi + + + mov [save_r12],r12 + mov [save_r13],r13 + mov [save_r14],r14 + mov [save_r15],r15 + + +//;;; uInt wmask = s->w_mask; +//;;; unsigned chain_length = s->max_chain_length; +//;;; if (s->prev_length >= s->good_match) { +//;;; chain_length >>= 2; +//;;; } + + + mov edi, prev_length + mov esi, good_match + mov eax, WMask + mov ebx, max_chain_length + cmp edi, esi + jl LastMatchGood + shr ebx, 2 +LastMatchGood: + +//;;; chainlen is decremented once beforehand so that the function can +//;;; use the sign flag instead of the zero flag for the exit test. +//;;; It is then shifted into the high word, to make room for the wmask +//;;; value, which it will always accompany. + + dec ebx + shl ebx, 16 + or ebx, eax + +//;;; on zlib only +//;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + + + mov eax, nice_match + mov [chainlenwmask], ebx + mov r10d, Lookahead + cmp r10d, eax + cmovnl r10d, eax + mov [nicematch],r10d + + + +//;;; register Bytef *scan = s->window + s->strstart; + mov r10, window_ad + mov ebp, strstart + lea r13, [r10 + rbp] + +//;;; Determine how many bytes the scan ptr is off from being +//;;; dword-aligned. + + mov r9,r13 + neg r13 + and r13,3 + +//;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? +//;;; s->strstart - (IPos)MAX_DIST(s) : NIL; + + + mov eax, window_size + sub eax, MIN_LOOKAHEAD + + + xor edi,edi + sub ebp, eax + + mov r11d, prev_length + + cmovng ebp,edi + +//;;; int best_len = s->prev_length; + + +//;;; Store the sum of s->window + best_len in esi locally, and in esi. + + lea rsi,[r10+r11] + +//;;; register ush scan_start = *(ushf*)scan; +//;;; register ush scan_end = *(ushf*)(scan+best_len-1); +//;;; Posf *prev = s->prev; + + movzx r12d,word ptr [r9] + movzx ebx, word ptr [r9 + r11 - 1] + + mov rdi, prev_ad + +//;;; Jump into the main loop. + + mov edx, [chainlenwmask] + + cmp bx,word ptr [rsi + r8 - 1] + jz LookupLoopIsZero + + + +LookupLoop1: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + jbe LeaveNow + + + + sub edx, 0x00010000 + BEFORE_JMP + js LeaveNow + AFTER_JMP + +LoopEntry1: + cmp bx,word ptr [rsi + r8 - 1] + BEFORE_JMP + jz LookupLoopIsZero + AFTER_JMP + +LookupLoop2: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + BEFORE_JMP + jbe LeaveNow + AFTER_JMP + sub edx, 0x00010000 + BEFORE_JMP + js LeaveNow + AFTER_JMP + +LoopEntry2: + cmp bx,word ptr [rsi + r8 - 1] + BEFORE_JMP + jz LookupLoopIsZero + AFTER_JMP + +LookupLoop4: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + BEFORE_JMP + jbe LeaveNow + AFTER_JMP + sub edx, 0x00010000 + BEFORE_JMP + js LeaveNow + AFTER_JMP + +LoopEntry4: + + cmp bx,word ptr [rsi + r8 - 1] + BEFORE_JMP + jnz LookupLoop1 + jmp LookupLoopIsZero + AFTER_JMP +/* +;;; do { +;;; match = s->window + cur_match; +;;; if (*(ushf*)(match+best_len-1) != scan_end || +;;; *(ushf*)match != scan_start) continue; +;;; [...] +;;; } while ((cur_match = prev[cur_match & wmask]) > limit +;;; && --chain_length != 0); +;;; +;;; Here is the inner loop of the function. The function will spend the +;;; majority of its time in this loop, and majority of that time will +;;; be spent in the first ten instructions. +;;; +;;; Within this loop: +;;; ebx = scanend +;;; r8d = curmatch +;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) +;;; esi = windowbestlen - i.e., (window + bestlen) +;;; edi = prev +;;; ebp = limit +*/ +.balign 16 +LookupLoop: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + BEFORE_JMP + jbe LeaveNow + AFTER_JMP + sub edx, 0x00010000 + BEFORE_JMP + js LeaveNow + AFTER_JMP + +LoopEntry: + + cmp bx,word ptr [rsi + r8 - 1] + BEFORE_JMP + jnz LookupLoop1 + AFTER_JMP +LookupLoopIsZero: + cmp r12w, word ptr [r10 + r8] + BEFORE_JMP + jnz LookupLoop1 + AFTER_JMP + + +//;;; Store the current value of chainlen. + mov [chainlenwmask], edx +/* +;;; Point edi to the string under scrutiny, and esi to the string we +;;; are hoping to match it up with. In actuality, esi and edi are +;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is +;;; initialized to -(MAX_MATCH_8 - scanalign). +*/ + lea rsi,[r8+r10] + mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8) + lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8] + lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8] + + prefetcht1 [rsi+rdx] + prefetcht1 [rdi+rdx] + +/* +;;; Test the strings for equality, 8 bytes at a time. At the end, +;;; adjust rdx so that it is offset to the exact byte that mismatched. +;;; +;;; We already know at this point that the first three bytes of the +;;; strings match each other, and they can be safely passed over before +;;; starting the compare loop. So what this code does is skip over 0-3 +;;; bytes, as much as necessary in order to dword-align the edi +;;; pointer. (rsi will still be misaligned three times out of four.) +;;; +;;; It should be confessed that this loop usually does not represent +;;; much of the total running time. Replacing it with a more +;;; straightforward "rep cmpsb" would not drastically degrade +;;; performance. +*/ + +LoopCmps: + mov rax, [rsi + rdx] + xor rax, [rdi + rdx] + jnz LeaveLoopCmps + + mov rax, [rsi + rdx + 8] + xor rax, [rdi + rdx + 8] + jnz LeaveLoopCmps8 + + + mov rax, [rsi + rdx + 8+8] + xor rax, [rdi + rdx + 8+8] + jnz LeaveLoopCmps16 + + add rdx,8+8+8 + + BEFORE_JMP + jnz LoopCmps + jmp LenMaximum + AFTER_JMP + +LeaveLoopCmps16: add rdx,8 +LeaveLoopCmps8: add rdx,8 +LeaveLoopCmps: + + test eax, 0x0000FFFF + jnz LenLower + + test eax,0xffffffff + + jnz LenLower32 + + add rdx,4 + shr rax,32 + or ax,ax + BEFORE_JMP + jnz LenLower + AFTER_JMP + +LenLower32: + shr eax,16 + add rdx,2 + +LenLower: + sub al, 1 + adc rdx, 0 +//;;; Calculate the length of the match. If it is longer than MAX_MATCH, +//;;; then automatically accept it as the best possible match and leave. + + lea rax, [rdi + rdx] + sub rax, r9 + cmp eax, MAX_MATCH + BEFORE_JMP + jge LenMaximum + AFTER_JMP +/* +;;; If the length of the match is not longer than the best match we +;;; have so far, then forget it and return to the lookup loop. +;/////////////////////////////////// +*/ + cmp eax, r11d + jg LongerMatch + + lea rsi,[r10+r11] + + mov rdi, prev_ad + mov edx, [chainlenwmask] + BEFORE_JMP + jmp LookupLoop + AFTER_JMP +/* +;;; s->match_start = cur_match; +;;; best_len = len; +;;; if (len >= nice_match) break; +;;; scan_end = *(ushf*)(scan+best_len-1); +*/ +LongerMatch: + mov r11d, eax + mov match_start, r8d + cmp eax, [nicematch] + BEFORE_JMP + jge LeaveNow + AFTER_JMP + + lea rsi,[r10+rax] + + movzx ebx, word ptr [r9 + rax - 1] + mov rdi, prev_ad + mov edx, [chainlenwmask] + BEFORE_JMP + jmp LookupLoop + AFTER_JMP + +//;;; Accept the current string, with the maximum possible length. + +LenMaximum: + mov r11d,MAX_MATCH + mov match_start, r8d + +//;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; +//;;; return s->lookahead; + +LeaveNow: + mov eax, Lookahead + cmp r11d, eax + cmovng eax, r11d + + + +//;;; Restore the stack and return from whence we came. + + +// mov rsi,[save_rsi] +// mov rdi,[save_rdi] + mov rbx,[save_rbx] + mov rbp,[save_rbp] + mov r12,[save_r12] + mov r13,[save_r13] + mov r14,[save_r14] + mov r15,[save_r15] + + + ret 0 +//; please don't remove this string ! +//; Your can freely use gvmat64 in any free or commercial app +//; but it is far better don't remove the string in the binary! + // db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 + + +match_init: + ret 0 + + diff --git a/third_party/zlib/v1_2_11/contrib/infback9/README b/third_party/zlib/v1_2_11/contrib/infback9/README new file mode 100644 index 0000000..e75ed13 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/README @@ -0,0 +1 @@ +See infback9.h for what this is and how to use it. diff --git a/third_party/zlib/v1_2_11/contrib/infback9/infback9.c b/third_party/zlib/v1_2_11/contrib/infback9/infback9.c new file mode 100644 index 0000000..05fb3e3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/infback9.c @@ -0,0 +1,615 @@ +/* infback9.c -- inflate deflate64 data using a call-back interface + * Copyright (C) 1995-2008 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "infback9.h" +#include "inftree9.h" +#include "inflate9.h" + +#define WSIZE 65536UL + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + window is a user-supplied window and output buffer that is 64K bytes. + */ +int ZEXPORT inflateBack9Init_(strm, window, version, stream_size) +z_stream FAR *strm; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (voidpf)state; + state->window = window; + return Z_OK; +} + +/* + Build and output length and distance decoding tables for fixed code + decoding. + */ +#ifdef MAKEFIXED +#include + +void makefixed9(void) +{ + unsigned sym, bits, low, size; + code *next, *lenfix, *distfix; + struct inflate_state state; + code fixed[544]; + + /* literal/length table */ + sym = 0; + while (sym < 144) state.lens[sym++] = 8; + while (sym < 256) state.lens[sym++] = 9; + while (sym < 280) state.lens[sym++] = 7; + while (sym < 288) state.lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work); + + /* distance table */ + sym = 0; + while (sym < 32) state.lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work); + + /* write tables */ + puts(" /* inffix9.h -- table for decoding deflate64 fixed codes"); + puts(" * Generated automatically by makefixed9()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits, + lenfix[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 5) == 0) printf("\n "); + printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits, + distfix[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* Macros for inflateBack(): */ + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n <= 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = window; \ + left = WSIZE; \ + wrap = 1; \ + if (out(out_desc, put, (unsigned)left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc) +z_stream FAR *strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have; /* available input */ + unsigned long left; /* available output */ + inflate_mode mode; /* current inflate mode */ + int lastblock; /* true if processing last block */ + int wrap; /* true if the window has wrapped */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned extra; /* extra bits needed */ + unsigned long length; /* literal or length of data to copy */ + unsigned long offset; /* distance back to copy string from */ + unsigned long copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; +#include "inffix9.h" + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + mode = TYPE; + lastblock = 0; + wrap = 0; + window = state->window; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = window; + left = WSIZE; + lencode = Z_NULL; + distcode = Z_NULL; + + /* Inflate until end of block marked as last */ + for (;;) + switch (mode) { + case TYPE: + /* determine and dispatch block type */ + if (lastblock) { + BYTEBITS(); + mode = DONE; + break; + } + NEEDBITS(3); + lastblock = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + lastblock ? " (last)" : "")); + mode = STORED; + break; + case 1: /* fixed block */ + lencode = lenfix; + lenbits = 9; + distcode = distfix; + distbits = 5; + Tracev((stderr, "inflate: fixed codes block%s\n", + lastblock ? " (last)" : "")); + mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + lastblock ? " (last)" : "")); + mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + mode = BAD; + break; + } + length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %lu\n", + length)); + INITBITS(); + + /* copy stored block from input to output */ + while (length != 0) { + copy = length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); + if (state->nlen > 286) { + strm->msg = (char *)"too many length symbols"; + mode = BAD; + break; + } + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + lencode = (code const FAR *)(state->next); + lenbits = 7; + ret = inflate_table9(CODES, state->lens, 19, &(state->next), + &(lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = lencode[BITS(lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + NEEDBITS(here.bits); + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftree9.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + lencode = (code const FAR *)(state->next); + lenbits = 9; + ret = inflate_table9(LENS, state->lens, state->nlen, + &(state->next), &(lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + mode = BAD; + break; + } + distcode = (code const FAR *)(state->next); + distbits = 6; + ret = inflate_table9(DISTS, state->lens + state->nlen, + state->ndist, &(state->next), &(distbits), + state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + mode = LEN; + + case LEN: + /* get a literal, length, or end-of-block code */ + for (;;) { + here = lencode[BITS(lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(length); + left--; + mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + extra = (unsigned)(here.op) & 31; + if (extra != 0) { + NEEDBITS(extra); + length += BITS(extra); + DROPBITS(extra); + } + Tracevv((stderr, "inflate: length %lu\n", length)); + + /* get distance code */ + for (;;) { + here = distcode[BITS(distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + mode = BAD; + break; + } + offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + extra = (unsigned)(here.op) & 15; + if (extra != 0) { + NEEDBITS(extra); + offset += BITS(extra); + DROPBITS(extra); + } + if (offset > WSIZE - (wrap ? 0: left)) { + strm->msg = (char *)"invalid distance too far back"; + mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %lu\n", offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = WSIZE - offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - offset; + copy = left; + } + if (copy > length) copy = length; + length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < WSIZE) { + if (out(out_desc, window, (unsigned)(WSIZE - left))) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBack9End(strm) +z_stream FAR *strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/third_party/zlib/v1_2_11/contrib/infback9/infback9.h b/third_party/zlib/v1_2_11/contrib/infback9/infback9.h new file mode 100644 index 0000000..1073c0a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/infback9.h @@ -0,0 +1,37 @@ +/* infback9.h -- header for using inflateBack9 functions + * Copyright (C) 2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * This header file and associated patches provide a decoder for PKWare's + * undocumented deflate64 compression method (method 9). Use with infback9.c, + * inftree9.h, inftree9.c, and inffix9.h. These patches are not supported. + * This should be compiled with zlib, since it uses zutil.h and zutil.o. + * This code has not yet been tested on 16-bit architectures. See the + * comments in zlib.h for inflateBack() usage. These functions are used + * identically, except that there is no windowBits parameter, and a 64K + * window must be provided. Also if int's are 16 bits, then a zero for + * the third parameter of the "out" function actually means 65536UL. + * zlib.h must be included before this header file. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +ZEXTERN int ZEXPORT inflateBack9 OF((z_stream FAR *strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +ZEXTERN int ZEXPORT inflateBack9End OF((z_stream FAR *strm)); +ZEXTERN int ZEXPORT inflateBack9Init_ OF((z_stream FAR *strm, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define inflateBack9Init(strm, window) \ + inflateBack9Init_((strm), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + +#ifdef __cplusplus +} +#endif diff --git a/third_party/zlib/v1_2_11/contrib/infback9/inffix9.h b/third_party/zlib/v1_2_11/contrib/infback9/inffix9.h new file mode 100644 index 0000000..ee5671d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/inffix9.h @@ -0,0 +1,107 @@ + /* inffix9.h -- table for decoding deflate64 fixed codes + * Generated automatically by makefixed9(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{132,8,115},{130,7,31},{0,8,112}, + {0,8,48},{0,9,192},{128,7,10},{0,8,96},{0,8,32},{0,9,160}, + {0,8,0},{0,8,128},{0,8,64},{0,9,224},{128,7,6},{0,8,88}, + {0,8,24},{0,9,144},{131,7,59},{0,8,120},{0,8,56},{0,9,208}, + {129,7,17},{0,8,104},{0,8,40},{0,9,176},{0,8,8},{0,8,136}, + {0,8,72},{0,9,240},{128,7,4},{0,8,84},{0,8,20},{133,8,227}, + {131,7,43},{0,8,116},{0,8,52},{0,9,200},{129,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232}, + {128,7,8},{0,8,92},{0,8,28},{0,9,152},{132,7,83},{0,8,124}, + {0,8,60},{0,9,216},{130,7,23},{0,8,108},{0,8,44},{0,9,184}, + {0,8,12},{0,8,140},{0,8,76},{0,9,248},{128,7,3},{0,8,82}, + {0,8,18},{133,8,163},{131,7,35},{0,8,114},{0,8,50},{0,9,196}, + {129,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},{0,8,130}, + {0,8,66},{0,9,228},{128,7,7},{0,8,90},{0,8,26},{0,9,148}, + {132,7,67},{0,8,122},{0,8,58},{0,9,212},{130,7,19},{0,8,106}, + {0,8,42},{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244}, + {128,7,5},{0,8,86},{0,8,22},{65,8,0},{131,7,51},{0,8,118}, + {0,8,54},{0,9,204},{129,7,15},{0,8,102},{0,8,38},{0,9,172}, + {0,8,6},{0,8,134},{0,8,70},{0,9,236},{128,7,9},{0,8,94}, + {0,8,30},{0,9,156},{132,7,99},{0,8,126},{0,8,62},{0,9,220}, + {130,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{133,8,131}, + {130,7,31},{0,8,113},{0,8,49},{0,9,194},{128,7,10},{0,8,97}, + {0,8,33},{0,9,162},{0,8,1},{0,8,129},{0,8,65},{0,9,226}, + {128,7,6},{0,8,89},{0,8,25},{0,9,146},{131,7,59},{0,8,121}, + {0,8,57},{0,9,210},{129,7,17},{0,8,105},{0,8,41},{0,9,178}, + {0,8,9},{0,8,137},{0,8,73},{0,9,242},{128,7,4},{0,8,85}, + {0,8,21},{144,8,3},{131,7,43},{0,8,117},{0,8,53},{0,9,202}, + {129,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133}, + {0,8,69},{0,9,234},{128,7,8},{0,8,93},{0,8,29},{0,9,154}, + {132,7,83},{0,8,125},{0,8,61},{0,9,218},{130,7,23},{0,8,109}, + {0,8,45},{0,9,186},{0,8,13},{0,8,141},{0,8,77},{0,9,250}, + {128,7,3},{0,8,83},{0,8,19},{133,8,195},{131,7,35},{0,8,115}, + {0,8,51},{0,9,198},{129,7,11},{0,8,99},{0,8,35},{0,9,166}, + {0,8,3},{0,8,131},{0,8,67},{0,9,230},{128,7,7},{0,8,91}, + {0,8,27},{0,9,150},{132,7,67},{0,8,123},{0,8,59},{0,9,214}, + {130,7,19},{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139}, + {0,8,75},{0,9,246},{128,7,5},{0,8,87},{0,8,23},{77,8,0}, + {131,7,51},{0,8,119},{0,8,55},{0,9,206},{129,7,15},{0,8,103}, + {0,8,39},{0,9,174},{0,8,7},{0,8,135},{0,8,71},{0,9,238}, + {128,7,9},{0,8,95},{0,8,31},{0,9,158},{132,7,99},{0,8,127}, + {0,8,63},{0,9,222},{130,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80}, + {0,8,16},{132,8,115},{130,7,31},{0,8,112},{0,8,48},{0,9,193}, + {128,7,10},{0,8,96},{0,8,32},{0,9,161},{0,8,0},{0,8,128}, + {0,8,64},{0,9,225},{128,7,6},{0,8,88},{0,8,24},{0,9,145}, + {131,7,59},{0,8,120},{0,8,56},{0,9,209},{129,7,17},{0,8,104}, + {0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},{0,9,241}, + {128,7,4},{0,8,84},{0,8,20},{133,8,227},{131,7,43},{0,8,116}, + {0,8,52},{0,9,201},{129,7,13},{0,8,100},{0,8,36},{0,9,169}, + {0,8,4},{0,8,132},{0,8,68},{0,9,233},{128,7,8},{0,8,92}, + {0,8,28},{0,9,153},{132,7,83},{0,8,124},{0,8,60},{0,9,217}, + {130,7,23},{0,8,108},{0,8,44},{0,9,185},{0,8,12},{0,8,140}, + {0,8,76},{0,9,249},{128,7,3},{0,8,82},{0,8,18},{133,8,163}, + {131,7,35},{0,8,114},{0,8,50},{0,9,197},{129,7,11},{0,8,98}, + {0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {128,7,7},{0,8,90},{0,8,26},{0,9,149},{132,7,67},{0,8,122}, + {0,8,58},{0,9,213},{130,7,19},{0,8,106},{0,8,42},{0,9,181}, + {0,8,10},{0,8,138},{0,8,74},{0,9,245},{128,7,5},{0,8,86}, + {0,8,22},{65,8,0},{131,7,51},{0,8,118},{0,8,54},{0,9,205}, + {129,7,15},{0,8,102},{0,8,38},{0,9,173},{0,8,6},{0,8,134}, + {0,8,70},{0,9,237},{128,7,9},{0,8,94},{0,8,30},{0,9,157}, + {132,7,99},{0,8,126},{0,8,62},{0,9,221},{130,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253}, + {96,7,0},{0,8,81},{0,8,17},{133,8,131},{130,7,31},{0,8,113}, + {0,8,49},{0,9,195},{128,7,10},{0,8,97},{0,8,33},{0,9,163}, + {0,8,1},{0,8,129},{0,8,65},{0,9,227},{128,7,6},{0,8,89}, + {0,8,25},{0,9,147},{131,7,59},{0,8,121},{0,8,57},{0,9,211}, + {129,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},{0,8,137}, + {0,8,73},{0,9,243},{128,7,4},{0,8,85},{0,8,21},{144,8,3}, + {131,7,43},{0,8,117},{0,8,53},{0,9,203},{129,7,13},{0,8,101}, + {0,8,37},{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235}, + {128,7,8},{0,8,93},{0,8,29},{0,9,155},{132,7,83},{0,8,125}, + {0,8,61},{0,9,219},{130,7,23},{0,8,109},{0,8,45},{0,9,187}, + {0,8,13},{0,8,141},{0,8,77},{0,9,251},{128,7,3},{0,8,83}, + {0,8,19},{133,8,195},{131,7,35},{0,8,115},{0,8,51},{0,9,199}, + {129,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{128,7,7},{0,8,91},{0,8,27},{0,9,151}, + {132,7,67},{0,8,123},{0,8,59},{0,9,215},{130,7,19},{0,8,107}, + {0,8,43},{0,9,183},{0,8,11},{0,8,139},{0,8,75},{0,9,247}, + {128,7,5},{0,8,87},{0,8,23},{77,8,0},{131,7,51},{0,8,119}, + {0,8,55},{0,9,207},{129,7,15},{0,8,103},{0,8,39},{0,9,175}, + {0,8,7},{0,8,135},{0,8,71},{0,9,239},{128,7,9},{0,8,95}, + {0,8,31},{0,9,159},{132,7,99},{0,8,127},{0,8,63},{0,9,223}, + {130,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143}, + {0,8,79},{0,9,255} + }; + + static const code distfix[32] = { + {128,5,1},{135,5,257},{131,5,17},{139,5,4097},{129,5,5}, + {137,5,1025},{133,5,65},{141,5,16385},{128,5,3},{136,5,513}, + {132,5,33},{140,5,8193},{130,5,9},{138,5,2049},{134,5,129}, + {142,5,32769},{128,5,2},{135,5,385},{131,5,25},{139,5,6145}, + {129,5,7},{137,5,1537},{133,5,97},{141,5,24577},{128,5,4}, + {136,5,769},{132,5,49},{140,5,12289},{130,5,13},{138,5,3073}, + {134,5,193},{142,5,49153} + }; diff --git a/third_party/zlib/v1_2_11/contrib/infback9/inflate9.h b/third_party/zlib/v1_2_11/contrib/infback9/inflate9.h new file mode 100644 index 0000000..ee9a793 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/inflate9.h @@ -0,0 +1,47 @@ +/* inflate9.h -- internal inflate state definition + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Possible inflate modes between inflate() calls */ +typedef enum { + TYPE, /* i: waiting for type bits, including last-flag bit */ + STORED, /* i: waiting for stored size (length and complement) */ + TABLE, /* i: waiting for dynamic block table lengths */ + LEN, /* i: waiting for length/lit code */ + DONE, /* finished check, done -- remain here until reset */ + BAD /* got a data error -- remain here until reset */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to the BAD mode -- not shown for clarity) + + Read deflate blocks: + TYPE -> STORED or TABLE or LEN or DONE + STORED -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN + Read deflate codes: + LEN -> LEN or TYPE + */ + +/* state maintained between inflate() calls. Approximately 7K bytes. */ +struct inflate_state { + /* sliding window */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ +}; diff --git a/third_party/zlib/v1_2_11/contrib/infback9/inftree9.c b/third_party/zlib/v1_2_11/contrib/infback9/inftree9.c new file mode 100644 index 0000000..5f4a767 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/inftree9.c @@ -0,0 +1,324 @@ +/* inftree9.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftree9.h" + +#define MAXBITS 15 + +const char inflate9_copyright[] = + " inflate9 1.2.11 Copyright 1995-2017 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int inflate_table9(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code this; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, + 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, + 131, 163, 195, 227, 3, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, + 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132, + 133, 133, 133, 133, 144, 77, 202}; + static const unsigned short dbase[32] = { /* Distance codes 0..31 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, + 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, + 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153}; + static const unsigned short dext[32] = { /* Distance codes 0..31 extra */ + 128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132, + 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, + 139, 139, 140, 140, 141, 141, 142, 142}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) return -1; /* no codes! */ + for (min = 1; min <= MAXBITS; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftree9.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used >= ENOUGH_LENS) || + (type == DISTS && used >= ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + this.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + this.op = (unsigned char)0; + this.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + this.op = (unsigned char)(extra[work[sym]]); + this.val = base[work[sym]]; + } + else { + this.op = (unsigned char)(32 + 64); /* end of block */ + this.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + do { + fill -= incr; + next[(huff >> drop) + fill] = this; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += 1U << curr; + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used >= ENOUGH_LENS) || + (type == DISTS && used >= ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* + Fill in rest of table for incomplete codes. This loop is similar to the + loop above in incrementing huff for table indices. It is assumed that + len is equal to curr + drop, so there is no loop needed to increment + through high index bits. When the current sub-table is filled, the loop + drops back to the root table to fill in any remaining entries there. + */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)(len - drop); + this.val = (unsigned short)0; + while (huff != 0) { + /* when done with sub-table, drop back to root table */ + if (drop != 0 && (huff & mask) != low) { + drop = 0; + len = root; + next = *table; + curr = root; + this.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = this; + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/third_party/zlib/v1_2_11/contrib/infback9/inftree9.h b/third_party/zlib/v1_2_11/contrib/infback9/inftree9.h new file mode 100644 index 0000000..5ab21f0 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/infback9/inftree9.h @@ -0,0 +1,61 @@ +/* inftree9.h -- header to use inftree9.c + * Copyright (C) 1995-2008 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 100eeeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1446, which is the sum of 852 for literal/length codes and 594 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 32 6 15" for distance codes returns 594. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in infback9.c. If the root table size is changed, + then these maximum sizes would be need to be recalculated and updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 594 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table9() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +extern int inflate_table9 OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/third_party/zlib/v1_2_11/contrib/inflate86/inffas86.c b/third_party/zlib/v1_2_11/contrib/inflate86/inffas86.c new file mode 100644 index 0000000..7292f67 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/inflate86/inffas86.c @@ -0,0 +1,1157 @@ +/* inffas86.c is a hand tuned assembler version of + * + * inffast.c -- fast decoding + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Copyright (C) 2003 Chris Anderson + * Please use the copyright conditions above. + * + * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also + * slightly quicker on x86 systems because, instead of using rep movsb to copy + * data, it uses rep movsw, which moves data in 2-byte chunks instead of single + * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates + * from http://fedora.linux.duke.edu/fc1_x86_64 + * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with + * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, + * when decompressing mozilla-source-1.3.tar.gz. + * + * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from + * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at + * the moment. I have successfully compiled and tested this code with gcc2.96, + * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S + * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX + * enabled. I will attempt to merge the MMX code into this version. Newer + * versions of this and inffast.S can be found at + * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* Mark Adler's comments from inffast.c: */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + struct inffast_ar { +/* 64 32 x86 x86_64 */ +/* ar offset register */ +/* 0 0 */ void *esp; /* esp save */ +/* 8 4 */ void *ebp; /* ebp save */ +/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ +/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ +/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ +/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ +/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ +/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ +/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ +/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ +/* 80 40 */ unsigned long hold; /* edx rdx local strm->hold */ +/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ +/* 92 48 */ unsigned wsize; /* window size */ +/* 96 52 */ unsigned write; /* window write index */ +/*100 56 */ unsigned lmask; /* r12 mask for lcode */ +/*104 60 */ unsigned dmask; /* r13 mask for dcode */ +/*108 64 */ unsigned len; /* r14 match length */ +/*112 68 */ unsigned dist; /* r15 match distance */ +/*116 72 */ unsigned status; /* set when state chng*/ + } ar; + +#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) +#define PAD_AVAIL_IN 6 +#define PAD_AVAIL_OUT 258 +#else +#define PAD_AVAIL_IN 5 +#define PAD_AVAIL_OUT 257 +#endif + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + ar.in = strm->next_in; + ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); + ar.out = strm->next_out; + ar.beg = ar.out - (start - strm->avail_out); + ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); + ar.wsize = state->wsize; + ar.write = state->wnext; + ar.window = state->window; + ar.hold = state->hold; + ar.bits = state->bits; + ar.lcode = state->lencode; + ar.dcode = state->distcode; + ar.lmask = (1U << state->lenbits) - 1; + ar.dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + /* align in on 1/2 hold size boundary */ + while (((unsigned long)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { + ar.hold += (unsigned long)*ar.in++ << ar.bits; + ar.bits += 8; + } + +#if defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 ) + __asm__ __volatile__ ( +" leaq %0, %%rax\n" +" movq %%rbp, 8(%%rax)\n" /* save regs rbp and rsp */ +" movq %%rsp, (%%rax)\n" +" movq %%rax, %%rsp\n" /* make rsp point to &ar */ +" movq 16(%%rsp), %%rsi\n" /* rsi = in */ +" movq 32(%%rsp), %%rdi\n" /* rdi = out */ +" movq 24(%%rsp), %%r9\n" /* r9 = last */ +" movq 48(%%rsp), %%r10\n" /* r10 = end */ +" movq 64(%%rsp), %%rbp\n" /* rbp = lcode */ +" movq 72(%%rsp), %%r11\n" /* r11 = dcode */ +" movq 80(%%rsp), %%rdx\n" /* rdx = hold */ +" movl 88(%%rsp), %%ebx\n" /* ebx = bits */ +" movl 100(%%rsp), %%r12d\n" /* r12d = lmask */ +" movl 104(%%rsp), %%r13d\n" /* r13d = dmask */ + /* r14d = len */ + /* r15d = dist */ +" cld\n" +" cmpq %%rdi, %%r10\n" +" je .L_one_time\n" /* if only one decode left */ +" cmpq %%rsi, %%r9\n" +" je .L_one_time\n" +" jmp .L_do_loop\n" + +".L_one_time:\n" +" movq %%r12, %%r8\n" /* r8 = lmask */ +" cmpb $32, %%bl\n" +" ja .L_get_length_code_one_time\n" + +" lodsl\n" /* eax = *(uint *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $32, %%bl\n" /* bits += 32 */ +" shlq %%cl, %%rax\n" +" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ +" jmp .L_get_length_code_one_time\n" + +".align 32,0x90\n" +".L_while_test:\n" +" cmpq %%rdi, %%r10\n" +" jbe .L_break_loop\n" +" cmpq %%rsi, %%r9\n" +" jbe .L_break_loop\n" + +".L_do_loop:\n" +" movq %%r12, %%r8\n" /* r8 = lmask */ +" cmpb $32, %%bl\n" +" ja .L_get_length_code\n" /* if (32 < bits) */ + +" lodsl\n" /* eax = *(uint *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $32, %%bl\n" /* bits += 32 */ +" shlq %%cl, %%rax\n" +" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ + +".L_get_length_code:\n" +" andq %%rdx, %%r8\n" /* r8 &= hold */ +" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ + +" movb %%ah, %%cl\n" /* cl = this.bits */ +" subb %%ah, %%bl\n" /* bits -= this.bits */ +" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ + +" testb %%al, %%al\n" +" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ + +" movq %%r12, %%r8\n" /* r8 = lmask */ +" shrl $16, %%eax\n" /* output this.val char */ +" stosb\n" + +".L_get_length_code_one_time:\n" +" andq %%rdx, %%r8\n" /* r8 &= hold */ +" movl (%%rbp,%%r8,4), %%eax\n" /* eax = lcode[hold & lmask] */ + +".L_dolen:\n" +" movb %%ah, %%cl\n" /* cl = this.bits */ +" subb %%ah, %%bl\n" /* bits -= this.bits */ +" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ + +" testb %%al, %%al\n" +" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ + +" shrl $16, %%eax\n" /* output this.val char */ +" stosb\n" +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_test_for_length_base:\n" +" movl %%eax, %%r14d\n" /* len = this */ +" shrl $16, %%r14d\n" /* len = this.val */ +" movb %%al, %%cl\n" + +" testb $16, %%al\n" +" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ +" andb $15, %%cl\n" /* op &= 15 */ +" jz .L_decode_distance\n" /* if (!op) */ + +".L_add_bits_to_len:\n" +" subb %%cl, %%bl\n" +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" shrq %%cl, %%rdx\n" +" addl %%eax, %%r14d\n" /* len += hold & mask[op] */ + +".L_decode_distance:\n" +" movq %%r13, %%r8\n" /* r8 = dmask */ +" cmpb $32, %%bl\n" +" ja .L_get_distance_code\n" /* if (32 < bits) */ + +" lodsl\n" /* eax = *(uint *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $32, %%bl\n" /* bits += 32 */ +" shlq %%cl, %%rax\n" +" orq %%rax, %%rdx\n" /* hold |= *((uint *)in)++ << bits */ + +".L_get_distance_code:\n" +" andq %%rdx, %%r8\n" /* r8 &= hold */ +" movl (%%r11,%%r8,4), %%eax\n" /* eax = dcode[hold & dmask] */ + +".L_dodist:\n" +" movl %%eax, %%r15d\n" /* dist = this */ +" shrl $16, %%r15d\n" /* dist = this.val */ +" movb %%ah, %%cl\n" +" subb %%ah, %%bl\n" /* bits -= this.bits */ +" shrq %%cl, %%rdx\n" /* hold >>= this.bits */ +" movb %%al, %%cl\n" /* cl = this.op */ + +" testb $16, %%al\n" /* if ((op & 16) == 0) */ +" jz .L_test_for_second_level_dist\n" +" andb $15, %%cl\n" /* op &= 15 */ +" jz .L_check_dist_one\n" + +".L_add_bits_to_dist:\n" +" subb %%cl, %%bl\n" +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" /* (1 << op) - 1 */ +" andl %%edx, %%eax\n" /* eax &= hold */ +" shrq %%cl, %%rdx\n" +" addl %%eax, %%r15d\n" /* dist += hold & ((1 << op) - 1) */ + +".L_check_window:\n" +" movq %%rsi, %%r8\n" /* save in so from can use it's reg */ +" movq %%rdi, %%rax\n" +" subq 40(%%rsp), %%rax\n" /* nbytes = out - beg */ + +" cmpl %%r15d, %%eax\n" +" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ + +" movl %%r14d, %%ecx\n" /* ecx = len */ +" movq %%rdi, %%rsi\n" +" subq %%r15, %%rsi\n" /* from = out - dist */ + +" sarl %%ecx\n" +" jnc .L_copy_two\n" /* if len % 2 == 0 */ + +" rep movsw\n" +" movb (%%rsi), %%al\n" +" movb %%al, (%%rdi)\n" +" incq %%rdi\n" + +" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ +" jmp .L_while_test\n" + +".L_copy_two:\n" +" rep movsw\n" +" movq %%r8, %%rsi\n" /* move in back to %rsi, toss from */ +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_check_dist_one:\n" +" cmpl $1, %%r15d\n" /* if dist 1, is a memset */ +" jne .L_check_window\n" +" cmpq %%rdi, 40(%%rsp)\n" /* if out == beg, outside window */ +" je .L_check_window\n" + +" movl %%r14d, %%ecx\n" /* ecx = len */ +" movb -1(%%rdi), %%al\n" +" movb %%al, %%ah\n" + +" sarl %%ecx\n" +" jnc .L_set_two\n" +" movb %%al, (%%rdi)\n" +" incq %%rdi\n" + +".L_set_two:\n" +" rep stosw\n" +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_test_for_second_level_length:\n" +" testb $64, %%al\n" +" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ + +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" addl %%r14d, %%eax\n" /* eax += len */ +" movl (%%rbp,%%rax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ +" jmp .L_dolen\n" + +".align 32,0x90\n" +".L_test_for_second_level_dist:\n" +" testb $64, %%al\n" +" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ + +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" addl %%r15d, %%eax\n" /* eax += dist */ +" movl (%%r11,%%rax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ +" jmp .L_dodist\n" + +".align 32,0x90\n" +".L_clip_window:\n" +" movl %%eax, %%ecx\n" /* ecx = nbytes */ +" movl 92(%%rsp), %%eax\n" /* eax = wsize, prepare for dist cmp */ +" negl %%ecx\n" /* nbytes = -nbytes */ + +" cmpl %%r15d, %%eax\n" +" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ + +" addl %%r15d, %%ecx\n" /* nbytes = dist - nbytes */ +" cmpl $0, 96(%%rsp)\n" +" jne .L_wrap_around_window\n" /* if (write != 0) */ + +" movq 56(%%rsp), %%rsi\n" /* from = window */ +" subl %%ecx, %%eax\n" /* eax -= nbytes */ +" addq %%rax, %%rsi\n" /* from += wsize - nbytes */ + +" movl %%r14d, %%eax\n" /* eax = len */ +" cmpl %%ecx, %%r14d\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* eax -= nbytes */ +" rep movsb\n" +" movq %%rdi, %%rsi\n" +" subq %%r15, %%rsi\n" /* from = &out[ -dist ] */ +" jmp .L_do_copy\n" + +".align 32,0x90\n" +".L_wrap_around_window:\n" +" movl 96(%%rsp), %%eax\n" /* eax = write */ +" cmpl %%eax, %%ecx\n" +" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ + +" movl 92(%%rsp), %%esi\n" /* from = wsize */ +" addq 56(%%rsp), %%rsi\n" /* from += window */ +" addq %%rax, %%rsi\n" /* from += write */ +" subq %%rcx, %%rsi\n" /* from -= nbytes */ +" subl %%eax, %%ecx\n" /* nbytes -= write */ + +" movl %%r14d, %%eax\n" /* eax = len */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movq 56(%%rsp), %%rsi\n" /* from = window */ +" movl 96(%%rsp), %%ecx\n" /* nbytes = write */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movq %%rdi, %%rsi\n" +" subq %%r15, %%rsi\n" /* from = out - dist */ +" jmp .L_do_copy\n" + +".align 32,0x90\n" +".L_contiguous_in_window:\n" +" movq 56(%%rsp), %%rsi\n" /* rsi = window */ +" addq %%rax, %%rsi\n" +" subq %%rcx, %%rsi\n" /* from += write - nbytes */ + +" movl %%r14d, %%eax\n" /* eax = len */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movq %%rdi, %%rsi\n" +" subq %%r15, %%rsi\n" /* from = out - dist */ +" jmp .L_do_copy\n" /* if (nbytes >= len) */ + +".align 32,0x90\n" +".L_do_copy:\n" +" movl %%eax, %%ecx\n" /* ecx = len */ +" rep movsb\n" + +" movq %%r8, %%rsi\n" /* move in back to %esi, toss from */ +" jmp .L_while_test\n" + +".L_test_for_end_of_block:\n" +" testb $32, %%al\n" +" jz .L_invalid_literal_length_code\n" +" movl $1, 116(%%rsp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_literal_length_code:\n" +" movl $2, 116(%%rsp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_distance_code:\n" +" movl $3, 116(%%rsp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_distance_too_far:\n" +" movl $4, 116(%%rsp)\n" +" jmp .L_break_loop_with_status\n" + +".L_break_loop:\n" +" movl $0, 116(%%rsp)\n" + +".L_break_loop_with_status:\n" +/* put in, out, bits, and hold back into ar and pop esp */ +" movq %%rsi, 16(%%rsp)\n" /* in */ +" movq %%rdi, 32(%%rsp)\n" /* out */ +" movl %%ebx, 88(%%rsp)\n" /* bits */ +" movq %%rdx, 80(%%rsp)\n" /* hold */ +" movq (%%rsp), %%rax\n" /* restore rbp and rsp */ +" movq 8(%%rsp), %%rbp\n" +" movq %%rax, %%rsp\n" + : + : "m" (ar) + : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", + "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" + ); +#elif ( defined( __GNUC__ ) || defined( __ICC ) ) && defined( __i386 ) + __asm__ __volatile__ ( +" leal %0, %%eax\n" +" movl %%esp, (%%eax)\n" /* save esp, ebp */ +" movl %%ebp, 4(%%eax)\n" +" movl %%eax, %%esp\n" +" movl 8(%%esp), %%esi\n" /* esi = in */ +" movl 16(%%esp), %%edi\n" /* edi = out */ +" movl 40(%%esp), %%edx\n" /* edx = hold */ +" movl 44(%%esp), %%ebx\n" /* ebx = bits */ +" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ + +" cld\n" +" jmp .L_do_loop\n" + +".align 32,0x90\n" +".L_while_test:\n" +" cmpl %%edi, 24(%%esp)\n" /* out < end */ +" jbe .L_break_loop\n" +" cmpl %%esi, 12(%%esp)\n" /* in < last */ +" jbe .L_break_loop\n" + +".L_do_loop:\n" +" cmpb $15, %%bl\n" +" ja .L_get_length_code\n" /* if (15 < bits) */ + +" xorl %%eax, %%eax\n" +" lodsw\n" /* al = *(ushort *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $16, %%bl\n" /* bits += 16 */ +" shll %%cl, %%eax\n" +" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ + +".L_get_length_code:\n" +" movl 56(%%esp), %%eax\n" /* eax = lmask */ +" andl %%edx, %%eax\n" /* eax &= hold */ +" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[hold & lmask] */ + +".L_dolen:\n" +" movb %%ah, %%cl\n" /* cl = this.bits */ +" subb %%ah, %%bl\n" /* bits -= this.bits */ +" shrl %%cl, %%edx\n" /* hold >>= this.bits */ + +" testb %%al, %%al\n" +" jnz .L_test_for_length_base\n" /* if (op != 0) 45.7% */ + +" shrl $16, %%eax\n" /* output this.val char */ +" stosb\n" +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_test_for_length_base:\n" +" movl %%eax, %%ecx\n" /* len = this */ +" shrl $16, %%ecx\n" /* len = this.val */ +" movl %%ecx, 64(%%esp)\n" /* save len */ +" movb %%al, %%cl\n" + +" testb $16, %%al\n" +" jz .L_test_for_second_level_length\n" /* if ((op & 16) == 0) 8% */ +" andb $15, %%cl\n" /* op &= 15 */ +" jz .L_decode_distance\n" /* if (!op) */ +" cmpb %%cl, %%bl\n" +" jae .L_add_bits_to_len\n" /* if (op <= bits) */ + +" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ +" xorl %%eax, %%eax\n" +" lodsw\n" /* al = *(ushort *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $16, %%bl\n" /* bits += 16 */ +" shll %%cl, %%eax\n" +" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ +" movb %%ch, %%cl\n" /* move op back to ecx */ + +".L_add_bits_to_len:\n" +" subb %%cl, %%bl\n" +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" shrl %%cl, %%edx\n" +" addl %%eax, 64(%%esp)\n" /* len += hold & mask[op] */ + +".L_decode_distance:\n" +" cmpb $15, %%bl\n" +" ja .L_get_distance_code\n" /* if (15 < bits) */ + +" xorl %%eax, %%eax\n" +" lodsw\n" /* al = *(ushort *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $16, %%bl\n" /* bits += 16 */ +" shll %%cl, %%eax\n" +" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ + +".L_get_distance_code:\n" +" movl 60(%%esp), %%eax\n" /* eax = dmask */ +" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ +" andl %%edx, %%eax\n" /* eax &= hold */ +" movl (%%ecx,%%eax,4), %%eax\n"/* eax = dcode[hold & dmask] */ + +".L_dodist:\n" +" movl %%eax, %%ebp\n" /* dist = this */ +" shrl $16, %%ebp\n" /* dist = this.val */ +" movb %%ah, %%cl\n" +" subb %%ah, %%bl\n" /* bits -= this.bits */ +" shrl %%cl, %%edx\n" /* hold >>= this.bits */ +" movb %%al, %%cl\n" /* cl = this.op */ + +" testb $16, %%al\n" /* if ((op & 16) == 0) */ +" jz .L_test_for_second_level_dist\n" +" andb $15, %%cl\n" /* op &= 15 */ +" jz .L_check_dist_one\n" +" cmpb %%cl, %%bl\n" +" jae .L_add_bits_to_dist\n" /* if (op <= bits) 97.6% */ + +" movb %%cl, %%ch\n" /* stash op in ch, freeing cl */ +" xorl %%eax, %%eax\n" +" lodsw\n" /* al = *(ushort *)in++ */ +" movb %%bl, %%cl\n" /* cl = bits, needs it for shifting */ +" addb $16, %%bl\n" /* bits += 16 */ +" shll %%cl, %%eax\n" +" orl %%eax, %%edx\n" /* hold |= *((ushort *)in)++ << bits */ +" movb %%ch, %%cl\n" /* move op back to ecx */ + +".L_add_bits_to_dist:\n" +" subb %%cl, %%bl\n" +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" /* (1 << op) - 1 */ +" andl %%edx, %%eax\n" /* eax &= hold */ +" shrl %%cl, %%edx\n" +" addl %%eax, %%ebp\n" /* dist += hold & ((1 << op) - 1) */ + +".L_check_window:\n" +" movl %%esi, 8(%%esp)\n" /* save in so from can use it's reg */ +" movl %%edi, %%eax\n" +" subl 20(%%esp), %%eax\n" /* nbytes = out - beg */ + +" cmpl %%ebp, %%eax\n" +" jb .L_clip_window\n" /* if (dist > nbytes) 4.2% */ + +" movl 64(%%esp), %%ecx\n" /* ecx = len */ +" movl %%edi, %%esi\n" +" subl %%ebp, %%esi\n" /* from = out - dist */ + +" sarl %%ecx\n" +" jnc .L_copy_two\n" /* if len % 2 == 0 */ + +" rep movsw\n" +" movb (%%esi), %%al\n" +" movb %%al, (%%edi)\n" +" incl %%edi\n" + +" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ +" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ +" jmp .L_while_test\n" + +".L_copy_two:\n" +" rep movsw\n" +" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ +" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_check_dist_one:\n" +" cmpl $1, %%ebp\n" /* if dist 1, is a memset */ +" jne .L_check_window\n" +" cmpl %%edi, 20(%%esp)\n" +" je .L_check_window\n" /* out == beg, if outside window */ + +" movl 64(%%esp), %%ecx\n" /* ecx = len */ +" movb -1(%%edi), %%al\n" +" movb %%al, %%ah\n" + +" sarl %%ecx\n" +" jnc .L_set_two\n" +" movb %%al, (%%edi)\n" +" incl %%edi\n" + +".L_set_two:\n" +" rep stosw\n" +" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ +" jmp .L_while_test\n" + +".align 32,0x90\n" +".L_test_for_second_level_length:\n" +" testb $64, %%al\n" +" jnz .L_test_for_end_of_block\n" /* if ((op & 64) != 0) */ + +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" addl 64(%%esp), %%eax\n" /* eax += len */ +" movl (%%ebp,%%eax,4), %%eax\n" /* eax = lcode[val+(hold&mask[op])]*/ +" jmp .L_dolen\n" + +".align 32,0x90\n" +".L_test_for_second_level_dist:\n" +" testb $64, %%al\n" +" jnz .L_invalid_distance_code\n" /* if ((op & 64) != 0) */ + +" xorl %%eax, %%eax\n" +" incl %%eax\n" +" shll %%cl, %%eax\n" +" decl %%eax\n" +" andl %%edx, %%eax\n" /* eax &= hold */ +" addl %%ebp, %%eax\n" /* eax += dist */ +" movl 36(%%esp), %%ecx\n" /* ecx = dcode */ +" movl (%%ecx,%%eax,4), %%eax\n" /* eax = dcode[val+(hold&mask[op])]*/ +" jmp .L_dodist\n" + +".align 32,0x90\n" +".L_clip_window:\n" +" movl %%eax, %%ecx\n" +" movl 48(%%esp), %%eax\n" /* eax = wsize */ +" negl %%ecx\n" /* nbytes = -nbytes */ +" movl 28(%%esp), %%esi\n" /* from = window */ + +" cmpl %%ebp, %%eax\n" +" jb .L_invalid_distance_too_far\n" /* if (dist > wsize) */ + +" addl %%ebp, %%ecx\n" /* nbytes = dist - nbytes */ +" cmpl $0, 52(%%esp)\n" +" jne .L_wrap_around_window\n" /* if (write != 0) */ + +" subl %%ecx, %%eax\n" +" addl %%eax, %%esi\n" /* from += wsize - nbytes */ + +" movl 64(%%esp), %%eax\n" /* eax = len */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movl %%edi, %%esi\n" +" subl %%ebp, %%esi\n" /* from = out - dist */ +" jmp .L_do_copy\n" + +".align 32,0x90\n" +".L_wrap_around_window:\n" +" movl 52(%%esp), %%eax\n" /* eax = write */ +" cmpl %%eax, %%ecx\n" +" jbe .L_contiguous_in_window\n" /* if (write >= nbytes) */ + +" addl 48(%%esp), %%esi\n" /* from += wsize */ +" addl %%eax, %%esi\n" /* from += write */ +" subl %%ecx, %%esi\n" /* from -= nbytes */ +" subl %%eax, %%ecx\n" /* nbytes -= write */ + +" movl 64(%%esp), %%eax\n" /* eax = len */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movl 28(%%esp), %%esi\n" /* from = window */ +" movl 52(%%esp), %%ecx\n" /* nbytes = write */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movl %%edi, %%esi\n" +" subl %%ebp, %%esi\n" /* from = out - dist */ +" jmp .L_do_copy\n" + +".align 32,0x90\n" +".L_contiguous_in_window:\n" +" addl %%eax, %%esi\n" +" subl %%ecx, %%esi\n" /* from += write - nbytes */ + +" movl 64(%%esp), %%eax\n" /* eax = len */ +" cmpl %%ecx, %%eax\n" +" jbe .L_do_copy\n" /* if (nbytes >= len) */ + +" subl %%ecx, %%eax\n" /* len -= nbytes */ +" rep movsb\n" +" movl %%edi, %%esi\n" +" subl %%ebp, %%esi\n" /* from = out - dist */ +" jmp .L_do_copy\n" /* if (nbytes >= len) */ + +".align 32,0x90\n" +".L_do_copy:\n" +" movl %%eax, %%ecx\n" +" rep movsb\n" + +" movl 8(%%esp), %%esi\n" /* move in back to %esi, toss from */ +" movl 32(%%esp), %%ebp\n" /* ebp = lcode */ +" jmp .L_while_test\n" + +".L_test_for_end_of_block:\n" +" testb $32, %%al\n" +" jz .L_invalid_literal_length_code\n" +" movl $1, 72(%%esp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_literal_length_code:\n" +" movl $2, 72(%%esp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_distance_code:\n" +" movl $3, 72(%%esp)\n" +" jmp .L_break_loop_with_status\n" + +".L_invalid_distance_too_far:\n" +" movl 8(%%esp), %%esi\n" +" movl $4, 72(%%esp)\n" +" jmp .L_break_loop_with_status\n" + +".L_break_loop:\n" +" movl $0, 72(%%esp)\n" + +".L_break_loop_with_status:\n" +/* put in, out, bits, and hold back into ar and pop esp */ +" movl %%esi, 8(%%esp)\n" /* save in */ +" movl %%edi, 16(%%esp)\n" /* save out */ +" movl %%ebx, 44(%%esp)\n" /* save bits */ +" movl %%edx, 40(%%esp)\n" /* save hold */ +" movl 4(%%esp), %%ebp\n" /* restore esp, ebp */ +" movl (%%esp), %%esp\n" + : + : "m" (ar) + : "memory", "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi" + ); +#elif defined( _MSC_VER ) && ! defined( _M_AMD64 ) + __asm { + lea eax, ar + mov [eax], esp /* save esp, ebp */ + mov [eax+4], ebp + mov esp, eax + mov esi, [esp+8] /* esi = in */ + mov edi, [esp+16] /* edi = out */ + mov edx, [esp+40] /* edx = hold */ + mov ebx, [esp+44] /* ebx = bits */ + mov ebp, [esp+32] /* ebp = lcode */ + + cld + jmp L_do_loop + +ALIGN 4 +L_while_test: + cmp [esp+24], edi + jbe L_break_loop + cmp [esp+12], esi + jbe L_break_loop + +L_do_loop: + cmp bl, 15 + ja L_get_length_code /* if (15 < bits) */ + + xor eax, eax + lodsw /* al = *(ushort *)in++ */ + mov cl, bl /* cl = bits, needs it for shifting */ + add bl, 16 /* bits += 16 */ + shl eax, cl + or edx, eax /* hold |= *((ushort *)in)++ << bits */ + +L_get_length_code: + mov eax, [esp+56] /* eax = lmask */ + and eax, edx /* eax &= hold */ + mov eax, [ebp+eax*4] /* eax = lcode[hold & lmask] */ + +L_dolen: + mov cl, ah /* cl = this.bits */ + sub bl, ah /* bits -= this.bits */ + shr edx, cl /* hold >>= this.bits */ + + test al, al + jnz L_test_for_length_base /* if (op != 0) 45.7% */ + + shr eax, 16 /* output this.val char */ + stosb + jmp L_while_test + +ALIGN 4 +L_test_for_length_base: + mov ecx, eax /* len = this */ + shr ecx, 16 /* len = this.val */ + mov [esp+64], ecx /* save len */ + mov cl, al + + test al, 16 + jz L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ + and cl, 15 /* op &= 15 */ + jz L_decode_distance /* if (!op) */ + cmp bl, cl + jae L_add_bits_to_len /* if (op <= bits) */ + + mov ch, cl /* stash op in ch, freeing cl */ + xor eax, eax + lodsw /* al = *(ushort *)in++ */ + mov cl, bl /* cl = bits, needs it for shifting */ + add bl, 16 /* bits += 16 */ + shl eax, cl + or edx, eax /* hold |= *((ushort *)in)++ << bits */ + mov cl, ch /* move op back to ecx */ + +L_add_bits_to_len: + sub bl, cl + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx /* eax &= hold */ + shr edx, cl + add [esp+64], eax /* len += hold & mask[op] */ + +L_decode_distance: + cmp bl, 15 + ja L_get_distance_code /* if (15 < bits) */ + + xor eax, eax + lodsw /* al = *(ushort *)in++ */ + mov cl, bl /* cl = bits, needs it for shifting */ + add bl, 16 /* bits += 16 */ + shl eax, cl + or edx, eax /* hold |= *((ushort *)in)++ << bits */ + +L_get_distance_code: + mov eax, [esp+60] /* eax = dmask */ + mov ecx, [esp+36] /* ecx = dcode */ + and eax, edx /* eax &= hold */ + mov eax, [ecx+eax*4]/* eax = dcode[hold & dmask] */ + +L_dodist: + mov ebp, eax /* dist = this */ + shr ebp, 16 /* dist = this.val */ + mov cl, ah + sub bl, ah /* bits -= this.bits */ + shr edx, cl /* hold >>= this.bits */ + mov cl, al /* cl = this.op */ + + test al, 16 /* if ((op & 16) == 0) */ + jz L_test_for_second_level_dist + and cl, 15 /* op &= 15 */ + jz L_check_dist_one + cmp bl, cl + jae L_add_bits_to_dist /* if (op <= bits) 97.6% */ + + mov ch, cl /* stash op in ch, freeing cl */ + xor eax, eax + lodsw /* al = *(ushort *)in++ */ + mov cl, bl /* cl = bits, needs it for shifting */ + add bl, 16 /* bits += 16 */ + shl eax, cl + or edx, eax /* hold |= *((ushort *)in)++ << bits */ + mov cl, ch /* move op back to ecx */ + +L_add_bits_to_dist: + sub bl, cl + xor eax, eax + inc eax + shl eax, cl + dec eax /* (1 << op) - 1 */ + and eax, edx /* eax &= hold */ + shr edx, cl + add ebp, eax /* dist += hold & ((1 << op) - 1) */ + +L_check_window: + mov [esp+8], esi /* save in so from can use it's reg */ + mov eax, edi + sub eax, [esp+20] /* nbytes = out - beg */ + + cmp eax, ebp + jb L_clip_window /* if (dist > nbytes) 4.2% */ + + mov ecx, [esp+64] /* ecx = len */ + mov esi, edi + sub esi, ebp /* from = out - dist */ + + sar ecx, 1 + jnc L_copy_two + + rep movsw + mov al, [esi] + mov [edi], al + inc edi + + mov esi, [esp+8] /* move in back to %esi, toss from */ + mov ebp, [esp+32] /* ebp = lcode */ + jmp L_while_test + +L_copy_two: + rep movsw + mov esi, [esp+8] /* move in back to %esi, toss from */ + mov ebp, [esp+32] /* ebp = lcode */ + jmp L_while_test + +ALIGN 4 +L_check_dist_one: + cmp ebp, 1 /* if dist 1, is a memset */ + jne L_check_window + cmp [esp+20], edi + je L_check_window /* out == beg, if outside window */ + + mov ecx, [esp+64] /* ecx = len */ + mov al, [edi-1] + mov ah, al + + sar ecx, 1 + jnc L_set_two + mov [edi], al /* memset out with from[-1] */ + inc edi + +L_set_two: + rep stosw + mov ebp, [esp+32] /* ebp = lcode */ + jmp L_while_test + +ALIGN 4 +L_test_for_second_level_length: + test al, 64 + jnz L_test_for_end_of_block /* if ((op & 64) != 0) */ + + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx /* eax &= hold */ + add eax, [esp+64] /* eax += len */ + mov eax, [ebp+eax*4] /* eax = lcode[val+(hold&mask[op])]*/ + jmp L_dolen + +ALIGN 4 +L_test_for_second_level_dist: + test al, 64 + jnz L_invalid_distance_code /* if ((op & 64) != 0) */ + + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx /* eax &= hold */ + add eax, ebp /* eax += dist */ + mov ecx, [esp+36] /* ecx = dcode */ + mov eax, [ecx+eax*4] /* eax = dcode[val+(hold&mask[op])]*/ + jmp L_dodist + +ALIGN 4 +L_clip_window: + mov ecx, eax + mov eax, [esp+48] /* eax = wsize */ + neg ecx /* nbytes = -nbytes */ + mov esi, [esp+28] /* from = window */ + + cmp eax, ebp + jb L_invalid_distance_too_far /* if (dist > wsize) */ + + add ecx, ebp /* nbytes = dist - nbytes */ + cmp dword ptr [esp+52], 0 + jne L_wrap_around_window /* if (write != 0) */ + + sub eax, ecx + add esi, eax /* from += wsize - nbytes */ + + mov eax, [esp+64] /* eax = len */ + cmp eax, ecx + jbe L_do_copy /* if (nbytes >= len) */ + + sub eax, ecx /* len -= nbytes */ + rep movsb + mov esi, edi + sub esi, ebp /* from = out - dist */ + jmp L_do_copy + +ALIGN 4 +L_wrap_around_window: + mov eax, [esp+52] /* eax = write */ + cmp ecx, eax + jbe L_contiguous_in_window /* if (write >= nbytes) */ + + add esi, [esp+48] /* from += wsize */ + add esi, eax /* from += write */ + sub esi, ecx /* from -= nbytes */ + sub ecx, eax /* nbytes -= write */ + + mov eax, [esp+64] /* eax = len */ + cmp eax, ecx + jbe L_do_copy /* if (nbytes >= len) */ + + sub eax, ecx /* len -= nbytes */ + rep movsb + mov esi, [esp+28] /* from = window */ + mov ecx, [esp+52] /* nbytes = write */ + cmp eax, ecx + jbe L_do_copy /* if (nbytes >= len) */ + + sub eax, ecx /* len -= nbytes */ + rep movsb + mov esi, edi + sub esi, ebp /* from = out - dist */ + jmp L_do_copy + +ALIGN 4 +L_contiguous_in_window: + add esi, eax + sub esi, ecx /* from += write - nbytes */ + + mov eax, [esp+64] /* eax = len */ + cmp eax, ecx + jbe L_do_copy /* if (nbytes >= len) */ + + sub eax, ecx /* len -= nbytes */ + rep movsb + mov esi, edi + sub esi, ebp /* from = out - dist */ + jmp L_do_copy + +ALIGN 4 +L_do_copy: + mov ecx, eax + rep movsb + + mov esi, [esp+8] /* move in back to %esi, toss from */ + mov ebp, [esp+32] /* ebp = lcode */ + jmp L_while_test + +L_test_for_end_of_block: + test al, 32 + jz L_invalid_literal_length_code + mov dword ptr [esp+72], 1 + jmp L_break_loop_with_status + +L_invalid_literal_length_code: + mov dword ptr [esp+72], 2 + jmp L_break_loop_with_status + +L_invalid_distance_code: + mov dword ptr [esp+72], 3 + jmp L_break_loop_with_status + +L_invalid_distance_too_far: + mov esi, [esp+4] + mov dword ptr [esp+72], 4 + jmp L_break_loop_with_status + +L_break_loop: + mov dword ptr [esp+72], 0 + +L_break_loop_with_status: +/* put in, out, bits, and hold back into ar and pop esp */ + mov [esp+8], esi /* save in */ + mov [esp+16], edi /* save out */ + mov [esp+44], ebx /* save bits */ + mov [esp+40], edx /* save hold */ + mov ebp, [esp+4] /* restore esp, ebp */ + mov esp, [esp] + } +#else +#error "x86 architecture not defined" +#endif + + if (ar.status > 1) { + if (ar.status == 2) + strm->msg = "invalid literal/length code"; + else if (ar.status == 3) + strm->msg = "invalid distance code"; + else + strm->msg = "invalid distance too far back"; + state->mode = BAD; + } + else if ( ar.status == 1 ) { + state->mode = TYPE; + } + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + ar.len = ar.bits >> 3; + ar.in -= ar.len; + ar.bits -= ar.len << 3; + ar.hold &= (1U << ar.bits) - 1; + + /* update state and return */ + strm->next_in = ar.in; + strm->next_out = ar.out; + strm->avail_in = (unsigned)(ar.in < ar.last ? + PAD_AVAIL_IN + (ar.last - ar.in) : + PAD_AVAIL_IN - (ar.in - ar.last)); + strm->avail_out = (unsigned)(ar.out < ar.end ? + PAD_AVAIL_OUT + (ar.end - ar.out) : + PAD_AVAIL_OUT - (ar.out - ar.end)); + state->hold = ar.hold; + state->bits = ar.bits; + return; +} + diff --git a/third_party/zlib/v1_2_11/contrib/inflate86/inffast.S b/third_party/zlib/v1_2_11/contrib/inflate86/inffast.S new file mode 100644 index 0000000..2245a29 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/inflate86/inffast.S @@ -0,0 +1,1368 @@ +/* + * inffast.S is a hand tuned assembler version of: + * + * inffast.c -- fast decoding + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Copyright (C) 2003 Chris Anderson + * Please use the copyright conditions above. + * + * This version (Jan-23-2003) of inflate_fast was coded and tested under + * GNU/Linux on a pentium 3, using the gcc-3.2 compiler distribution. On that + * machine, I found that gzip style archives decompressed about 20% faster than + * the gcc-3.2 -O3 -fomit-frame-pointer compiled version. Your results will + * depend on how large of a buffer is used for z_stream.next_in & next_out + * (8K-32K worked best for my 256K cpu cache) and how much overhead there is in + * stream processing I/O and crc32/addler32. In my case, this routine used + * 70% of the cpu time and crc32 used 20%. + * + * I am confident that this version will work in the general case, but I have + * not tested a wide variety of datasets or a wide variety of platforms. + * + * Jan-24-2003 -- Added -DUSE_MMX define for slightly faster inflating. + * It should be a runtime flag instead of compile time flag... + * + * Jan-26-2003 -- Added runtime check for MMX support with cpuid instruction. + * With -DUSE_MMX, only MMX code is compiled. With -DNO_MMX, only non-MMX code + * is compiled. Without either option, runtime detection is enabled. Runtime + * detection should work on all modern cpus and the recomended algorithm (flip + * ID bit on eflags and then use the cpuid instruction) is used in many + * multimedia applications. Tested under win2k with gcc-2.95 and gas-2.12 + * distributed with cygwin3. Compiling with gcc-2.95 -c inffast.S -o + * inffast.obj generates a COFF object which can then be linked with MSVC++ + * compiled code. Tested under FreeBSD 4.7 with gcc-2.95. + * + * Jan-28-2003 -- Tested Athlon XP... MMX mode is slower than no MMX (and + * slower than compiler generated code). Adjusted cpuid check to use the MMX + * code only for Pentiums < P4 until I have more data on the P4. Speed + * improvment is only about 15% on the Athlon when compared with code generated + * with MSVC++. Not sure yet, but I think the P4 will also be slower using the + * MMX mode because many of it's x86 ALU instructions execute in .5 cycles and + * have less latency than MMX ops. Added code to buffer the last 11 bytes of + * the input stream since the MMX code grabs bits in chunks of 32, which + * differs from the inffast.c algorithm. I don't think there would have been + * read overruns where a page boundary was crossed (a segfault), but there + * could have been overruns when next_in ends on unaligned memory (unintialized + * memory read). + * + * Mar-13-2003 -- P4 MMX is slightly slower than P4 NO_MMX. I created a C + * version of the non-MMX code so that it doesn't depend on zstrm and zstate + * structure offsets which are hard coded in this file. This was last tested + * with zlib-1.2.0 which is currently in beta testing, newer versions of this + * and inffas86.c can be found at http://www.eetbeetee.com/zlib/ and + * http://www.charm.net/~christop/zlib/ + */ + + +/* + * if you have underscore linking problems (_inflate_fast undefined), try + * using -DGAS_COFF + */ +#if ! defined( GAS_COFF ) && ! defined( GAS_ELF ) + +#if defined( WIN32 ) || defined( __CYGWIN__ ) +#define GAS_COFF /* windows object format */ +#else +#define GAS_ELF +#endif + +#endif /* ! GAS_COFF && ! GAS_ELF */ + + +#if defined( GAS_COFF ) + +/* coff externals have underscores */ +#define inflate_fast _inflate_fast +#define inflate_fast_use_mmx _inflate_fast_use_mmx + +#endif /* GAS_COFF */ + + +.file "inffast.S" + +.globl inflate_fast + +.text +.align 4,0 +.L_invalid_literal_length_code_msg: +.string "invalid literal/length code" + +.align 4,0 +.L_invalid_distance_code_msg: +.string "invalid distance code" + +.align 4,0 +.L_invalid_distance_too_far_msg: +.string "invalid distance too far back" + +#if ! defined( NO_MMX ) +.align 4,0 +.L_mask: /* mask[N] = ( 1 << N ) - 1 */ +.long 0 +.long 1 +.long 3 +.long 7 +.long 15 +.long 31 +.long 63 +.long 127 +.long 255 +.long 511 +.long 1023 +.long 2047 +.long 4095 +.long 8191 +.long 16383 +.long 32767 +.long 65535 +.long 131071 +.long 262143 +.long 524287 +.long 1048575 +.long 2097151 +.long 4194303 +.long 8388607 +.long 16777215 +.long 33554431 +.long 67108863 +.long 134217727 +.long 268435455 +.long 536870911 +.long 1073741823 +.long 2147483647 +.long 4294967295 +#endif /* NO_MMX */ + +.text + +/* + * struct z_stream offsets, in zlib.h + */ +#define next_in_strm 0 /* strm->next_in */ +#define avail_in_strm 4 /* strm->avail_in */ +#define next_out_strm 12 /* strm->next_out */ +#define avail_out_strm 16 /* strm->avail_out */ +#define msg_strm 24 /* strm->msg */ +#define state_strm 28 /* strm->state */ + +/* + * struct inflate_state offsets, in inflate.h + */ +#define mode_state 0 /* state->mode */ +#define wsize_state 32 /* state->wsize */ +#define write_state 40 /* state->write */ +#define window_state 44 /* state->window */ +#define hold_state 48 /* state->hold */ +#define bits_state 52 /* state->bits */ +#define lencode_state 68 /* state->lencode */ +#define distcode_state 72 /* state->distcode */ +#define lenbits_state 76 /* state->lenbits */ +#define distbits_state 80 /* state->distbits */ + +/* + * inflate_fast's activation record + */ +#define local_var_size 64 /* how much local space for vars */ +#define strm_sp 88 /* first arg: z_stream * (local_var_size + 24) */ +#define start_sp 92 /* second arg: unsigned int (local_var_size + 28) */ + +/* + * offsets for local vars on stack + */ +#define out 60 /* unsigned char* */ +#define window 56 /* unsigned char* */ +#define wsize 52 /* unsigned int */ +#define write 48 /* unsigned int */ +#define in 44 /* unsigned char* */ +#define beg 40 /* unsigned char* */ +#define buf 28 /* char[ 12 ] */ +#define len 24 /* unsigned int */ +#define last 20 /* unsigned char* */ +#define end 16 /* unsigned char* */ +#define dcode 12 /* code* */ +#define lcode 8 /* code* */ +#define dmask 4 /* unsigned int */ +#define lmask 0 /* unsigned int */ + +/* + * typedef enum inflate_mode consts, in inflate.h + */ +#define INFLATE_MODE_TYPE 11 /* state->mode flags enum-ed in inflate.h */ +#define INFLATE_MODE_BAD 26 + + +#if ! defined( USE_MMX ) && ! defined( NO_MMX ) + +#define RUN_TIME_MMX + +#define CHECK_MMX 1 +#define DO_USE_MMX 2 +#define DONT_USE_MMX 3 + +.globl inflate_fast_use_mmx + +.data + +.align 4,0 +inflate_fast_use_mmx: /* integer flag for run time control 1=check,2=mmx,3=no */ +.long CHECK_MMX + +#if defined( GAS_ELF ) +/* elf info */ +.type inflate_fast_use_mmx,@object +.size inflate_fast_use_mmx,4 +#endif + +#endif /* RUN_TIME_MMX */ + +#if defined( GAS_COFF ) +/* coff info: scl 2 = extern, type 32 = function */ +.def inflate_fast; .scl 2; .type 32; .endef +#endif + +.text + +.align 32,0x90 +inflate_fast: + pushl %edi + pushl %esi + pushl %ebp + pushl %ebx + pushf /* save eflags (strm_sp, state_sp assumes this is 32 bits) */ + subl $local_var_size, %esp + cld + +#define strm_r %esi +#define state_r %edi + + movl strm_sp(%esp), strm_r + movl state_strm(strm_r), state_r + + /* in = strm->next_in; + * out = strm->next_out; + * last = in + strm->avail_in - 11; + * beg = out - (start - strm->avail_out); + * end = out + (strm->avail_out - 257); + */ + movl avail_in_strm(strm_r), %edx + movl next_in_strm(strm_r), %eax + + addl %eax, %edx /* avail_in += next_in */ + subl $11, %edx /* avail_in -= 11 */ + + movl %eax, in(%esp) + movl %edx, last(%esp) + + movl start_sp(%esp), %ebp + movl avail_out_strm(strm_r), %ecx + movl next_out_strm(strm_r), %ebx + + subl %ecx, %ebp /* start -= avail_out */ + negl %ebp /* start = -start */ + addl %ebx, %ebp /* start += next_out */ + + subl $257, %ecx /* avail_out -= 257 */ + addl %ebx, %ecx /* avail_out += out */ + + movl %ebx, out(%esp) + movl %ebp, beg(%esp) + movl %ecx, end(%esp) + + /* wsize = state->wsize; + * write = state->write; + * window = state->window; + * hold = state->hold; + * bits = state->bits; + * lcode = state->lencode; + * dcode = state->distcode; + * lmask = ( 1 << state->lenbits ) - 1; + * dmask = ( 1 << state->distbits ) - 1; + */ + + movl lencode_state(state_r), %eax + movl distcode_state(state_r), %ecx + + movl %eax, lcode(%esp) + movl %ecx, dcode(%esp) + + movl $1, %eax + movl lenbits_state(state_r), %ecx + shll %cl, %eax + decl %eax + movl %eax, lmask(%esp) + + movl $1, %eax + movl distbits_state(state_r), %ecx + shll %cl, %eax + decl %eax + movl %eax, dmask(%esp) + + movl wsize_state(state_r), %eax + movl write_state(state_r), %ecx + movl window_state(state_r), %edx + + movl %eax, wsize(%esp) + movl %ecx, write(%esp) + movl %edx, window(%esp) + + movl hold_state(state_r), %ebp + movl bits_state(state_r), %ebx + +#undef strm_r +#undef state_r + +#define in_r %esi +#define from_r %esi +#define out_r %edi + + movl in(%esp), in_r + movl last(%esp), %ecx + cmpl in_r, %ecx + ja .L_align_long /* if in < last */ + + addl $11, %ecx /* ecx = &in[ avail_in ] */ + subl in_r, %ecx /* ecx = avail_in */ + movl $12, %eax + subl %ecx, %eax /* eax = 12 - avail_in */ + leal buf(%esp), %edi + rep movsb /* memcpy( buf, in, avail_in ) */ + movl %eax, %ecx + xorl %eax, %eax + rep stosb /* memset( &buf[ avail_in ], 0, 12 - avail_in ) */ + leal buf(%esp), in_r /* in = buf */ + movl in_r, last(%esp) /* last = in, do just one iteration */ + jmp .L_is_aligned + + /* align in_r on long boundary */ +.L_align_long: + testl $3, in_r + jz .L_is_aligned + xorl %eax, %eax + movb (in_r), %al + incl in_r + movl %ebx, %ecx + addl $8, %ebx + shll %cl, %eax + orl %eax, %ebp + jmp .L_align_long + +.L_is_aligned: + movl out(%esp), out_r + +#if defined( NO_MMX ) + jmp .L_do_loop +#endif + +#if defined( USE_MMX ) + jmp .L_init_mmx +#endif + +/*** Runtime MMX check ***/ + +#if defined( RUN_TIME_MMX ) +.L_check_mmx: + cmpl $DO_USE_MMX, inflate_fast_use_mmx + je .L_init_mmx + ja .L_do_loop /* > 2 */ + + pushl %eax + pushl %ebx + pushl %ecx + pushl %edx + pushf + movl (%esp), %eax /* copy eflags to eax */ + xorl $0x200000, (%esp) /* try toggling ID bit of eflags (bit 21) + * to see if cpu supports cpuid... + * ID bit method not supported by NexGen but + * bios may load a cpuid instruction and + * cpuid may be disabled on Cyrix 5-6x86 */ + popf + pushf + popl %edx /* copy new eflags to edx */ + xorl %eax, %edx /* test if ID bit is flipped */ + jz .L_dont_use_mmx /* not flipped if zero */ + xorl %eax, %eax + cpuid + cmpl $0x756e6547, %ebx /* check for GenuineIntel in ebx,ecx,edx */ + jne .L_dont_use_mmx + cmpl $0x6c65746e, %ecx + jne .L_dont_use_mmx + cmpl $0x49656e69, %edx + jne .L_dont_use_mmx + movl $1, %eax + cpuid /* get cpu features */ + shrl $8, %eax + andl $15, %eax + cmpl $6, %eax /* check for Pentium family, is 0xf for P4 */ + jne .L_dont_use_mmx + testl $0x800000, %edx /* test if MMX feature is set (bit 23) */ + jnz .L_use_mmx + jmp .L_dont_use_mmx +.L_use_mmx: + movl $DO_USE_MMX, inflate_fast_use_mmx + jmp .L_check_mmx_pop +.L_dont_use_mmx: + movl $DONT_USE_MMX, inflate_fast_use_mmx +.L_check_mmx_pop: + popl %edx + popl %ecx + popl %ebx + popl %eax + jmp .L_check_mmx +#endif + + +/*** Non-MMX code ***/ + +#if defined ( NO_MMX ) || defined( RUN_TIME_MMX ) + +#define hold_r %ebp +#define bits_r %bl +#define bitslong_r %ebx + +.align 32,0x90 +.L_while_test: + /* while (in < last && out < end) + */ + cmpl out_r, end(%esp) + jbe .L_break_loop /* if (out >= end) */ + + cmpl in_r, last(%esp) + jbe .L_break_loop + +.L_do_loop: + /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out + * + * do { + * if (bits < 15) { + * hold |= *((unsigned short *)in)++ << bits; + * bits += 16 + * } + * this = lcode[hold & lmask] + */ + cmpb $15, bits_r + ja .L_get_length_code /* if (15 < bits) */ + + xorl %eax, %eax + lodsw /* al = *(ushort *)in++ */ + movb bits_r, %cl /* cl = bits, needs it for shifting */ + addb $16, bits_r /* bits += 16 */ + shll %cl, %eax + orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ + +.L_get_length_code: + movl lmask(%esp), %edx /* edx = lmask */ + movl lcode(%esp), %ecx /* ecx = lcode */ + andl hold_r, %edx /* edx &= hold */ + movl (%ecx,%edx,4), %eax /* eax = lcode[hold & lmask] */ + +.L_dolen: + /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out + * + * dolen: + * bits -= this.bits; + * hold >>= this.bits + */ + movb %ah, %cl /* cl = this.bits */ + subb %ah, bits_r /* bits -= this.bits */ + shrl %cl, hold_r /* hold >>= this.bits */ + + /* check if op is a literal + * if (op == 0) { + * PUP(out) = this.val; + * } + */ + testb %al, %al + jnz .L_test_for_length_base /* if (op != 0) 45.7% */ + + shrl $16, %eax /* output this.val char */ + stosb + jmp .L_while_test + +.L_test_for_length_base: + /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = len + * + * else if (op & 16) { + * len = this.val + * op &= 15 + * if (op) { + * if (op > bits) { + * hold |= *((unsigned short *)in)++ << bits; + * bits += 16 + * } + * len += hold & mask[op]; + * bits -= op; + * hold >>= op; + * } + */ +#define len_r %edx + movl %eax, len_r /* len = this */ + shrl $16, len_r /* len = this.val */ + movb %al, %cl + + testb $16, %al + jz .L_test_for_second_level_length /* if ((op & 16) == 0) 8% */ + andb $15, %cl /* op &= 15 */ + jz .L_save_len /* if (!op) */ + cmpb %cl, bits_r + jae .L_add_bits_to_len /* if (op <= bits) */ + + movb %cl, %ch /* stash op in ch, freeing cl */ + xorl %eax, %eax + lodsw /* al = *(ushort *)in++ */ + movb bits_r, %cl /* cl = bits, needs it for shifting */ + addb $16, bits_r /* bits += 16 */ + shll %cl, %eax + orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ + movb %ch, %cl /* move op back to ecx */ + +.L_add_bits_to_len: + movl $1, %eax + shll %cl, %eax + decl %eax + subb %cl, bits_r + andl hold_r, %eax /* eax &= hold */ + shrl %cl, hold_r + addl %eax, len_r /* len += hold & mask[op] */ + +.L_save_len: + movl len_r, len(%esp) /* save len */ +#undef len_r + +.L_decode_distance: + /* regs: %esi = in, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * + * if (bits < 15) { + * hold |= *((unsigned short *)in)++ << bits; + * bits += 16 + * } + * this = dcode[hold & dmask]; + * dodist: + * bits -= this.bits; + * hold >>= this.bits; + * op = this.op; + */ + + cmpb $15, bits_r + ja .L_get_distance_code /* if (15 < bits) */ + + xorl %eax, %eax + lodsw /* al = *(ushort *)in++ */ + movb bits_r, %cl /* cl = bits, needs it for shifting */ + addb $16, bits_r /* bits += 16 */ + shll %cl, %eax + orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ + +.L_get_distance_code: + movl dmask(%esp), %edx /* edx = dmask */ + movl dcode(%esp), %ecx /* ecx = dcode */ + andl hold_r, %edx /* edx &= hold */ + movl (%ecx,%edx,4), %eax /* eax = dcode[hold & dmask] */ + +#define dist_r %edx +.L_dodist: + movl %eax, dist_r /* dist = this */ + shrl $16, dist_r /* dist = this.val */ + movb %ah, %cl + subb %ah, bits_r /* bits -= this.bits */ + shrl %cl, hold_r /* hold >>= this.bits */ + + /* if (op & 16) { + * dist = this.val + * op &= 15 + * if (op > bits) { + * hold |= *((unsigned short *)in)++ << bits; + * bits += 16 + * } + * dist += hold & mask[op]; + * bits -= op; + * hold >>= op; + */ + movb %al, %cl /* cl = this.op */ + + testb $16, %al /* if ((op & 16) == 0) */ + jz .L_test_for_second_level_dist + andb $15, %cl /* op &= 15 */ + jz .L_check_dist_one + cmpb %cl, bits_r + jae .L_add_bits_to_dist /* if (op <= bits) 97.6% */ + + movb %cl, %ch /* stash op in ch, freeing cl */ + xorl %eax, %eax + lodsw /* al = *(ushort *)in++ */ + movb bits_r, %cl /* cl = bits, needs it for shifting */ + addb $16, bits_r /* bits += 16 */ + shll %cl, %eax + orl %eax, hold_r /* hold |= *((ushort *)in)++ << bits */ + movb %ch, %cl /* move op back to ecx */ + +.L_add_bits_to_dist: + movl $1, %eax + shll %cl, %eax + decl %eax /* (1 << op) - 1 */ + subb %cl, bits_r + andl hold_r, %eax /* eax &= hold */ + shrl %cl, hold_r + addl %eax, dist_r /* dist += hold & ((1 << op) - 1) */ + jmp .L_check_window + +.L_check_window: + /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * %ecx = nbytes + * + * nbytes = out - beg; + * if (dist <= nbytes) { + * from = out - dist; + * do { + * PUP(out) = PUP(from); + * } while (--len > 0) { + * } + */ + + movl in_r, in(%esp) /* save in so from can use it's reg */ + movl out_r, %eax + subl beg(%esp), %eax /* nbytes = out - beg */ + + cmpl dist_r, %eax + jb .L_clip_window /* if (dist > nbytes) 4.2% */ + + movl len(%esp), %ecx + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + + subl $3, %ecx + movb (from_r), %al + movb %al, (out_r) + movb 1(from_r), %al + movb 2(from_r), %dl + addl $3, from_r + movb %al, 1(out_r) + movb %dl, 2(out_r) + addl $3, out_r + rep movsb + + movl in(%esp), in_r /* move in back to %esi, toss from */ + jmp .L_while_test + +.align 16,0x90 +.L_check_dist_one: + cmpl $1, dist_r + jne .L_check_window + cmpl out_r, beg(%esp) + je .L_check_window + + decl out_r + movl len(%esp), %ecx + movb (out_r), %al + subl $3, %ecx + + movb %al, 1(out_r) + movb %al, 2(out_r) + movb %al, 3(out_r) + addl $4, out_r + rep stosb + + jmp .L_while_test + +.align 16,0x90 +.L_test_for_second_level_length: + /* else if ((op & 64) == 0) { + * this = lcode[this.val + (hold & mask[op])]; + * } + */ + testb $64, %al + jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ + + movl $1, %eax + shll %cl, %eax + decl %eax + andl hold_r, %eax /* eax &= hold */ + addl %edx, %eax /* eax += this.val */ + movl lcode(%esp), %edx /* edx = lcode */ + movl (%edx,%eax,4), %eax /* eax = lcode[val + (hold&mask[op])] */ + jmp .L_dolen + +.align 16,0x90 +.L_test_for_second_level_dist: + /* else if ((op & 64) == 0) { + * this = dcode[this.val + (hold & mask[op])]; + * } + */ + testb $64, %al + jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ + + movl $1, %eax + shll %cl, %eax + decl %eax + andl hold_r, %eax /* eax &= hold */ + addl %edx, %eax /* eax += this.val */ + movl dcode(%esp), %edx /* edx = dcode */ + movl (%edx,%eax,4), %eax /* eax = dcode[val + (hold&mask[op])] */ + jmp .L_dodist + +.align 16,0x90 +.L_clip_window: + /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * %ecx = nbytes + * + * else { + * if (dist > wsize) { + * invalid distance + * } + * from = window; + * nbytes = dist - nbytes; + * if (write == 0) { + * from += wsize - nbytes; + */ +#define nbytes_r %ecx + movl %eax, nbytes_r + movl wsize(%esp), %eax /* prepare for dist compare */ + negl nbytes_r /* nbytes = -nbytes */ + movl window(%esp), from_r /* from = window */ + + cmpl dist_r, %eax + jb .L_invalid_distance_too_far /* if (dist > wsize) */ + + addl dist_r, nbytes_r /* nbytes = dist - nbytes */ + cmpl $0, write(%esp) + jne .L_wrap_around_window /* if (write != 0) */ + + subl nbytes_r, %eax + addl %eax, from_r /* from += wsize - nbytes */ + + /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * %ecx = nbytes, %eax = len + * + * if (nbytes < len) { + * len -= nbytes; + * do { + * PUP(out) = PUP(from); + * } while (--nbytes); + * from = out - dist; + * } + * } + */ +#define len_r %eax + movl len(%esp), len_r + cmpl nbytes_r, len_r + jbe .L_do_copy1 /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1 + + cmpl nbytes_r, len_r + jbe .L_do_copy1 /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1 + +.L_wrap_around_window: + /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * %ecx = nbytes, %eax = write, %eax = len + * + * else if (write < nbytes) { + * from += wsize + write - nbytes; + * nbytes -= write; + * if (nbytes < len) { + * len -= nbytes; + * do { + * PUP(out) = PUP(from); + * } while (--nbytes); + * from = window; + * nbytes = write; + * if (nbytes < len) { + * len -= nbytes; + * do { + * PUP(out) = PUP(from); + * } while(--nbytes); + * from = out - dist; + * } + * } + * } + */ +#define write_r %eax + movl write(%esp), write_r + cmpl write_r, nbytes_r + jbe .L_contiguous_in_window /* if (write >= nbytes) */ + + addl wsize(%esp), from_r + addl write_r, from_r + subl nbytes_r, from_r /* from += wsize + write - nbytes */ + subl write_r, nbytes_r /* nbytes -= write */ +#undef write_r + + movl len(%esp), len_r + cmpl nbytes_r, len_r + jbe .L_do_copy1 /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl window(%esp), from_r /* from = window */ + movl write(%esp), nbytes_r /* nbytes = write */ + cmpl nbytes_r, len_r + jbe .L_do_copy1 /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1 + +.L_contiguous_in_window: + /* regs: %esi = from, %ebp = hold, %bl = bits, %edi = out, %edx = dist + * %ecx = nbytes, %eax = write, %eax = len + * + * else { + * from += write - nbytes; + * if (nbytes < len) { + * len -= nbytes; + * do { + * PUP(out) = PUP(from); + * } while (--nbytes); + * from = out - dist; + * } + * } + */ +#define write_r %eax + addl write_r, from_r + subl nbytes_r, from_r /* from += write - nbytes */ +#undef write_r + + movl len(%esp), len_r + cmpl nbytes_r, len_r + jbe .L_do_copy1 /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + +.L_do_copy1: + /* regs: %esi = from, %esi = in, %ebp = hold, %bl = bits, %edi = out + * %eax = len + * + * while (len > 0) { + * PUP(out) = PUP(from); + * len--; + * } + * } + * } while (in < last && out < end); + */ +#undef nbytes_r +#define in_r %esi + movl len_r, %ecx + rep movsb + + movl in(%esp), in_r /* move in back to %esi, toss from */ + jmp .L_while_test + +#undef len_r +#undef dist_r + +#endif /* NO_MMX || RUN_TIME_MMX */ + + +/*** MMX code ***/ + +#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) + +.align 32,0x90 +.L_init_mmx: + emms + +#undef bits_r +#undef bitslong_r +#define bitslong_r %ebp +#define hold_mm %mm0 + movd %ebp, hold_mm + movl %ebx, bitslong_r + +#define used_mm %mm1 +#define dmask2_mm %mm2 +#define lmask2_mm %mm3 +#define lmask_mm %mm4 +#define dmask_mm %mm5 +#define tmp_mm %mm6 + + movd lmask(%esp), lmask_mm + movq lmask_mm, lmask2_mm + movd dmask(%esp), dmask_mm + movq dmask_mm, dmask2_mm + pxor used_mm, used_mm + movl lcode(%esp), %ebx /* ebx = lcode */ + jmp .L_do_loop_mmx + +.align 32,0x90 +.L_while_test_mmx: + /* while (in < last && out < end) + */ + cmpl out_r, end(%esp) + jbe .L_break_loop /* if (out >= end) */ + + cmpl in_r, last(%esp) + jbe .L_break_loop + +.L_do_loop_mmx: + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + + cmpl $32, bitslong_r + ja .L_get_length_code_mmx /* if (32 < bits) */ + + movd bitslong_r, tmp_mm + movd (in_r), %mm7 + addl $4, in_r + psllq tmp_mm, %mm7 + addl $32, bitslong_r + por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ + +.L_get_length_code_mmx: + pand hold_mm, lmask_mm + movd lmask_mm, %eax + movq lmask2_mm, lmask_mm + movl (%ebx,%eax,4), %eax /* eax = lcode[hold & lmask] */ + +.L_dolen_mmx: + movzbl %ah, %ecx /* ecx = this.bits */ + movd %ecx, used_mm + subl %ecx, bitslong_r /* bits -= this.bits */ + + testb %al, %al + jnz .L_test_for_length_base_mmx /* if (op != 0) 45.7% */ + + shrl $16, %eax /* output this.val char */ + stosb + jmp .L_while_test_mmx + +.L_test_for_length_base_mmx: +#define len_r %edx + movl %eax, len_r /* len = this */ + shrl $16, len_r /* len = this.val */ + + testb $16, %al + jz .L_test_for_second_level_length_mmx /* if ((op & 16) == 0) 8% */ + andl $15, %eax /* op &= 15 */ + jz .L_decode_distance_mmx /* if (!op) */ + + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + movd %eax, used_mm + movd hold_mm, %ecx + subl %eax, bitslong_r + andl .L_mask(,%eax,4), %ecx + addl %ecx, len_r /* len += hold & mask[op] */ + +.L_decode_distance_mmx: + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + + cmpl $32, bitslong_r + ja .L_get_dist_code_mmx /* if (32 < bits) */ + + movd bitslong_r, tmp_mm + movd (in_r), %mm7 + addl $4, in_r + psllq tmp_mm, %mm7 + addl $32, bitslong_r + por %mm7, hold_mm /* hold_mm |= *((uint *)in)++ << bits */ + +.L_get_dist_code_mmx: + movl dcode(%esp), %ebx /* ebx = dcode */ + pand hold_mm, dmask_mm + movd dmask_mm, %eax + movq dmask2_mm, dmask_mm + movl (%ebx,%eax,4), %eax /* eax = dcode[hold & lmask] */ + +.L_dodist_mmx: +#define dist_r %ebx + movzbl %ah, %ecx /* ecx = this.bits */ + movl %eax, dist_r + shrl $16, dist_r /* dist = this.val */ + subl %ecx, bitslong_r /* bits -= this.bits */ + movd %ecx, used_mm + + testb $16, %al /* if ((op & 16) == 0) */ + jz .L_test_for_second_level_dist_mmx + andl $15, %eax /* op &= 15 */ + jz .L_check_dist_one_mmx + +.L_add_bits_to_dist_mmx: + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + movd %eax, used_mm /* save bit length of current op */ + movd hold_mm, %ecx /* get the next bits on input stream */ + subl %eax, bitslong_r /* bits -= op bits */ + andl .L_mask(,%eax,4), %ecx /* ecx = hold & mask[op] */ + addl %ecx, dist_r /* dist += hold & mask[op] */ + +.L_check_window_mmx: + movl in_r, in(%esp) /* save in so from can use it's reg */ + movl out_r, %eax + subl beg(%esp), %eax /* nbytes = out - beg */ + + cmpl dist_r, %eax + jb .L_clip_window_mmx /* if (dist > nbytes) 4.2% */ + + movl len_r, %ecx + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + + subl $3, %ecx + movb (from_r), %al + movb %al, (out_r) + movb 1(from_r), %al + movb 2(from_r), %dl + addl $3, from_r + movb %al, 1(out_r) + movb %dl, 2(out_r) + addl $3, out_r + rep movsb + + movl in(%esp), in_r /* move in back to %esi, toss from */ + movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ + jmp .L_while_test_mmx + +.align 16,0x90 +.L_check_dist_one_mmx: + cmpl $1, dist_r + jne .L_check_window_mmx + cmpl out_r, beg(%esp) + je .L_check_window_mmx + + decl out_r + movl len_r, %ecx + movb (out_r), %al + subl $3, %ecx + + movb %al, 1(out_r) + movb %al, 2(out_r) + movb %al, 3(out_r) + addl $4, out_r + rep stosb + + movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ + jmp .L_while_test_mmx + +.align 16,0x90 +.L_test_for_second_level_length_mmx: + testb $64, %al + jnz .L_test_for_end_of_block /* if ((op & 64) != 0) */ + + andl $15, %eax + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + movd hold_mm, %ecx + andl .L_mask(,%eax,4), %ecx + addl len_r, %ecx + movl (%ebx,%ecx,4), %eax /* eax = lcode[hold & lmask] */ + jmp .L_dolen_mmx + +.align 16,0x90 +.L_test_for_second_level_dist_mmx: + testb $64, %al + jnz .L_invalid_distance_code /* if ((op & 64) != 0) */ + + andl $15, %eax + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + movd hold_mm, %ecx + andl .L_mask(,%eax,4), %ecx + movl dcode(%esp), %eax /* ecx = dcode */ + addl dist_r, %ecx + movl (%eax,%ecx,4), %eax /* eax = lcode[hold & lmask] */ + jmp .L_dodist_mmx + +.align 16,0x90 +.L_clip_window_mmx: +#define nbytes_r %ecx + movl %eax, nbytes_r + movl wsize(%esp), %eax /* prepare for dist compare */ + negl nbytes_r /* nbytes = -nbytes */ + movl window(%esp), from_r /* from = window */ + + cmpl dist_r, %eax + jb .L_invalid_distance_too_far /* if (dist > wsize) */ + + addl dist_r, nbytes_r /* nbytes = dist - nbytes */ + cmpl $0, write(%esp) + jne .L_wrap_around_window_mmx /* if (write != 0) */ + + subl nbytes_r, %eax + addl %eax, from_r /* from += wsize - nbytes */ + + cmpl nbytes_r, len_r + jbe .L_do_copy1_mmx /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1_mmx + + cmpl nbytes_r, len_r + jbe .L_do_copy1_mmx /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1_mmx + +.L_wrap_around_window_mmx: +#define write_r %eax + movl write(%esp), write_r + cmpl write_r, nbytes_r + jbe .L_contiguous_in_window_mmx /* if (write >= nbytes) */ + + addl wsize(%esp), from_r + addl write_r, from_r + subl nbytes_r, from_r /* from += wsize + write - nbytes */ + subl write_r, nbytes_r /* nbytes -= write */ +#undef write_r + + cmpl nbytes_r, len_r + jbe .L_do_copy1_mmx /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl window(%esp), from_r /* from = window */ + movl write(%esp), nbytes_r /* nbytes = write */ + cmpl nbytes_r, len_r + jbe .L_do_copy1_mmx /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + jmp .L_do_copy1_mmx + +.L_contiguous_in_window_mmx: +#define write_r %eax + addl write_r, from_r + subl nbytes_r, from_r /* from += write - nbytes */ +#undef write_r + + cmpl nbytes_r, len_r + jbe .L_do_copy1_mmx /* if (nbytes >= len) */ + + subl nbytes_r, len_r /* len -= nbytes */ + rep movsb + movl out_r, from_r + subl dist_r, from_r /* from = out - dist */ + +.L_do_copy1_mmx: +#undef nbytes_r +#define in_r %esi + movl len_r, %ecx + rep movsb + + movl in(%esp), in_r /* move in back to %esi, toss from */ + movl lcode(%esp), %ebx /* move lcode back to %ebx, toss dist */ + jmp .L_while_test_mmx + +#undef hold_r +#undef bitslong_r + +#endif /* USE_MMX || RUN_TIME_MMX */ + + +/*** USE_MMX, NO_MMX, and RUNTIME_MMX from here on ***/ + +.L_invalid_distance_code: + /* else { + * strm->msg = "invalid distance code"; + * state->mode = BAD; + * } + */ + movl $.L_invalid_distance_code_msg, %ecx + movl $INFLATE_MODE_BAD, %edx + jmp .L_update_stream_state + +.L_test_for_end_of_block: + /* else if (op & 32) { + * state->mode = TYPE; + * break; + * } + */ + testb $32, %al + jz .L_invalid_literal_length_code /* if ((op & 32) == 0) */ + + movl $0, %ecx + movl $INFLATE_MODE_TYPE, %edx + jmp .L_update_stream_state + +.L_invalid_literal_length_code: + /* else { + * strm->msg = "invalid literal/length code"; + * state->mode = BAD; + * } + */ + movl $.L_invalid_literal_length_code_msg, %ecx + movl $INFLATE_MODE_BAD, %edx + jmp .L_update_stream_state + +.L_invalid_distance_too_far: + /* strm->msg = "invalid distance too far back"; + * state->mode = BAD; + */ + movl in(%esp), in_r /* from_r has in's reg, put in back */ + movl $.L_invalid_distance_too_far_msg, %ecx + movl $INFLATE_MODE_BAD, %edx + jmp .L_update_stream_state + +.L_update_stream_state: + /* set strm->msg = %ecx, strm->state->mode = %edx */ + movl strm_sp(%esp), %eax + testl %ecx, %ecx /* if (msg != NULL) */ + jz .L_skip_msg + movl %ecx, msg_strm(%eax) /* strm->msg = msg */ +.L_skip_msg: + movl state_strm(%eax), %eax /* state = strm->state */ + movl %edx, mode_state(%eax) /* state->mode = edx (BAD | TYPE) */ + jmp .L_break_loop + +.align 32,0x90 +.L_break_loop: + +/* + * Regs: + * + * bits = %ebp when mmx, and in %ebx when non-mmx + * hold = %hold_mm when mmx, and in %ebp when non-mmx + * in = %esi + * out = %edi + */ + +#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) + +#if defined( RUN_TIME_MMX ) + + cmpl $DO_USE_MMX, inflate_fast_use_mmx + jne .L_update_next_in + +#endif /* RUN_TIME_MMX */ + + movl %ebp, %ebx + +.L_update_next_in: + +#endif + +#define strm_r %eax +#define state_r %edx + + /* len = bits >> 3; + * in -= len; + * bits -= len << 3; + * hold &= (1U << bits) - 1; + * state->hold = hold; + * state->bits = bits; + * strm->next_in = in; + * strm->next_out = out; + */ + movl strm_sp(%esp), strm_r + movl %ebx, %ecx + movl state_strm(strm_r), state_r + shrl $3, %ecx + subl %ecx, in_r + shll $3, %ecx + subl %ecx, %ebx + movl out_r, next_out_strm(strm_r) + movl %ebx, bits_state(state_r) + movl %ebx, %ecx + + leal buf(%esp), %ebx + cmpl %ebx, last(%esp) + jne .L_buf_not_used /* if buf != last */ + + subl %ebx, in_r /* in -= buf */ + movl next_in_strm(strm_r), %ebx + movl %ebx, last(%esp) /* last = strm->next_in */ + addl %ebx, in_r /* in += strm->next_in */ + movl avail_in_strm(strm_r), %ebx + subl $11, %ebx + addl %ebx, last(%esp) /* last = &strm->next_in[ avail_in - 11 ] */ + +.L_buf_not_used: + movl in_r, next_in_strm(strm_r) + + movl $1, %ebx + shll %cl, %ebx + decl %ebx + +#if defined( USE_MMX ) || defined( RUN_TIME_MMX ) + +#if defined( RUN_TIME_MMX ) + + cmpl $DO_USE_MMX, inflate_fast_use_mmx + jne .L_update_hold + +#endif /* RUN_TIME_MMX */ + + psrlq used_mm, hold_mm /* hold_mm >>= last bit length */ + movd hold_mm, %ebp + + emms + +.L_update_hold: + +#endif /* USE_MMX || RUN_TIME_MMX */ + + andl %ebx, %ebp + movl %ebp, hold_state(state_r) + +#define last_r %ebx + + /* strm->avail_in = in < last ? 11 + (last - in) : 11 - (in - last) */ + movl last(%esp), last_r + cmpl in_r, last_r + jbe .L_last_is_smaller /* if (in >= last) */ + + subl in_r, last_r /* last -= in */ + addl $11, last_r /* last += 11 */ + movl last_r, avail_in_strm(strm_r) + jmp .L_fixup_out +.L_last_is_smaller: + subl last_r, in_r /* in -= last */ + negl in_r /* in = -in */ + addl $11, in_r /* in += 11 */ + movl in_r, avail_in_strm(strm_r) + +#undef last_r +#define end_r %ebx + +.L_fixup_out: + /* strm->avail_out = out < end ? 257 + (end - out) : 257 - (out - end)*/ + movl end(%esp), end_r + cmpl out_r, end_r + jbe .L_end_is_smaller /* if (out >= end) */ + + subl out_r, end_r /* end -= out */ + addl $257, end_r /* end += 257 */ + movl end_r, avail_out_strm(strm_r) + jmp .L_done +.L_end_is_smaller: + subl end_r, out_r /* out -= end */ + negl out_r /* out = -out */ + addl $257, out_r /* out += 257 */ + movl out_r, avail_out_strm(strm_r) + +#undef end_r +#undef strm_r +#undef state_r + +.L_done: + addl $local_var_size, %esp + popf + popl %ebx + popl %ebp + popl %esi + popl %edi + ret + +#if defined( GAS_ELF ) +/* elf info */ +.type inflate_fast,@function +.size inflate_fast,.-inflate_fast +#endif diff --git a/third_party/zlib/v1_2_11/contrib/iostream/test.cpp b/third_party/zlib/v1_2_11/contrib/iostream/test.cpp new file mode 100644 index 0000000..7d265b3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream/test.cpp @@ -0,0 +1,24 @@ + +#include "zfstream.h" + +int main() { + + // Construct a stream object with this filebuffer. Anything sent + // to this stream will go to standard out. + gzofstream os( 1, ios::out ); + + // This text is getting compressed and sent to stdout. + // To prove this, run 'test | zcat'. + os << "Hello, Mommy" << endl; + + os << setcompressionlevel( Z_NO_COMPRESSION ); + os << "hello, hello, hi, ho!" << endl; + + setcompressionlevel( os, Z_DEFAULT_COMPRESSION ) + << "I'm compressing again" << endl; + + os.close(); + + return 0; + +} diff --git a/third_party/zlib/v1_2_11/contrib/iostream/zfstream.cpp b/third_party/zlib/v1_2_11/contrib/iostream/zfstream.cpp new file mode 100644 index 0000000..d0cd85f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream/zfstream.cpp @@ -0,0 +1,329 @@ + +#include "zfstream.h" + +gzfilebuf::gzfilebuf() : + file(NULL), + mode(0), + own_file_descriptor(0) +{ } + +gzfilebuf::~gzfilebuf() { + + sync(); + if ( own_file_descriptor ) + close(); + +} + +gzfilebuf *gzfilebuf::open( const char *name, + int io_mode ) { + + if ( is_open() ) + return NULL; + + char char_mode[10]; + char *p = char_mode; + + if ( io_mode & ios::in ) { + mode = ios::in; + *p++ = 'r'; + } else if ( io_mode & ios::app ) { + mode = ios::app; + *p++ = 'a'; + } else { + mode = ios::out; + *p++ = 'w'; + } + + if ( io_mode & ios::binary ) { + mode |= ios::binary; + *p++ = 'b'; + } + + // Hard code the compression level + if ( io_mode & (ios::out|ios::app )) { + *p++ = '9'; + } + + // Put the end-of-string indicator + *p = '\0'; + + if ( (file = gzopen(name, char_mode)) == NULL ) + return NULL; + + own_file_descriptor = 1; + + return this; + +} + +gzfilebuf *gzfilebuf::attach( int file_descriptor, + int io_mode ) { + + if ( is_open() ) + return NULL; + + char char_mode[10]; + char *p = char_mode; + + if ( io_mode & ios::in ) { + mode = ios::in; + *p++ = 'r'; + } else if ( io_mode & ios::app ) { + mode = ios::app; + *p++ = 'a'; + } else { + mode = ios::out; + *p++ = 'w'; + } + + if ( io_mode & ios::binary ) { + mode |= ios::binary; + *p++ = 'b'; + } + + // Hard code the compression level + if ( io_mode & (ios::out|ios::app )) { + *p++ = '9'; + } + + // Put the end-of-string indicator + *p = '\0'; + + if ( (file = gzdopen(file_descriptor, char_mode)) == NULL ) + return NULL; + + own_file_descriptor = 0; + + return this; + +} + +gzfilebuf *gzfilebuf::close() { + + if ( is_open() ) { + + sync(); + gzclose( file ); + file = NULL; + + } + + return this; + +} + +int gzfilebuf::setcompressionlevel( int comp_level ) { + + return gzsetparams(file, comp_level, -2); + +} + +int gzfilebuf::setcompressionstrategy( int comp_strategy ) { + + return gzsetparams(file, -2, comp_strategy); + +} + + +streampos gzfilebuf::seekoff( streamoff off, ios::seek_dir dir, int which ) { + + return streampos(EOF); + +} + +int gzfilebuf::underflow() { + + // If the file hasn't been opened for reading, error. + if ( !is_open() || !(mode & ios::in) ) + return EOF; + + // if a buffer doesn't exists, allocate one. + if ( !base() ) { + + if ( (allocate()) == EOF ) + return EOF; + setp(0,0); + + } else { + + if ( in_avail() ) + return (unsigned char) *gptr(); + + if ( out_waiting() ) { + if ( flushbuf() == EOF ) + return EOF; + } + + } + + // Attempt to fill the buffer. + + int result = fillbuf(); + if ( result == EOF ) { + // disable get area + setg(0,0,0); + return EOF; + } + + return (unsigned char) *gptr(); + +} + +int gzfilebuf::overflow( int c ) { + + if ( !is_open() || !(mode & ios::out) ) + return EOF; + + if ( !base() ) { + if ( allocate() == EOF ) + return EOF; + setg(0,0,0); + } else { + if (in_avail()) { + return EOF; + } + if (out_waiting()) { + if (flushbuf() == EOF) + return EOF; + } + } + + int bl = blen(); + setp( base(), base() + bl); + + if ( c != EOF ) { + + *pptr() = c; + pbump(1); + + } + + return 0; + +} + +int gzfilebuf::sync() { + + if ( !is_open() ) + return EOF; + + if ( out_waiting() ) + return flushbuf(); + + return 0; + +} + +int gzfilebuf::flushbuf() { + + int n; + char *q; + + q = pbase(); + n = pptr() - q; + + if ( gzwrite( file, q, n) < n ) + return EOF; + + setp(0,0); + + return 0; + +} + +int gzfilebuf::fillbuf() { + + int required; + char *p; + + p = base(); + + required = blen(); + + int t = gzread( file, p, required ); + + if ( t <= 0) return EOF; + + setg( base(), base(), base()+t); + + return t; + +} + +gzfilestream_common::gzfilestream_common() : + ios( gzfilestream_common::rdbuf() ) +{ } + +gzfilestream_common::~gzfilestream_common() +{ } + +void gzfilestream_common::attach( int fd, int io_mode ) { + + if ( !buffer.attach( fd, io_mode) ) + clear( ios::failbit | ios::badbit ); + else + clear(); + +} + +void gzfilestream_common::open( const char *name, int io_mode ) { + + if ( !buffer.open( name, io_mode ) ) + clear( ios::failbit | ios::badbit ); + else + clear(); + +} + +void gzfilestream_common::close() { + + if ( !buffer.close() ) + clear( ios::failbit | ios::badbit ); + +} + +gzfilebuf *gzfilestream_common::rdbuf() +{ + return &buffer; +} + +gzifstream::gzifstream() : + ios( gzfilestream_common::rdbuf() ) +{ + clear( ios::badbit ); +} + +gzifstream::gzifstream( const char *name, int io_mode ) : + ios( gzfilestream_common::rdbuf() ) +{ + gzfilestream_common::open( name, io_mode ); +} + +gzifstream::gzifstream( int fd, int io_mode ) : + ios( gzfilestream_common::rdbuf() ) +{ + gzfilestream_common::attach( fd, io_mode ); +} + +gzifstream::~gzifstream() { } + +gzofstream::gzofstream() : + ios( gzfilestream_common::rdbuf() ) +{ + clear( ios::badbit ); +} + +gzofstream::gzofstream( const char *name, int io_mode ) : + ios( gzfilestream_common::rdbuf() ) +{ + gzfilestream_common::open( name, io_mode ); +} + +gzofstream::gzofstream( int fd, int io_mode ) : + ios( gzfilestream_common::rdbuf() ) +{ + gzfilestream_common::attach( fd, io_mode ); +} + +gzofstream::~gzofstream() { } diff --git a/third_party/zlib/v1_2_11/contrib/iostream/zfstream.h b/third_party/zlib/v1_2_11/contrib/iostream/zfstream.h new file mode 100644 index 0000000..ed79098 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream/zfstream.h @@ -0,0 +1,128 @@ + +#ifndef zfstream_h +#define zfstream_h + +#include +#include "zlib.h" + +class gzfilebuf : public streambuf { + +public: + + gzfilebuf( ); + virtual ~gzfilebuf(); + + gzfilebuf *open( const char *name, int io_mode ); + gzfilebuf *attach( int file_descriptor, int io_mode ); + gzfilebuf *close(); + + int setcompressionlevel( int comp_level ); + int setcompressionstrategy( int comp_strategy ); + + inline int is_open() const { return (file !=NULL); } + + virtual streampos seekoff( streamoff, ios::seek_dir, int ); + + virtual int sync(); + +protected: + + virtual int underflow(); + virtual int overflow( int = EOF ); + +private: + + gzFile file; + short mode; + short own_file_descriptor; + + int flushbuf(); + int fillbuf(); + +}; + +class gzfilestream_common : virtual public ios { + + friend class gzifstream; + friend class gzofstream; + friend gzofstream &setcompressionlevel( gzofstream &, int ); + friend gzofstream &setcompressionstrategy( gzofstream &, int ); + +public: + virtual ~gzfilestream_common(); + + void attach( int fd, int io_mode ); + void open( const char *name, int io_mode ); + void close(); + +protected: + gzfilestream_common(); + +private: + gzfilebuf *rdbuf(); + + gzfilebuf buffer; + +}; + +class gzifstream : public gzfilestream_common, public istream { + +public: + + gzifstream(); + gzifstream( const char *name, int io_mode = ios::in ); + gzifstream( int fd, int io_mode = ios::in ); + + virtual ~gzifstream(); + +}; + +class gzofstream : public gzfilestream_common, public ostream { + +public: + + gzofstream(); + gzofstream( const char *name, int io_mode = ios::out ); + gzofstream( int fd, int io_mode = ios::out ); + + virtual ~gzofstream(); + +}; + +template class gzomanip { + friend gzofstream &operator<<(gzofstream &, const gzomanip &); +public: + gzomanip(gzofstream &(*f)(gzofstream &, T), T v) : func(f), val(v) { } +private: + gzofstream &(*func)(gzofstream &, T); + T val; +}; + +template gzofstream &operator<<(gzofstream &s, const gzomanip &m) +{ + return (*m.func)(s, m.val); +} + +inline gzofstream &setcompressionlevel( gzofstream &s, int l ) +{ + (s.rdbuf())->setcompressionlevel(l); + return s; +} + +inline gzofstream &setcompressionstrategy( gzofstream &s, int l ) +{ + (s.rdbuf())->setcompressionstrategy(l); + return s; +} + +inline gzomanip setcompressionlevel(int l) +{ + return gzomanip(&setcompressionlevel,l); +} + +inline gzomanip setcompressionstrategy(int l) +{ + return gzomanip(&setcompressionstrategy,l); +} + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/iostream2/zstream.h b/third_party/zlib/v1_2_11/contrib/iostream2/zstream.h new file mode 100644 index 0000000..43d2332 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream2/zstream.h @@ -0,0 +1,307 @@ +/* + * + * Copyright (c) 1997 + * Christian Michelsen Research AS + * Advanced Computing + * Fantoftvegen 38, 5036 BERGEN, Norway + * http://www.cmr.no + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Christian Michelsen Research AS makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + */ + +#ifndef ZSTREAM__H +#define ZSTREAM__H + +/* + * zstream.h - C++ interface to the 'zlib' general purpose compression library + * $Id: zstream.h 1.1 1997-06-25 12:00:56+02 tyge Exp tyge $ + */ + +#include +#include +#include +#include "zlib.h" + +#if defined(_WIN32) +# include +# include +# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif + +class zstringlen { +public: + zstringlen(class izstream&); + zstringlen(class ozstream&, const char*); + size_t value() const { return val.word; } +private: + struct Val { unsigned char byte; size_t word; } val; +}; + +// ----------------------------- izstream ----------------------------- + +class izstream +{ + public: + izstream() : m_fp(0) {} + izstream(FILE* fp) : m_fp(0) { open(fp); } + izstream(const char* name) : m_fp(0) { open(name); } + ~izstream() { close(); } + + /* Opens a gzip (.gz) file for reading. + * open() can be used to read a file which is not in gzip format; + * in this case read() will directly read from the file without + * decompression. errno can be checked to distinguish two error + * cases (if errno is zero, the zlib error is Z_MEM_ERROR). + */ + void open(const char* name) { + if (m_fp) close(); + m_fp = ::gzopen(name, "rb"); + } + + void open(FILE* fp) { + SET_BINARY_MODE(fp); + if (m_fp) close(); + m_fp = ::gzdopen(fileno(fp), "rb"); + } + + /* Flushes all pending input if necessary, closes the compressed file + * and deallocates all the (de)compression state. The return value is + * the zlib error number (see function error() below). + */ + int close() { + int r = ::gzclose(m_fp); + m_fp = 0; return r; + } + + /* Binary read the given number of bytes from the compressed file. + */ + int read(void* buf, size_t len) { + return ::gzread(m_fp, buf, len); + } + + /* Returns the error message for the last error which occurred on the + * given compressed file. errnum is set to zlib error number. If an + * error occurred in the file system and not in the compression library, + * errnum is set to Z_ERRNO and the application may consult errno + * to get the exact error code. + */ + const char* error(int* errnum) { + return ::gzerror(m_fp, errnum); + } + + gzFile fp() { return m_fp; } + + private: + gzFile m_fp; +}; + +/* + * Binary read the given (array of) object(s) from the compressed file. + * If the input file was not in gzip format, read() copies the objects number + * of bytes into the buffer. + * returns the number of uncompressed bytes actually read + * (0 for end of file, -1 for error). + */ +template +inline int read(izstream& zs, T* x, Items items) { + return ::gzread(zs.fp(), x, items*sizeof(T)); +} + +/* + * Binary input with the '>' operator. + */ +template +inline izstream& operator>(izstream& zs, T& x) { + ::gzread(zs.fp(), &x, sizeof(T)); + return zs; +} + + +inline zstringlen::zstringlen(izstream& zs) { + zs > val.byte; + if (val.byte == 255) zs > val.word; + else val.word = val.byte; +} + +/* + * Read length of string + the string with the '>' operator. + */ +inline izstream& operator>(izstream& zs, char* x) { + zstringlen len(zs); + ::gzread(zs.fp(), x, len.value()); + x[len.value()] = '\0'; + return zs; +} + +inline char* read_string(izstream& zs) { + zstringlen len(zs); + char* x = new char[len.value()+1]; + ::gzread(zs.fp(), x, len.value()); + x[len.value()] = '\0'; + return x; +} + +// ----------------------------- ozstream ----------------------------- + +class ozstream +{ + public: + ozstream() : m_fp(0), m_os(0) { + } + ozstream(FILE* fp, int level = Z_DEFAULT_COMPRESSION) + : m_fp(0), m_os(0) { + open(fp, level); + } + ozstream(const char* name, int level = Z_DEFAULT_COMPRESSION) + : m_fp(0), m_os(0) { + open(name, level); + } + ~ozstream() { + close(); + } + + /* Opens a gzip (.gz) file for writing. + * The compression level parameter should be in 0..9 + * errno can be checked to distinguish two error cases + * (if errno is zero, the zlib error is Z_MEM_ERROR). + */ + void open(const char* name, int level = Z_DEFAULT_COMPRESSION) { + char mode[4] = "wb\0"; + if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; + if (m_fp) close(); + m_fp = ::gzopen(name, mode); + } + + /* open from a FILE pointer. + */ + void open(FILE* fp, int level = Z_DEFAULT_COMPRESSION) { + SET_BINARY_MODE(fp); + char mode[4] = "wb\0"; + if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level; + if (m_fp) close(); + m_fp = ::gzdopen(fileno(fp), mode); + } + + /* Flushes all pending output if necessary, closes the compressed file + * and deallocates all the (de)compression state. The return value is + * the zlib error number (see function error() below). + */ + int close() { + if (m_os) { + ::gzwrite(m_fp, m_os->str(), m_os->pcount()); + delete[] m_os->str(); delete m_os; m_os = 0; + } + int r = ::gzclose(m_fp); m_fp = 0; return r; + } + + /* Binary write the given number of bytes into the compressed file. + */ + int write(const void* buf, size_t len) { + return ::gzwrite(m_fp, (voidp) buf, len); + } + + /* Flushes all pending output into the compressed file. The parameter + * _flush is as in the deflate() function. The return value is the zlib + * error number (see function gzerror below). flush() returns Z_OK if + * the flush_ parameter is Z_FINISH and all output could be flushed. + * flush() should be called only when strictly necessary because it can + * degrade compression. + */ + int flush(int _flush) { + os_flush(); + return ::gzflush(m_fp, _flush); + } + + /* Returns the error message for the last error which occurred on the + * given compressed file. errnum is set to zlib error number. If an + * error occurred in the file system and not in the compression library, + * errnum is set to Z_ERRNO and the application may consult errno + * to get the exact error code. + */ + const char* error(int* errnum) { + return ::gzerror(m_fp, errnum); + } + + gzFile fp() { return m_fp; } + + ostream& os() { + if (m_os == 0) m_os = new ostrstream; + return *m_os; + } + + void os_flush() { + if (m_os && m_os->pcount()>0) { + ostrstream* oss = new ostrstream; + oss->fill(m_os->fill()); + oss->flags(m_os->flags()); + oss->precision(m_os->precision()); + oss->width(m_os->width()); + ::gzwrite(m_fp, m_os->str(), m_os->pcount()); + delete[] m_os->str(); delete m_os; m_os = oss; + } + } + + private: + gzFile m_fp; + ostrstream* m_os; +}; + +/* + * Binary write the given (array of) object(s) into the compressed file. + * returns the number of uncompressed bytes actually written + * (0 in case of error). + */ +template +inline int write(ozstream& zs, const T* x, Items items) { + return ::gzwrite(zs.fp(), (voidp) x, items*sizeof(T)); +} + +/* + * Binary output with the '<' operator. + */ +template +inline ozstream& operator<(ozstream& zs, const T& x) { + ::gzwrite(zs.fp(), (voidp) &x, sizeof(T)); + return zs; +} + +inline zstringlen::zstringlen(ozstream& zs, const char* x) { + val.byte = 255; val.word = ::strlen(x); + if (val.word < 255) zs < (val.byte = val.word); + else zs < val; +} + +/* + * Write length of string + the string with the '<' operator. + */ +inline ozstream& operator<(ozstream& zs, const char* x) { + zstringlen len(zs, x); + ::gzwrite(zs.fp(), (voidp) x, len.value()); + return zs; +} + +#ifdef _MSC_VER +inline ozstream& operator<(ozstream& zs, char* const& x) { + return zs < (const char*) x; +} +#endif + +/* + * Ascii write with the << operator; + */ +template +inline ostream& operator<<(ozstream& zs, const T& x) { + zs.os_flush(); + return zs.os() << x; +} + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/iostream2/zstream_test.cpp b/third_party/zlib/v1_2_11/contrib/iostream2/zstream_test.cpp new file mode 100644 index 0000000..6273f62 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream2/zstream_test.cpp @@ -0,0 +1,25 @@ +#include "zstream.h" +#include +#include +#include + +void main() { + char h[256] = "Hello"; + char* g = "Goodbye"; + ozstream out("temp.gz"); + out < "This works well" < h < g; + out.close(); + + izstream in("temp.gz"); // read it back + char *x = read_string(in), *y = new char[256], z[256]; + in > y > z; + in.close(); + cout << x << endl << y << endl << z << endl; + + out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results + out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl; + out << z << endl << y << endl << x << endl; + out << 1.1234567890123456789 << endl; + + delete[] x; delete[] y; +} diff --git a/third_party/zlib/v1_2_11/contrib/iostream3/README b/third_party/zlib/v1_2_11/contrib/iostream3/README new file mode 100644 index 0000000..f7b319a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream3/README @@ -0,0 +1,35 @@ +These classes provide a C++ stream interface to the zlib library. It allows you +to do things like: + + gzofstream outf("blah.gz"); + outf << "These go into the gzip file " << 123 << endl; + +It does this by deriving a specialized stream buffer for gzipped files, which is +the way Stroustrup would have done it. :-> + +The gzifstream and gzofstream classes were originally written by Kevin Ruland +and made available in the zlib contrib/iostream directory. The older version still +compiles under gcc 2.xx, but not under gcc 3.xx, which sparked the development of +this version. + +The new classes are as standard-compliant as possible, closely following the +approach of the standard library's fstream classes. It compiles under gcc versions +3.2 and 3.3, but not under gcc 2.xx. This is mainly due to changes in the standard +library naming scheme. The new version of gzifstream/gzofstream/gzfilebuf differs +from the previous one in the following respects: +- added showmanyc +- added setbuf, with support for unbuffered output via setbuf(0,0) +- a few bug fixes of stream behavior +- gzipped output file opened with default compression level instead of maximum level +- setcompressionlevel()/strategy() members replaced by single setcompression() + +The code is provided "as is", with the permission to use, copy, modify, distribute +and sell it for any purpose without fee. + +Ludwig Schwardt + + +DSP Lab +Electrical & Electronic Engineering Department +University of Stellenbosch +South Africa diff --git a/third_party/zlib/v1_2_11/contrib/iostream3/TODO b/third_party/zlib/v1_2_11/contrib/iostream3/TODO new file mode 100644 index 0000000..7032f97 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream3/TODO @@ -0,0 +1,17 @@ +Possible upgrades to gzfilebuf: + +- The ability to do putback (e.g. putbackfail) + +- The ability to seek (zlib supports this, but could be slow/tricky) + +- Simultaneous read/write access (does it make sense?) + +- Support for ios_base::ate open mode + +- Locale support? + +- Check public interface to see which calls give problems + (due to dependence on library internals) + +- Override operator<<(ostream&, gzfilebuf*) to allow direct copying + of stream buffer to stream ( i.e. os << is.rdbuf(); ) diff --git a/third_party/zlib/v1_2_11/contrib/iostream3/test.cc b/third_party/zlib/v1_2_11/contrib/iostream3/test.cc new file mode 100644 index 0000000..9423533 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream3/test.cc @@ -0,0 +1,50 @@ +/* + * Test program for gzifstream and gzofstream + * + * by Ludwig Schwardt + * original version by Kevin Ruland + */ + +#include "zfstream.h" +#include // for cout + +int main() { + + gzofstream outf; + gzifstream inf; + char buf[80]; + + outf.open("test1.txt.gz"); + outf << "The quick brown fox sidestepped the lazy canine\n" + << 1.3 << "\nPlan " << 9 << std::endl; + outf.close(); + std::cout << "Wrote the following message to 'test1.txt.gz' (check with zcat or zless):\n" + << "The quick brown fox sidestepped the lazy canine\n" + << 1.3 << "\nPlan " << 9 << std::endl; + + std::cout << "\nReading 'test1.txt.gz' (buffered) produces:\n"; + inf.open("test1.txt.gz"); + while (inf.getline(buf,80,'\n')) { + std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; + } + inf.close(); + + outf.rdbuf()->pubsetbuf(0,0); + outf.open("test2.txt.gz"); + outf << setcompression(Z_NO_COMPRESSION) + << "The quick brown fox sidestepped the lazy canine\n" + << 1.3 << "\nPlan " << 9 << std::endl; + outf.close(); + std::cout << "\nWrote the same message to 'test2.txt.gz' in uncompressed form"; + + std::cout << "\nReading 'test2.txt.gz' (unbuffered) produces:\n"; + inf.rdbuf()->pubsetbuf(0,0); + inf.open("test2.txt.gz"); + while (inf.getline(buf,80,'\n')) { + std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n"; + } + inf.close(); + + return 0; + +} diff --git a/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.cc b/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.cc new file mode 100644 index 0000000..94eb933 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.cc @@ -0,0 +1,479 @@ +/* + * A C++ I/O streams interface to the zlib gz* functions + * + * by Ludwig Schwardt + * original version by Kevin Ruland + * + * This version is standard-compliant and compatible with gcc 3.x. + */ + +#include "zfstream.h" +#include // for strcpy, strcat, strlen (mode strings) +#include // for BUFSIZ + +// Internal buffer sizes (default and "unbuffered" versions) +#define BIGBUFSIZE BUFSIZ +#define SMALLBUFSIZE 1 + +/*****************************************************************************/ + +// Default constructor +gzfilebuf::gzfilebuf() +: file(NULL), io_mode(std::ios_base::openmode(0)), own_fd(false), + buffer(NULL), buffer_size(BIGBUFSIZE), own_buffer(true) +{ + // No buffers to start with + this->disable_buffer(); +} + +// Destructor +gzfilebuf::~gzfilebuf() +{ + // Sync output buffer and close only if responsible for file + // (i.e. attached streams should be left open at this stage) + this->sync(); + if (own_fd) + this->close(); + // Make sure internal buffer is deallocated + this->disable_buffer(); +} + +// Set compression level and strategy +int +gzfilebuf::setcompression(int comp_level, + int comp_strategy) +{ + return gzsetparams(file, comp_level, comp_strategy); +} + +// Open gzipped file +gzfilebuf* +gzfilebuf::open(const char *name, + std::ios_base::openmode mode) +{ + // Fail if file already open + if (this->is_open()) + return NULL; + // Don't support simultaneous read/write access (yet) + if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) + return NULL; + + // Build mode string for gzopen and check it [27.8.1.3.2] + char char_mode[6] = "\0\0\0\0\0"; + if (!this->open_mode(mode, char_mode)) + return NULL; + + // Attempt to open file + if ((file = gzopen(name, char_mode)) == NULL) + return NULL; + + // On success, allocate internal buffer and set flags + this->enable_buffer(); + io_mode = mode; + own_fd = true; + return this; +} + +// Attach to gzipped file +gzfilebuf* +gzfilebuf::attach(int fd, + std::ios_base::openmode mode) +{ + // Fail if file already open + if (this->is_open()) + return NULL; + // Don't support simultaneous read/write access (yet) + if ((mode & std::ios_base::in) && (mode & std::ios_base::out)) + return NULL; + + // Build mode string for gzdopen and check it [27.8.1.3.2] + char char_mode[6] = "\0\0\0\0\0"; + if (!this->open_mode(mode, char_mode)) + return NULL; + + // Attempt to attach to file + if ((file = gzdopen(fd, char_mode)) == NULL) + return NULL; + + // On success, allocate internal buffer and set flags + this->enable_buffer(); + io_mode = mode; + own_fd = false; + return this; +} + +// Close gzipped file +gzfilebuf* +gzfilebuf::close() +{ + // Fail immediately if no file is open + if (!this->is_open()) + return NULL; + // Assume success + gzfilebuf* retval = this; + // Attempt to sync and close gzipped file + if (this->sync() == -1) + retval = NULL; + if (gzclose(file) < 0) + retval = NULL; + // File is now gone anyway (postcondition [27.8.1.3.8]) + file = NULL; + own_fd = false; + // Destroy internal buffer if it exists + this->disable_buffer(); + return retval; +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// Convert int open mode to mode string +bool +gzfilebuf::open_mode(std::ios_base::openmode mode, + char* c_mode) const +{ + bool testb = mode & std::ios_base::binary; + bool testi = mode & std::ios_base::in; + bool testo = mode & std::ios_base::out; + bool testt = mode & std::ios_base::trunc; + bool testa = mode & std::ios_base::app; + + // Check for valid flag combinations - see [27.8.1.3.2] (Table 92) + // Original zfstream hardcoded the compression level to maximum here... + // Double the time for less than 1% size improvement seems + // excessive though - keeping it at the default level + // To change back, just append "9" to the next three mode strings + if (!testi && testo && !testt && !testa) + strcpy(c_mode, "w"); + if (!testi && testo && !testt && testa) + strcpy(c_mode, "a"); + if (!testi && testo && testt && !testa) + strcpy(c_mode, "w"); + if (testi && !testo && !testt && !testa) + strcpy(c_mode, "r"); + // No read/write mode yet +// if (testi && testo && !testt && !testa) +// strcpy(c_mode, "r+"); +// if (testi && testo && testt && !testa) +// strcpy(c_mode, "w+"); + + // Mode string should be empty for invalid combination of flags + if (strlen(c_mode) == 0) + return false; + if (testb) + strcat(c_mode, "b"); + return true; +} + +// Determine number of characters in internal get buffer +std::streamsize +gzfilebuf::showmanyc() +{ + // Calls to underflow will fail if file not opened for reading + if (!this->is_open() || !(io_mode & std::ios_base::in)) + return -1; + // Make sure get area is in use + if (this->gptr() && (this->gptr() < this->egptr())) + return std::streamsize(this->egptr() - this->gptr()); + else + return 0; +} + +// Fill get area from gzipped file +gzfilebuf::int_type +gzfilebuf::underflow() +{ + // If something is left in the get area by chance, return it + // (this shouldn't normally happen, as underflow is only supposed + // to be called when gptr >= egptr, but it serves as error check) + if (this->gptr() && (this->gptr() < this->egptr())) + return traits_type::to_int_type(*(this->gptr())); + + // If the file hasn't been opened for reading, produce error + if (!this->is_open() || !(io_mode & std::ios_base::in)) + return traits_type::eof(); + + // Attempt to fill internal buffer from gzipped file + // (buffer must be guaranteed to exist...) + int bytes_read = gzread(file, buffer, buffer_size); + // Indicates error or EOF + if (bytes_read <= 0) + { + // Reset get area + this->setg(buffer, buffer, buffer); + return traits_type::eof(); + } + // Make all bytes read from file available as get area + this->setg(buffer, buffer, buffer + bytes_read); + + // Return next character in get area + return traits_type::to_int_type(*(this->gptr())); +} + +// Write put area to gzipped file +gzfilebuf::int_type +gzfilebuf::overflow(int_type c) +{ + // Determine whether put area is in use + if (this->pbase()) + { + // Double-check pointer range + if (this->pptr() > this->epptr() || this->pptr() < this->pbase()) + return traits_type::eof(); + // Add extra character to buffer if not EOF + if (!traits_type::eq_int_type(c, traits_type::eof())) + { + *(this->pptr()) = traits_type::to_char_type(c); + this->pbump(1); + } + // Number of characters to write to file + int bytes_to_write = this->pptr() - this->pbase(); + // Overflow doesn't fail if nothing is to be written + if (bytes_to_write > 0) + { + // If the file hasn't been opened for writing, produce error + if (!this->is_open() || !(io_mode & std::ios_base::out)) + return traits_type::eof(); + // If gzipped file won't accept all bytes written to it, fail + if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write) + return traits_type::eof(); + // Reset next pointer to point to pbase on success + this->pbump(-bytes_to_write); + } + } + // Write extra character to file if not EOF + else if (!traits_type::eq_int_type(c, traits_type::eof())) + { + // If the file hasn't been opened for writing, produce error + if (!this->is_open() || !(io_mode & std::ios_base::out)) + return traits_type::eof(); + // Impromptu char buffer (allows "unbuffered" output) + char_type last_char = traits_type::to_char_type(c); + // If gzipped file won't accept this character, fail + if (gzwrite(file, &last_char, 1) != 1) + return traits_type::eof(); + } + + // If you got here, you have succeeded (even if c was EOF) + // The return value should therefore be non-EOF + if (traits_type::eq_int_type(c, traits_type::eof())) + return traits_type::not_eof(c); + else + return c; +} + +// Assign new buffer +std::streambuf* +gzfilebuf::setbuf(char_type* p, + std::streamsize n) +{ + // First make sure stuff is sync'ed, for safety + if (this->sync() == -1) + return NULL; + // If buffering is turned off on purpose via setbuf(0,0), still allocate one... + // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at + // least a buffer of size 1 (very inefficient though, therefore make it bigger?) + // This follows from [27.5.2.4.3]/12 (gptr needs to point at something, it seems) + if (!p || !n) + { + // Replace existing buffer (if any) with small internal buffer + this->disable_buffer(); + buffer = NULL; + buffer_size = 0; + own_buffer = true; + this->enable_buffer(); + } + else + { + // Replace existing buffer (if any) with external buffer + this->disable_buffer(); + buffer = p; + buffer_size = n; + own_buffer = false; + this->enable_buffer(); + } + return this; +} + +// Write put area to gzipped file (i.e. ensures that put area is empty) +int +gzfilebuf::sync() +{ + return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0; +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// Allocate internal buffer +void +gzfilebuf::enable_buffer() +{ + // If internal buffer required, allocate one + if (own_buffer && !buffer) + { + // Check for buffered vs. "unbuffered" + if (buffer_size > 0) + { + // Allocate internal buffer + buffer = new char_type[buffer_size]; + // Get area starts empty and will be expanded by underflow as need arises + this->setg(buffer, buffer, buffer); + // Setup entire internal buffer as put area. + // The one-past-end pointer actually points to the last element of the buffer, + // so that overflow(c) can safely add the extra character c to the sequence. + // These pointers remain in place for the duration of the buffer + this->setp(buffer, buffer + buffer_size - 1); + } + else + { + // Even in "unbuffered" case, (small?) get buffer is still required + buffer_size = SMALLBUFSIZE; + buffer = new char_type[buffer_size]; + this->setg(buffer, buffer, buffer); + // "Unbuffered" means no put buffer + this->setp(0, 0); + } + } + else + { + // If buffer already allocated, reset buffer pointers just to make sure no + // stale chars are lying around + this->setg(buffer, buffer, buffer); + this->setp(buffer, buffer + buffer_size - 1); + } +} + +// Destroy internal buffer +void +gzfilebuf::disable_buffer() +{ + // If internal buffer exists, deallocate it + if (own_buffer && buffer) + { + // Preserve unbuffered status by zeroing size + if (!this->pbase()) + buffer_size = 0; + delete[] buffer; + buffer = NULL; + this->setg(0, 0, 0); + this->setp(0, 0); + } + else + { + // Reset buffer pointers to initial state if external buffer exists + this->setg(buffer, buffer, buffer); + if (buffer) + this->setp(buffer, buffer + buffer_size - 1); + else + this->setp(0, 0); + } +} + +/*****************************************************************************/ + +// Default constructor initializes stream buffer +gzifstream::gzifstream() +: std::istream(NULL), sb() +{ this->init(&sb); } + +// Initialize stream buffer and open file +gzifstream::gzifstream(const char* name, + std::ios_base::openmode mode) +: std::istream(NULL), sb() +{ + this->init(&sb); + this->open(name, mode); +} + +// Initialize stream buffer and attach to file +gzifstream::gzifstream(int fd, + std::ios_base::openmode mode) +: std::istream(NULL), sb() +{ + this->init(&sb); + this->attach(fd, mode); +} + +// Open file and go into fail() state if unsuccessful +void +gzifstream::open(const char* name, + std::ios_base::openmode mode) +{ + if (!sb.open(name, mode | std::ios_base::in)) + this->setstate(std::ios_base::failbit); + else + this->clear(); +} + +// Attach to file and go into fail() state if unsuccessful +void +gzifstream::attach(int fd, + std::ios_base::openmode mode) +{ + if (!sb.attach(fd, mode | std::ios_base::in)) + this->setstate(std::ios_base::failbit); + else + this->clear(); +} + +// Close file +void +gzifstream::close() +{ + if (!sb.close()) + this->setstate(std::ios_base::failbit); +} + +/*****************************************************************************/ + +// Default constructor initializes stream buffer +gzofstream::gzofstream() +: std::ostream(NULL), sb() +{ this->init(&sb); } + +// Initialize stream buffer and open file +gzofstream::gzofstream(const char* name, + std::ios_base::openmode mode) +: std::ostream(NULL), sb() +{ + this->init(&sb); + this->open(name, mode); +} + +// Initialize stream buffer and attach to file +gzofstream::gzofstream(int fd, + std::ios_base::openmode mode) +: std::ostream(NULL), sb() +{ + this->init(&sb); + this->attach(fd, mode); +} + +// Open file and go into fail() state if unsuccessful +void +gzofstream::open(const char* name, + std::ios_base::openmode mode) +{ + if (!sb.open(name, mode | std::ios_base::out)) + this->setstate(std::ios_base::failbit); + else + this->clear(); +} + +// Attach to file and go into fail() state if unsuccessful +void +gzofstream::attach(int fd, + std::ios_base::openmode mode) +{ + if (!sb.attach(fd, mode | std::ios_base::out)) + this->setstate(std::ios_base::failbit); + else + this->clear(); +} + +// Close file +void +gzofstream::close() +{ + if (!sb.close()) + this->setstate(std::ios_base::failbit); +} diff --git a/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.h b/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.h new file mode 100644 index 0000000..8574479 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/iostream3/zfstream.h @@ -0,0 +1,466 @@ +/* + * A C++ I/O streams interface to the zlib gz* functions + * + * by Ludwig Schwardt + * original version by Kevin Ruland + * + * This version is standard-compliant and compatible with gcc 3.x. + */ + +#ifndef ZFSTREAM_H +#define ZFSTREAM_H + +#include // not iostream, since we don't need cin/cout +#include +#include "zlib.h" + +/*****************************************************************************/ + +/** + * @brief Gzipped file stream buffer class. + * + * This class implements basic_filebuf for gzipped files. It doesn't yet support + * seeking (allowed by zlib but slow/limited), putback and read/write access + * (tricky). Otherwise, it attempts to be a drop-in replacement for the standard + * file streambuf. +*/ +class gzfilebuf : public std::streambuf +{ +public: + // Default constructor. + gzfilebuf(); + + // Destructor. + virtual + ~gzfilebuf(); + + /** + * @brief Set compression level and strategy on the fly. + * @param comp_level Compression level (see zlib.h for allowed values) + * @param comp_strategy Compression strategy (see zlib.h for allowed values) + * @return Z_OK on success, Z_STREAM_ERROR otherwise. + * + * Unfortunately, these parameters cannot be modified separately, as the + * previous zfstream version assumed. Since the strategy is seldom changed, + * it can default and setcompression(level) then becomes like the old + * setcompressionlevel(level). + */ + int + setcompression(int comp_level, + int comp_strategy = Z_DEFAULT_STRATEGY); + + /** + * @brief Check if file is open. + * @return True if file is open. + */ + bool + is_open() const { return (file != NULL); } + + /** + * @brief Open gzipped file. + * @param name File name. + * @param mode Open mode flags. + * @return @c this on success, NULL on failure. + */ + gzfilebuf* + open(const char* name, + std::ios_base::openmode mode); + + /** + * @brief Attach to already open gzipped file. + * @param fd File descriptor. + * @param mode Open mode flags. + * @return @c this on success, NULL on failure. + */ + gzfilebuf* + attach(int fd, + std::ios_base::openmode mode); + + /** + * @brief Close gzipped file. + * @return @c this on success, NULL on failure. + */ + gzfilebuf* + close(); + +protected: + /** + * @brief Convert ios open mode int to mode string used by zlib. + * @return True if valid mode flag combination. + */ + bool + open_mode(std::ios_base::openmode mode, + char* c_mode) const; + + /** + * @brief Number of characters available in stream buffer. + * @return Number of characters. + * + * This indicates number of characters in get area of stream buffer. + * These characters can be read without accessing the gzipped file. + */ + virtual std::streamsize + showmanyc(); + + /** + * @brief Fill get area from gzipped file. + * @return First character in get area on success, EOF on error. + * + * This actually reads characters from gzipped file to stream + * buffer. Always buffered. + */ + virtual int_type + underflow(); + + /** + * @brief Write put area to gzipped file. + * @param c Extra character to add to buffer contents. + * @return Non-EOF on success, EOF on error. + * + * This actually writes characters in stream buffer to + * gzipped file. With unbuffered output this is done one + * character at a time. + */ + virtual int_type + overflow(int_type c = traits_type::eof()); + + /** + * @brief Installs external stream buffer. + * @param p Pointer to char buffer. + * @param n Size of external buffer. + * @return @c this on success, NULL on failure. + * + * Call setbuf(0,0) to enable unbuffered output. + */ + virtual std::streambuf* + setbuf(char_type* p, + std::streamsize n); + + /** + * @brief Flush stream buffer to file. + * @return 0 on success, -1 on error. + * + * This calls underflow(EOF) to do the job. + */ + virtual int + sync(); + +// +// Some future enhancements +// +// virtual int_type uflow(); +// virtual int_type pbackfail(int_type c = traits_type::eof()); +// virtual pos_type +// seekoff(off_type off, +// std::ios_base::seekdir way, +// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); +// virtual pos_type +// seekpos(pos_type sp, +// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out); + +private: + /** + * @brief Allocate internal buffer. + * + * This function is safe to call multiple times. It will ensure + * that a proper internal buffer exists if it is required. If the + * buffer already exists or is external, the buffer pointers will be + * reset to their original state. + */ + void + enable_buffer(); + + /** + * @brief Destroy internal buffer. + * + * This function is safe to call multiple times. It will ensure + * that the internal buffer is deallocated if it exists. In any + * case, it will also reset the buffer pointers. + */ + void + disable_buffer(); + + /** + * Underlying file pointer. + */ + gzFile file; + + /** + * Mode in which file was opened. + */ + std::ios_base::openmode io_mode; + + /** + * @brief True if this object owns file descriptor. + * + * This makes the class responsible for closing the file + * upon destruction. + */ + bool own_fd; + + /** + * @brief Stream buffer. + * + * For simplicity this remains allocated on the free store for the + * entire life span of the gzfilebuf object, unless replaced by setbuf. + */ + char_type* buffer; + + /** + * @brief Stream buffer size. + * + * Defaults to system default buffer size (typically 8192 bytes). + * Modified by setbuf. + */ + std::streamsize buffer_size; + + /** + * @brief True if this object owns stream buffer. + * + * This makes the class responsible for deleting the buffer + * upon destruction. + */ + bool own_buffer; +}; + +/*****************************************************************************/ + +/** + * @brief Gzipped file input stream class. + * + * This class implements ifstream for gzipped files. Seeking and putback + * is not supported yet. +*/ +class gzifstream : public std::istream +{ +public: + // Default constructor + gzifstream(); + + /** + * @brief Construct stream on gzipped file to be opened. + * @param name File name. + * @param mode Open mode flags (forced to contain ios::in). + */ + explicit + gzifstream(const char* name, + std::ios_base::openmode mode = std::ios_base::in); + + /** + * @brief Construct stream on already open gzipped file. + * @param fd File descriptor. + * @param mode Open mode flags (forced to contain ios::in). + */ + explicit + gzifstream(int fd, + std::ios_base::openmode mode = std::ios_base::in); + + /** + * Obtain underlying stream buffer. + */ + gzfilebuf* + rdbuf() const + { return const_cast(&sb); } + + /** + * @brief Check if file is open. + * @return True if file is open. + */ + bool + is_open() { return sb.is_open(); } + + /** + * @brief Open gzipped file. + * @param name File name. + * @param mode Open mode flags (forced to contain ios::in). + * + * Stream will be in state good() if file opens successfully; + * otherwise in state fail(). This differs from the behavior of + * ifstream, which never sets the state to good() and therefore + * won't allow you to reuse the stream for a second file unless + * you manually clear() the state. The choice is a matter of + * convenience. + */ + void + open(const char* name, + std::ios_base::openmode mode = std::ios_base::in); + + /** + * @brief Attach to already open gzipped file. + * @param fd File descriptor. + * @param mode Open mode flags (forced to contain ios::in). + * + * Stream will be in state good() if attach succeeded; otherwise + * in state fail(). + */ + void + attach(int fd, + std::ios_base::openmode mode = std::ios_base::in); + + /** + * @brief Close gzipped file. + * + * Stream will be in state fail() if close failed. + */ + void + close(); + +private: + /** + * Underlying stream buffer. + */ + gzfilebuf sb; +}; + +/*****************************************************************************/ + +/** + * @brief Gzipped file output stream class. + * + * This class implements ofstream for gzipped files. Seeking and putback + * is not supported yet. +*/ +class gzofstream : public std::ostream +{ +public: + // Default constructor + gzofstream(); + + /** + * @brief Construct stream on gzipped file to be opened. + * @param name File name. + * @param mode Open mode flags (forced to contain ios::out). + */ + explicit + gzofstream(const char* name, + std::ios_base::openmode mode = std::ios_base::out); + + /** + * @brief Construct stream on already open gzipped file. + * @param fd File descriptor. + * @param mode Open mode flags (forced to contain ios::out). + */ + explicit + gzofstream(int fd, + std::ios_base::openmode mode = std::ios_base::out); + + /** + * Obtain underlying stream buffer. + */ + gzfilebuf* + rdbuf() const + { return const_cast(&sb); } + + /** + * @brief Check if file is open. + * @return True if file is open. + */ + bool + is_open() { return sb.is_open(); } + + /** + * @brief Open gzipped file. + * @param name File name. + * @param mode Open mode flags (forced to contain ios::out). + * + * Stream will be in state good() if file opens successfully; + * otherwise in state fail(). This differs from the behavior of + * ofstream, which never sets the state to good() and therefore + * won't allow you to reuse the stream for a second file unless + * you manually clear() the state. The choice is a matter of + * convenience. + */ + void + open(const char* name, + std::ios_base::openmode mode = std::ios_base::out); + + /** + * @brief Attach to already open gzipped file. + * @param fd File descriptor. + * @param mode Open mode flags (forced to contain ios::out). + * + * Stream will be in state good() if attach succeeded; otherwise + * in state fail(). + */ + void + attach(int fd, + std::ios_base::openmode mode = std::ios_base::out); + + /** + * @brief Close gzipped file. + * + * Stream will be in state fail() if close failed. + */ + void + close(); + +private: + /** + * Underlying stream buffer. + */ + gzfilebuf sb; +}; + +/*****************************************************************************/ + +/** + * @brief Gzipped file output stream manipulator class. + * + * This class defines a two-argument manipulator for gzofstream. It is used + * as base for the setcompression(int,int) manipulator. +*/ +template + class gzomanip2 + { + public: + // Allows insertor to peek at internals + template + friend gzofstream& + operator<<(gzofstream&, + const gzomanip2&); + + // Constructor + gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2), + T1 v1, + T2 v2); + private: + // Underlying manipulator function + gzofstream& + (*func)(gzofstream&, T1, T2); + + // Arguments for manipulator function + T1 val1; + T2 val2; + }; + +/*****************************************************************************/ + +// Manipulator function thunks through to stream buffer +inline gzofstream& +setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY) +{ + (gzs.rdbuf())->setcompression(l, s); + return gzs; +} + +// Manipulator constructor stores arguments +template + inline + gzomanip2::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2), + T1 v1, + T2 v2) + : func(f), val1(v1), val2(v2) + { } + +// Insertor applies underlying manipulator function to stream +template + inline gzofstream& + operator<<(gzofstream& s, const gzomanip2& m) + { return (*m.func)(s, m.val1, m.val2); } + +// Insert this onto stream to simplify setting of compression level +inline gzomanip2 +setcompression(int l, int s = Z_DEFAULT_STRATEGY) +{ return gzomanip2(&setcompression, l, s); } + +#endif // ZFSTREAM_H diff --git a/third_party/zlib/v1_2_11/contrib/masmx64/bld_ml64.bat b/third_party/zlib/v1_2_11/contrib/masmx64/bld_ml64.bat new file mode 100644 index 0000000..8f9343d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx64/bld_ml64.bat @@ -0,0 +1,2 @@ +ml64.exe /Flinffasx64 /c /Zi inffasx64.asm +ml64.exe /Flgvmat64 /c /Zi gvmat64.asm diff --git a/third_party/zlib/v1_2_11/contrib/masmx64/gvmat64.asm b/third_party/zlib/v1_2_11/contrib/masmx64/gvmat64.asm new file mode 100644 index 0000000..9879c28 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx64/gvmat64.asm @@ -0,0 +1,553 @@ +;uInt longest_match_x64( +; deflate_state *s, +; IPos cur_match); /* current match */ + +; gvmat64.asm -- Asm portion of the optimized longest_match for 32 bits x86_64 +; (AMD64 on Athlon 64, Opteron, Phenom +; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7) +; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant. +; +; File written by Gilles Vollant, by converting to assembly the longest_match +; from Jean-loup Gailly in deflate.c of zLib and infoZip zip. +; +; and by taking inspiration on asm686 with masm, optimised assembly code +; from Brian Raiter, written 1998 +; +; This software is provided 'as-is', without any express or implied +; warranty. In no event will the authors be held liable for any damages +; arising from the use of this software. +; +; Permission is granted to anyone to use this software for any purpose, +; including commercial applications, and to alter it and redistribute it +; freely, subject to the following restrictions: +; +; 1. The origin of this software must not be misrepresented; you must not +; claim that you wrote the original software. If you use this software +; in a product, an acknowledgment in the product documentation would be +; appreciated but is not required. +; 2. Altered source versions must be plainly marked as such, and must not be +; misrepresented as being the original software +; 3. This notice may not be removed or altered from any source distribution. +; +; +; +; http://www.zlib.net +; http://www.winimage.com/zLibDll +; http://www.muppetlabs.com/~breadbox/software/assembly.html +; +; to compile this file for infozip Zip, I use option: +; ml64.exe /Flgvmat64 /c /Zi /DINFOZIP gvmat64.asm +; +; to compile this file for zLib, I use option: +; ml64.exe /Flgvmat64 /c /Zi gvmat64.asm +; Be carrefull to adapt zlib1222add below to your version of zLib +; (if you use a version of zLib before 1.0.4 or after 1.2.2.2, change +; value of zlib1222add later) +; +; This file compile with Microsoft Macro Assembler (x64) for AMD64 +; +; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK +; +; (you can get Windows WDK with ml64 for AMD64 from +; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) +; + + +;uInt longest_match(s, cur_match) +; deflate_state *s; +; IPos cur_match; /* current match */ +.code +longest_match PROC + + +;LocalVarsSize equ 88 + LocalVarsSize equ 72 + +; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12 +; free register : r14,r15 +; register can be saved : rsp + + chainlenwmask equ rsp + 8 - LocalVarsSize ; high word: current chain len + ; low word: s->wmask +;window equ rsp + xx - LocalVarsSize ; local copy of s->window ; stored in r10 +;windowbestlen equ rsp + xx - LocalVarsSize ; s->window + bestlen , use r10+r11 +;scanstart equ rsp + xx - LocalVarsSize ; first two bytes of string ; stored in r12w +;scanend equ rsp + xx - LocalVarsSize ; last two bytes of string use ebx +;scanalign equ rsp + xx - LocalVarsSize ; dword-misalignment of string r13 +;bestlen equ rsp + xx - LocalVarsSize ; size of best match so far -> r11d +;scan equ rsp + xx - LocalVarsSize ; ptr to string wanting match -> r9 +IFDEF INFOZIP +ELSE + nicematch equ (rsp + 16 - LocalVarsSize) ; a good enough match size +ENDIF + +save_rdi equ rsp + 24 - LocalVarsSize +save_rsi equ rsp + 32 - LocalVarsSize +save_rbx equ rsp + 40 - LocalVarsSize +save_rbp equ rsp + 48 - LocalVarsSize +save_r12 equ rsp + 56 - LocalVarsSize +save_r13 equ rsp + 64 - LocalVarsSize +;save_r14 equ rsp + 72 - LocalVarsSize +;save_r15 equ rsp + 80 - LocalVarsSize + + +; summary of register usage +; scanend ebx +; scanendw bx +; chainlenwmask edx +; curmatch rsi +; curmatchd esi +; windowbestlen r8 +; scanalign r9 +; scanalignd r9d +; window r10 +; bestlen r11 +; bestlend r11d +; scanstart r12d +; scanstartw r12w +; scan r13 +; nicematch r14d +; limit r15 +; limitd r15d +; prev rcx + +; all the +4 offsets are due to the addition of pending_buf_size (in zlib +; in the deflate_state structure since the asm code was first written +; (if you compile with zlib 1.0.4 or older, remove the +4). +; Note : these value are good with a 8 bytes boundary pack structure + + + MAX_MATCH equ 258 + MIN_MATCH equ 3 + MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) + + +;;; Offsets for fields in the deflate_state structure. These numbers +;;; are calculated from the definition of deflate_state, with the +;;; assumption that the compiler will dword-align the fields. (Thus, +;;; changing the definition of deflate_state could easily cause this +;;; program to crash horribly, without so much as a warning at +;;; compile time. Sigh.) + +; all the +zlib1222add offsets are due to the addition of fields +; in zlib in the deflate_state structure since the asm code was first written +; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). +; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). +; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). + + +IFDEF INFOZIP + +_DATA SEGMENT +COMM window_size:DWORD +; WMask ; 7fff +COMM window:BYTE:010040H +COMM prev:WORD:08000H +; MatchLen : unused +; PrevMatch : unused +COMM strstart:DWORD +COMM match_start:DWORD +; Lookahead : ignore +COMM prev_length:DWORD ; PrevLen +COMM max_chain_length:DWORD +COMM good_match:DWORD +COMM nice_match:DWORD +prev_ad equ OFFSET prev +window_ad equ OFFSET window +nicematch equ nice_match +_DATA ENDS +WMask equ 07fffh + +ELSE + + IFNDEF zlib1222add + zlib1222add equ 8 + ENDIF +dsWSize equ 56+zlib1222add+(zlib1222add/2) +dsWMask equ 64+zlib1222add+(zlib1222add/2) +dsWindow equ 72+zlib1222add +dsPrev equ 88+zlib1222add +dsMatchLen equ 128+zlib1222add +dsPrevMatch equ 132+zlib1222add +dsStrStart equ 140+zlib1222add +dsMatchStart equ 144+zlib1222add +dsLookahead equ 148+zlib1222add +dsPrevLen equ 152+zlib1222add +dsMaxChainLen equ 156+zlib1222add +dsGoodMatch equ 172+zlib1222add +dsNiceMatch equ 176+zlib1222add + +window_size equ [ rcx + dsWSize] +WMask equ [ rcx + dsWMask] +window_ad equ [ rcx + dsWindow] +prev_ad equ [ rcx + dsPrev] +strstart equ [ rcx + dsStrStart] +match_start equ [ rcx + dsMatchStart] +Lookahead equ [ rcx + dsLookahead] ; 0ffffffffh on infozip +prev_length equ [ rcx + dsPrevLen] +max_chain_length equ [ rcx + dsMaxChainLen] +good_match equ [ rcx + dsGoodMatch] +nice_match equ [ rcx + dsNiceMatch] +ENDIF + +; parameter 1 in r8(deflate state s), param 2 in rdx (cur match) + +; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and +; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp +; +; All registers must be preserved across the call, except for +; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch. + + + +;;; Save registers that the compiler may be using, and adjust esp to +;;; make room for our stack frame. + + +;;; Retrieve the function arguments. r8d will hold cur_match +;;; throughout the entire function. edx will hold the pointer to the +;;; deflate_state structure during the function's setup (before +;;; entering the main loop. + +; parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match) + +; this clear high 32 bits of r8, which can be garbage in both r8 and rdx + + mov [save_rdi],rdi + mov [save_rsi],rsi + mov [save_rbx],rbx + mov [save_rbp],rbp +IFDEF INFOZIP + mov r8d,ecx +ELSE + mov r8d,edx +ENDIF + mov [save_r12],r12 + mov [save_r13],r13 +; mov [save_r14],r14 +; mov [save_r15],r15 + + +;;; uInt wmask = s->w_mask; +;;; unsigned chain_length = s->max_chain_length; +;;; if (s->prev_length >= s->good_match) { +;;; chain_length >>= 2; +;;; } + + mov edi, prev_length + mov esi, good_match + mov eax, WMask + mov ebx, max_chain_length + cmp edi, esi + jl LastMatchGood + shr ebx, 2 +LastMatchGood: + +;;; chainlen is decremented once beforehand so that the function can +;;; use the sign flag instead of the zero flag for the exit test. +;;; It is then shifted into the high word, to make room for the wmask +;;; value, which it will always accompany. + + dec ebx + shl ebx, 16 + or ebx, eax + +;;; on zlib only +;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + +IFDEF INFOZIP + mov [chainlenwmask], ebx +; on infozip nice_match = [nice_match] +ELSE + mov eax, nice_match + mov [chainlenwmask], ebx + mov r10d, Lookahead + cmp r10d, eax + cmovnl r10d, eax + mov [nicematch],r10d +ENDIF + +;;; register Bytef *scan = s->window + s->strstart; + mov r10, window_ad + mov ebp, strstart + lea r13, [r10 + rbp] + +;;; Determine how many bytes the scan ptr is off from being +;;; dword-aligned. + + mov r9,r13 + neg r13 + and r13,3 + +;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? +;;; s->strstart - (IPos)MAX_DIST(s) : NIL; +IFDEF INFOZIP + mov eax,07efah ; MAX_DIST = (WSIZE-MIN_LOOKAHEAD) (0x8000-(3+8+1)) +ELSE + mov eax, window_size + sub eax, MIN_LOOKAHEAD +ENDIF + xor edi,edi + sub ebp, eax + + mov r11d, prev_length + + cmovng ebp,edi + +;;; int best_len = s->prev_length; + + +;;; Store the sum of s->window + best_len in esi locally, and in esi. + + lea rsi,[r10+r11] + +;;; register ush scan_start = *(ushf*)scan; +;;; register ush scan_end = *(ushf*)(scan+best_len-1); +;;; Posf *prev = s->prev; + + movzx r12d,word ptr [r9] + movzx ebx, word ptr [r9 + r11 - 1] + + mov rdi, prev_ad + +;;; Jump into the main loop. + + mov edx, [chainlenwmask] + + cmp bx,word ptr [rsi + r8 - 1] + jz LookupLoopIsZero + +LookupLoop1: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + jbe LeaveNow + sub edx, 00010000h + js LeaveNow + +LoopEntry1: + cmp bx,word ptr [rsi + r8 - 1] + jz LookupLoopIsZero + +LookupLoop2: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + jbe LeaveNow + sub edx, 00010000h + js LeaveNow + +LoopEntry2: + cmp bx,word ptr [rsi + r8 - 1] + jz LookupLoopIsZero + +LookupLoop4: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + jbe LeaveNow + sub edx, 00010000h + js LeaveNow + +LoopEntry4: + + cmp bx,word ptr [rsi + r8 - 1] + jnz LookupLoop1 + jmp LookupLoopIsZero + + +;;; do { +;;; match = s->window + cur_match; +;;; if (*(ushf*)(match+best_len-1) != scan_end || +;;; *(ushf*)match != scan_start) continue; +;;; [...] +;;; } while ((cur_match = prev[cur_match & wmask]) > limit +;;; && --chain_length != 0); +;;; +;;; Here is the inner loop of the function. The function will spend the +;;; majority of its time in this loop, and majority of that time will +;;; be spent in the first ten instructions. +;;; +;;; Within this loop: +;;; ebx = scanend +;;; r8d = curmatch +;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) +;;; esi = windowbestlen - i.e., (window + bestlen) +;;; edi = prev +;;; ebp = limit + +LookupLoop: + and r8d, edx + + movzx r8d, word ptr [rdi + r8*2] + cmp r8d, ebp + jbe LeaveNow + sub edx, 00010000h + js LeaveNow + +LoopEntry: + + cmp bx,word ptr [rsi + r8 - 1] + jnz LookupLoop1 +LookupLoopIsZero: + cmp r12w, word ptr [r10 + r8] + jnz LookupLoop1 + + +;;; Store the current value of chainlen. + mov [chainlenwmask], edx + +;;; Point edi to the string under scrutiny, and esi to the string we +;;; are hoping to match it up with. In actuality, esi and edi are +;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is +;;; initialized to -(MAX_MATCH_8 - scanalign). + + lea rsi,[r8+r10] + mov rdx, 0fffffffffffffef8h; -(MAX_MATCH_8) + lea rsi, [rsi + r13 + 0108h] ;MAX_MATCH_8] + lea rdi, [r9 + r13 + 0108h] ;MAX_MATCH_8] + + prefetcht1 [rsi+rdx] + prefetcht1 [rdi+rdx] + + +;;; Test the strings for equality, 8 bytes at a time. At the end, +;;; adjust rdx so that it is offset to the exact byte that mismatched. +;;; +;;; We already know at this point that the first three bytes of the +;;; strings match each other, and they can be safely passed over before +;;; starting the compare loop. So what this code does is skip over 0-3 +;;; bytes, as much as necessary in order to dword-align the edi +;;; pointer. (rsi will still be misaligned three times out of four.) +;;; +;;; It should be confessed that this loop usually does not represent +;;; much of the total running time. Replacing it with a more +;;; straightforward "rep cmpsb" would not drastically degrade +;;; performance. + + +LoopCmps: + mov rax, [rsi + rdx] + xor rax, [rdi + rdx] + jnz LeaveLoopCmps + + mov rax, [rsi + rdx + 8] + xor rax, [rdi + rdx + 8] + jnz LeaveLoopCmps8 + + + mov rax, [rsi + rdx + 8+8] + xor rax, [rdi + rdx + 8+8] + jnz LeaveLoopCmps16 + + add rdx,8+8+8 + + jnz short LoopCmps + jmp short LenMaximum +LeaveLoopCmps16: add rdx,8 +LeaveLoopCmps8: add rdx,8 +LeaveLoopCmps: + + test eax, 0000FFFFh + jnz LenLower + + test eax,0ffffffffh + + jnz LenLower32 + + add rdx,4 + shr rax,32 + or ax,ax + jnz LenLower + +LenLower32: + shr eax,16 + add rdx,2 +LenLower: sub al, 1 + adc rdx, 0 +;;; Calculate the length of the match. If it is longer than MAX_MATCH, +;;; then automatically accept it as the best possible match and leave. + + lea rax, [rdi + rdx] + sub rax, r9 + cmp eax, MAX_MATCH + jge LenMaximum + +;;; If the length of the match is not longer than the best match we +;;; have so far, then forget it and return to the lookup loop. +;/////////////////////////////////// + + cmp eax, r11d + jg LongerMatch + + lea rsi,[r10+r11] + + mov rdi, prev_ad + mov edx, [chainlenwmask] + jmp LookupLoop + +;;; s->match_start = cur_match; +;;; best_len = len; +;;; if (len >= nice_match) break; +;;; scan_end = *(ushf*)(scan+best_len-1); + +LongerMatch: + mov r11d, eax + mov match_start, r8d + cmp eax, [nicematch] + jge LeaveNow + + lea rsi,[r10+rax] + + movzx ebx, word ptr [r9 + rax - 1] + mov rdi, prev_ad + mov edx, [chainlenwmask] + jmp LookupLoop + +;;; Accept the current string, with the maximum possible length. + +LenMaximum: + mov r11d,MAX_MATCH + mov match_start, r8d + +;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; +;;; return s->lookahead; + +LeaveNow: +IFDEF INFOZIP + mov eax,r11d +ELSE + mov eax, Lookahead + cmp r11d, eax + cmovng eax, r11d +ENDIF + +;;; Restore the stack and return from whence we came. + + + mov rsi,[save_rsi] + mov rdi,[save_rdi] + mov rbx,[save_rbx] + mov rbp,[save_rbp] + mov r12,[save_r12] + mov r13,[save_r13] +; mov r14,[save_r14] +; mov r15,[save_r15] + + + ret 0 +; please don't remove this string ! +; Your can freely use gvmat64 in any free or commercial app +; but it is far better don't remove the string in the binary! + db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0 +longest_match ENDP + +match_init PROC + ret 0 +match_init ENDP + + +END diff --git a/third_party/zlib/v1_2_11/contrib/masmx64/inffas8664.c b/third_party/zlib/v1_2_11/contrib/masmx64/inffas8664.c new file mode 100644 index 0000000..e8af06f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx64/inffas8664.c @@ -0,0 +1,186 @@ +/* inffas8664.c is a hand tuned assembler version of inffast.c - fast decoding + * version for AMD64 on Windows using Microsoft C compiler + * + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Copyright (C) 2003 Chris Anderson + * Please use the copyright conditions above. + * + * 2005 - Adaptation to Microsoft C Compiler for AMD64 by Gilles Vollant + * + * inffas8664.c call function inffas8664fnc in inffasx64.asm + * inffasx64.asm is automatically convert from AMD64 portion of inffas86.c + * + * Dec-29-2003 -- I added AMD64 inflate asm support. This version is also + * slightly quicker on x86 systems because, instead of using rep movsb to copy + * data, it uses rep movsw, which moves data in 2-byte chunks instead of single + * bytes. I've tested the AMD64 code on a Fedora Core 1 + the x86_64 updates + * from http://fedora.linux.duke.edu/fc1_x86_64 + * which is running on an Athlon 64 3000+ / Gigabyte GA-K8VT800M system with + * 1GB ram. The 64-bit version is about 4% faster than the 32-bit version, + * when decompressing mozilla-source-1.3.tar.gz. + * + * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from + * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at + * the moment. I have successfully compiled and tested this code with gcc2.96, + * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S + * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX + * enabled. I will attempt to merge the MMX code into this version. Newer + * versions of this and inffast.S can be found at + * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ + * + */ + +#include +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* Mark Adler's comments from inffast.c: */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ + + + + typedef struct inffast_ar { +/* 64 32 x86 x86_64 */ +/* ar offset register */ +/* 0 0 */ void *esp; /* esp save */ +/* 8 4 */ void *ebp; /* ebp save */ +/* 16 8 */ unsigned char FAR *in; /* esi rsi local strm->next_in */ +/* 24 12 */ unsigned char FAR *last; /* r9 while in < last */ +/* 32 16 */ unsigned char FAR *out; /* edi rdi local strm->next_out */ +/* 40 20 */ unsigned char FAR *beg; /* inflate()'s init next_out */ +/* 48 24 */ unsigned char FAR *end; /* r10 while out < end */ +/* 56 28 */ unsigned char FAR *window;/* size of window, wsize!=0 */ +/* 64 32 */ code const FAR *lcode; /* ebp rbp local strm->lencode */ +/* 72 36 */ code const FAR *dcode; /* r11 local strm->distcode */ +/* 80 40 */ size_t /*unsigned long */hold; /* edx rdx local strm->hold */ +/* 88 44 */ unsigned bits; /* ebx rbx local strm->bits */ +/* 92 48 */ unsigned wsize; /* window size */ +/* 96 52 */ unsigned write; /* window write index */ +/*100 56 */ unsigned lmask; /* r12 mask for lcode */ +/*104 60 */ unsigned dmask; /* r13 mask for dcode */ +/*108 64 */ unsigned len; /* r14 match length */ +/*112 68 */ unsigned dist; /* r15 match distance */ +/*116 72 */ unsigned status; /* set when state chng*/ + } type_ar; +#ifdef ASMINF + +void inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + type_ar ar; + void inffas8664fnc(struct inffast_ar * par); + + + +#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) +#define PAD_AVAIL_IN 6 +#define PAD_AVAIL_OUT 258 +#else +#define PAD_AVAIL_IN 5 +#define PAD_AVAIL_OUT 257 +#endif + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + + ar.in = strm->next_in; + ar.last = ar.in + (strm->avail_in - PAD_AVAIL_IN); + ar.out = strm->next_out; + ar.beg = ar.out - (start - strm->avail_out); + ar.end = ar.out + (strm->avail_out - PAD_AVAIL_OUT); + ar.wsize = state->wsize; + ar.write = state->wnext; + ar.window = state->window; + ar.hold = state->hold; + ar.bits = state->bits; + ar.lcode = state->lencode; + ar.dcode = state->distcode; + ar.lmask = (1U << state->lenbits) - 1; + ar.dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + /* align in on 1/2 hold size boundary */ + while (((size_t)(void *)ar.in & (sizeof(ar.hold) / 2 - 1)) != 0) { + ar.hold += (unsigned long)*ar.in++ << ar.bits; + ar.bits += 8; + } + + inffas8664fnc(&ar); + + if (ar.status > 1) { + if (ar.status == 2) + strm->msg = "invalid literal/length code"; + else if (ar.status == 3) + strm->msg = "invalid distance code"; + else + strm->msg = "invalid distance too far back"; + state->mode = BAD; + } + else if ( ar.status == 1 ) { + state->mode = TYPE; + } + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + ar.len = ar.bits >> 3; + ar.in -= ar.len; + ar.bits -= ar.len << 3; + ar.hold &= (1U << ar.bits) - 1; + + /* update state and return */ + strm->next_in = ar.in; + strm->next_out = ar.out; + strm->avail_in = (unsigned)(ar.in < ar.last ? + PAD_AVAIL_IN + (ar.last - ar.in) : + PAD_AVAIL_IN - (ar.in - ar.last)); + strm->avail_out = (unsigned)(ar.out < ar.end ? + PAD_AVAIL_OUT + (ar.end - ar.out) : + PAD_AVAIL_OUT - (ar.out - ar.end)); + state->hold = (unsigned long)ar.hold; + state->bits = ar.bits; + return; +} + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/masmx64/inffasx64.asm b/third_party/zlib/v1_2_11/contrib/masmx64/inffasx64.asm new file mode 100644 index 0000000..60a8d89 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx64/inffasx64.asm @@ -0,0 +1,396 @@ +; inffasx64.asm is a hand tuned assembler version of inffast.c - fast decoding +; version for AMD64 on Windows using Microsoft C compiler +; +; inffasx64.asm is automatically convert from AMD64 portion of inffas86.c +; inffasx64.asm is called by inffas8664.c, which contain more info. + + +; to compile this file, I use option +; ml64.exe /Flinffasx64 /c /Zi inffasx64.asm +; with Microsoft Macro Assembler (x64) for AMD64 +; + +; This file compile with Microsoft Macro Assembler (x64) for AMD64 +; +; ml64.exe is given with Visual Studio 2005/2008/2010 and Windows WDK +; +; (you can get Windows WDK with ml64 for AMD64 from +; http://www.microsoft.com/whdc/Devtools/wdk/default.mspx for low price) +; + + +.code +inffas8664fnc PROC + +; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and +; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp +; +; All registers must be preserved across the call, except for +; rax, rcx, rdx, r8, r-9, r10, and r11, which are scratch. + + + mov [rsp-8],rsi + mov [rsp-16],rdi + mov [rsp-24],r12 + mov [rsp-32],r13 + mov [rsp-40],r14 + mov [rsp-48],r15 + mov [rsp-56],rbx + + mov rax,rcx + + mov [rax+8], rbp ; /* save regs rbp and rsp */ + mov [rax], rsp + + mov rsp, rax ; /* make rsp point to &ar */ + + mov rsi, [rsp+16] ; /* rsi = in */ + mov rdi, [rsp+32] ; /* rdi = out */ + mov r9, [rsp+24] ; /* r9 = last */ + mov r10, [rsp+48] ; /* r10 = end */ + mov rbp, [rsp+64] ; /* rbp = lcode */ + mov r11, [rsp+72] ; /* r11 = dcode */ + mov rdx, [rsp+80] ; /* rdx = hold */ + mov ebx, [rsp+88] ; /* ebx = bits */ + mov r12d, [rsp+100] ; /* r12d = lmask */ + mov r13d, [rsp+104] ; /* r13d = dmask */ + ; /* r14d = len */ + ; /* r15d = dist */ + + + cld + cmp r10, rdi + je L_one_time ; /* if only one decode left */ + cmp r9, rsi + + jne L_do_loop + + +L_one_time: + mov r8, r12 ; /* r8 = lmask */ + cmp bl, 32 + ja L_get_length_code_one_time + + lodsd ; /* eax = *(uint *)in++ */ + mov cl, bl ; /* cl = bits, needs it for shifting */ + add bl, 32 ; /* bits += 32 */ + shl rax, cl + or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ + jmp L_get_length_code_one_time + +ALIGN 4 +L_while_test: + cmp r10, rdi + jbe L_break_loop + cmp r9, rsi + jbe L_break_loop + +L_do_loop: + mov r8, r12 ; /* r8 = lmask */ + cmp bl, 32 + ja L_get_length_code ; /* if (32 < bits) */ + + lodsd ; /* eax = *(uint *)in++ */ + mov cl, bl ; /* cl = bits, needs it for shifting */ + add bl, 32 ; /* bits += 32 */ + shl rax, cl + or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ + +L_get_length_code: + and r8, rdx ; /* r8 &= hold */ + mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ + + mov cl, ah ; /* cl = this.bits */ + sub bl, ah ; /* bits -= this.bits */ + shr rdx, cl ; /* hold >>= this.bits */ + + test al, al + jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ + + mov r8, r12 ; /* r8 = lmask */ + shr eax, 16 ; /* output this.val char */ + stosb + +L_get_length_code_one_time: + and r8, rdx ; /* r8 &= hold */ + mov eax, [rbp+r8*4] ; /* eax = lcode[hold & lmask] */ + +L_dolen: + mov cl, ah ; /* cl = this.bits */ + sub bl, ah ; /* bits -= this.bits */ + shr rdx, cl ; /* hold >>= this.bits */ + + test al, al + jnz L_test_for_length_base ; /* if (op != 0) 45.7% */ + + shr eax, 16 ; /* output this.val char */ + stosb + jmp L_while_test + +ALIGN 4 +L_test_for_length_base: + mov r14d, eax ; /* len = this */ + shr r14d, 16 ; /* len = this.val */ + mov cl, al + + test al, 16 + jz L_test_for_second_level_length ; /* if ((op & 16) == 0) 8% */ + and cl, 15 ; /* op &= 15 */ + jz L_decode_distance ; /* if (!op) */ + +L_add_bits_to_len: + sub bl, cl + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx ; /* eax &= hold */ + shr rdx, cl + add r14d, eax ; /* len += hold & mask[op] */ + +L_decode_distance: + mov r8, r13 ; /* r8 = dmask */ + cmp bl, 32 + ja L_get_distance_code ; /* if (32 < bits) */ + + lodsd ; /* eax = *(uint *)in++ */ + mov cl, bl ; /* cl = bits, needs it for shifting */ + add bl, 32 ; /* bits += 32 */ + shl rax, cl + or rdx, rax ; /* hold |= *((uint *)in)++ << bits */ + +L_get_distance_code: + and r8, rdx ; /* r8 &= hold */ + mov eax, [r11+r8*4] ; /* eax = dcode[hold & dmask] */ + +L_dodist: + mov r15d, eax ; /* dist = this */ + shr r15d, 16 ; /* dist = this.val */ + mov cl, ah + sub bl, ah ; /* bits -= this.bits */ + shr rdx, cl ; /* hold >>= this.bits */ + mov cl, al ; /* cl = this.op */ + + test al, 16 ; /* if ((op & 16) == 0) */ + jz L_test_for_second_level_dist + and cl, 15 ; /* op &= 15 */ + jz L_check_dist_one + +L_add_bits_to_dist: + sub bl, cl + xor eax, eax + inc eax + shl eax, cl + dec eax ; /* (1 << op) - 1 */ + and eax, edx ; /* eax &= hold */ + shr rdx, cl + add r15d, eax ; /* dist += hold & ((1 << op) - 1) */ + +L_check_window: + mov r8, rsi ; /* save in so from can use it's reg */ + mov rax, rdi + sub rax, [rsp+40] ; /* nbytes = out - beg */ + + cmp eax, r15d + jb L_clip_window ; /* if (dist > nbytes) 4.2% */ + + mov ecx, r14d ; /* ecx = len */ + mov rsi, rdi + sub rsi, r15 ; /* from = out - dist */ + + sar ecx, 1 + jnc L_copy_two ; /* if len % 2 == 0 */ + + rep movsw + mov al, [rsi] + mov [rdi], al + inc rdi + + mov rsi, r8 ; /* move in back to %rsi, toss from */ + jmp L_while_test + +L_copy_two: + rep movsw + mov rsi, r8 ; /* move in back to %rsi, toss from */ + jmp L_while_test + +ALIGN 4 +L_check_dist_one: + cmp r15d, 1 ; /* if dist 1, is a memset */ + jne L_check_window + cmp [rsp+40], rdi ; /* if out == beg, outside window */ + je L_check_window + + mov ecx, r14d ; /* ecx = len */ + mov al, [rdi-1] + mov ah, al + + sar ecx, 1 + jnc L_set_two + mov [rdi], al + inc rdi + +L_set_two: + rep stosw + jmp L_while_test + +ALIGN 4 +L_test_for_second_level_length: + test al, 64 + jnz L_test_for_end_of_block ; /* if ((op & 64) != 0) */ + + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx ; /* eax &= hold */ + add eax, r14d ; /* eax += len */ + mov eax, [rbp+rax*4] ; /* eax = lcode[val+(hold&mask[op])]*/ + jmp L_dolen + +ALIGN 4 +L_test_for_second_level_dist: + test al, 64 + jnz L_invalid_distance_code ; /* if ((op & 64) != 0) */ + + xor eax, eax + inc eax + shl eax, cl + dec eax + and eax, edx ; /* eax &= hold */ + add eax, r15d ; /* eax += dist */ + mov eax, [r11+rax*4] ; /* eax = dcode[val+(hold&mask[op])]*/ + jmp L_dodist + +ALIGN 4 +L_clip_window: + mov ecx, eax ; /* ecx = nbytes */ + mov eax, [rsp+92] ; /* eax = wsize, prepare for dist cmp */ + neg ecx ; /* nbytes = -nbytes */ + + cmp eax, r15d + jb L_invalid_distance_too_far ; /* if (dist > wsize) */ + + add ecx, r15d ; /* nbytes = dist - nbytes */ + cmp dword ptr [rsp+96], 0 + jne L_wrap_around_window ; /* if (write != 0) */ + + mov rsi, [rsp+56] ; /* from = window */ + sub eax, ecx ; /* eax -= nbytes */ + add rsi, rax ; /* from += wsize - nbytes */ + + mov eax, r14d ; /* eax = len */ + cmp r14d, ecx + jbe L_do_copy ; /* if (nbytes >= len) */ + + sub eax, ecx ; /* eax -= nbytes */ + rep movsb + mov rsi, rdi + sub rsi, r15 ; /* from = &out[ -dist ] */ + jmp L_do_copy + +ALIGN 4 +L_wrap_around_window: + mov eax, [rsp+96] ; /* eax = write */ + cmp ecx, eax + jbe L_contiguous_in_window ; /* if (write >= nbytes) */ + + mov esi, [rsp+92] ; /* from = wsize */ + add rsi, [rsp+56] ; /* from += window */ + add rsi, rax ; /* from += write */ + sub rsi, rcx ; /* from -= nbytes */ + sub ecx, eax ; /* nbytes -= write */ + + mov eax, r14d ; /* eax = len */ + cmp eax, ecx + jbe L_do_copy ; /* if (nbytes >= len) */ + + sub eax, ecx ; /* len -= nbytes */ + rep movsb + mov rsi, [rsp+56] ; /* from = window */ + mov ecx, [rsp+96] ; /* nbytes = write */ + cmp eax, ecx + jbe L_do_copy ; /* if (nbytes >= len) */ + + sub eax, ecx ; /* len -= nbytes */ + rep movsb + mov rsi, rdi + sub rsi, r15 ; /* from = out - dist */ + jmp L_do_copy + +ALIGN 4 +L_contiguous_in_window: + mov rsi, [rsp+56] ; /* rsi = window */ + add rsi, rax + sub rsi, rcx ; /* from += write - nbytes */ + + mov eax, r14d ; /* eax = len */ + cmp eax, ecx + jbe L_do_copy ; /* if (nbytes >= len) */ + + sub eax, ecx ; /* len -= nbytes */ + rep movsb + mov rsi, rdi + sub rsi, r15 ; /* from = out - dist */ + jmp L_do_copy ; /* if (nbytes >= len) */ + +ALIGN 4 +L_do_copy: + mov ecx, eax ; /* ecx = len */ + rep movsb + + mov rsi, r8 ; /* move in back to %esi, toss from */ + jmp L_while_test + +L_test_for_end_of_block: + test al, 32 + jz L_invalid_literal_length_code + mov dword ptr [rsp+116], 1 + jmp L_break_loop_with_status + +L_invalid_literal_length_code: + mov dword ptr [rsp+116], 2 + jmp L_break_loop_with_status + +L_invalid_distance_code: + mov dword ptr [rsp+116], 3 + jmp L_break_loop_with_status + +L_invalid_distance_too_far: + mov dword ptr [rsp+116], 4 + jmp L_break_loop_with_status + +L_break_loop: + mov dword ptr [rsp+116], 0 + +L_break_loop_with_status: +; /* put in, out, bits, and hold back into ar and pop esp */ + mov [rsp+16], rsi ; /* in */ + mov [rsp+32], rdi ; /* out */ + mov [rsp+88], ebx ; /* bits */ + mov [rsp+80], rdx ; /* hold */ + + mov rax, [rsp] ; /* restore rbp and rsp */ + mov rbp, [rsp+8] + mov rsp, rax + + + + mov rsi,[rsp-8] + mov rdi,[rsp-16] + mov r12,[rsp-24] + mov r13,[rsp-32] + mov r14,[rsp-40] + mov r15,[rsp-48] + mov rbx,[rsp-56] + + ret 0 +; : +; : "m" (ar) +; : "memory", "%rax", "%rbx", "%rcx", "%rdx", "%rsi", "%rdi", +; "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15" +; ); + +inffas8664fnc ENDP +;_TEXT ENDS +END diff --git a/third_party/zlib/v1_2_11/contrib/masmx64/readme.txt b/third_party/zlib/v1_2_11/contrib/masmx64/readme.txt new file mode 100644 index 0000000..2da6733 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx64/readme.txt @@ -0,0 +1,31 @@ +Summary +------- +This directory contains ASM implementations of the functions +longest_match() and inflate_fast(), for 64 bits x86 (both AMD64 and Intel EM64t), +for use with Microsoft Macro Assembler (x64) for AMD64 and Microsoft C++ 64 bits. + +gvmat64.asm is written by Gilles Vollant (2005), by using Brian Raiter 686/32 bits + assembly optimized version from Jean-loup Gailly original longest_match function + +inffasx64.asm and inffas8664.c were written by Chris Anderson, by optimizing + original function from Mark Adler + +Use instructions +---------------- +Assemble the .asm files using MASM and put the object files into the zlib source +directory. You can also get object files here: + + http://www.winimage.com/zLibDll/zlib124_masm_obj.zip + +define ASMV and ASMINF in your project. Include inffas8664.c in your source tree, +and inffasx64.obj and gvmat64.obj as object to link. + + +Build instructions +------------------ +run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe) + +ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK + +You can get Windows 2003 server DDK with ml64 and cl for AMD64 from + http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) diff --git a/third_party/zlib/v1_2_11/contrib/masmx86/bld_ml32.bat b/third_party/zlib/v1_2_11/contrib/masmx86/bld_ml32.bat new file mode 100644 index 0000000..e1b86bf --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx86/bld_ml32.bat @@ -0,0 +1,2 @@ +ml /coff /Zi /c /Flmatch686.lst match686.asm +ml /coff /Zi /c /Flinffas32.lst inffas32.asm diff --git a/third_party/zlib/v1_2_11/contrib/masmx86/inffas32.asm b/third_party/zlib/v1_2_11/contrib/masmx86/inffas32.asm new file mode 100644 index 0000000..03d20f8 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx86/inffas32.asm @@ -0,0 +1,1080 @@ +;/* inffas32.asm is a hand tuned assembler version of inffast.c -- fast decoding +; * +; * inffas32.asm is derivated from inffas86.c, with translation of assembly code +; * +; * Copyright (C) 1995-2003 Mark Adler +; * For conditions of distribution and use, see copyright notice in zlib.h +; * +; * Copyright (C) 2003 Chris Anderson +; * Please use the copyright conditions above. +; * +; * Mar-13-2003 -- Most of this is derived from inffast.S which is derived from +; * the gcc -S output of zlib-1.2.0/inffast.c. Zlib-1.2.0 is in beta release at +; * the moment. I have successfully compiled and tested this code with gcc2.96, +; * gcc3.2, icc5.0, msvc6.0. It is very close to the speed of inffast.S +; * compiled with gcc -DNO_MMX, but inffast.S is still faster on the P3 with MMX +; * enabled. I will attempt to merge the MMX code into this version. Newer +; * versions of this and inffast.S can be found at +; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ +; * +; * 2005 : modification by Gilles Vollant +; */ +; For Visual C++ 4.x and higher and ML 6.x and higher +; ml.exe is in directory \MASM611C of Win95 DDK +; ml.exe is also distributed in http://www.masm32.com/masmdl.htm +; and in VC++2003 toolkit at http://msdn.microsoft.com/visualc/vctoolkit2003/ +; +; +; compile with command line option +; ml /coff /Zi /c /Flinffas32.lst inffas32.asm + +; if you define NO_GZIP (see inflate.h), compile with +; ml /coff /Zi /c /Flinffas32.lst /DNO_GUNZIP inffas32.asm + + +; zlib122sup is 0 fort zlib 1.2.2.1 and lower +; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head +; in inflate_state in inflate.h) +zlib1222sup equ 8 + + +IFDEF GUNZIP + INFLATE_MODE_TYPE equ 11 + INFLATE_MODE_BAD equ 26 +ELSE + IFNDEF NO_GUNZIP + INFLATE_MODE_TYPE equ 11 + INFLATE_MODE_BAD equ 26 + ELSE + INFLATE_MODE_TYPE equ 3 + INFLATE_MODE_BAD equ 17 + ENDIF +ENDIF + + +; 75 "inffast.S" +;FILE "inffast.S" + +;;;GLOBAL _inflate_fast + +;;;SECTION .text + + + + .586p + .mmx + + name inflate_fast_x86 + .MODEL FLAT + +_DATA segment +inflate_fast_use_mmx: + dd 1 + + +_TEXT segment + + + +ALIGN 4 + db 'Fast decoding Code from Chris Anderson' + db 0 + +ALIGN 4 +invalid_literal_length_code_msg: + db 'invalid literal/length code' + db 0 + +ALIGN 4 +invalid_distance_code_msg: + db 'invalid distance code' + db 0 + +ALIGN 4 +invalid_distance_too_far_msg: + db 'invalid distance too far back' + db 0 + + +ALIGN 4 +inflate_fast_mask: +dd 0 +dd 1 +dd 3 +dd 7 +dd 15 +dd 31 +dd 63 +dd 127 +dd 255 +dd 511 +dd 1023 +dd 2047 +dd 4095 +dd 8191 +dd 16383 +dd 32767 +dd 65535 +dd 131071 +dd 262143 +dd 524287 +dd 1048575 +dd 2097151 +dd 4194303 +dd 8388607 +dd 16777215 +dd 33554431 +dd 67108863 +dd 134217727 +dd 268435455 +dd 536870911 +dd 1073741823 +dd 2147483647 +dd 4294967295 + + +mode_state equ 0 ;/* state->mode */ +wsize_state equ (32+zlib1222sup) ;/* state->wsize */ +write_state equ (36+4+zlib1222sup) ;/* state->write */ +window_state equ (40+4+zlib1222sup) ;/* state->window */ +hold_state equ (44+4+zlib1222sup) ;/* state->hold */ +bits_state equ (48+4+zlib1222sup) ;/* state->bits */ +lencode_state equ (64+4+zlib1222sup) ;/* state->lencode */ +distcode_state equ (68+4+zlib1222sup) ;/* state->distcode */ +lenbits_state equ (72+4+zlib1222sup) ;/* state->lenbits */ +distbits_state equ (76+4+zlib1222sup) ;/* state->distbits */ + + +;;SECTION .text +; 205 "inffast.S" +;GLOBAL inflate_fast_use_mmx + +;SECTION .data + + +; GLOBAL inflate_fast_use_mmx:object +;.size inflate_fast_use_mmx, 4 +; 226 "inffast.S" +;SECTION .text + +ALIGN 4 +_inflate_fast proc near +.FPO (16, 4, 0, 0, 1, 0) + push edi + push esi + push ebp + push ebx + pushfd + sub esp,64 + cld + + + + + mov esi, [esp+88] + mov edi, [esi+28] + + + + + + + + mov edx, [esi+4] + mov eax, [esi+0] + + add edx,eax + sub edx,11 + + mov [esp+44],eax + mov [esp+20],edx + + mov ebp, [esp+92] + mov ecx, [esi+16] + mov ebx, [esi+12] + + sub ebp,ecx + neg ebp + add ebp,ebx + + sub ecx,257 + add ecx,ebx + + mov [esp+60],ebx + mov [esp+40],ebp + mov [esp+16],ecx +; 285 "inffast.S" + mov eax, [edi+lencode_state] + mov ecx, [edi+distcode_state] + + mov [esp+8],eax + mov [esp+12],ecx + + mov eax,1 + mov ecx, [edi+lenbits_state] + shl eax,cl + dec eax + mov [esp+0],eax + + mov eax,1 + mov ecx, [edi+distbits_state] + shl eax,cl + dec eax + mov [esp+4],eax + + mov eax, [edi+wsize_state] + mov ecx, [edi+write_state] + mov edx, [edi+window_state] + + mov [esp+52],eax + mov [esp+48],ecx + mov [esp+56],edx + + mov ebp, [edi+hold_state] + mov ebx, [edi+bits_state] +; 321 "inffast.S" + mov esi, [esp+44] + mov ecx, [esp+20] + cmp ecx,esi + ja L_align_long + + add ecx,11 + sub ecx,esi + mov eax,12 + sub eax,ecx + lea edi, [esp+28] + rep movsb + mov ecx,eax + xor eax,eax + rep stosb + lea esi, [esp+28] + mov [esp+20],esi + jmp L_is_aligned + + +L_align_long: + test esi,3 + jz L_is_aligned + xor eax,eax + mov al, [esi] + inc esi + mov ecx,ebx + add ebx,8 + shl eax,cl + or ebp,eax + jmp L_align_long + +L_is_aligned: + mov edi, [esp+60] +; 366 "inffast.S" +L_check_mmx: + cmp dword ptr [inflate_fast_use_mmx],2 + je L_init_mmx + ja L_do_loop + + push eax + push ebx + push ecx + push edx + pushfd + mov eax, [esp] + xor dword ptr [esp],0200000h + + + + + popfd + pushfd + pop edx + xor edx,eax + jz L_dont_use_mmx + xor eax,eax + cpuid + cmp ebx,0756e6547h + jne L_dont_use_mmx + cmp ecx,06c65746eh + jne L_dont_use_mmx + cmp edx,049656e69h + jne L_dont_use_mmx + mov eax,1 + cpuid + shr eax,8 + and eax,15 + cmp eax,6 + jne L_dont_use_mmx + test edx,0800000h + jnz L_use_mmx + jmp L_dont_use_mmx +L_use_mmx: + mov dword ptr [inflate_fast_use_mmx],2 + jmp L_check_mmx_pop +L_dont_use_mmx: + mov dword ptr [inflate_fast_use_mmx],3 +L_check_mmx_pop: + pop edx + pop ecx + pop ebx + pop eax + jmp L_check_mmx +; 426 "inffast.S" +ALIGN 4 +L_do_loop: +; 437 "inffast.S" + cmp bl,15 + ja L_get_length_code + + xor eax,eax + lodsw + mov cl,bl + add bl,16 + shl eax,cl + or ebp,eax + +L_get_length_code: + mov edx, [esp+0] + mov ecx, [esp+8] + and edx,ebp + mov eax, [ecx+edx*4] + +L_dolen: + + + + + + + mov cl,ah + sub bl,ah + shr ebp,cl + + + + + + + test al,al + jnz L_test_for_length_base + + shr eax,16 + stosb + +L_while_test: + + + cmp [esp+16],edi + jbe L_break_loop + + cmp [esp+20],esi + ja L_do_loop + jmp L_break_loop + +L_test_for_length_base: +; 502 "inffast.S" + mov edx,eax + shr edx,16 + mov cl,al + + test al,16 + jz L_test_for_second_level_length + and cl,15 + jz L_save_len + cmp bl,cl + jae L_add_bits_to_len + + mov ch,cl + xor eax,eax + lodsw + mov cl,bl + add bl,16 + shl eax,cl + or ebp,eax + mov cl,ch + +L_add_bits_to_len: + mov eax,1 + shl eax,cl + dec eax + sub bl,cl + and eax,ebp + shr ebp,cl + add edx,eax + +L_save_len: + mov [esp+24],edx + + +L_decode_distance: +; 549 "inffast.S" + cmp bl,15 + ja L_get_distance_code + + xor eax,eax + lodsw + mov cl,bl + add bl,16 + shl eax,cl + or ebp,eax + +L_get_distance_code: + mov edx, [esp+4] + mov ecx, [esp+12] + and edx,ebp + mov eax, [ecx+edx*4] + + +L_dodist: + mov edx,eax + shr edx,16 + mov cl,ah + sub bl,ah + shr ebp,cl +; 584 "inffast.S" + mov cl,al + + test al,16 + jz L_test_for_second_level_dist + and cl,15 + jz L_check_dist_one + cmp bl,cl + jae L_add_bits_to_dist + + mov ch,cl + xor eax,eax + lodsw + mov cl,bl + add bl,16 + shl eax,cl + or ebp,eax + mov cl,ch + +L_add_bits_to_dist: + mov eax,1 + shl eax,cl + dec eax + sub bl,cl + and eax,ebp + shr ebp,cl + add edx,eax + jmp L_check_window + +L_check_window: +; 625 "inffast.S" + mov [esp+44],esi + mov eax,edi + sub eax, [esp+40] + + cmp eax,edx + jb L_clip_window + + mov ecx, [esp+24] + mov esi,edi + sub esi,edx + + sub ecx,3 + mov al, [esi] + mov [edi],al + mov al, [esi+1] + mov dl, [esi+2] + add esi,3 + mov [edi+1],al + mov [edi+2],dl + add edi,3 + rep movsb + + mov esi, [esp+44] + jmp L_while_test + +ALIGN 4 +L_check_dist_one: + cmp edx,1 + jne L_check_window + cmp [esp+40],edi + je L_check_window + + dec edi + mov ecx, [esp+24] + mov al, [edi] + sub ecx,3 + + mov [edi+1],al + mov [edi+2],al + mov [edi+3],al + add edi,4 + rep stosb + + jmp L_while_test + +ALIGN 4 +L_test_for_second_level_length: + + + + + test al,64 + jnz L_test_for_end_of_block + + mov eax,1 + shl eax,cl + dec eax + and eax,ebp + add eax,edx + mov edx, [esp+8] + mov eax, [edx+eax*4] + jmp L_dolen + +ALIGN 4 +L_test_for_second_level_dist: + + + + + test al,64 + jnz L_invalid_distance_code + + mov eax,1 + shl eax,cl + dec eax + and eax,ebp + add eax,edx + mov edx, [esp+12] + mov eax, [edx+eax*4] + jmp L_dodist + +ALIGN 4 +L_clip_window: +; 721 "inffast.S" + mov ecx,eax + mov eax, [esp+52] + neg ecx + mov esi, [esp+56] + + cmp eax,edx + jb L_invalid_distance_too_far + + add ecx,edx + cmp dword ptr [esp+48],0 + jne L_wrap_around_window + + sub eax,ecx + add esi,eax +; 749 "inffast.S" + mov eax, [esp+24] + cmp eax,ecx + jbe L_do_copy1 + + sub eax,ecx + rep movsb + mov esi,edi + sub esi,edx + jmp L_do_copy1 + + cmp eax,ecx + jbe L_do_copy1 + + sub eax,ecx + rep movsb + mov esi,edi + sub esi,edx + jmp L_do_copy1 + +L_wrap_around_window: +; 793 "inffast.S" + mov eax, [esp+48] + cmp ecx,eax + jbe L_contiguous_in_window + + add esi, [esp+52] + add esi,eax + sub esi,ecx + sub ecx,eax + + + mov eax, [esp+24] + cmp eax,ecx + jbe L_do_copy1 + + sub eax,ecx + rep movsb + mov esi, [esp+56] + mov ecx, [esp+48] + cmp eax,ecx + jbe L_do_copy1 + + sub eax,ecx + rep movsb + mov esi,edi + sub esi,edx + jmp L_do_copy1 + +L_contiguous_in_window: +; 836 "inffast.S" + add esi,eax + sub esi,ecx + + + mov eax, [esp+24] + cmp eax,ecx + jbe L_do_copy1 + + sub eax,ecx + rep movsb + mov esi,edi + sub esi,edx + +L_do_copy1: +; 862 "inffast.S" + mov ecx,eax + rep movsb + + mov esi, [esp+44] + jmp L_while_test +; 878 "inffast.S" +ALIGN 4 +L_init_mmx: + emms + + + + + + movd mm0,ebp + mov ebp,ebx +; 896 "inffast.S" + movd mm4,dword ptr [esp+0] + movq mm3,mm4 + movd mm5,dword ptr [esp+4] + movq mm2,mm5 + pxor mm1,mm1 + mov ebx, [esp+8] + jmp L_do_loop_mmx + +ALIGN 4 +L_do_loop_mmx: + psrlq mm0,mm1 + + cmp ebp,32 + ja L_get_length_code_mmx + + movd mm6,ebp + movd mm7,dword ptr [esi] + add esi,4 + psllq mm7,mm6 + add ebp,32 + por mm0,mm7 + +L_get_length_code_mmx: + pand mm4,mm0 + movd eax,mm4 + movq mm4,mm3 + mov eax, [ebx+eax*4] + +L_dolen_mmx: + movzx ecx,ah + movd mm1,ecx + sub ebp,ecx + + test al,al + jnz L_test_for_length_base_mmx + + shr eax,16 + stosb + +L_while_test_mmx: + + + cmp [esp+16],edi + jbe L_break_loop + + cmp [esp+20],esi + ja L_do_loop_mmx + jmp L_break_loop + +L_test_for_length_base_mmx: + + mov edx,eax + shr edx,16 + + test al,16 + jz L_test_for_second_level_length_mmx + and eax,15 + jz L_decode_distance_mmx + + psrlq mm0,mm1 + movd mm1,eax + movd ecx,mm0 + sub ebp,eax + and ecx, [inflate_fast_mask+eax*4] + add edx,ecx + +L_decode_distance_mmx: + psrlq mm0,mm1 + + cmp ebp,32 + ja L_get_dist_code_mmx + + movd mm6,ebp + movd mm7,dword ptr [esi] + add esi,4 + psllq mm7,mm6 + add ebp,32 + por mm0,mm7 + +L_get_dist_code_mmx: + mov ebx, [esp+12] + pand mm5,mm0 + movd eax,mm5 + movq mm5,mm2 + mov eax, [ebx+eax*4] + +L_dodist_mmx: + + movzx ecx,ah + mov ebx,eax + shr ebx,16 + sub ebp,ecx + movd mm1,ecx + + test al,16 + jz L_test_for_second_level_dist_mmx + and eax,15 + jz L_check_dist_one_mmx + +L_add_bits_to_dist_mmx: + psrlq mm0,mm1 + movd mm1,eax + movd ecx,mm0 + sub ebp,eax + and ecx, [inflate_fast_mask+eax*4] + add ebx,ecx + +L_check_window_mmx: + mov [esp+44],esi + mov eax,edi + sub eax, [esp+40] + + cmp eax,ebx + jb L_clip_window_mmx + + mov ecx,edx + mov esi,edi + sub esi,ebx + + sub ecx,3 + mov al, [esi] + mov [edi],al + mov al, [esi+1] + mov dl, [esi+2] + add esi,3 + mov [edi+1],al + mov [edi+2],dl + add edi,3 + rep movsb + + mov esi, [esp+44] + mov ebx, [esp+8] + jmp L_while_test_mmx + +ALIGN 4 +L_check_dist_one_mmx: + cmp ebx,1 + jne L_check_window_mmx + cmp [esp+40],edi + je L_check_window_mmx + + dec edi + mov ecx,edx + mov al, [edi] + sub ecx,3 + + mov [edi+1],al + mov [edi+2],al + mov [edi+3],al + add edi,4 + rep stosb + + mov ebx, [esp+8] + jmp L_while_test_mmx + +ALIGN 4 +L_test_for_second_level_length_mmx: + test al,64 + jnz L_test_for_end_of_block + + and eax,15 + psrlq mm0,mm1 + movd ecx,mm0 + and ecx, [inflate_fast_mask+eax*4] + add ecx,edx + mov eax, [ebx+ecx*4] + jmp L_dolen_mmx + +ALIGN 4 +L_test_for_second_level_dist_mmx: + test al,64 + jnz L_invalid_distance_code + + and eax,15 + psrlq mm0,mm1 + movd ecx,mm0 + and ecx, [inflate_fast_mask+eax*4] + mov eax, [esp+12] + add ecx,ebx + mov eax, [eax+ecx*4] + jmp L_dodist_mmx + +ALIGN 4 +L_clip_window_mmx: + + mov ecx,eax + mov eax, [esp+52] + neg ecx + mov esi, [esp+56] + + cmp eax,ebx + jb L_invalid_distance_too_far + + add ecx,ebx + cmp dword ptr [esp+48],0 + jne L_wrap_around_window_mmx + + sub eax,ecx + add esi,eax + + cmp edx,ecx + jbe L_do_copy1_mmx + + sub edx,ecx + rep movsb + mov esi,edi + sub esi,ebx + jmp L_do_copy1_mmx + + cmp edx,ecx + jbe L_do_copy1_mmx + + sub edx,ecx + rep movsb + mov esi,edi + sub esi,ebx + jmp L_do_copy1_mmx + +L_wrap_around_window_mmx: + + mov eax, [esp+48] + cmp ecx,eax + jbe L_contiguous_in_window_mmx + + add esi, [esp+52] + add esi,eax + sub esi,ecx + sub ecx,eax + + + cmp edx,ecx + jbe L_do_copy1_mmx + + sub edx,ecx + rep movsb + mov esi, [esp+56] + mov ecx, [esp+48] + cmp edx,ecx + jbe L_do_copy1_mmx + + sub edx,ecx + rep movsb + mov esi,edi + sub esi,ebx + jmp L_do_copy1_mmx + +L_contiguous_in_window_mmx: + + add esi,eax + sub esi,ecx + + + cmp edx,ecx + jbe L_do_copy1_mmx + + sub edx,ecx + rep movsb + mov esi,edi + sub esi,ebx + +L_do_copy1_mmx: + + + mov ecx,edx + rep movsb + + mov esi, [esp+44] + mov ebx, [esp+8] + jmp L_while_test_mmx +; 1174 "inffast.S" +L_invalid_distance_code: + + + + + + mov ecx, invalid_distance_code_msg + mov edx,INFLATE_MODE_BAD + jmp L_update_stream_state + +L_test_for_end_of_block: + + + + + + test al,32 + jz L_invalid_literal_length_code + + mov ecx,0 + mov edx,INFLATE_MODE_TYPE + jmp L_update_stream_state + +L_invalid_literal_length_code: + + + + + + mov ecx, invalid_literal_length_code_msg + mov edx,INFLATE_MODE_BAD + jmp L_update_stream_state + +L_invalid_distance_too_far: + + + + mov esi, [esp+44] + mov ecx, invalid_distance_too_far_msg + mov edx,INFLATE_MODE_BAD + jmp L_update_stream_state + +L_update_stream_state: + + mov eax, [esp+88] + test ecx,ecx + jz L_skip_msg + mov [eax+24],ecx +L_skip_msg: + mov eax, [eax+28] + mov [eax+mode_state],edx + jmp L_break_loop + +ALIGN 4 +L_break_loop: +; 1243 "inffast.S" + cmp dword ptr [inflate_fast_use_mmx],2 + jne L_update_next_in + + + + mov ebx,ebp + +L_update_next_in: +; 1266 "inffast.S" + mov eax, [esp+88] + mov ecx,ebx + mov edx, [eax+28] + shr ecx,3 + sub esi,ecx + shl ecx,3 + sub ebx,ecx + mov [eax+12],edi + mov [edx+bits_state],ebx + mov ecx,ebx + + lea ebx, [esp+28] + cmp [esp+20],ebx + jne L_buf_not_used + + sub esi,ebx + mov ebx, [eax+0] + mov [esp+20],ebx + add esi,ebx + mov ebx, [eax+4] + sub ebx,11 + add [esp+20],ebx + +L_buf_not_used: + mov [eax+0],esi + + mov ebx,1 + shl ebx,cl + dec ebx + + + + + + cmp dword ptr [inflate_fast_use_mmx],2 + jne L_update_hold + + + + psrlq mm0,mm1 + movd ebp,mm0 + + emms + +L_update_hold: + + + + and ebp,ebx + mov [edx+hold_state],ebp + + + + + mov ebx, [esp+20] + cmp ebx,esi + jbe L_last_is_smaller + + sub ebx,esi + add ebx,11 + mov [eax+4],ebx + jmp L_fixup_out +L_last_is_smaller: + sub esi,ebx + neg esi + add esi,11 + mov [eax+4],esi + + + + +L_fixup_out: + + mov ebx, [esp+16] + cmp ebx,edi + jbe L_end_is_smaller + + sub ebx,edi + add ebx,257 + mov [eax+16],ebx + jmp L_done +L_end_is_smaller: + sub edi,ebx + neg edi + add edi,257 + mov [eax+16],edi + + + + + +L_done: + add esp,64 + popfd + pop ebx + pop ebp + pop esi + pop edi + ret +_inflate_fast endp + +_TEXT ends +end diff --git a/third_party/zlib/v1_2_11/contrib/masmx86/match686.asm b/third_party/zlib/v1_2_11/contrib/masmx86/match686.asm new file mode 100644 index 0000000..3b09212 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx86/match686.asm @@ -0,0 +1,479 @@ +; match686.asm -- Asm portion of the optimized longest_match for 32 bits x86 +; Copyright (C) 1995-1996 Jean-loup Gailly, Brian Raiter and Gilles Vollant. +; File written by Gilles Vollant, by converting match686.S from Brian Raiter +; for MASM. This is as assembly version of longest_match +; from Jean-loup Gailly in deflate.c +; +; http://www.zlib.net +; http://www.winimage.com/zLibDll +; http://www.muppetlabs.com/~breadbox/software/assembly.html +; +; For Visual C++ 4.x and higher and ML 6.x and higher +; ml.exe is distributed in +; http://www.microsoft.com/downloads/details.aspx?FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 +; +; this file contain two implementation of longest_match +; +; this longest_match was written by Brian raiter (1998), optimized for Pentium Pro +; (and the faster known version of match_init on modern Core 2 Duo and AMD Phenom) +; +; for using an assembly version of longest_match, you need define ASMV in project +; +; compile the asm file running +; ml /coff /Zi /c /Flmatch686.lst match686.asm +; and do not include match686.obj in your project +; +; note: contrib of zLib 1.2.3 and earlier contained both a deprecated version for +; Pentium (prior Pentium Pro) and this version for Pentium Pro and modern processor +; with autoselect (with cpu detection code) +; if you want support the old pentium optimization, you can still use these version +; +; this file is not optimized for old pentium, but it compatible with all x86 32 bits +; processor (starting 80386) +; +; +; see below : zlib1222add must be adjuster if you use a zlib version < 1.2.2.2 + +;uInt longest_match(s, cur_match) +; deflate_state *s; +; IPos cur_match; /* current match */ + + NbStack equ 76 + cur_match equ dword ptr[esp+NbStack-0] + str_s equ dword ptr[esp+NbStack-4] +; 5 dword on top (ret,ebp,esi,edi,ebx) + adrret equ dword ptr[esp+NbStack-8] + pushebp equ dword ptr[esp+NbStack-12] + pushedi equ dword ptr[esp+NbStack-16] + pushesi equ dword ptr[esp+NbStack-20] + pushebx equ dword ptr[esp+NbStack-24] + + chain_length equ dword ptr [esp+NbStack-28] + limit equ dword ptr [esp+NbStack-32] + best_len equ dword ptr [esp+NbStack-36] + window equ dword ptr [esp+NbStack-40] + prev equ dword ptr [esp+NbStack-44] + scan_start equ word ptr [esp+NbStack-48] + wmask equ dword ptr [esp+NbStack-52] + match_start_ptr equ dword ptr [esp+NbStack-56] + nice_match equ dword ptr [esp+NbStack-60] + scan equ dword ptr [esp+NbStack-64] + + windowlen equ dword ptr [esp+NbStack-68] + match_start equ dword ptr [esp+NbStack-72] + strend equ dword ptr [esp+NbStack-76] + NbStackAdd equ (NbStack-24) + + .386p + + name gvmatch + .MODEL FLAT + + + +; all the +zlib1222add offsets are due to the addition of fields +; in zlib in the deflate_state structure since the asm code was first written +; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)"). +; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0"). +; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8"). + + zlib1222add equ 8 + +; Note : these value are good with a 8 bytes boundary pack structure + dep_chain_length equ 74h+zlib1222add + dep_window equ 30h+zlib1222add + dep_strstart equ 64h+zlib1222add + dep_prev_length equ 70h+zlib1222add + dep_nice_match equ 88h+zlib1222add + dep_w_size equ 24h+zlib1222add + dep_prev equ 38h+zlib1222add + dep_w_mask equ 2ch+zlib1222add + dep_good_match equ 84h+zlib1222add + dep_match_start equ 68h+zlib1222add + dep_lookahead equ 6ch+zlib1222add + + +_TEXT segment + +IFDEF NOUNDERLINE + public longest_match + public match_init +ELSE + public _longest_match + public _match_init +ENDIF + + MAX_MATCH equ 258 + MIN_MATCH equ 3 + MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1) + + + +MAX_MATCH equ 258 +MIN_MATCH equ 3 +MIN_LOOKAHEAD equ (MAX_MATCH + MIN_MATCH + 1) +MAX_MATCH_8_ equ ((MAX_MATCH + 7) AND 0FFF0h) + + +;;; stack frame offsets + +chainlenwmask equ esp + 0 ; high word: current chain len + ; low word: s->wmask +window equ esp + 4 ; local copy of s->window +windowbestlen equ esp + 8 ; s->window + bestlen +scanstart equ esp + 16 ; first two bytes of string +scanend equ esp + 12 ; last two bytes of string +scanalign equ esp + 20 ; dword-misalignment of string +nicematch equ esp + 24 ; a good enough match size +bestlen equ esp + 28 ; size of best match so far +scan equ esp + 32 ; ptr to string wanting match + +LocalVarsSize equ 36 +; saved ebx byte esp + 36 +; saved edi byte esp + 40 +; saved esi byte esp + 44 +; saved ebp byte esp + 48 +; return address byte esp + 52 +deflatestate equ esp + 56 ; the function arguments +curmatch equ esp + 60 + +;;; Offsets for fields in the deflate_state structure. These numbers +;;; are calculated from the definition of deflate_state, with the +;;; assumption that the compiler will dword-align the fields. (Thus, +;;; changing the definition of deflate_state could easily cause this +;;; program to crash horribly, without so much as a warning at +;;; compile time. Sigh.) + +dsWSize equ 36+zlib1222add +dsWMask equ 44+zlib1222add +dsWindow equ 48+zlib1222add +dsPrev equ 56+zlib1222add +dsMatchLen equ 88+zlib1222add +dsPrevMatch equ 92+zlib1222add +dsStrStart equ 100+zlib1222add +dsMatchStart equ 104+zlib1222add +dsLookahead equ 108+zlib1222add +dsPrevLen equ 112+zlib1222add +dsMaxChainLen equ 116+zlib1222add +dsGoodMatch equ 132+zlib1222add +dsNiceMatch equ 136+zlib1222add + + +;;; match686.asm -- Pentium-Pro-optimized version of longest_match() +;;; Written for zlib 1.1.2 +;;; Copyright (C) 1998 Brian Raiter +;;; You can look at http://www.muppetlabs.com/~breadbox/software/assembly.html +;;; +;; +;; This software is provided 'as-is', without any express or implied +;; warranty. In no event will the authors be held liable for any damages +;; arising from the use of this software. +;; +;; Permission is granted to anyone to use this software for any purpose, +;; including commercial applications, and to alter it and redistribute it +;; freely, subject to the following restrictions: +;; +;; 1. The origin of this software must not be misrepresented; you must not +;; claim that you wrote the original software. If you use this software +;; in a product, an acknowledgment in the product documentation would be +;; appreciated but is not required. +;; 2. Altered source versions must be plainly marked as such, and must not be +;; misrepresented as being the original software +;; 3. This notice may not be removed or altered from any source distribution. +;; + +;GLOBAL _longest_match, _match_init + + +;SECTION .text + +;;; uInt longest_match(deflate_state *deflatestate, IPos curmatch) + +;_longest_match: + IFDEF NOUNDERLINE + longest_match proc near + ELSE + _longest_match proc near + ENDIF +.FPO (9, 4, 0, 0, 1, 0) + +;;; Save registers that the compiler may be using, and adjust esp to +;;; make room for our stack frame. + + push ebp + push edi + push esi + push ebx + sub esp, LocalVarsSize + +;;; Retrieve the function arguments. ecx will hold cur_match +;;; throughout the entire function. edx will hold the pointer to the +;;; deflate_state structure during the function's setup (before +;;; entering the main loop. + + mov edx, [deflatestate] + mov ecx, [curmatch] + +;;; uInt wmask = s->w_mask; +;;; unsigned chain_length = s->max_chain_length; +;;; if (s->prev_length >= s->good_match) { +;;; chain_length >>= 2; +;;; } + + mov eax, [edx + dsPrevLen] + mov ebx, [edx + dsGoodMatch] + cmp eax, ebx + mov eax, [edx + dsWMask] + mov ebx, [edx + dsMaxChainLen] + jl LastMatchGood + shr ebx, 2 +LastMatchGood: + +;;; chainlen is decremented once beforehand so that the function can +;;; use the sign flag instead of the zero flag for the exit test. +;;; It is then shifted into the high word, to make room for the wmask +;;; value, which it will always accompany. + + dec ebx + shl ebx, 16 + or ebx, eax + mov [chainlenwmask], ebx + +;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + mov eax, [edx + dsNiceMatch] + mov ebx, [edx + dsLookahead] + cmp ebx, eax + jl LookaheadLess + mov ebx, eax +LookaheadLess: mov [nicematch], ebx + +;;; register Bytef *scan = s->window + s->strstart; + + mov esi, [edx + dsWindow] + mov [window], esi + mov ebp, [edx + dsStrStart] + lea edi, [esi + ebp] + mov [scan], edi + +;;; Determine how many bytes the scan ptr is off from being +;;; dword-aligned. + + mov eax, edi + neg eax + and eax, 3 + mov [scanalign], eax + +;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ? +;;; s->strstart - (IPos)MAX_DIST(s) : NIL; + + mov eax, [edx + dsWSize] + sub eax, MIN_LOOKAHEAD + sub ebp, eax + jg LimitPositive + xor ebp, ebp +LimitPositive: + +;;; int best_len = s->prev_length; + + mov eax, [edx + dsPrevLen] + mov [bestlen], eax + +;;; Store the sum of s->window + best_len in esi locally, and in esi. + + add esi, eax + mov [windowbestlen], esi + +;;; register ush scan_start = *(ushf*)scan; +;;; register ush scan_end = *(ushf*)(scan+best_len-1); +;;; Posf *prev = s->prev; + + movzx ebx, word ptr [edi] + mov [scanstart], ebx + movzx ebx, word ptr [edi + eax - 1] + mov [scanend], ebx + mov edi, [edx + dsPrev] + +;;; Jump into the main loop. + + mov edx, [chainlenwmask] + jmp short LoopEntry + +align 4 + +;;; do { +;;; match = s->window + cur_match; +;;; if (*(ushf*)(match+best_len-1) != scan_end || +;;; *(ushf*)match != scan_start) continue; +;;; [...] +;;; } while ((cur_match = prev[cur_match & wmask]) > limit +;;; && --chain_length != 0); +;;; +;;; Here is the inner loop of the function. The function will spend the +;;; majority of its time in this loop, and majority of that time will +;;; be spent in the first ten instructions. +;;; +;;; Within this loop: +;;; ebx = scanend +;;; ecx = curmatch +;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask) +;;; esi = windowbestlen - i.e., (window + bestlen) +;;; edi = prev +;;; ebp = limit + +LookupLoop: + and ecx, edx + movzx ecx, word ptr [edi + ecx*2] + cmp ecx, ebp + jbe LeaveNow + sub edx, 00010000h + js LeaveNow +LoopEntry: movzx eax, word ptr [esi + ecx - 1] + cmp eax, ebx + jnz LookupLoop + mov eax, [window] + movzx eax, word ptr [eax + ecx] + cmp eax, [scanstart] + jnz LookupLoop + +;;; Store the current value of chainlen. + + mov [chainlenwmask], edx + +;;; Point edi to the string under scrutiny, and esi to the string we +;;; are hoping to match it up with. In actuality, esi and edi are +;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is +;;; initialized to -(MAX_MATCH_8 - scanalign). + + mov esi, [window] + mov edi, [scan] + add esi, ecx + mov eax, [scanalign] + mov edx, 0fffffef8h; -(MAX_MATCH_8) + lea edi, [edi + eax + 0108h] ;MAX_MATCH_8] + lea esi, [esi + eax + 0108h] ;MAX_MATCH_8] + +;;; Test the strings for equality, 8 bytes at a time. At the end, +;;; adjust edx so that it is offset to the exact byte that mismatched. +;;; +;;; We already know at this point that the first three bytes of the +;;; strings match each other, and they can be safely passed over before +;;; starting the compare loop. So what this code does is skip over 0-3 +;;; bytes, as much as necessary in order to dword-align the edi +;;; pointer. (esi will still be misaligned three times out of four.) +;;; +;;; It should be confessed that this loop usually does not represent +;;; much of the total running time. Replacing it with a more +;;; straightforward "rep cmpsb" would not drastically degrade +;;; performance. + +LoopCmps: + mov eax, [esi + edx] + xor eax, [edi + edx] + jnz LeaveLoopCmps + mov eax, [esi + edx + 4] + xor eax, [edi + edx + 4] + jnz LeaveLoopCmps4 + add edx, 8 + jnz LoopCmps + jmp short LenMaximum +LeaveLoopCmps4: add edx, 4 +LeaveLoopCmps: test eax, 0000FFFFh + jnz LenLower + add edx, 2 + shr eax, 16 +LenLower: sub al, 1 + adc edx, 0 + +;;; Calculate the length of the match. If it is longer than MAX_MATCH, +;;; then automatically accept it as the best possible match and leave. + + lea eax, [edi + edx] + mov edi, [scan] + sub eax, edi + cmp eax, MAX_MATCH + jge LenMaximum + +;;; If the length of the match is not longer than the best match we +;;; have so far, then forget it and return to the lookup loop. + + mov edx, [deflatestate] + mov ebx, [bestlen] + cmp eax, ebx + jg LongerMatch + mov esi, [windowbestlen] + mov edi, [edx + dsPrev] + mov ebx, [scanend] + mov edx, [chainlenwmask] + jmp LookupLoop + +;;; s->match_start = cur_match; +;;; best_len = len; +;;; if (len >= nice_match) break; +;;; scan_end = *(ushf*)(scan+best_len-1); + +LongerMatch: mov ebx, [nicematch] + mov [bestlen], eax + mov [edx + dsMatchStart], ecx + cmp eax, ebx + jge LeaveNow + mov esi, [window] + add esi, eax + mov [windowbestlen], esi + movzx ebx, word ptr [edi + eax - 1] + mov edi, [edx + dsPrev] + mov [scanend], ebx + mov edx, [chainlenwmask] + jmp LookupLoop + +;;; Accept the current string, with the maximum possible length. + +LenMaximum: mov edx, [deflatestate] + mov dword ptr [bestlen], MAX_MATCH + mov [edx + dsMatchStart], ecx + +;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len; +;;; return s->lookahead; + +LeaveNow: + mov edx, [deflatestate] + mov ebx, [bestlen] + mov eax, [edx + dsLookahead] + cmp ebx, eax + jg LookaheadRet + mov eax, ebx +LookaheadRet: + +;;; Restore the stack and return from whence we came. + + add esp, LocalVarsSize + pop ebx + pop esi + pop edi + pop ebp + + ret +; please don't remove this string ! +; Your can freely use match686 in any free or commercial app if you don't remove the string in the binary! + db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998",0dh,0ah + + + IFDEF NOUNDERLINE + longest_match endp + ELSE + _longest_match endp + ENDIF + + IFDEF NOUNDERLINE + match_init proc near + ret + match_init endp + ELSE + _match_init proc near + ret + _match_init endp + ENDIF + + +_TEXT ends +end diff --git a/third_party/zlib/v1_2_11/contrib/masmx86/readme.txt b/third_party/zlib/v1_2_11/contrib/masmx86/readme.txt new file mode 100644 index 0000000..3271f720 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/masmx86/readme.txt @@ -0,0 +1,27 @@ + +Summary +------- +This directory contains ASM implementations of the functions +longest_match() and inflate_fast(). + + +Use instructions +---------------- +Assemble using MASM, and copy the object files into the zlib source +directory, then run the appropriate makefile, as suggested below. You can +donwload MASM from here: + + http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7a1c9da0-0510-44a2-b042-7ef370530c64 + +You can also get objects files here: + + http://www.winimage.com/zLibDll/zlib124_masm_obj.zip + +Build instructions +------------------ +* With Microsoft C and MASM: +nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" + +* With Borland C and TASM: +make -f win32/Makefile.bor LOCAL_ZLIB="-DASMV -DASMINF" OBJA="match686.obj inffas32.obj" OBJPA="+match686c.obj+match686.obj+inffas32.obj" + diff --git a/third_party/zlib/v1_2_11/contrib/minizip/Makefile b/third_party/zlib/v1_2_11/contrib/minizip/Makefile new file mode 100644 index 0000000..84eaad2 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/Makefile @@ -0,0 +1,25 @@ +CC=cc +CFLAGS=-O -I../.. + +UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a +ZIP_OBJS = minizip.o zip.o ioapi.o ../../libz.a + +.c.o: + $(CC) -c $(CFLAGS) $*.c + +all: miniunz minizip + +miniunz: $(UNZ_OBJS) + $(CC) $(CFLAGS) -o $@ $(UNZ_OBJS) + +minizip: $(ZIP_OBJS) + $(CC) $(CFLAGS) -o $@ $(ZIP_OBJS) + +test: miniunz minizip + ./minizip test readme.txt + ./miniunz -l test.zip + mv readme.txt readme.old + ./miniunz test.zip + +clean: + /bin/rm -f *.o *~ minizip miniunz diff --git a/third_party/zlib/v1_2_11/contrib/minizip/Makefile.am b/third_party/zlib/v1_2_11/contrib/minizip/Makefile.am new file mode 100644 index 0000000..d343011 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/Makefile.am @@ -0,0 +1,45 @@ +lib_LTLIBRARIES = libminizip.la + +if COND_DEMOS +bin_PROGRAMS = miniunzip minizip +endif + +zlib_top_srcdir = $(top_srcdir)/../.. +zlib_top_builddir = $(top_builddir)/../.. + +AM_CPPFLAGS = -I$(zlib_top_srcdir) +AM_LDFLAGS = -L$(zlib_top_builddir) + +if WIN32 +iowin32_src = iowin32.c +iowin32_h = iowin32.h +endif + +libminizip_la_SOURCES = \ + ioapi.c \ + mztools.c \ + unzip.c \ + zip.c \ + ${iowin32_src} + +libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz + +minizip_includedir = $(includedir)/minizip +minizip_include_HEADERS = \ + crypt.h \ + ioapi.h \ + mztools.h \ + unzip.h \ + zip.h \ + ${iowin32_h} + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = minizip.pc + +EXTRA_PROGRAMS = miniunzip minizip + +miniunzip_SOURCES = miniunz.c +miniunzip_LDADD = libminizip.la + +minizip_SOURCES = minizip.c +minizip_LDADD = libminizip.la -lz diff --git a/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_Changes.txt b/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_Changes.txt new file mode 100644 index 0000000..13a1bd9 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_Changes.txt @@ -0,0 +1,6 @@ + +MiniZip 1.1 was derrived from MiniZip at version 1.01f + +Change in 1.0 (Okt 2009) + - **TODO - Add history** + diff --git a/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_info.txt b/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_info.txt new file mode 100644 index 0000000..57d7152 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/MiniZip64_info.txt @@ -0,0 +1,74 @@ +MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson + +Introduction +--------------------- +MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html ) + +When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0. +All possible work was done for compatibility. + + +Background +--------------------- +When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64 +support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ ) + +That was used as a starting point. And after that ZIP64 support was added to zip.c +some refactoring and code cleanup was also done. + + +Changed from MiniZip 1.0 to MiniZip 1.1 +--------------------------------------- +* Added ZIP64 support for unzip ( by Even Rouault ) +* Added ZIP64 support for zip ( by Mathias Svensson ) +* Reverted some changed that Even Rouault did. +* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users. +* Added unzip patch for BZIP Compression method (patch create by Daniel Borca) +* Added BZIP Compress method for zip +* Did some refactoring and code cleanup + + +Credits + + Gilles Vollant - Original MiniZip author + Even Rouault - ZIP64 unzip Support + Daniel Borca - BZip Compression method support in unzip + Mathias Svensson - ZIP64 zip support + Mathias Svensson - BZip Compression method support in zip + + Resources + + ZipLayout http://result42.com/projects/ZipFileLayout + Command line tool for Windows that shows the layout and information of the headers in a zip archive. + Used when debugging and validating the creation of zip files using MiniZip64 + + + ZIP App Note http://www.pkware.com/documents/casestudies/APPNOTE.TXT + Zip File specification + + +Notes. + * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined. + +License +---------------------------------------------------------- + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + +---------------------------------------------------------- + diff --git a/third_party/zlib/v1_2_11/contrib/minizip/configure.ac b/third_party/zlib/v1_2_11/contrib/minizip/configure.ac new file mode 100644 index 0000000..5b11970 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/configure.ac @@ -0,0 +1,32 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_INIT([minizip], [1.2.11], [bugzilla.redhat.com]) +AC_CONFIG_SRCDIR([minizip.c]) +AM_INIT_AUTOMAKE([foreign]) +LT_INIT + +AC_MSG_CHECKING([whether to build example programs]) +AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs])) +AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes]) +if test "$enable_demos" = yes +then + AC_MSG_RESULT([yes]) +else + AC_MSG_RESULT([no]) +fi + +case "${host}" in + *-mingw* | mingw*) + WIN32="yes" + ;; + *) + ;; +esac +AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"]) + + +AC_SUBST([HAVE_UNISTD_H], [0]) +AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], []) +AC_CONFIG_FILES([Makefile minizip.pc]) +AC_OUTPUT diff --git a/third_party/zlib/v1_2_11/contrib/minizip/crypt.h b/third_party/zlib/v1_2_11/contrib/minizip/crypt.h new file mode 100644 index 0000000..1e9e820 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/crypt.h @@ -0,0 +1,131 @@ +/* crypt.h -- base code for crypt/uncrypt ZIPfile + + + Version 1.01e, February 12th, 2005 + + Copyright (C) 1998-2005 Gilles Vollant + + This code is a modified version of crypting code in Infozip distribution + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + If you don't need crypting in your application, just define symbols + NOCRYPT and NOUNCRYPT. + + This code support the "Traditional PKWARE Encryption". + + The new AES encryption added on Zip format by Winzip (see the page + http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong + Encryption is not supported. +*/ + +#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) + +/*********************************************************************** + * Return the next byte in the pseudo-random sequence + */ +static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab) +{ + unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an + * unpredictable manner on 16-bit systems; not a problem + * with any known compiler so far, though */ + + temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; + return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); +} + +/*********************************************************************** + * Update the encryption keys with the next byte of plain text + */ +static int update_keys(unsigned long* pkeys,const z_crc_t* pcrc_32_tab,int c) +{ + (*(pkeys+0)) = CRC32((*(pkeys+0)), c); + (*(pkeys+1)) += (*(pkeys+0)) & 0xff; + (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; + { + register int keyshift = (int)((*(pkeys+1)) >> 24); + (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); + } + return c; +} + + +/*********************************************************************** + * Initialize the encryption keys and the random header according to + * the given password. + */ +static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t* pcrc_32_tab) +{ + *(pkeys+0) = 305419896L; + *(pkeys+1) = 591751049L; + *(pkeys+2) = 878082192L; + while (*passwd != '\0') { + update_keys(pkeys,pcrc_32_tab,(int)*passwd); + passwd++; + } +} + +#define zdecode(pkeys,pcrc_32_tab,c) \ + (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab))) + +#define zencode(pkeys,pcrc_32_tab,c,t) \ + (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c)) + +#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED + +#define RAND_HEAD_LEN 12 + /* "last resort" source for second part of crypt seed pattern */ +# ifndef ZCR_SEED2 +# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ +# endif + +static int crypthead(const char* passwd, /* password string */ + unsigned char* buf, /* where to write header */ + int bufSize, + unsigned long* pkeys, + const z_crc_t* pcrc_32_tab, + unsigned long crcForCrypting) +{ + int n; /* index in random header */ + int t; /* temporary */ + int c; /* random byte */ + unsigned char header[RAND_HEAD_LEN-2]; /* random header */ + static unsigned calls = 0; /* ensure different random header each time */ + + if (bufSize> 7) & 0xff; + header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); + } + /* Encrypt random header (last two bytes is high word of crc) */ + init_keys(passwd, pkeys, pcrc_32_tab); + for (n = 0; n < RAND_HEAD_LEN-2; n++) + { + buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); + } + buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); + buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); + return n; +} + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/minizip/ioapi.c b/third_party/zlib/v1_2_11/contrib/minizip/ioapi.c new file mode 100644 index 0000000..7f5c191 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/ioapi.c @@ -0,0 +1,247 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS))) + #define _CRT_SECURE_NO_WARNINGS +#endif + +#if defined(__APPLE__) || defined(IOAPI_NO_64) +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + + +#include "ioapi.h" + +voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) +{ + if (pfilefunc->zfile_func64.zopen64_file != NULL) + return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); + else + { + return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); + } +} + +long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); + else + { + uLong offsetTruncated = (uLong)offset; + if (offsetTruncated != offset) + return -1; + else + return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); + } +} + +ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) +{ + if (pfilefunc->zfile_func64.zseek64_file != NULL) + return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); + else + { + uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); + if ((tell_uLong) == MAXU32) + return (ZPOS64_T)-1; + else + return tell_uLong; + } +} + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) +{ + p_filefunc64_32->zfile_func64.zopen64_file = NULL; + p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; + p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; + p_filefunc64_32->zfile_func64.ztell64_file = NULL; + p_filefunc64_32->zfile_func64.zseek64_file = NULL; + p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; + p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; + p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; + p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; + p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; +} + + + +static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); +static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); +static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); +static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); +static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); + +static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + file = fopen(filename, mode_fopen); + return file; +} + +static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) +{ + FILE* file = NULL; + const char* mode_fopen = NULL; + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else + if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else + if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename!=NULL) && (mode_fopen != NULL)) + file = FOPEN_FUNC((const char*)filename, mode_fopen); + return file; +} + + +static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) +{ + uLong ret; + ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); + return ret; +} + +static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) +{ + long ret; + ret = ftell((FILE *)stream); + return ret; +} + + +static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) +{ + ZPOS64_T ret; + ret = FTELLO_FUNC((FILE *)stream); + return ret; +} + +static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) +{ + int fseek_origin=0; + long ret; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + ret = 0; + if (fseek((FILE *)stream, offset, fseek_origin) != 0) + ret = -1; + return ret; +} + +static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) +{ + int fseek_origin=0; + long ret; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + fseek_origin = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END : + fseek_origin = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + fseek_origin = SEEK_SET; + break; + default: return -1; + } + ret = 0; + + if(FSEEKO_FUNC((FILE *)stream, offset, fseek_origin) != 0) + ret = -1; + + return ret; +} + + +static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = fclose((FILE *)stream); + return ret; +} + +static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) +{ + int ret; + ret = ferror((FILE *)stream); + return ret; +} + +void fill_fopen_filefunc (pzlib_filefunc_def) + zlib_filefunc_def* pzlib_filefunc_def; +{ + pzlib_filefunc_def->zopen_file = fopen_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell_file = ftell_file_func; + pzlib_filefunc_def->zseek_file = fseek_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = fopen64_file_func; + pzlib_filefunc_def->zread_file = fread_file_func; + pzlib_filefunc_def->zwrite_file = fwrite_file_func; + pzlib_filefunc_def->ztell64_file = ftell64_file_func; + pzlib_filefunc_def->zseek64_file = fseek64_file_func; + pzlib_filefunc_def->zclose_file = fclose_file_func; + pzlib_filefunc_def->zerror_file = ferror_file_func; + pzlib_filefunc_def->opaque = NULL; +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/ioapi.h b/third_party/zlib/v1_2_11/contrib/minizip/ioapi.h new file mode 100644 index 0000000..8dcbdb0 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/ioapi.h @@ -0,0 +1,208 @@ +/* ioapi.h -- IO base function header for compress/uncompress .zip + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + Changes + + Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) + Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. + More if/def section may be needed to support other platforms + Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. + (but you should use iowin32.c for windows instead) + +*/ + +#ifndef _ZLIBIOAPI64_H +#define _ZLIBIOAPI64_H + +#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) + + // Linux needs this to support file operation on files larger then 4+GB + // But might need better if/def to select just the platforms that needs them. + + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif + +#endif + +#include +#include +#include "zlib.h" + +#if defined(USE_FILE32API) +#define fopen64 fopen +#define ftello64 ftell +#define fseeko64 fseek +#else +#ifdef __FreeBSD__ +#define fopen64 fopen +#define ftello64 ftello +#define fseeko64 fseeko +#endif +#ifdef _MSC_VER + #define fopen64 fopen + #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) + #define ftello64 _ftelli64 + #define fseeko64 _fseeki64 + #else // old MSC + #define ftello64 ftell + #define fseeko64 fseek + #endif +#endif +#endif + +/* +#ifndef ZPOS64_T + #ifdef _WIN32 + #define ZPOS64_T fpos_t + #else + #include + #define ZPOS64_T uint64_t + #endif +#endif +*/ + +#ifdef HAVE_MINIZIP64_CONF_H +#include "mz64conf.h" +#endif + +/* a type choosen by DEFINE */ +#ifdef HAVE_64BIT_INT_CUSTOM +typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; +#else +#ifdef HAS_STDINT_H +#include "stdint.h" +typedef uint64_t ZPOS64_T; +#else + +/* Maximum unsigned 32-bit value used as placeholder for zip64 */ +#define MAXU32 0xffffffff + +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef unsigned __int64 ZPOS64_T; +#else +typedef unsigned long long int ZPOS64_T; +#endif +#endif +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + +#define ZLIB_FILEFUNC_SEEK_CUR (1) +#define ZLIB_FILEFUNC_SEEK_END (2) +#define ZLIB_FILEFUNC_SEEK_SET (0) + +#define ZLIB_FILEFUNC_MODE_READ (1) +#define ZLIB_FILEFUNC_MODE_WRITE (2) +#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) + +#define ZLIB_FILEFUNC_MODE_EXISTING (4) +#define ZLIB_FILEFUNC_MODE_CREATE (8) + + +#ifndef ZCALLBACK + #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) + #define ZCALLBACK CALLBACK + #else + #define ZCALLBACK + #endif +#endif + + + + +typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); +typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); +typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); + +typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); + + +/* here is the "old" 32 bits structure structure */ +typedef struct zlib_filefunc_def_s +{ + open_file_func zopen_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell_file_func ztell_file; + seek_file_func zseek_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc_def; + +typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); +typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode)); + +typedef struct zlib_filefunc64_def_s +{ + open64_file_func zopen64_file; + read_file_func zread_file; + write_file_func zwrite_file; + tell64_file_func ztell64_file; + seek64_file_func zseek64_file; + close_file_func zclose_file; + testerror_file_func zerror_file; + voidpf opaque; +} zlib_filefunc64_def; + +void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); + +/* now internal definition, only for zip.c and unzip.h */ +typedef struct zlib_filefunc64_32_def_s +{ + zlib_filefunc64_def zfile_func64; + open_file_func zopen32_file; + tell_file_func ztell32_file; + seek_file_func zseek32_file; +} zlib_filefunc64_32_def; + + +#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) +//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) +//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) +#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) +#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) + +voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)); +long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); +ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); + +void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); + +#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) +#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) +#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/minizip/iowin32.c b/third_party/zlib/v1_2_11/contrib/minizip/iowin32.c new file mode 100644 index 0000000..274f39e --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/iowin32.c @@ -0,0 +1,462 @@ +/* iowin32.c -- IO base function header for compress/uncompress .zip + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#include + +#include "zlib.h" +#include "ioapi.h" +#include "iowin32.h" + +#ifndef INVALID_HANDLE_VALUE +#define INVALID_HANDLE_VALUE (0xFFFFFFFF) +#endif + +#ifndef INVALID_SET_FILE_POINTER +#define INVALID_SET_FILE_POINTER ((DWORD)-1) +#endif + + +// see Include/shared/winapifamily.h in the Windows Kit +#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) +#if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) +#define IOWIN32_USING_WINRT_API 1 +#endif +#endif + +voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); +uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); +uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); +ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream)); +long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); +int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream)); +int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream)); + +typedef struct +{ + HANDLE hf; + int error; +} WIN32FILE_IOWIN; + + +static void win32_translate_open_mode(int mode, + DWORD* lpdwDesiredAccess, + DWORD* lpdwCreationDisposition, + DWORD* lpdwShareMode, + DWORD* lpdwFlagsAndAttributes) +{ + *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) + { + *lpdwDesiredAccess = GENERIC_READ; + *lpdwCreationDisposition = OPEN_EXISTING; + *lpdwShareMode = FILE_SHARE_READ; + } + else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + { + *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; + *lpdwCreationDisposition = OPEN_EXISTING; + } + else if (mode & ZLIB_FILEFUNC_MODE_CREATE) + { + *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; + *lpdwCreationDisposition = CREATE_ALWAYS; + } +} + +static voidpf win32_build_iowin(HANDLE hFile) +{ + voidpf ret=NULL; + + if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE)) + { + WIN32FILE_IOWIN w32fiow; + w32fiow.hf = hFile; + w32fiow.error = 0; + ret = malloc(sizeof(WIN32FILE_IOWIN)); + + if (ret==NULL) + CloseHandle(hFile); + else + *((WIN32FILE_IOWIN*)ret) = w32fiow; + } + return ret; +} + +voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API +#ifdef UNICODE + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#endif +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition,NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode) +{ + const char* mode_fopen = NULL; + DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; + HANDLE hFile = NULL; + + win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); + +#ifdef IOWIN32_USING_WINRT_API +#ifdef UNICODE + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + { + WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; + MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); + hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); + } +#endif +#else + if ((filename!=NULL) && (dwDesiredAccess != 0)) + hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); +#endif + + return win32_build_iowin(hFile); +} + + +uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size) +{ + uLong ret=0; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + + if (hFile != NULL) + { + if (!ReadFile(hFile, buf, size, &ret, NULL)) + { + DWORD dwErr = GetLastError(); + if (dwErr == ERROR_HANDLE_EOF) + dwErr = 0; + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + } + } + + return ret; +} + + +uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size) +{ + uLong ret=0; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + + if (hFile != NULL) + { + if (!WriteFile(hFile, buf, size, &ret, NULL)) + { + DWORD dwErr = GetLastError(); + if (dwErr == ERROR_HANDLE_EOF) + dwErr = 0; + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + } + } + + return ret; +} + +static BOOL MySetFilePointerEx(HANDLE hFile, LARGE_INTEGER pos, LARGE_INTEGER *newPos, DWORD dwMoveMethod) +{ +#ifdef IOWIN32_USING_WINRT_API + return SetFilePointerEx(hFile, pos, newPos, dwMoveMethod); +#else + LONG lHigh = pos.HighPart; + DWORD dwNewPos = SetFilePointer(hFile, pos.LowPart, &lHigh, dwMoveMethod); + BOOL fOk = TRUE; + if (dwNewPos == 0xFFFFFFFF) + if (GetLastError() != NO_ERROR) + fOk = FALSE; + if ((newPos != NULL) && (fOk)) + { + newPos->LowPart = dwNewPos; + newPos->HighPart = lHigh; + } + return fOk; +#endif +} + +long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream) +{ + long ret=-1; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + if (hFile != NULL) + { + LARGE_INTEGER pos; + pos.QuadPart = 0; + + if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=(long)pos.LowPart; + } + return ret; +} + +ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream) +{ + ZPOS64_T ret= (ZPOS64_T)-1; + HANDLE hFile = NULL; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream)->hf; + + if (hFile) + { + LARGE_INTEGER pos; + pos.QuadPart = 0; + + if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = (ZPOS64_T)-1; + } + else + ret=pos.QuadPart; + } + return ret; +} + + +long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin) +{ + DWORD dwMoveMethod=0xFFFFFFFF; + HANDLE hFile = NULL; + + long ret=-1; + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + dwMoveMethod = FILE_CURRENT; + break; + case ZLIB_FILEFUNC_SEEK_END : + dwMoveMethod = FILE_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + dwMoveMethod = FILE_BEGIN; + break; + default: return -1; + } + + if (hFile != NULL) + { + LARGE_INTEGER pos; + pos.QuadPart = offset; + if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=0; + } + return ret; +} + +long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin) +{ + DWORD dwMoveMethod=0xFFFFFFFF; + HANDLE hFile = NULL; + long ret=-1; + + if (stream!=NULL) + hFile = ((WIN32FILE_IOWIN*)stream)->hf; + + switch (origin) + { + case ZLIB_FILEFUNC_SEEK_CUR : + dwMoveMethod = FILE_CURRENT; + break; + case ZLIB_FILEFUNC_SEEK_END : + dwMoveMethod = FILE_END; + break; + case ZLIB_FILEFUNC_SEEK_SET : + dwMoveMethod = FILE_BEGIN; + break; + default: return -1; + } + + if (hFile) + { + LARGE_INTEGER pos; + pos.QuadPart = offset; + if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) + { + DWORD dwErr = GetLastError(); + ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; + ret = -1; + } + else + ret=0; + } + return ret; +} + +int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream) +{ + int ret=-1; + + if (stream!=NULL) + { + HANDLE hFile; + hFile = ((WIN32FILE_IOWIN*)stream) -> hf; + if (hFile != NULL) + { + CloseHandle(hFile); + ret=0; + } + free(stream); + } + return ret; +} + +int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream) +{ + int ret=-1; + if (stream!=NULL) + { + ret = ((WIN32FILE_IOWIN*)stream) -> error; + } + return ret; +} + +void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen_file = win32_open_file_func; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell_file = win32_tell_file_func; + pzlib_filefunc_def->zseek_file = win32_seek_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + +void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_func; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + + +void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} + + +void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def) +{ + pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW; + pzlib_filefunc_def->zread_file = win32_read_file_func; + pzlib_filefunc_def->zwrite_file = win32_write_file_func; + pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; + pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; + pzlib_filefunc_def->zclose_file = win32_close_file_func; + pzlib_filefunc_def->zerror_file = win32_error_file_func; + pzlib_filefunc_def->opaque = NULL; +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/iowin32.h b/third_party/zlib/v1_2_11/contrib/minizip/iowin32.h new file mode 100644 index 0000000..0ca0969 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/iowin32.h @@ -0,0 +1,28 @@ +/* iowin32.h -- IO base function header for compress/uncompress .zip + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + +*/ + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); +void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def)); +void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def)); + +#ifdef __cplusplus +} +#endif diff --git a/third_party/zlib/v1_2_11/contrib/minizip/make_vms.com b/third_party/zlib/v1_2_11/contrib/minizip/make_vms.com new file mode 100644 index 0000000..9ac13a9 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/make_vms.com @@ -0,0 +1,25 @@ +$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig +$ open/write zdef vmsdefs.h +$ copy sys$input: zdef +$ deck +#define unix +#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from +#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator +#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord +#define Write_EndOfCentralDirectoryRecord Write_EoDRecord +$ eod +$ close zdef +$ copy vmsdefs.h,ioapi.h_orig ioapi.h +$ cc/include=[--]/prefix=all ioapi.c +$ cc/include=[--]/prefix=all miniunz.c +$ cc/include=[--]/prefix=all unzip.c +$ cc/include=[--]/prefix=all minizip.c +$ cc/include=[--]/prefix=all zip.c +$ link miniunz,unzip,ioapi,[--]libz.olb/lib +$ link minizip,zip,ioapi,[--]libz.olb/lib +$ mcr []minizip test minizip_info.txt +$ mcr []miniunz -l test.zip +$ rename minizip_info.txt; minizip_info.txt_old +$ mcr []miniunz test.zip +$ delete test.zip;* +$exit diff --git a/third_party/zlib/v1_2_11/contrib/minizip/miniunz.c b/third_party/zlib/v1_2_11/contrib/minizip/miniunz.c new file mode 100644 index 0000000..3d65401 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/miniunz.c @@ -0,0 +1,660 @@ +/* + miniunz.c + Version 1.1, February 14h, 2010 + sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) +*/ + +#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif +#endif + +#ifdef __APPLE__ +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# include +# include +#else +# include +# include +#endif + + +#include "unzip.h" + +#define CASESENSITIVITY (0) +#define WRITEBUFFERSIZE (8192) +#define MAXFILENAME (256) + +#ifdef _WIN32 +#define USEWIN32IOAPI +#include "iowin32.h" +#endif +/* + mini unzip, demo of unzip package + + usage : + Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir] + + list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT + if it exists +*/ + + +/* change_file_date : change the date/time of a file + filename : the filename of the file where date/time must be modified + dosdate : the new date at the MSDos format (4 bytes) + tmu_date : the SAME new date at the tm_unz format */ +void change_file_date(filename,dosdate,tmu_date) + const char *filename; + uLong dosdate; + tm_unz tmu_date; +{ +#ifdef _WIN32 + HANDLE hFile; + FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; + + hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, + 0,NULL,OPEN_EXISTING,0,NULL); + GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); + DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); + LocalFileTimeToFileTime(&ftLocal,&ftm); + SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); + CloseHandle(hFile); +#else +#ifdef unix || __APPLE__ + struct utimbuf ut; + struct tm newdate; + newdate.tm_sec = tmu_date.tm_sec; + newdate.tm_min=tmu_date.tm_min; + newdate.tm_hour=tmu_date.tm_hour; + newdate.tm_mday=tmu_date.tm_mday; + newdate.tm_mon=tmu_date.tm_mon; + if (tmu_date.tm_year > 1900) + newdate.tm_year=tmu_date.tm_year - 1900; + else + newdate.tm_year=tmu_date.tm_year ; + newdate.tm_isdst=-1; + + ut.actime=ut.modtime=mktime(&newdate); + utime(filename,&ut); +#endif +#endif +} + + +/* mymkdir and change_file_date are not 100 % portable + As I don't know well Unix, I wait feedback for the unix portion */ + +int mymkdir(dirname) + const char* dirname; +{ + int ret=0; +#ifdef _WIN32 + ret = _mkdir(dirname); +#elif unix + ret = mkdir (dirname,0775); +#elif __APPLE__ + ret = mkdir (dirname,0775); +#endif + return ret; +} + +int makedir (newdir) + char *newdir; +{ + char *buffer ; + char *p; + int len = (int)strlen(newdir); + + if (len <= 0) + return 0; + + buffer = (char*)malloc(len+1); + if (buffer==NULL) + { + printf("Error allocating memory\n"); + return UNZ_INTERNALERROR; + } + strcpy(buffer,newdir); + + if (buffer[len-1] == '/') { + buffer[len-1] = '\0'; + } + if (mymkdir(buffer) == 0) + { + free(buffer); + return 1; + } + + p = buffer+1; + while (1) + { + char hold; + + while(*p && *p != '\\' && *p != '/') + p++; + hold = *p; + *p = 0; + if ((mymkdir(buffer) == -1) && (errno == ENOENT)) + { + printf("couldn't create directory %s\n",buffer); + free(buffer); + return 0; + } + if (hold == 0) + break; + *p++ = hold; + } + free(buffer); + return 1; +} + +void do_banner() +{ + printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n"); + printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); +} + +void do_help() +{ + printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ + " -e Extract without pathname (junk paths)\n" \ + " -x Extract with pathname\n" \ + " -v list files\n" \ + " -l list files\n" \ + " -d directory to extract into\n" \ + " -o overwrite files without prompting\n" \ + " -p extract crypted file using password\n\n"); +} + +void Display64BitsSize(ZPOS64_T n, int size_char) +{ + /* to avoid compatibility problem , we do here the conversion */ + char number[21]; + int offset=19; + int pos_string = 19; + number[20]=0; + for (;;) { + number[offset]=(char)((n%10)+'0'); + if (number[offset] != '0') + pos_string=offset; + n/=10; + if (offset==0) + break; + offset--; + } + { + int size_display_string = 19-pos_string; + while (size_char > size_display_string) + { + size_char--; + printf(" "); + } + } + + printf("%s",&number[pos_string]); +} + +int do_list(uf) + unzFile uf; +{ + uLong i; + unz_global_info64 gi; + int err; + + err = unzGetGlobalInfo64(uf,&gi); + if (err!=UNZ_OK) + printf("error %d with zipfile in unzGetGlobalInfo \n",err); + printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); + printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); + for (i=0;i0) + ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); + + /* display a '*' if the file is crypted */ + if ((file_info.flag & 1) != 0) + charCrypt='*'; + + if (file_info.compression_method==0) + string_method="Stored"; + else + if (file_info.compression_method==Z_DEFLATED) + { + uInt iLevel=(uInt)((file_info.flag & 0x6)/2); + if (iLevel==0) + string_method="Defl:N"; + else if (iLevel==1) + string_method="Defl:X"; + else if ((iLevel==2) || (iLevel==3)) + string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ + } + else + if (file_info.compression_method==Z_BZIP2ED) + { + string_method="BZip2 "; + } + else + string_method="Unkn. "; + + Display64BitsSize(file_info.uncompressed_size,7); + printf(" %6s%c",string_method,charCrypt); + Display64BitsSize(file_info.compressed_size,7); + printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", + ratio, + (uLong)file_info.tmu_date.tm_mon + 1, + (uLong)file_info.tmu_date.tm_mday, + (uLong)file_info.tmu_date.tm_year % 100, + (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, + (uLong)file_info.crc,filename_inzip); + if ((i+1)='a') && (rep<='z')) + rep -= 0x20; + } + while ((rep!='Y') && (rep!='N') && (rep!='A')); + } + + if (rep == 'N') + skip = 1; + + if (rep == 'A') + *popt_overwrite=1; + } + + if ((skip==0) && (err==UNZ_OK)) + { + fout=FOPEN_FUNC(write_filename,"wb"); + /* some zipfile don't contain directory alone before file */ + if ((fout==NULL) && ((*popt_extract_without_path)==0) && + (filename_withoutpath!=(char*)filename_inzip)) + { + char c=*(filename_withoutpath-1); + *(filename_withoutpath-1)='\0'; + makedir(write_filename); + *(filename_withoutpath-1)=c; + fout=FOPEN_FUNC(write_filename,"wb"); + } + + if (fout==NULL) + { + printf("error opening %s\n",write_filename); + } + } + + if (fout!=NULL) + { + printf(" extracting: %s\n",write_filename); + + do + { + err = unzReadCurrentFile(uf,buf,size_buf); + if (err<0) + { + printf("error %d with zipfile in unzReadCurrentFile\n",err); + break; + } + if (err>0) + if (fwrite(buf,err,1,fout)!=1) + { + printf("error in writing extracted file\n"); + err=UNZ_ERRNO; + break; + } + } + while (err>0); + if (fout) + fclose(fout); + + if (err==0) + change_file_date(write_filename,file_info.dosDate, + file_info.tmu_date); + } + + if (err==UNZ_OK) + { + err = unzCloseCurrentFile (uf); + if (err!=UNZ_OK) + { + printf("error %d with zipfile in unzCloseCurrentFile\n",err); + } + } + else + unzCloseCurrentFile(uf); /* don't lose the error */ + } + + free(buf); + return err; +} + + +int do_extract(uf,opt_extract_without_path,opt_overwrite,password) + unzFile uf; + int opt_extract_without_path; + int opt_overwrite; + const char* password; +{ + uLong i; + unz_global_info64 gi; + int err; + FILE* fout=NULL; + + err = unzGetGlobalInfo64(uf,&gi); + if (err!=UNZ_OK) + printf("error %d with zipfile in unzGetGlobalInfo \n",err); + + for (i=0;i insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +miniunzip - uncompress and examine ZIP archives +.SH SYNOPSIS +.B miniunzip +.RI [ -exvlo ] +zipfile [ files_to_extract ] [-d tempdir] +.SH DESCRIPTION +.B minizip +is a simple tool which allows the extraction of compressed file +archives in the ZIP format used by the MS-DOS utility PKZIP. It was +written as a demonstration of the +.IR zlib (3) +library and therefore lack many of the features of the +.IR unzip (1) +program. +.SH OPTIONS +A number of options are supported. With the exception of +.BI \-d\ tempdir +these must be supplied before any +other arguments and are: +.TP +.BI \-l\ ,\ \-\-v +List the files in the archive without extracting them. +.TP +.B \-o +Overwrite files without prompting for confirmation. +.TP +.B \-x +Extract files (default). +.PP +The +.I zipfile +argument is the name of the archive to process. The next argument can be used +to specify a single file to extract from the archive. + +Lastly, the following option can be specified at the end of the command-line: +.TP +.BI \-d\ tempdir +Extract the archive in the directory +.I tempdir +rather than the current directory. +.SH SEE ALSO +.BR minizip (1), +.BR zlib (3), +.BR unzip (1). +.SH AUTHOR +This program was written by Gilles Vollant. This manual page was +written by Mark Brown . The -d tempdir option +was added by Dirk Eddelbuettel . diff --git a/third_party/zlib/v1_2_11/contrib/minizip/minizip.1 b/third_party/zlib/v1_2_11/contrib/minizip/minizip.1 new file mode 100644 index 0000000..1154484 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/minizip.1 @@ -0,0 +1,46 @@ +.\" Hey, EMACS: -*- nroff -*- +.TH minizip 1 "May 2, 2001" +.\" Please adjust this date whenever revising the manpage. +.\" +.\" Some roff macros, for reference: +.\" .nh disable hyphenation +.\" .hy enable hyphenation +.\" .ad l left justify +.\" .ad b justify to both left and right margins +.\" .nf disable filling +.\" .fi enable filling +.\" .br insert line break +.\" .sp insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +minizip - create ZIP archives +.SH SYNOPSIS +.B minizip +.RI [ -o ] +zipfile [ " files" ... ] +.SH DESCRIPTION +.B minizip +is a simple tool which allows the creation of compressed file archives +in the ZIP format used by the MS-DOS utility PKZIP. It was written as +a demonstration of the +.IR zlib (3) +library and therefore lack many of the features of the +.IR zip (1) +program. +.SH OPTIONS +The first argument supplied is the name of the ZIP archive to create or +.RI -o +in which case it is ignored and the second argument treated as the +name of the ZIP file. If the ZIP file already exists it will be +overwritten. +.PP +Subsequent arguments specify a list of files to place in the ZIP +archive. If none are specified then an empty archive will be created. +.SH SEE ALSO +.BR miniunzip (1), +.BR zlib (3), +.BR zip (1). +.SH AUTHOR +This program was written by Gilles Vollant. This manual page was +written by Mark Brown . + diff --git a/third_party/zlib/v1_2_11/contrib/minizip/minizip.c b/third_party/zlib/v1_2_11/contrib/minizip/minizip.c new file mode 100644 index 0000000..4288962 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/minizip.c @@ -0,0 +1,520 @@ +/* + minizip.c + Version 1.1, February 14h, 2010 + sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) +*/ + + +#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) + #ifndef __USE_FILE_OFFSET64 + #define __USE_FILE_OFFSET64 + #endif + #ifndef __USE_LARGEFILE64 + #define __USE_LARGEFILE64 + #endif + #ifndef _LARGEFILE64_SOURCE + #define _LARGEFILE64_SOURCE + #endif + #ifndef _FILE_OFFSET_BIT + #define _FILE_OFFSET_BIT 64 + #endif +#endif + +#ifdef __APPLE__ +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + + + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +# include +# include +#else +# include +# include +# include +# include +#endif + +#include "zip.h" + +#ifdef _WIN32 + #define USEWIN32IOAPI + #include "iowin32.h" +#endif + + + +#define WRITEBUFFERSIZE (16384) +#define MAXFILENAME (256) + +#ifdef _WIN32 +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + int ret = 0; + { + FILETIME ftLocal; + HANDLE hFind; + WIN32_FIND_DATAA ff32; + + hFind = FindFirstFileA(f,&ff32); + if (hFind != INVALID_HANDLE_VALUE) + { + FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); + FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); + FindClose(hFind); + ret = 1; + } + } + return ret; +} +#else +#ifdef unix || __APPLE__ +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + int ret=0; + struct stat s; /* results of stat() */ + struct tm* filedate; + time_t tm_t=0; + + if (strcmp(f,"-")!=0) + { + char name[MAXFILENAME+1]; + int len = strlen(f); + if (len > MAXFILENAME) + len = MAXFILENAME; + + strncpy(name, f,MAXFILENAME-1); + /* strncpy doesnt append the trailing NULL, of the string is too long. */ + name[ MAXFILENAME ] = '\0'; + + if (name[len - 1] == '/') + name[len - 1] = '\0'; + /* not all systems allow stat'ing a file with / appended */ + if (stat(name,&s)==0) + { + tm_t = s.st_mtime; + ret = 1; + } + } + filedate = localtime(&tm_t); + + tmzip->tm_sec = filedate->tm_sec; + tmzip->tm_min = filedate->tm_min; + tmzip->tm_hour = filedate->tm_hour; + tmzip->tm_mday = filedate->tm_mday; + tmzip->tm_mon = filedate->tm_mon ; + tmzip->tm_year = filedate->tm_year; + + return ret; +} +#else +uLong filetime(f, tmzip, dt) + char *f; /* name of file to get info on */ + tm_zip *tmzip; /* return value: access, modific. and creation times */ + uLong *dt; /* dostime */ +{ + return 0; +} +#endif +#endif + + + + +int check_exist_file(filename) + const char* filename; +{ + FILE* ftestexist; + int ret = 1; + ftestexist = FOPEN_FUNC(filename,"rb"); + if (ftestexist==NULL) + ret = 0; + else + fclose(ftestexist); + return ret; +} + +void do_banner() +{ + printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n"); + printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n"); +} + +void do_help() +{ + printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \ + " -o Overwrite existing file.zip\n" \ + " -a Append to existing file.zip\n" \ + " -0 Store only\n" \ + " -1 Compress faster\n" \ + " -9 Compress better\n\n" \ + " -j exclude path. store only the file name.\n\n"); +} + +/* calculate the CRC32 of a file, + because to encrypt a file, we need known the CRC32 of the file before */ +int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) +{ + unsigned long calculate_crc=0; + int err=ZIP_OK; + FILE * fin = FOPEN_FUNC(filenameinzip,"rb"); + + unsigned long size_read = 0; + unsigned long total_read = 0; + if (fin==NULL) + { + err = ZIP_ERRNO; + } + + if (err == ZIP_OK) + do + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin); + if (size_read < size_buf) + if (feof(fin)==0) + { + printf("error in reading %s\n",filenameinzip); + err = ZIP_ERRNO; + } + + if (size_read>0) + calculate_crc = crc32(calculate_crc,buf,size_read); + total_read += size_read; + + } while ((err == ZIP_OK) && (size_read>0)); + + if (fin) + fclose(fin); + + *result_crc=calculate_crc; + printf("file %s crc %lx\n", filenameinzip, calculate_crc); + return err; +} + +int isLargeFile(const char* filename) +{ + int largeFile = 0; + ZPOS64_T pos = 0; + FILE* pFile = FOPEN_FUNC(filename, "rb"); + + if(pFile != NULL) + { + int n = FSEEKO_FUNC(pFile, 0, SEEK_END); + pos = FTELLO_FUNC(pFile); + + printf("File : %s is %lld bytes\n", filename, pos); + + if(pos >= 0xffffffff) + largeFile = 1; + + fclose(pFile); + } + + return largeFile; +} + +int main(argc,argv) + int argc; + char *argv[]; +{ + int i; + int opt_overwrite=0; + int opt_compress_level=Z_DEFAULT_COMPRESSION; + int opt_exclude_path=0; + int zipfilenamearg = 0; + char filename_try[MAXFILENAME+16]; + int zipok; + int err=0; + int size_buf=0; + void* buf=NULL; + const char* password=NULL; + + + do_banner(); + if (argc==1) + { + do_help(); + return 0; + } + else + { + for (i=1;i='0') && (c<='9')) + opt_compress_level = c-'0'; + if ((c=='j') || (c=='J')) + opt_exclude_path = 1; + + if (((c=='p') || (c=='P')) && (i+1='a') && (rep<='z')) + rep -= 0x20; + } + while ((rep!='Y') && (rep!='N') && (rep!='A')); + if (rep=='N') + zipok = 0; + if (rep=='A') + opt_overwrite = 2; + } + } + + if (zipok==1) + { + zipFile zf; + int errclose; +# ifdef USEWIN32IOAPI + zlib_filefunc64_def ffunc; + fill_win32_filefunc64A(&ffunc); + zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); +# else + zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0); +# endif + + if (zf == NULL) + { + printf("error opening %s\n",filename_try); + err= ZIP_ERRNO; + } + else + printf("creating %s\n",filename_try); + + for (i=zipfilenamearg+1;(i='0') || (argv[i][1]<='9'))) && + (strlen(argv[i]) == 2))) + { + FILE * fin; + int size_read; + const char* filenameinzip = argv[i]; + const char *savefilenameinzip; + zip_fileinfo zi; + unsigned long crcFile=0; + int zip64 = 0; + + zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = + zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; + zi.dosDate = 0; + zi.internal_fa = 0; + zi.external_fa = 0; + filetime(filenameinzip,&zi.tmz_date,&zi.dosDate); + +/* + err = zipOpenNewFileInZip(zf,filenameinzip,&zi, + NULL,0,NULL,0,NULL / * comment * /, + (opt_compress_level != 0) ? Z_DEFLATED : 0, + opt_compress_level); +*/ + if ((password != NULL) && (err==ZIP_OK)) + err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); + + zip64 = isLargeFile(filenameinzip); + + /* The path name saved, should not include a leading slash. */ + /*if it did, windows/xp and dynazip couldn't read the zip file. */ + savefilenameinzip = filenameinzip; + while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' ) + { + savefilenameinzip++; + } + + /*should the zip file contain any path at all?*/ + if( opt_exclude_path ) + { + const char *tmpptr; + const char *lastslash = 0; + for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++) + { + if( *tmpptr == '\\' || *tmpptr == '/') + { + lastslash = tmpptr; + } + } + if( lastslash != NULL ) + { + savefilenameinzip = lastslash+1; // base filename follows last slash. + } + } + + /**/ + err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi, + NULL,0,NULL,0,NULL /* comment*/, + (opt_compress_level != 0) ? Z_DEFLATED : 0, + opt_compress_level,0, + /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + password,crcFile, zip64); + + if (err != ZIP_OK) + printf("error in opening %s in zipfile\n",filenameinzip); + else + { + fin = FOPEN_FUNC(filenameinzip,"rb"); + if (fin==NULL) + { + err=ZIP_ERRNO; + printf("error in opening %s for reading\n",filenameinzip); + } + } + + if (err == ZIP_OK) + do + { + err = ZIP_OK; + size_read = (int)fread(buf,1,size_buf,fin); + if (size_read < size_buf) + if (feof(fin)==0) + { + printf("error in reading %s\n",filenameinzip); + err = ZIP_ERRNO; + } + + if (size_read>0) + { + err = zipWriteInFileInZip (zf,buf,size_read); + if (err<0) + { + printf("error in writing %s in the zipfile\n", + filenameinzip); + } + + } + } while ((err == ZIP_OK) && (size_read>0)); + + if (fin) + fclose(fin); + + if (err<0) + err=ZIP_ERRNO; + else + { + err = zipCloseFileInZip(zf); + if (err!=ZIP_OK) + printf("error in closing %s in the zipfile\n", + filenameinzip); + } + } + } + errclose = zipClose(zf,NULL); + if (errclose != ZIP_OK) + printf("error in closing %s\n",filename_try); + } + else + { + do_help(); + } + + free(buf); + return 0; +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/minizip.pc.in b/third_party/zlib/v1_2_11/contrib/minizip/minizip.pc.in new file mode 100644 index 0000000..69b5b7f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/minizip.pc.in @@ -0,0 +1,12 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@/minizip + +Name: minizip +Description: Minizip zip file manipulation library +Requires: +Version: @PACKAGE_VERSION@ +Libs: -L${libdir} -lminizip +Libs.private: -lz +Cflags: -I${includedir} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/mztools.c b/third_party/zlib/v1_2_11/contrib/minizip/mztools.c new file mode 100644 index 0000000..96891c2 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/mztools.c @@ -0,0 +1,291 @@ +/* + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) +*/ + +/* Code */ +#include +#include +#include +#include "zlib.h" +#include "unzip.h" + +#define READ_8(adr) ((unsigned char)*(adr)) +#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) ) +#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) ) + +#define WRITE_8(buff, n) do { \ + *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \ +} while(0) +#define WRITE_16(buff, n) do { \ + WRITE_8((unsigned char*)(buff), n); \ + WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \ +} while(0) +#define WRITE_32(buff, n) do { \ + WRITE_16((unsigned char*)(buff), (n) & 0xffff); \ + WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ +} while(0) + +extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) +const char* file; +const char* fileOut; +const char* fileOutTmp; +uLong* nRecovered; +uLong* bytesRecovered; +{ + int err = Z_OK; + FILE* fpZip = fopen(file, "rb"); + FILE* fpOut = fopen(fileOut, "wb"); + FILE* fpOutCD = fopen(fileOutTmp, "wb"); + if (fpZip != NULL && fpOut != NULL) { + int entries = 0; + uLong totalBytes = 0; + char header[30]; + char filename[1024]; + char extra[1024]; + int offset = 0; + int offsetCD = 0; + while ( fread(header, 1, 30, fpZip) == 30 ) { + int currentOffset = offset; + + /* File entry */ + if (READ_32(header) == 0x04034b50) { + unsigned int version = READ_16(header + 4); + unsigned int gpflag = READ_16(header + 6); + unsigned int method = READ_16(header + 8); + unsigned int filetime = READ_16(header + 10); + unsigned int filedate = READ_16(header + 12); + unsigned int crc = READ_32(header + 14); /* crc */ + unsigned int cpsize = READ_32(header + 18); /* compressed size */ + unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ + unsigned int fnsize = READ_16(header + 26); /* file name length */ + unsigned int extsize = READ_16(header + 28); /* extra field length */ + filename[0] = extra[0] = '\0'; + + /* Header */ + if (fwrite(header, 1, 30, fpOut) == 30) { + offset += 30; + } else { + err = Z_ERRNO; + break; + } + + /* Filename */ + if (fnsize > 0) { + if (fnsize < sizeof(filename)) { + if (fread(filename, 1, fnsize, fpZip) == fnsize) { + if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { + offset += fnsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_STREAM_ERROR; + break; + } + + /* Extra field */ + if (extsize > 0) { + if (extsize < sizeof(extra)) { + if (fread(extra, 1, extsize, fpZip) == extsize) { + if (fwrite(extra, 1, extsize, fpOut) == extsize) { + offset += extsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_ERRNO; + break; + } + } + + /* Data */ + { + int dataSize = cpsize; + if (dataSize == 0) { + dataSize = uncpsize; + } + if (dataSize > 0) { + char* data = malloc(dataSize); + if (data != NULL) { + if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { + if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { + offset += dataSize; + totalBytes += dataSize; + } else { + err = Z_ERRNO; + } + } else { + err = Z_ERRNO; + } + free(data); + if (err != Z_OK) { + break; + } + } else { + err = Z_MEM_ERROR; + break; + } + } + } + + /* Central directory entry */ + { + char header[46]; + char* comment = ""; + int comsize = (int) strlen(comment); + WRITE_32(header, 0x02014b50); + WRITE_16(header + 4, version); + WRITE_16(header + 6, version); + WRITE_16(header + 8, gpflag); + WRITE_16(header + 10, method); + WRITE_16(header + 12, filetime); + WRITE_16(header + 14, filedate); + WRITE_32(header + 16, crc); + WRITE_32(header + 20, cpsize); + WRITE_32(header + 24, uncpsize); + WRITE_16(header + 28, fnsize); + WRITE_16(header + 30, extsize); + WRITE_16(header + 32, comsize); + WRITE_16(header + 34, 0); /* disk # */ + WRITE_16(header + 36, 0); /* int attrb */ + WRITE_32(header + 38, 0); /* ext attrb */ + WRITE_32(header + 42, currentOffset); + /* Header */ + if (fwrite(header, 1, 46, fpOutCD) == 46) { + offsetCD += 46; + + /* Filename */ + if (fnsize > 0) { + if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { + offsetCD += fnsize; + } else { + err = Z_ERRNO; + break; + } + } else { + err = Z_STREAM_ERROR; + break; + } + + /* Extra field */ + if (extsize > 0) { + if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { + offsetCD += extsize; + } else { + err = Z_ERRNO; + break; + } + } + + /* Comment field */ + if (comsize > 0) { + if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { + offsetCD += comsize; + } else { + err = Z_ERRNO; + break; + } + } + + + } else { + err = Z_ERRNO; + break; + } + } + + /* Success */ + entries++; + + } else { + break; + } + } + + /* Final central directory */ + { + int entriesZip = entries; + char header[22]; + char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; + int comsize = (int) strlen(comment); + if (entriesZip > 0xffff) { + entriesZip = 0xffff; + } + WRITE_32(header, 0x06054b50); + WRITE_16(header + 4, 0); /* disk # */ + WRITE_16(header + 6, 0); /* disk # */ + WRITE_16(header + 8, entriesZip); /* hack */ + WRITE_16(header + 10, entriesZip); /* hack */ + WRITE_32(header + 12, offsetCD); /* size of CD */ + WRITE_32(header + 16, offset); /* offset to CD */ + WRITE_16(header + 20, comsize); /* comment */ + + /* Header */ + if (fwrite(header, 1, 22, fpOutCD) == 22) { + + /* Comment field */ + if (comsize > 0) { + if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { + err = Z_ERRNO; + } + } + + } else { + err = Z_ERRNO; + } + } + + /* Final merge (file + central directory) */ + fclose(fpOutCD); + if (err == Z_OK) { + fpOutCD = fopen(fileOutTmp, "rb"); + if (fpOutCD != NULL) { + int nRead; + char buffer[8192]; + while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { + if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { + err = Z_ERRNO; + break; + } + } + fclose(fpOutCD); + } + } + + /* Close */ + fclose(fpZip); + fclose(fpOut); + + /* Wipe temporary file */ + (void)remove(fileOutTmp); + + /* Number of recovered entries */ + if (err == Z_OK) { + if (nRecovered != NULL) { + *nRecovered = entries; + } + if (bytesRecovered != NULL) { + *bytesRecovered = totalBytes; + } + } + } else { + err = Z_STREAM_ERROR; + } + return err; +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/mztools.h b/third_party/zlib/v1_2_11/contrib/minizip/mztools.h new file mode 100644 index 0000000..a49a426 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/mztools.h @@ -0,0 +1,37 @@ +/* + Additional tools for Minizip + Code: Xavier Roche '2004 + License: Same as ZLIB (www.gzip.org) +*/ + +#ifndef _zip_tools_H +#define _zip_tools_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#include "unzip.h" + +/* Repair a ZIP file (missing central directory) + file: file to recover + fileOut: output file after recovery + fileOutTmp: temporary file name used for recovery +*/ +extern int ZEXPORT unzRepair(const char* file, + const char* fileOut, + const char* fileOutTmp, + uLong* nRecovered, + uLong* bytesRecovered); + + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/third_party/zlib/v1_2_11/contrib/minizip/unzip.c b/third_party/zlib/v1_2_11/contrib/minizip/unzip.c new file mode 100644 index 0000000..bcfb941 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/unzip.c @@ -0,0 +1,2125 @@ +/* unzip.c -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + + ------------------------------------------------------------------------------------ + Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of + compatibility with older software. The following is from the original crypt.c. + Code woven in by Terry Thorsen 1/2003. + + Copyright (c) 1990-2000 Info-ZIP. All rights reserved. + + See the accompanying file LICENSE, version 2000-Apr-09 or later + (the contents of which are also included in zip.h) for terms of use. + If, for some reason, all these files are missing, the Info-ZIP license + also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html + + crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] + + The encryption/decryption parts of this source code (as opposed to the + non-echoing password parts) were originally written in Europe. The + whole source package can be freely distributed, including from the USA. + (Prior to January 2000, re-export from the US was a violation of US law.) + + This encryption code is a direct transcription of the algorithm from + Roger Schlafly, described by Phil Katz in the file appnote.txt. This + file (appnote.txt) is distributed with the PKZIP program (even in the + version without encryption capabilities). + + ------------------------------------------------------------------------------------ + + Changes in unzip.c + + 2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos + 2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz* + 2007-2008 - Even Rouault - Remove old C style function prototypes + 2007-2008 - Even Rouault - Add unzip support for ZIP64 + + Copyright (C) 2007-2008 Even Rouault + + + Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again). + Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G + should only read the compressed/uncompressed size from the Zip64 format if + the size from normal header was 0xFFFFFFFF + Oct-2009 - Mathias Svensson - Applied some bug fixes from paches recived from Gilles Vollant + Oct-2009 - Mathias Svensson - Applied support to unzip files with compression mathod BZIP2 (bzip2 lib is required) + Patch created by Daniel Borca + + Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer + + Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson + +*/ + + +#include +#include +#include + +#ifndef NOUNCRYPT + #define NOUNCRYPT +#endif + +#include "zlib.h" +#include "unzip.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + + +#ifndef CASESENSITIVITYDEFAULT_NO +# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) +# define CASESENSITIVITYDEFAULT_NO +# endif +#endif + + +#ifndef UNZ_BUFSIZE +#define UNZ_BUFSIZE (16384) +#endif + +#ifndef UNZ_MAXFILENAMEINZIP +#define UNZ_MAXFILENAMEINZIP (256) +#endif + +#ifndef ALLOC +# define ALLOC(size) (malloc(size)) +#endif +#ifndef TRYFREE +# define TRYFREE(p) {if (p) free(p);} +#endif + +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) + + +const char unz_copyright[] = + " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + +/* unz_file_info_interntal contain internal info about a file in zipfile*/ +typedef struct unz_file_info64_internal_s +{ + ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */ +} unz_file_info64_internal; + + +/* file_in_zip_read_info_s contain internal information about a file in zipfile, + when reading and decompress it */ +typedef struct +{ + char *read_buffer; /* internal buffer for compressed data */ + z_stream stream; /* zLib stream structure for inflate */ + +#ifdef HAVE_BZIP2 + bz_stream bstream; /* bzLib stream structure for bziped */ +#endif + + ZPOS64_T pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ + uLong stream_initialised; /* flag set if stream structure is initialised*/ + + ZPOS64_T offset_local_extrafield;/* offset of the local extra field */ + uInt size_local_extrafield;/* size of the local extra field */ + ZPOS64_T pos_local_extrafield; /* position in the local extra field in read*/ + ZPOS64_T total_out_64; + + uLong crc32; /* crc32 of all data uncompressed */ + uLong crc32_wait; /* crc32 we must obtain after decompress all */ + ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */ + ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/ + zlib_filefunc64_32_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + uLong compression_method; /* compression method (0==store) */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + int raw; +} file_in_zip64_read_info_s; + + +/* unz64_s contain internal information about the zipfile +*/ +typedef struct +{ + zlib_filefunc64_32_def z_filefunc; + int is64bitOpenFunction; + voidpf filestream; /* io structore of the zipfile */ + unz_global_info64 gi; /* public global information */ + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + ZPOS64_T num_file; /* number of the current file in the zipfile*/ + ZPOS64_T pos_in_central_dir; /* pos of the current file in the central dir*/ + ZPOS64_T current_file_ok; /* flag about the usability of the current file*/ + ZPOS64_T central_pos; /* position of the beginning of the central dir*/ + + ZPOS64_T size_central_dir; /* size of the central directory */ + ZPOS64_T offset_central_dir; /* offset of start of central directory with + respect to the starting disk number */ + + unz_file_info64 cur_file_info; /* public info about the current file in zip*/ + unz_file_info64_internal cur_file_info_internal; /* private info about it*/ + file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current + file if we are decompressing it */ + int encrypted; + + int isZip64; + +# ifndef NOUNCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const z_crc_t* pcrc_32_tab; +# endif +} unz64_s; + + +#ifndef NOUNCRYPT +#include "crypt.h" +#endif + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been successfully opened for reading. +*/ + + +local int unz64local_getByte OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + int *pi)); + +local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi) +{ + unsigned char c; + int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); + if (err==1) + { + *pi = (int)c; + return UNZ_OK; + } + else + { + if (ZERROR64(*pzlib_filefunc_def,filestream)) + return UNZ_ERRNO; + else + return UNZ_EOF; + } +} + + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets +*/ +local int unz64local_getShort OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX)); + +local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + uLong *pX) +{ + uLong x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((uLong)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<24; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int unz64local_getLong64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX)); + + +local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream, + ZPOS64_T *pX) +{ + ZPOS64_T x ; + int i = 0; + int err; + + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (ZPOS64_T)i; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<8; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<16; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<24; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<32; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<40; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<48; + + if (err==UNZ_OK) + err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); + x |= ((ZPOS64_T)i)<<56; + + if (err==UNZ_OK) + *pX = x; + else + *pX = 0; + return err; +} + +/* My own strcmpi / strcasecmp */ +local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2) +{ + for (;;) + { + char c1=*(fileName1++); + char c2=*(fileName2++); + if ((c1>='a') && (c1<='z')) + c1 -= 0x20; + if ((c2>='a') && (c2<='z')) + c2 -= 0x20; + if (c1=='\0') + return ((c2=='\0') ? 0 : -1); + if (c2=='\0') + return 1; + if (c1c2) + return 1; + } +} + + +#ifdef CASESENSITIVITYDEFAULT_NO +#define CASESENSITIVITYDEFAULTVALUE 2 +#else +#define CASESENSITIVITYDEFAULTVALUE 1 +#endif + +#ifndef STRCMPCASENOSENTIVEFUNCTION +#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal +#endif + +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) + +*/ +extern int ZEXPORT unzStringFileNameCompare (const char* fileName1, + const char* fileName2, + int iCaseSensitivity) + +{ + if (iCaseSensitivity==0) + iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; + + if (iCaseSensitivity==1) + return strcmp(fileName1,fileName2); + + return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); +} + +#ifndef BUFREADCOMMENT +#define BUFREADCOMMENT (0x400) +#endif + +/* + Locate the Central directory of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); +local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + return uPosFound; +} + + +/* + Locate the Central directory 64 of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T unz64local_SearchCentralDir64 OF(( + const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream)); + +local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, + voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + uLong uL; + ZPOS64_T relativeOffset; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + if (uPosFound == 0) + return 0; + + /* Zip64 end of central directory locator */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature, already checked */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + /* number of the disk with the start of the zip64 end of central directory */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 0) + return 0; + + /* relative offset of the zip64 end of central directory record */ + if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK) + return 0; + + /* total number of disks */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + if (uL != 1) + return 0; + + /* Goto end of central directory record */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature */ + if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) + return 0; + + if (uL != 0x06064b50) + return 0; + + return relativeOffset; +} + +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer + "zlib/zlib114.zip". + If the zipfile cannot be opened (file doesn't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. +*/ +local unzFile unzOpenInternal (const void *path, + zlib_filefunc64_32_def* pzlib_filefunc64_32_def, + int is64bitOpenFunction) +{ + unz64_s us; + unz64_s *s; + ZPOS64_T central_pos; + uLong uL; + + uLong number_disk; /* number of the current dist, used for + spaning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spaning ZIP, unsupported, always 0*/ + ZPOS64_T number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ + + int err=UNZ_OK; + + if (unz_copyright[0]!=' ') + return NULL; + + us.z_filefunc.zseek32_file = NULL; + us.z_filefunc.ztell32_file = NULL; + if (pzlib_filefunc64_32_def==NULL) + fill_fopen64_filefunc(&us.z_filefunc.zfile_func64); + else + us.z_filefunc = *pzlib_filefunc64_32_def; + us.is64bitOpenFunction = is64bitOpenFunction; + + + + us.filestream = ZOPEN64(us.z_filefunc, + path, + ZLIB_FILEFUNC_MODE_READ | + ZLIB_FILEFUNC_MODE_EXISTING); + if (us.filestream==NULL) + return NULL; + + central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream); + if (central_pos) + { + uLong uS; + ZPOS64_T uL64; + + us.isZip64 = 1; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* size of zip64 end of central directory record */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version made by */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* version needed to extract */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory on this disk */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) + err=UNZ_ERRNO; + + us.gi.size_comment = 0; + } + else + { + central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream); + if (central_pos==0) + err=UNZ_ERRNO; + + us.isZip64 = 0; + + if (ZSEEK64(us.z_filefunc, us.filestream, + central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + /* the signature, already checked */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) + err=UNZ_ERRNO; + + /* number of the disk with the start of the central directory */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) + err=UNZ_ERRNO; + + /* total number of entries in the central dir on this disk */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.gi.number_entry = uL; + + /* total number of entries in the central dir */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + number_entry_CD = uL; + + if ((number_entry_CD!=us.gi.number_entry) || + (number_disk_with_CD!=0) || + (number_disk!=0)) + err=UNZ_BADZIPFILE; + + /* size of the central directory */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.size_central_dir = uL; + + /* offset of start of central directory with respect to the + starting disk number */ + if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) + err=UNZ_ERRNO; + us.offset_central_dir = uL; + + /* zipfile comment length */ + if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) + err=UNZ_ERRNO; + } + + if ((central_pospfile_in_zip_read!=NULL) + unzCloseCurrentFile(file); + + ZCLOSE64(s->z_filefunc, s->filestream); + TRYFREE(s); + return UNZ_OK; +} + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ +extern int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + *pglobal_info=s->gi; + return UNZ_OK; +} + +extern int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32) +{ + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + /* to do : check if number_entry is not truncated */ + pglobal_info32->number_entry = (uLong)s->gi.number_entry; + pglobal_info32->size_comment = s->gi.size_comment; + return UNZ_OK; +} +/* + Translate date/time from Dos format to tm_unz (readable more easilty) +*/ +local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm) +{ + ZPOS64_T uDate; + uDate = (ZPOS64_T)(ulDosDate>>16); + ptm->tm_mday = (uInt)(uDate&0x1f) ; + ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; + ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; + + ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; + ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; +} + +/* + Get Info about the current file in the zipfile, with internal only info +*/ +local int unz64local_GetCurrentFileInfoInternal OF((unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +local int unz64local_GetCurrentFileInfoInternal (unzFile file, + unz_file_info64 *pfile_info, + unz_file_info64_internal + *pfile_info_internal, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize) +{ + unz64_s* s; + unz_file_info64 file_info; + unz_file_info64_internal file_info_internal; + int err=UNZ_OK; + uLong uMagic; + long lSeek=0; + uLong uL; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pos_in_central_dir+s->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + err=UNZ_ERRNO; + + + /* we check the magic */ + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x02014b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) + err=UNZ_ERRNO; + + unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.compressed_size = uL; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info.uncompressed_size = uL; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) + err=UNZ_ERRNO; + + // relative offset of local header + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + file_info_internal.offset_curfile = uL; + + lSeek+=file_info.size_filename; + if ((err==UNZ_OK) && (szFileName!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_filename0) && (fileNameBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + lSeek -= uSizeRead; + } + + // Read extrafield + if ((err==UNZ_OK) && (extraField!=NULL)) + { + ZPOS64_T uSizeRead ; + if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + + lSeek += file_info.size_file_extra - (uLong)uSizeRead; + } + else + lSeek += file_info.size_file_extra; + + + if ((err==UNZ_OK) && (file_info.size_file_extra != 0)) + { + uLong acc = 0; + + // since lSeek now points to after the extra field we need to move back + lSeek -= file_info.size_file_extra; + + if (lSeek!=0) + { + if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + while(acc < file_info.size_file_extra) + { + uLong headerId; + uLong dataSize; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK) + err=UNZ_ERRNO; + + /* ZIP64 extra fields */ + if (headerId == 0x0001) + { + uLong uL; + + if(file_info.uncompressed_size == MAXU32) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.compressed_size == MAXU32) + { + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info_internal.offset_curfile == MAXU32) + { + /* Relative Header offset */ + if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) + err=UNZ_ERRNO; + } + + if(file_info.disk_num_start == MAXU32) + { + /* Disk Start Number */ + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) + err=UNZ_ERRNO; + } + + } + else + { + if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) + err=UNZ_ERRNO; + } + + acc += 2 + 2 + dataSize; + } + } + + if ((err==UNZ_OK) && (szComment!=NULL)) + { + uLong uSizeRead ; + if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) + lSeek=0; + else + err=UNZ_ERRNO; + } + + if ((file_info.size_file_comment>0) && (commentBufferSize>0)) + if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) + err=UNZ_ERRNO; + lSeek+=file_info.size_file_comment - uSizeRead; + } + else + lSeek+=file_info.size_file_comment; + + + if ((err==UNZ_OK) && (pfile_info!=NULL)) + *pfile_info=file_info; + + if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) + *pfile_info_internal=file_info_internal; + + return err; +} + + + +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. +*/ +extern int ZEXPORT unzGetCurrentFileInfo64 (unzFile file, + unz_file_info64 * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); +} + +extern int ZEXPORT unzGetCurrentFileInfo (unzFile file, + unz_file_info * pfile_info, + char * szFileName, uLong fileNameBufferSize, + void *extraField, uLong extraFieldBufferSize, + char* szComment, uLong commentBufferSize) +{ + int err; + unz_file_info64 file_info64; + err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL, + szFileName,fileNameBufferSize, + extraField,extraFieldBufferSize, + szComment,commentBufferSize); + if ((err==UNZ_OK) && (pfile_info != NULL)) + { + pfile_info->version = file_info64.version; + pfile_info->version_needed = file_info64.version_needed; + pfile_info->flag = file_info64.flag; + pfile_info->compression_method = file_info64.compression_method; + pfile_info->dosDate = file_info64.dosDate; + pfile_info->crc = file_info64.crc; + + pfile_info->size_filename = file_info64.size_filename; + pfile_info->size_file_extra = file_info64.size_file_extra; + pfile_info->size_file_comment = file_info64.size_file_comment; + + pfile_info->disk_num_start = file_info64.disk_num_start; + pfile_info->internal_fa = file_info64.internal_fa; + pfile_info->external_fa = file_info64.external_fa; + + pfile_info->tmu_date = file_info64.tmu_date, + + + pfile_info->compressed_size = (uLong)file_info64.compressed_size; + pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; + + } + return err; +} +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ +extern int ZEXPORT unzGoToFirstFile (unzFile file) +{ + int err=UNZ_OK; + unz64_s* s; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + s->pos_in_central_dir=s->offset_central_dir; + s->num_file=0; + err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ +extern int ZEXPORT unzGoToNextFile (unzFile file) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ + if (s->num_file+1==s->gi.number_entry) + return UNZ_END_OF_LIST_OF_FILE; + + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + + s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; + s->num_file++; + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + + +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ +extern int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) +{ + unz64_s* s; + int err; + + /* We remember the 'current' position in the file so that we can jump + * back there if we fail. + */ + unz_file_info64 cur_file_infoSaved; + unz_file_info64_internal cur_file_info_internalSaved; + ZPOS64_T num_fileSaved; + ZPOS64_T pos_in_central_dirSaved; + + + if (file==NULL) + return UNZ_PARAMERROR; + + if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) + return UNZ_PARAMERROR; + + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + /* Save the current state */ + num_fileSaved = s->num_file; + pos_in_central_dirSaved = s->pos_in_central_dir; + cur_file_infoSaved = s->cur_file_info; + cur_file_info_internalSaved = s->cur_file_info_internal; + + err = unzGoToFirstFile(file); + + while (err == UNZ_OK) + { + char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; + err = unzGetCurrentFileInfo64(file,NULL, + szCurrentFileName,sizeof(szCurrentFileName)-1, + NULL,0,NULL,0); + if (err == UNZ_OK) + { + if (unzStringFileNameCompare(szCurrentFileName, + szFileName,iCaseSensitivity)==0) + return UNZ_OK; + err = unzGoToNextFile(file); + } + } + + /* We failed, so restore the state of the 'current file' to where we + * were. + */ + s->num_file = num_fileSaved ; + s->pos_in_central_dir = pos_in_central_dirSaved ; + s->cur_file_info = cur_file_infoSaved; + s->cur_file_info_internal = cur_file_info_internalSaved; + return err; +} + + +/* +/////////////////////////////////////////// +// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) +// I need random access +// +// Further optimization could be realized by adding an ability +// to cache the directory in memory. The goal being a single +// comprehensive file read to put the file I need in a memory. +*/ + +/* +typedef struct unz_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; // offset in file + ZPOS64_T num_of_file; // # of file +} unz_file_pos; +*/ + +extern int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos* file_pos) +{ + unz64_s* s; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_END_OF_LIST_OF_FILE; + + file_pos->pos_in_zip_directory = s->pos_in_central_dir; + file_pos->num_of_file = s->num_file; + + return UNZ_OK; +} + +extern int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + int err = unzGetFilePos64(file,&file_pos64); + if (err==UNZ_OK) + { + file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory; + file_pos->num_of_file = (uLong)file_pos64.num_of_file; + } + return err; +} + +extern int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos) +{ + unz64_s* s; + int err; + + if (file==NULL || file_pos==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + /* jump to the right spot */ + s->pos_in_central_dir = file_pos->pos_in_zip_directory; + s->num_file = file_pos->num_of_file; + + /* set the current file */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + /* return results */ + s->current_file_ok = (err == UNZ_OK); + return err; +} + +extern int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos) +{ + unz64_file_pos file_pos64; + if (file_pos == NULL) + return UNZ_PARAMERROR; + + file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; + file_pos64.num_of_file = file_pos->num_of_file; + return unzGoToFilePos64(file,&file_pos64); +} + +/* +// Unzip Helper Functions - should be here? +/////////////////////////////////////////// +*/ + +/* + Read the local header of the current zipfile + Check the coherency of the local header and info in the end of central + directory about this file + store in *piSizeVar the size of extra info in local header + (filename and size of extra field data) +*/ +local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar, + ZPOS64_T * poffset_local_extrafield, + uInt * psize_local_extrafield) +{ + uLong uMagic,uData,uFlags; + uLong size_filename; + uLong size_extra_field; + int err=UNZ_OK; + + *piSizeVar = 0; + *poffset_local_extrafield = 0; + *psize_local_extrafield = 0; + + if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + + s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + + if (err==UNZ_OK) + { + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) + err=UNZ_ERRNO; + else if (uMagic!=0x04034b50) + err=UNZ_BADZIPFILE; + } + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; +/* + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) + err=UNZ_BADZIPFILE; +*/ + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) + err=UNZ_ERRNO; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) + err=UNZ_BADZIPFILE; + + if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ + err=UNZ_ERRNO; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ + err=UNZ_ERRNO; + else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) + err=UNZ_BADZIPFILE; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) + err=UNZ_ERRNO; + else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) + err=UNZ_BADZIPFILE; + + *piSizeVar += (uInt)size_filename; + + if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) + err=UNZ_ERRNO; + *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + + SIZEZIPLOCALHEADER + size_filename; + *psize_local_extrafield = (uInt)size_extra_field; + + *piSizeVar += (uInt)size_extra_field; + + return err; +} + +/* + Open for reading data the current file in the zipfile. + If there is no error and the file is opened, the return value is UNZ_OK. +*/ +extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, + int* level, int raw, const char* password) +{ + int err=UNZ_OK; + uInt iSizeVar; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + ZPOS64_T offset_local_extrafield; /* offset of the local extra field */ + uInt size_local_extrafield; /* size of the local extra field */ +# ifndef NOUNCRYPT + char source[12]; +# else + if (password != NULL) + return UNZ_PARAMERROR; +# endif + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return UNZ_PARAMERROR; + + if (s->pfile_in_zip_read != NULL) + unzCloseCurrentFile(file); + + if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) + return UNZ_BADZIPFILE; + + pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s)); + if (pfile_in_zip_read_info==NULL) + return UNZ_INTERNALERROR; + + pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); + pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; + pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; + pfile_in_zip_read_info->pos_local_extrafield=0; + pfile_in_zip_read_info->raw=raw; + + if (pfile_in_zip_read_info->read_buffer==NULL) + { + TRYFREE(pfile_in_zip_read_info); + return UNZ_INTERNALERROR; + } + + pfile_in_zip_read_info->stream_initialised=0; + + if (method!=NULL) + *method = (int)s->cur_file_info.compression_method; + + if (level!=NULL) + { + *level = 6; + switch (s->cur_file_info.flag & 0x06) + { + case 6 : *level = 1; break; + case 4 : *level = 2; break; + case 2 : *level = 9; break; + } + } + + if ((s->cur_file_info.compression_method!=0) && +/* #ifdef HAVE_BZIP2 */ + (s->cur_file_info.compression_method!=Z_BZIP2ED) && +/* #endif */ + (s->cur_file_info.compression_method!=Z_DEFLATED)) + + err=UNZ_BADZIPFILE; + + pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; + pfile_in_zip_read_info->crc32=0; + pfile_in_zip_read_info->total_out_64=0; + pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; + pfile_in_zip_read_info->filestream=s->filestream; + pfile_in_zip_read_info->z_filefunc=s->z_filefunc; + pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; + + pfile_in_zip_read_info->stream.total_out = 0; + + if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) + { +#ifdef HAVE_BZIP2 + pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; + pfile_in_zip_read_info->bstream.bzfree = (free_func)0; + pfile_in_zip_read_info->bstream.opaque = (voidpf)0; + pfile_in_zip_read_info->bstream.state = (voidpf)0; + + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = (voidpf)0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } +#else + pfile_in_zip_read_info->raw=1; +#endif + } + else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) + { + pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; + pfile_in_zip_read_info->stream.zfree = (free_func)0; + pfile_in_zip_read_info->stream.opaque = (voidpf)0; + pfile_in_zip_read_info->stream.next_in = 0; + pfile_in_zip_read_info->stream.avail_in = 0; + + err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); + if (err == Z_OK) + pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; + else + { + TRYFREE(pfile_in_zip_read_info); + return err; + } + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. + * In unzip, i don't wait absolutely Z_STREAM_END because I known the + * size of both compressed and uncompressed data + */ + } + pfile_in_zip_read_info->rest_read_compressed = + s->cur_file_info.compressed_size ; + pfile_in_zip_read_info->rest_read_uncompressed = + s->cur_file_info.uncompressed_size ; + + + pfile_in_zip_read_info->pos_in_zipfile = + s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + + iSizeVar; + + pfile_in_zip_read_info->stream.avail_in = (uInt)0; + + s->pfile_in_zip_read = pfile_in_zip_read_info; + s->encrypted = 0; + +# ifndef NOUNCRYPT + if (password != NULL) + { + int i; + s->pcrc_32_tab = get_crc_table(); + init_keys(password,s->keys,s->pcrc_32_tab); + if (ZSEEK64(s->z_filefunc, s->filestream, + s->pfile_in_zip_read->pos_in_zipfile + + s->pfile_in_zip_read->byte_before_the_zipfile, + SEEK_SET)!=0) + return UNZ_INTERNALERROR; + if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12) + return UNZ_INTERNALERROR; + + for (i = 0; i<12; i++) + zdecode(s->keys,s->pcrc_32_tab,source[i]); + + s->pfile_in_zip_read->pos_in_zipfile+=12; + s->encrypted=1; + } +# endif + + + return UNZ_OK; +} + +extern int ZEXPORT unzOpenCurrentFile (unzFile file) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); +} + +extern int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char* password) +{ + return unzOpenCurrentFile3(file, NULL, NULL, 0, password); +} + +extern int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw) +{ + return unzOpenCurrentFile3(file, method, level, raw, NULL); +} + +/** Addition for GDAL : START */ + +extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + s=(unz64_s*)file; + if (file==NULL) + return 0; //UNZ_PARAMERROR; + pfile_in_zip_read_info=s->pfile_in_zip_read; + if (pfile_in_zip_read_info==NULL) + return 0; //UNZ_PARAMERROR; + return pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile; +} + +/** Addition for GDAL : END */ + +/* + Read bytes from the current file. + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ +extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) +{ + int err=UNZ_OK; + uInt iRead = 0; + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if (pfile_in_zip_read_info->read_buffer == NULL) + return UNZ_END_OF_LIST_OF_FILE; + if (len==0) + return 0; + + pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; + + pfile_in_zip_read_info->stream.avail_out = (uInt)len; + + if ((len>pfile_in_zip_read_info->rest_read_uncompressed) && + (!(pfile_in_zip_read_info->raw))) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_uncompressed; + + if ((len>pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in) && + (pfile_in_zip_read_info->raw)) + pfile_in_zip_read_info->stream.avail_out = + (uInt)pfile_in_zip_read_info->rest_read_compressed+ + pfile_in_zip_read_info->stream.avail_in; + + while (pfile_in_zip_read_info->stream.avail_out>0) + { + if ((pfile_in_zip_read_info->stream.avail_in==0) && + (pfile_in_zip_read_info->rest_read_compressed>0)) + { + uInt uReadThis = UNZ_BUFSIZE; + if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; + if (uReadThis == 0) + return UNZ_EOF; + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->pos_in_zipfile + + pfile_in_zip_read_info->byte_before_the_zipfile, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->read_buffer, + uReadThis)!=uReadThis) + return UNZ_ERRNO; + + +# ifndef NOUNCRYPT + if(s->encrypted) + { + uInt i; + for(i=0;iread_buffer[i] = + zdecode(s->keys,s->pcrc_32_tab, + pfile_in_zip_read_info->read_buffer[i]); + } +# endif + + + pfile_in_zip_read_info->pos_in_zipfile += uReadThis; + + pfile_in_zip_read_info->rest_read_compressed-=uReadThis; + + pfile_in_zip_read_info->stream.next_in = + (Bytef*)pfile_in_zip_read_info->read_buffer; + pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; + } + + if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) + { + uInt uDoCopy,i ; + + if ((pfile_in_zip_read_info->stream.avail_in == 0) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + return (iRead==0) ? UNZ_EOF : iRead; + + if (pfile_in_zip_read_info->stream.avail_out < + pfile_in_zip_read_info->stream.avail_in) + uDoCopy = pfile_in_zip_read_info->stream.avail_out ; + else + uDoCopy = pfile_in_zip_read_info->stream.avail_in ; + + for (i=0;istream.next_out+i) = + *(pfile_in_zip_read_info->stream.next_in+i); + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, + pfile_in_zip_read_info->stream.next_out, + uDoCopy); + pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; + pfile_in_zip_read_info->stream.avail_in -= uDoCopy; + pfile_in_zip_read_info->stream.avail_out -= uDoCopy; + pfile_in_zip_read_info->stream.next_out += uDoCopy; + pfile_in_zip_read_info->stream.next_in += uDoCopy; + pfile_in_zip_read_info->stream.total_out += uDoCopy; + iRead += uDoCopy; + } + else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) + { +#ifdef HAVE_BZIP2 + uLong uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + uLong uOutThis; + + pfile_in_zip_read_info->bstream.next_in = (char*)pfile_in_zip_read_info->stream.next_in; + pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; + pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; + pfile_in_zip_read_info->bstream.total_in_hi32 = 0; + pfile_in_zip_read_info->bstream.next_out = (char*)pfile_in_zip_read_info->stream.next_out; + pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; + pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; + pfile_in_zip_read_info->bstream.total_out_hi32 = 0; + + uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; + bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out; + + err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); + + uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); + pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->bstream.next_in; + pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; + pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; + pfile_in_zip_read_info->stream.next_out = (Bytef*)pfile_in_zip_read_info->bstream.next_out; + pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; + pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; + + if (err==BZ_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=BZ_OK) + break; +#endif + } // end Z_BZIP2ED + else + { + ZPOS64_T uTotalOutBefore,uTotalOutAfter; + const Bytef *bufBefore; + ZPOS64_T uOutThis; + int flush=Z_SYNC_FLUSH; + + uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; + bufBefore = pfile_in_zip_read_info->stream.next_out; + + /* + if ((pfile_in_zip_read_info->rest_read_uncompressed == + pfile_in_zip_read_info->stream.avail_out) && + (pfile_in_zip_read_info->rest_read_compressed == 0)) + flush = Z_FINISH; + */ + err=inflate(&pfile_in_zip_read_info->stream,flush); + + if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) + err = Z_DATA_ERROR; + + uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; + uOutThis = uTotalOutAfter-uTotalOutBefore; + + pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; + + pfile_in_zip_read_info->crc32 = + crc32(pfile_in_zip_read_info->crc32,bufBefore, + (uInt)(uOutThis)); + + pfile_in_zip_read_info->rest_read_uncompressed -= + uOutThis; + + iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); + + if (err==Z_STREAM_END) + return (iRead==0) ? UNZ_EOF : iRead; + if (err!=Z_OK) + break; + } + } + + if (err==Z_OK) + return iRead; + return err; +} + + +/* + Give the current position in uncompressed data +*/ +extern z_off_t ZEXPORT unztell (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + return (z_off_t)pfile_in_zip_read_info->stream.total_out; +} + +extern ZPOS64_T ZEXPORT unztell64 (unzFile file) +{ + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return (ZPOS64_T)-1; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return (ZPOS64_T)-1; + + return pfile_in_zip_read_info->total_out_64; +} + + +/* + return 1 if the end of file was reached, 0 elsewhere +*/ +extern int ZEXPORT unzeof (unzFile file) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + if (pfile_in_zip_read_info->rest_read_uncompressed == 0) + return 1; + else + return 0; +} + + + +/* +Read extra field from the current file (opened by unzOpenCurrentFile) +This is the local-header version of the extra field (sometimes, there is +more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field that can be read + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ +extern int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len) +{ + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + uInt read_now; + ZPOS64_T size_to_read; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + size_to_read = (pfile_in_zip_read_info->size_local_extrafield - + pfile_in_zip_read_info->pos_local_extrafield); + + if (buf==NULL) + return (int)size_to_read; + + if (len>size_to_read) + read_now = (uInt)size_to_read; + else + read_now = (uInt)len ; + + if (read_now==0) + return 0; + + if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + pfile_in_zip_read_info->offset_local_extrafield + + pfile_in_zip_read_info->pos_local_extrafield, + ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (ZREAD64(pfile_in_zip_read_info->z_filefunc, + pfile_in_zip_read_info->filestream, + buf,read_now)!=read_now) + return UNZ_ERRNO; + + return (int)read_now; +} + +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ +extern int ZEXPORT unzCloseCurrentFile (unzFile file) +{ + int err=UNZ_OK; + + unz64_s* s; + file_in_zip64_read_info_s* pfile_in_zip_read_info; + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + pfile_in_zip_read_info=s->pfile_in_zip_read; + + if (pfile_in_zip_read_info==NULL) + return UNZ_PARAMERROR; + + + if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && + (!pfile_in_zip_read_info->raw)) + { + if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) + err=UNZ_CRCERROR; + } + + + TRYFREE(pfile_in_zip_read_info->read_buffer); + pfile_in_zip_read_info->read_buffer = NULL; + if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) + inflateEnd(&pfile_in_zip_read_info->stream); +#ifdef HAVE_BZIP2 + else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) + BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); +#endif + + + pfile_in_zip_read_info->stream_initialised = 0; + TRYFREE(pfile_in_zip_read_info); + + s->pfile_in_zip_read=NULL; + + return err; +} + + +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ +extern int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf) +{ + unz64_s* s; + uLong uReadThis ; + if (file==NULL) + return (int)UNZ_PARAMERROR; + s=(unz64_s*)file; + + uReadThis = uSizeBuf; + if (uReadThis>s->gi.size_comment) + uReadThis = s->gi.size_comment; + + if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) + return UNZ_ERRNO; + + if (uReadThis>0) + { + *szComment='\0'; + if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) + return UNZ_ERRNO; + } + + if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) + *(szComment+s->gi.size_comment)='\0'; + return (int)uReadThis; +} + +/* Additions by RX '2004 */ +extern ZPOS64_T ZEXPORT unzGetOffset64(unzFile file) +{ + unz64_s* s; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + s=(unz64_s*)file; + if (!s->current_file_ok) + return 0; + if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) + if (s->num_file==s->gi.number_entry) + return 0; + return s->pos_in_central_dir; +} + +extern uLong ZEXPORT unzGetOffset (unzFile file) +{ + ZPOS64_T offset64; + + if (file==NULL) + return 0; //UNZ_PARAMERROR; + offset64 = unzGetOffset64(file); + return (uLong)offset64; +} + +extern int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos) +{ + unz64_s* s; + int err; + + if (file==NULL) + return UNZ_PARAMERROR; + s=(unz64_s*)file; + + s->pos_in_central_dir = pos; + s->num_file = s->gi.number_entry; /* hack */ + err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, + &s->cur_file_info_internal, + NULL,0,NULL,0,NULL,0); + s->current_file_ok = (err == UNZ_OK); + return err; +} + +extern int ZEXPORT unzSetOffset (unzFile file, uLong pos) +{ + return unzSetOffset64(file,pos); +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/unzip.h b/third_party/zlib/v1_2_11/contrib/minizip/unzip.h new file mode 100644 index 0000000..2104e39 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/unzip.h @@ -0,0 +1,437 @@ +/* unzip.h -- IO for uncompress .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications of Unzip for Zip64 + Copyright (C) 2007-2008 Even Rouault + + Modifications for Zip64 support on both zip and unzip + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------------- + + Changes + + See header of unzip64.c + +*/ + +#ifndef _unz64_H +#define _unz64_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagunzFile__ { int unused; } unzFile__; +typedef unzFile__ *unzFile; +#else +typedef voidp unzFile; +#endif + + +#define UNZ_OK (0) +#define UNZ_END_OF_LIST_OF_FILE (-100) +#define UNZ_ERRNO (Z_ERRNO) +#define UNZ_EOF (0) +#define UNZ_PARAMERROR (-102) +#define UNZ_BADZIPFILE (-103) +#define UNZ_INTERNALERROR (-104) +#define UNZ_CRCERROR (-105) + +/* tm_unz contain date/time info */ +typedef struct tm_unz_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_unz; + +/* unz_global_info structure contain global data about the ZIPfile + These data comes from the end of central dir */ +typedef struct unz_global_info64_s +{ + ZPOS64_T number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info64; + +typedef struct unz_global_info_s +{ + uLong number_entry; /* total number of entries in + the central dir on this disk */ + uLong size_comment; /* size of the global comment of the zipfile */ +} unz_global_info; + +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_info64_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + ZPOS64_T compressed_size; /* compressed size 8 bytes */ + ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info64; + +typedef struct unz_file_info_s +{ + uLong version; /* version made by 2 bytes */ + uLong version_needed; /* version needed to extract 2 bytes */ + uLong flag; /* general purpose bit flag 2 bytes */ + uLong compression_method; /* compression method 2 bytes */ + uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ + uLong crc; /* crc-32 4 bytes */ + uLong compressed_size; /* compressed size 4 bytes */ + uLong uncompressed_size; /* uncompressed size 4 bytes */ + uLong size_filename; /* filename length 2 bytes */ + uLong size_file_extra; /* extra field length 2 bytes */ + uLong size_file_comment; /* file comment length 2 bytes */ + + uLong disk_num_start; /* disk number start 2 bytes */ + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ + + tm_unz tmu_date; +} unz_file_info; + +extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, + const char* fileName2, + int iCaseSensitivity)); +/* + Compare two filename (fileName1,fileName2). + If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) + If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi + or strcasecmp) + If iCaseSenisivity = 0, case sensitivity is defaut of your operating system + (like 1 on Unix, 2 on Windows) +*/ + + +extern unzFile ZEXPORT unzOpen OF((const char *path)); +extern unzFile ZEXPORT unzOpen64 OF((const void *path)); +/* + Open a Zip file. path contain the full pathname (by example, + on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer + "zlib/zlib113.zip". + If the zipfile cannot be opened (file don't exist or in not valid), the + return value is NULL. + Else, the return value is a unzFile Handle, usable with other function + of this unzip package. + the "64" function take a const void* pointer, because the path is just the + value passed to the open64_file_func callback. + Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path + is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* + does not describe the reality +*/ + + +extern unzFile ZEXPORT unzOpen2 OF((const char *path, + zlib_filefunc_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unzOpen, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +extern unzFile ZEXPORT unzOpen2_64 OF((const void *path, + zlib_filefunc64_def* pzlib_filefunc_def)); +/* + Open a Zip file, like unz64Open, but provide a set of file low level API + for read/write the zip file (see ioapi.h) +*/ + +extern int ZEXPORT unzClose OF((unzFile file)); +/* + Close a ZipFile opened with unzOpen. + If there is files inside the .Zip opened with unzOpenCurrentFile (see later), + these files MUST be closed with unzCloseCurrentFile before call unzClose. + return UNZ_OK if there is no problem. */ + +extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, + unz_global_info *pglobal_info)); + +extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file, + unz_global_info64 *pglobal_info)); +/* + Write info about the ZipFile in the *pglobal_info structure. + No preparation of the structure is needed + return UNZ_OK if there is no problem. */ + + +extern int ZEXPORT unzGetGlobalComment OF((unzFile file, + char *szComment, + uLong uSizeBuf)); +/* + Get the global comment string of the ZipFile, in the szComment buffer. + uSizeBuf is the size of the szComment buffer. + return the number of byte copied or an error code <0 +*/ + + +/***************************************************************************/ +/* Unzip package allow you browse the directory of the zipfile */ + +extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); +/* + Set the current file of the zipfile to the first file. + return UNZ_OK if there is no problem +*/ + +extern int ZEXPORT unzGoToNextFile OF((unzFile file)); +/* + Set the current file of the zipfile to the next file. + return UNZ_OK if there is no problem + return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. +*/ + +extern int ZEXPORT unzLocateFile OF((unzFile file, + const char *szFileName, + int iCaseSensitivity)); +/* + Try locate the file szFileName in the zipfile. + For the iCaseSensitivity signification, see unzStringFileNameCompare + + return value : + UNZ_OK if the file is found. It becomes the current file. + UNZ_END_OF_LIST_OF_FILE if the file is not found +*/ + + +/* ****************************************** */ +/* Ryan supplied functions */ +/* unz_file_info contain information about a file in the zipfile */ +typedef struct unz_file_pos_s +{ + uLong pos_in_zip_directory; /* offset in zip file directory */ + uLong num_of_file; /* # of file */ +} unz_file_pos; + +extern int ZEXPORT unzGetFilePos( + unzFile file, + unz_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos( + unzFile file, + unz_file_pos* file_pos); + +typedef struct unz64_file_pos_s +{ + ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ + ZPOS64_T num_of_file; /* # of file */ +} unz64_file_pos; + +extern int ZEXPORT unzGetFilePos64( + unzFile file, + unz64_file_pos* file_pos); + +extern int ZEXPORT unzGoToFilePos64( + unzFile file, + const unz64_file_pos* file_pos); + +/* ****************************************** */ + +extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file, + unz_file_info64 *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); + +extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, + unz_file_info *pfile_info, + char *szFileName, + uLong fileNameBufferSize, + void *extraField, + uLong extraFieldBufferSize, + char *szComment, + uLong commentBufferSize)); +/* + Get Info about the current file + if pfile_info!=NULL, the *pfile_info structure will contain somes info about + the current file + if szFileName!=NULL, the filemane string will be copied in szFileName + (fileNameBufferSize is the size of the buffer) + if extraField!=NULL, the extra field information will be copied in extraField + (extraFieldBufferSize is the size of the buffer). + This is the Central-header version of the extra field + if szComment!=NULL, the comment string of the file will be copied in szComment + (commentBufferSize is the size of the buffer) +*/ + + +/** Addition for GDAL : START */ + +extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file)); + +/** Addition for GDAL : END */ + + +/***************************************************************************/ +/* for reading the content of the current zipfile, you can open it, read data + from it, and close it (you can close it before reading all the file) + */ + +extern int ZEXPORT unzOpenCurrentFile OF((unzFile file)); +/* + Open for reading data the current file in the zipfile. + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, + const char* password)); +/* + Open for reading data the current file in the zipfile. + password is a crypting password + If there is no error, the return value is UNZ_OK. +*/ + +extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, + int* method, + int* level, + int raw)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + +extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, + int* method, + int* level, + int raw, + const char* password)); +/* + Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) + if raw==1 + *method will receive method of compression, *level will receive level of + compression + note : you can set level parameter as NULL (if you did not want known level, + but you CANNOT set method parameter as NULL +*/ + + +extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); +/* + Close the file in zip opened with unzOpenCurrentFile + Return UNZ_CRCERROR if all the file was read but the CRC is not good +*/ + +extern int ZEXPORT unzReadCurrentFile OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read bytes from the current file (opened by unzOpenCurrentFile) + buf contain buffer where data must be copied + len the size of buf. + + return the number of byte copied if somes bytes are copied + return 0 if the end of file was reached + return <0 with error code if there is an error + (UNZ_ERRNO for IO error, or zLib error for uncompress error) +*/ + +extern z_off_t ZEXPORT unztell OF((unzFile file)); + +extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file)); +/* + Give the current position in uncompressed data +*/ + +extern int ZEXPORT unzeof OF((unzFile file)); +/* + return 1 if the end of file was reached, 0 elsewhere +*/ + +extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, + voidp buf, + unsigned len)); +/* + Read extra field from the current file (opened by unzOpenCurrentFile) + This is the local-header version of the extra field (sometimes, there is + more info in the local-header version than in the central-header) + + if buf==NULL, it return the size of the local extra field + + if buf!=NULL, len is the size of the buffer, the extra header is copied in + buf. + the return value is the number of bytes copied in buf, or (if <0) + the error code +*/ + +/***************************************************************************/ + +/* Get the current file offset */ +extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file); +extern uLong ZEXPORT unzGetOffset (unzFile file); + +/* Set the current file offset */ +extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos); +extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); + + + +#ifdef __cplusplus +} +#endif + +#endif /* _unz64_H */ diff --git a/third_party/zlib/v1_2_11/contrib/minizip/zip.c b/third_party/zlib/v1_2_11/contrib/minizip/zip.c new file mode 100644 index 0000000..44e88a9 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/zip.c @@ -0,0 +1,2007 @@ +/* zip.c -- IO on .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + Changes + Oct-2009 - Mathias Svensson - Remove old C style function prototypes + Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives + Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions. + Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data + It is used when recreting zip archive with RAW when deleting items from a zip. + ZIP64 data is automatically added to items that needs it, and existing ZIP64 data need to be removed. + Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required) + Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer + +*/ + + +#include +#include +#include +#include +#include "zlib.h" +#include "zip.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +#ifndef VERSIONMADEBY +# define VERSIONMADEBY (0x0) /* platform depedent */ +#endif + +#ifndef Z_BUFSIZE +#define Z_BUFSIZE (64*1024) //(16384) +#endif + +#ifndef Z_MAXFILENAMEINZIP +#define Z_MAXFILENAMEINZIP (256) +#endif + +#ifndef ALLOC +# define ALLOC(size) (malloc(size)) +#endif +#ifndef TRYFREE +# define TRYFREE(p) {if (p) free(p);} +#endif + +/* +#define SIZECENTRALDIRITEM (0x2e) +#define SIZEZIPLOCALHEADER (0x1e) +*/ + +/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ + + +// NOT sure that this work on ALL platform +#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32)) + +#ifndef SEEK_CUR +#define SEEK_CUR 1 +#endif + +#ifndef SEEK_END +#define SEEK_END 2 +#endif + +#ifndef SEEK_SET +#define SEEK_SET 0 +#endif + +#ifndef DEF_MEM_LEVEL +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +#endif +const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; + + +#define SIZEDATA_INDATABLOCK (4096-(4*4)) + +#define LOCALHEADERMAGIC (0x04034b50) +#define CENTRALHEADERMAGIC (0x02014b50) +#define ENDHEADERMAGIC (0x06054b50) +#define ZIP64ENDHEADERMAGIC (0x6064b50) +#define ZIP64ENDLOCHEADERMAGIC (0x7064b50) + +#define FLAG_LOCALHEADER_OFFSET (0x06) +#define CRC_LOCALHEADER_OFFSET (0x0e) + +#define SIZECENTRALHEADER (0x2e) /* 46 */ + +typedef struct linkedlist_datablock_internal_s +{ + struct linkedlist_datablock_internal_s* next_datablock; + uLong avail_in_this_block; + uLong filled_in_this_block; + uLong unused; /* for future use and alignment */ + unsigned char data[SIZEDATA_INDATABLOCK]; +} linkedlist_datablock_internal; + +typedef struct linkedlist_data_s +{ + linkedlist_datablock_internal* first_block; + linkedlist_datablock_internal* last_block; +} linkedlist_data; + + +typedef struct +{ + z_stream stream; /* zLib stream structure for inflate */ +#ifdef HAVE_BZIP2 + bz_stream bstream; /* bzLib stream structure for bziped */ +#endif + + int stream_initialised; /* 1 is stream is initialised */ + uInt pos_in_buffered_data; /* last written byte in buffered_data */ + + ZPOS64_T pos_local_header; /* offset of the local header of the file + currenty writing */ + char* central_header; /* central header data for the current file */ + uLong size_centralExtra; + uLong size_centralheader; /* size of the central header for cur file */ + uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */ + uLong flag; /* flag of the file currently writing */ + + int method; /* compression method of file currenty wr.*/ + int raw; /* 1 for directly writing raw data */ + Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ + uLong dosDate; + uLong crc32; + int encrypt; + int zip64; /* Add ZIP64 extened information in the extra field */ + ZPOS64_T pos_zip64extrainfo; + ZPOS64_T totalCompressedData; + ZPOS64_T totalUncompressedData; +#ifndef NOCRYPT + unsigned long keys[3]; /* keys defining the pseudo-random sequence */ + const z_crc_t* pcrc_32_tab; + int crypt_header_size; +#endif +} curfile64_info; + +typedef struct +{ + zlib_filefunc64_32_def z_filefunc; + voidpf filestream; /* io structore of the zipfile */ + linkedlist_data central_dir;/* datablock with central dir in construction*/ + int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ + curfile64_info ci; /* info on the file curretly writing */ + + ZPOS64_T begin_pos; /* position of the beginning of the zipfile */ + ZPOS64_T add_position_when_writing_offset; + ZPOS64_T number_entry; + +#ifndef NO_ADDFILEINEXISTINGZIP + char *globalcomment; +#endif + +} zip64_internal; + + +#ifndef NOCRYPT +#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED +#include "crypt.h" +#endif + +local linkedlist_datablock_internal* allocate_new_datablock() +{ + linkedlist_datablock_internal* ldi; + ldi = (linkedlist_datablock_internal*) + ALLOC(sizeof(linkedlist_datablock_internal)); + if (ldi!=NULL) + { + ldi->next_datablock = NULL ; + ldi->filled_in_this_block = 0 ; + ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; + } + return ldi; +} + +local void free_datablock(linkedlist_datablock_internal* ldi) +{ + while (ldi!=NULL) + { + linkedlist_datablock_internal* ldinext = ldi->next_datablock; + TRYFREE(ldi); + ldi = ldinext; + } +} + +local void init_linkedlist(linkedlist_data* ll) +{ + ll->first_block = ll->last_block = NULL; +} + +local void free_linkedlist(linkedlist_data* ll) +{ + free_datablock(ll->first_block); + ll->first_block = ll->last_block = NULL; +} + + +local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len) +{ + linkedlist_datablock_internal* ldi; + const unsigned char* from_copy; + + if (ll==NULL) + return ZIP_INTERNALERROR; + + if (ll->last_block == NULL) + { + ll->first_block = ll->last_block = allocate_new_datablock(); + if (ll->first_block == NULL) + return ZIP_INTERNALERROR; + } + + ldi = ll->last_block; + from_copy = (unsigned char*)buf; + + while (len>0) + { + uInt copy_this; + uInt i; + unsigned char* to_copy; + + if (ldi->avail_in_this_block==0) + { + ldi->next_datablock = allocate_new_datablock(); + if (ldi->next_datablock == NULL) + return ZIP_INTERNALERROR; + ldi = ldi->next_datablock ; + ll->last_block = ldi; + } + + if (ldi->avail_in_this_block < len) + copy_this = (uInt)ldi->avail_in_this_block; + else + copy_this = (uInt)len; + + to_copy = &(ldi->data[ldi->filled_in_this_block]); + + for (i=0;ifilled_in_this_block += copy_this; + ldi->avail_in_this_block -= copy_this; + from_copy += copy_this ; + len -= copy_this; + } + return ZIP_OK; +} + + + +/****************************************************************************/ + +#ifndef NO_ADDFILEINEXISTINGZIP +/* =========================================================================== + Inputs a long in LSB order to the given file + nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T) +*/ + +local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)); +local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte) +{ + unsigned char buf[8]; + int n; + for (n = 0; n < nbByte; n++) + { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + if (x != 0) + { /* data overflow - hack for ZIP64 (X Roche) */ + for (n = 0; n < nbByte; n++) + { + buf[n] = 0xff; + } + } + + if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) + return ZIP_ERRNO; + else + return ZIP_OK; +} + +local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte)); +local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte) +{ + unsigned char* buf=(unsigned char*)dest; + int n; + for (n = 0; n < nbByte; n++) { + buf[n] = (unsigned char)(x & 0xff); + x >>= 8; + } + + if (x != 0) + { /* data overflow - hack for ZIP64 */ + for (n = 0; n < nbByte; n++) + { + buf[n] = 0xff; + } + } +} + +/****************************************************************************/ + + +local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm) +{ + uLong year = (uLong)ptm->tm_year; + if (year>=1980) + year-=1980; + else if (year>=80) + year-=80; + return + (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | + ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); +} + + +/****************************************************************************/ + +local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi)); + +local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi) +{ + unsigned char c; + int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); + if (err==1) + { + *pi = (int)c; + return ZIP_OK; + } + else + { + if (ZERROR64(*pzlib_filefunc_def,filestream)) + return ZIP_ERRNO; + else + return ZIP_EOF; + } +} + + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets +*/ +local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); + +local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) +{ + uLong x ; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<8; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); + +local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) +{ + uLong x ; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (uLong)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<8; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<16; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((uLong)i)<<24; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + return err; +} + +local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)); + + +local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX) +{ + ZPOS64_T x; + int i = 0; + int err; + + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x = (ZPOS64_T)i; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<8; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<16; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<24; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<32; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<40; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<48; + + if (err==ZIP_OK) + err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); + x += ((ZPOS64_T)i)<<56; + + if (err==ZIP_OK) + *pX = x; + else + *pX = 0; + + return err; +} + +#ifndef BUFREADCOMMENT +#define BUFREADCOMMENT (0x400) +#endif +/* + Locate the Central directory of a zipfile (at the end, just before + the global comment) +*/ +local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); + +local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && + ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) + { + uPosFound = uReadPos+i; + break; + } + + if (uPosFound!=0) + break; + } + TRYFREE(buf); + return uPosFound; +} + +/* +Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before +the global comment) +*/ +local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); + +local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) +{ + unsigned char* buf; + ZPOS64_T uSizeFile; + ZPOS64_T uBackRead; + ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ + ZPOS64_T uPosFound=0; + uLong uL; + ZPOS64_T relativeOffset; + + if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) + return 0; + + uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); + + if (uMaxBack>uSizeFile) + uMaxBack = uSizeFile; + + buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); + if (buf==NULL) + return 0; + + uBackRead = 4; + while (uBackReaduMaxBack) + uBackRead = uMaxBack; + else + uBackRead+=BUFREADCOMMENT; + uReadPos = uSizeFile-uBackRead ; + + uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? + (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); + if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) + break; + + if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) + break; + + for (i=(int)uReadSize-3; (i--)>0;) + { + // Signature "0x07064b50" Zip64 end of central directory locater + if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) + { + uPosFound = uReadPos+i; + break; + } + } + + if (uPosFound!=0) + break; + } + + TRYFREE(buf); + if (uPosFound == 0) + return 0; + + /* Zip64 end of central directory locator */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature, already checked */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + + /* number of the disk with the start of the zip64 end of central directory */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + if (uL != 0) + return 0; + + /* relative offset of the zip64 end of central directory record */ + if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK) + return 0; + + /* total number of disks */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + if (uL != 1) + return 0; + + /* Goto Zip64 end of central directory record */ + if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) + return 0; + + /* the signature */ + if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) + return 0; + + if (uL != 0x06064b50) // signature of 'Zip64 end of central directory' + return 0; + + return relativeOffset; +} + +int LoadCentralDirectoryRecord(zip64_internal* pziinit) +{ + int err=ZIP_OK; + ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ + + ZPOS64_T size_central_dir; /* size of the central directory */ + ZPOS64_T offset_central_dir; /* offset of start of central directory */ + ZPOS64_T central_pos; + uLong uL; + + uLong number_disk; /* number of the current dist, used for + spaning ZIP, unsupported, always 0*/ + uLong number_disk_with_CD; /* number the the disk with central dir, used + for spaning ZIP, unsupported, always 0*/ + ZPOS64_T number_entry; + ZPOS64_T number_entry_CD; /* total number of entries in + the central dir + (same than number_entry on nospan) */ + uLong VersionMadeBy; + uLong VersionNeeded; + uLong size_comment; + + int hasZIP64Record = 0; + + // check first if we find a ZIP64 record + central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream); + if(central_pos > 0) + { + hasZIP64Record = 1; + } + else if(central_pos == 0) + { + central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream); + } + +/* disable to allow appending to empty ZIP archive + if (central_pos==0) + err=ZIP_ERRNO; +*/ + + if(hasZIP64Record) + { + ZPOS64_T sizeEndOfCentralDirectory; + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + /* the signature, already checked */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) + err=ZIP_ERRNO; + + /* size of zip64 end of central directory record */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK) + err=ZIP_ERRNO; + + /* version made by */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK) + err=ZIP_ERRNO; + + /* version needed to extract */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of this disk */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of the disk with the start of the central directory */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central directory on this disk */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central directory */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) + err=ZIP_BADZIPFILE; + + /* size of the central directory */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK) + err=ZIP_ERRNO; + + /* offset of start of central directory with respect to the + starting disk number */ + if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK) + err=ZIP_ERRNO; + + // TODO.. + // read the comment from the standard central header. + size_comment = 0; + } + else + { + // Read End of central Directory info + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) + err=ZIP_ERRNO; + + /* the signature, already checked */ + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of this disk */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) + err=ZIP_ERRNO; + + /* number of the disk with the start of the central directory */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) + err=ZIP_ERRNO; + + /* total number of entries in the central dir on this disk */ + number_entry = 0; + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + number_entry = uL; + + /* total number of entries in the central dir */ + number_entry_CD = 0; + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + number_entry_CD = uL; + + if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) + err=ZIP_BADZIPFILE; + + /* size of the central directory */ + size_central_dir = 0; + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + size_central_dir = uL; + + /* offset of start of central directory with respect to the starting disk number */ + offset_central_dir = 0; + if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) + err=ZIP_ERRNO; + else + offset_central_dir = uL; + + + /* zipfile global comment length */ + if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK) + err=ZIP_ERRNO; + } + + if ((central_posz_filefunc, pziinit->filestream); + return ZIP_ERRNO; + } + + if (size_comment>0) + { + pziinit->globalcomment = (char*)ALLOC(size_comment+1); + if (pziinit->globalcomment) + { + size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment); + pziinit->globalcomment[size_comment]=0; + } + } + + byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir); + pziinit->add_position_when_writing_offset = byte_before_the_zipfile; + + { + ZPOS64_T size_central_dir_to_read = size_central_dir; + size_t buf_size = SIZEDATA_INDATABLOCK; + void* buf_read = (void*)ALLOC(buf_size); + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + while ((size_central_dir_to_read>0) && (err==ZIP_OK)) + { + ZPOS64_T read_this = SIZEDATA_INDATABLOCK; + if (read_this > size_central_dir_to_read) + read_this = size_central_dir_to_read; + + if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this) + err=ZIP_ERRNO; + + if (err==ZIP_OK) + err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this); + + size_central_dir_to_read-=read_this; + } + TRYFREE(buf_read); + } + pziinit->begin_pos = byte_before_the_zipfile; + pziinit->number_entry = number_entry_CD; + + if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0) + err=ZIP_ERRNO; + + return err; +} + + +#endif /* !NO_ADDFILEINEXISTINGZIP*/ + + +/************************************************************/ +extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def) +{ + zip64_internal ziinit; + zip64_internal* zi; + int err=ZIP_OK; + + ziinit.z_filefunc.zseek32_file = NULL; + ziinit.z_filefunc.ztell32_file = NULL; + if (pzlib_filefunc64_32_def==NULL) + fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64); + else + ziinit.z_filefunc = *pzlib_filefunc64_32_def; + + ziinit.filestream = ZOPEN64(ziinit.z_filefunc, + pathname, + (append == APPEND_STATUS_CREATE) ? + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : + (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); + + if (ziinit.filestream == NULL) + return NULL; + + if (append == APPEND_STATUS_CREATEAFTER) + ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END); + + ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream); + ziinit.in_opened_file_inzip = 0; + ziinit.ci.stream_initialised = 0; + ziinit.number_entry = 0; + ziinit.add_position_when_writing_offset = 0; + init_linkedlist(&(ziinit.central_dir)); + + + + zi = (zip64_internal*)ALLOC(sizeof(zip64_internal)); + if (zi==NULL) + { + ZCLOSE64(ziinit.z_filefunc,ziinit.filestream); + return NULL; + } + + /* now we add file in a zipfile */ +# ifndef NO_ADDFILEINEXISTINGZIP + ziinit.globalcomment = NULL; + if (append == APPEND_STATUS_ADDINZIP) + { + // Read and Cache Central Directory Records + err = LoadCentralDirectoryRecord(&ziinit); + } + + if (globalcomment) + { + *globalcomment = ziinit.globalcomment; + } +# endif /* !NO_ADDFILEINEXISTINGZIP*/ + + if (err != ZIP_OK) + { +# ifndef NO_ADDFILEINEXISTINGZIP + TRYFREE(ziinit.globalcomment); +# endif /* !NO_ADDFILEINEXISTINGZIP*/ + TRYFREE(zi); + return NULL; + } + else + { + *zi = ziinit; + return (zipFile)zi; + } +} + +extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def) +{ + if (pzlib_filefunc32_def != NULL) + { + zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; + fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def); + return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); + } + else + return zipOpen3(pathname, append, globalcomment, NULL); +} + +extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def) +{ + if (pzlib_filefunc_def != NULL) + { + zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; + zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def; + zlib_filefunc64_32_def_fill.ztell32_file = NULL; + zlib_filefunc64_32_def_fill.zseek32_file = NULL; + return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); + } + else + return zipOpen3(pathname, append, globalcomment, NULL); +} + + + +extern zipFile ZEXPORT zipOpen (const char* pathname, int append) +{ + return zipOpen3((const void*)pathname,append,NULL,NULL); +} + +extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append) +{ + return zipOpen3(pathname,append,NULL,NULL); +} + +int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local) +{ + /* write the local header */ + int err; + uInt size_filename = (uInt)strlen(filename); + uInt size_extrafield = size_extrafield_local; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4); + + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); + + // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ + } + if (err==ZIP_OK) + { + if(zi->ci.zip64) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */ + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); + + if(zi->ci.zip64) + { + size_extrafield += 20; + } + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2); + + if ((err==ZIP_OK) && (size_filename > 0)) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) + err = ZIP_ERRNO; + } + + if ((err==ZIP_OK) && (size_extrafield_local > 0)) + { + if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local) + err = ZIP_ERRNO; + } + + + if ((err==ZIP_OK) && (zi->ci.zip64)) + { + // write the Zip64 extended info + short HeaderID = 1; + short DataSize = 16; + ZPOS64_T CompressedSize = 0; + ZPOS64_T UncompressedSize = 0; + + // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file) + zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream); + + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2); + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2); + + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8); + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8); + } + + return err; +} + +/* + NOTE. + When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped + before calling this function it can be done with zipRemoveExtraInfoBlock + + It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize + unnecessary allocations. + */ +extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, + uLong versionMadeBy, uLong flagBase, int zip64) +{ + zip64_internal* zi; + uInt size_filename; + uInt size_comment; + uInt i; + int err = ZIP_OK; + +# ifdef NOCRYPT + (crcForCrypting); + if (password != NULL) + return ZIP_PARAMERROR; +# endif + + if (file == NULL) + return ZIP_PARAMERROR; + +#ifdef HAVE_BZIP2 + if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED)) + return ZIP_PARAMERROR; +#else + if ((method!=0) && (method!=Z_DEFLATED)) + return ZIP_PARAMERROR; +#endif + + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 1) + { + err = zipCloseFileInZip (file); + if (err != ZIP_OK) + return err; + } + + if (filename==NULL) + filename="-"; + + if (comment==NULL) + size_comment = 0; + else + size_comment = (uInt)strlen(comment); + + size_filename = (uInt)strlen(filename); + + if (zipfi == NULL) + zi->ci.dosDate = 0; + else + { + if (zipfi->dosDate != 0) + zi->ci.dosDate = zipfi->dosDate; + else + zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date); + } + + zi->ci.flag = flagBase; + if ((level==8) || (level==9)) + zi->ci.flag |= 2; + if (level==2) + zi->ci.flag |= 4; + if (level==1) + zi->ci.flag |= 6; + if (password != NULL) + zi->ci.flag |= 1; + + zi->ci.crc32 = 0; + zi->ci.method = method; + zi->ci.encrypt = 0; + zi->ci.stream_initialised = 0; + zi->ci.pos_in_buffered_data = 0; + zi->ci.raw = raw; + zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream); + + zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment; + zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data + + zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree); + + zi->ci.size_centralExtra = size_extrafield_global; + zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); + /* version info */ + zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2); + zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); + zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); + zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); + zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); + zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ + zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ + zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ + zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); + zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); + zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); + zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ + + if (zipfi==NULL) + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); + else + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); + + if (zipfi==NULL) + zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); + else + zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); + + if(zi->ci.pos_local_header >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4); + else + zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writing_offset,4); + + for (i=0;ici.central_header+SIZECENTRALHEADER+i) = *(filename+i); + + for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+i) = + *(((const char*)extrafield_global)+i); + + for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+ + size_extrafield_global+i) = *(comment+i); + if (zi->ci.central_header == NULL) + return ZIP_INTERNALERROR; + + zi->ci.zip64 = zip64; + zi->ci.totalCompressedData = 0; + zi->ci.totalUncompressedData = 0; + zi->ci.pos_zip64extrainfo = 0; + + err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local); + +#ifdef HAVE_BZIP2 + zi->ci.bstream.avail_in = (uInt)0; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + zi->ci.bstream.total_in_hi32 = 0; + zi->ci.bstream.total_in_lo32 = 0; + zi->ci.bstream.total_out_hi32 = 0; + zi->ci.bstream.total_out_lo32 = 0; +#endif + + zi->ci.stream.avail_in = (uInt)0; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + zi->ci.stream.total_in = 0; + zi->ci.stream.total_out = 0; + zi->ci.stream.data_type = Z_BINARY; + +#ifdef HAVE_BZIP2 + if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) +#else + if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) +#endif + { + if(zi->ci.method == Z_DEFLATED) + { + zi->ci.stream.zalloc = (alloc_func)0; + zi->ci.stream.zfree = (free_func)0; + zi->ci.stream.opaque = (voidpf)0; + + if (windowBits>0) + windowBits = -windowBits; + + err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy); + + if (err==Z_OK) + zi->ci.stream_initialised = Z_DEFLATED; + } + else if(zi->ci.method == Z_BZIP2ED) + { +#ifdef HAVE_BZIP2 + // Init BZip stuff here + zi->ci.bstream.bzalloc = 0; + zi->ci.bstream.bzfree = 0; + zi->ci.bstream.opaque = (voidpf)0; + + err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35); + if(err == BZ_OK) + zi->ci.stream_initialised = Z_BZIP2ED; +#endif + } + + } + +# ifndef NOCRYPT + zi->ci.crypt_header_size = 0; + if ((err==Z_OK) && (password != NULL)) + { + unsigned char bufHead[RAND_HEAD_LEN]; + unsigned int sizeHead; + zi->ci.encrypt = 1; + zi->ci.pcrc_32_tab = get_crc_table(); + /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ + + sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); + zi->ci.crypt_header_size = sizeHead; + + if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) + err = ZIP_ERRNO; + } +# endif + + if (err==Z_OK) + zi->in_opened_file_inzip = 1; + return err; +} + +extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, + uLong versionMadeBy, uLong flagBase) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, versionMadeBy, flagBase, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, VERSIONMADEBY, 0, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, + int windowBits,int memLevel, int strategy, + const char* password, uLong crcForCrypting, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + windowBits, memLevel, strategy, + password, crcForCrypting, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, 0); +} + +extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void* extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int raw, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, raw, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void*extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level, int zip64) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, 0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, zip64); +} + +extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi, + const void* extrafield_local, uInt size_extrafield_local, + const void*extrafield_global, uInt size_extrafield_global, + const char* comment, int method, int level) +{ + return zipOpenNewFileInZip4_64 (file, filename, zipfi, + extrafield_local, size_extrafield_local, + extrafield_global, size_extrafield_global, + comment, method, level, 0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL, 0, VERSIONMADEBY, 0, 0); +} + +local int zip64FlushWriteBuffer(zip64_internal* zi) +{ + int err=ZIP_OK; + + if (zi->ci.encrypt != 0) + { +#ifndef NOCRYPT + uInt i; + int t; + for (i=0;ici.pos_in_buffered_data;i++) + zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t); +#endif + } + + if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data) + err = ZIP_ERRNO; + + zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data; + +#ifdef HAVE_BZIP2 + if(zi->ci.method == Z_BZIP2ED) + { + zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32; + zi->ci.bstream.total_in_lo32 = 0; + zi->ci.bstream.total_in_hi32 = 0; + } + else +#endif + { + zi->ci.totalUncompressedData += zi->ci.stream.total_in; + zi->ci.stream.total_in = 0; + } + + + zi->ci.pos_in_buffered_data = 0; + + return err; +} + +extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len) +{ + zip64_internal* zi; + int err=ZIP_OK; + + if (file == NULL) + return ZIP_PARAMERROR; + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 0) + return ZIP_PARAMERROR; + + zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len); + +#ifdef HAVE_BZIP2 + if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw)) + { + zi->ci.bstream.next_in = (void*)buf; + zi->ci.bstream.avail_in = len; + err = BZ_RUN_OK; + + while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0)) + { + if (zi->ci.bstream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + } + + + if(err != BZ_RUN_OK) + break; + + if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { + uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32; +// uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32; + err=BZ2_bzCompress(&zi->ci.bstream, BZ_RUN); + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ; + } + } + + if(err == BZ_RUN_OK) + err = ZIP_OK; + } + else +#endif + { + zi->ci.stream.next_in = (Bytef*)buf; + zi->ci.stream.avail_in = len; + + while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) + { + if (zi->ci.stream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + + + if(err != ZIP_OK) + break; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + uLong uTotalOutBefore = zi->ci.stream.total_out; + err=deflate(&zi->ci.stream, Z_NO_FLUSH); + if(uTotalOutBefore > zi->ci.stream.total_out) + { + int bBreak = 0; + bBreak++; + } + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; + } + else + { + uInt copy_this,i; + if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) + copy_this = zi->ci.stream.avail_in; + else + copy_this = zi->ci.stream.avail_out; + + for (i = 0; i < copy_this; i++) + *(((char*)zi->ci.stream.next_out)+i) = + *(((const char*)zi->ci.stream.next_in)+i); + { + zi->ci.stream.avail_in -= copy_this; + zi->ci.stream.avail_out-= copy_this; + zi->ci.stream.next_in+= copy_this; + zi->ci.stream.next_out+= copy_this; + zi->ci.stream.total_in+= copy_this; + zi->ci.stream.total_out+= copy_this; + zi->ci.pos_in_buffered_data += copy_this; + } + } + }// while(...) + } + + return err; +} + +extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32) +{ + return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32); +} + +extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32) +{ + zip64_internal* zi; + ZPOS64_T compressed_size; + uLong invalidValue = 0xffffffff; + short datasize = 0; + int err=ZIP_OK; + + if (file == NULL) + return ZIP_PARAMERROR; + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 0) + return ZIP_PARAMERROR; + zi->ci.stream.avail_in = 0; + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + while (err==ZIP_OK) + { + uLong uTotalOutBefore; + if (zi->ci.stream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.stream.next_out = zi->ci.buffered_data; + } + uTotalOutBefore = zi->ci.stream.total_out; + err=deflate(&zi->ci.stream, Z_FINISH); + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; + } + } + else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { +#ifdef HAVE_BZIP2 + err = BZ_FINISH_OK; + while (err==BZ_FINISH_OK) + { + uLong uTotalOutBefore; + if (zi->ci.bstream.avail_out == 0) + { + if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) + err = ZIP_ERRNO; + zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; + zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; + } + uTotalOutBefore = zi->ci.bstream.total_out_lo32; + err=BZ2_bzCompress(&zi->ci.bstream, BZ_FINISH); + if(err == BZ_STREAM_END) + err = Z_STREAM_END; + + zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore); + } + + if(err == BZ_FINISH_OK) + err = ZIP_OK; +#endif + } + + if (err==Z_STREAM_END) + err=ZIP_OK; /* this is normal */ + + if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) + { + if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO) + err = ZIP_ERRNO; + } + + if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) + { + int tmp_err = deflateEnd(&zi->ci.stream); + if (err == ZIP_OK) + err = tmp_err; + zi->ci.stream_initialised = 0; + } +#ifdef HAVE_BZIP2 + else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) + { + int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream); + if (err==ZIP_OK) + err = tmperr; + zi->ci.stream_initialised = 0; + } +#endif + + if (!zi->ci.raw) + { + crc32 = (uLong)zi->ci.crc32; + uncompressed_size = zi->ci.totalUncompressedData; + } + compressed_size = zi->ci.totalCompressedData; + +# ifndef NOCRYPT + compressed_size += zi->ci.crypt_header_size; +# endif + + // update Current Item crc and sizes, + if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff) + { + /*version Made by*/ + zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2); + /*version needed*/ + zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2); + + } + + zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ + + + if(compressed_size >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/ + else + zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/ + + /// set internal file attributes field + if (zi->ci.stream.data_type == Z_ASCII) + zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); + + if(uncompressed_size >= 0xffffffff) + zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/ + else + zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/ + + // Add ZIP64 extra info field for uncompressed size + if(uncompressed_size >= 0xffffffff) + datasize += 8; + + // Add ZIP64 extra info field for compressed size + if(compressed_size >= 0xffffffff) + datasize += 8; + + // Add ZIP64 extra info field for relative offset to local file header of current file + if(zi->ci.pos_local_header >= 0xffffffff) + datasize += 8; + + if(datasize > 0) + { + char* p = NULL; + + if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree) + { + // we can not write more data to the buffer that we have room for. + return ZIP_BADZIPFILE; + } + + p = zi->ci.central_header + zi->ci.size_centralheader; + + // Add Extra Information Header for 'ZIP64 information' + zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID + p += 2; + zip64local_putValue_inmemory(p, datasize, 2); // DataSize + p += 2; + + if(uncompressed_size >= 0xffffffff) + { + zip64local_putValue_inmemory(p, uncompressed_size, 8); + p += 8; + } + + if(compressed_size >= 0xffffffff) + { + zip64local_putValue_inmemory(p, compressed_size, 8); + p += 8; + } + + if(zi->ci.pos_local_header >= 0xffffffff) + { + zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8); + p += 8; + } + + // Update how much extra free space we got in the memory buffer + // and increase the centralheader size so the new ZIP64 fields are included + // ( 4 below is the size of HeaderID and DataSize field ) + zi->ci.size_centralExtraFree -= datasize + 4; + zi->ci.size_centralheader += datasize + 4; + + // Update the extra info size field + zi->ci.size_centralExtra += datasize + 4; + zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2); + } + + if (err==ZIP_OK) + err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader); + + free(zi->ci.central_header); + + if (err==ZIP_OK) + { + // Update the LocalFileHeader with the new values. + + ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); + + if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + + if (err==ZIP_OK) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ + + if(uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff ) + { + if(zi->ci.pos_zip64extrainfo > 0) + { + // Update the size in the ZIP64 extended field. + if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + + if (err==ZIP_OK) /* compressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8); + + if (err==ZIP_OK) /* uncompressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8); + } + else + err = ZIP_BADZIPFILE; // Caller passed zip64 = 0, so no room for zip64 info -> fatal + } + else + { + if (err==ZIP_OK) /* compressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); + + if (err==ZIP_OK) /* uncompressed size, unknown */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); + } + + if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) + err = ZIP_ERRNO; + } + + zi->number_entry ++; + zi->in_opened_file_inzip = 0; + + return err; +} + +extern int ZEXPORT zipCloseFileInZip (zipFile file) +{ + return zipCloseFileInZipRaw (file,0,0); +} + +int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip) +{ + int err = ZIP_OK; + ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writing_offset; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4); + + /*num disks*/ + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + /*relative offset*/ + if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8); + + /*total disks*/ /* Do not support spawning of disk so always say 1 here*/ + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4); + + return err; +} + +int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) +{ + int err = ZIP_OK; + + uLong Zip64DataSize = 44; + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4); + + if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ? + + if (err==ZIP_OK) /* version made by */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); + + if (err==ZIP_OK) /* version needed */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); + + if (err==ZIP_OK) /* number of this disk */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); + + if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); + + if (err==ZIP_OK) /* total number of entries in the central dir */ + err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); + + if (err==ZIP_OK) /* size of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8); + + if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ + { + ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8); + } + return err; +} +int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) +{ + int err = ZIP_OK; + + /*signature*/ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); + + if (err==ZIP_OK) /* number of this disk */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); + + if (err==ZIP_OK) /* number of the disk with the start of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); + + if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ + { + { + if(zi->number_entry >= 0xFFFF) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); + } + } + + if (err==ZIP_OK) /* total number of entries in the central dir */ + { + if(zi->number_entry >= 0xFFFF) + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); + } + + if (err==ZIP_OK) /* size of the central directory */ + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); + + if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ + { + ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + if(pos >= 0xffffffff) + { + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4); + } + else + err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writing_offset),4); + } + + return err; +} + +int Write_GlobalComment(zip64_internal* zi, const char* global_comment) +{ + int err = ZIP_OK; + uInt size_global_comment = 0; + + if(global_comment != NULL) + size_global_comment = (uInt)strlen(global_comment); + + err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); + + if (err == ZIP_OK && size_global_comment > 0) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment) + err = ZIP_ERRNO; + } + return err; +} + +extern int ZEXPORT zipClose (zipFile file, const char* global_comment) +{ + zip64_internal* zi; + int err = 0; + uLong size_centraldir = 0; + ZPOS64_T centraldir_pos_inzip; + ZPOS64_T pos; + + if (file == NULL) + return ZIP_PARAMERROR; + + zi = (zip64_internal*)file; + + if (zi->in_opened_file_inzip == 1) + { + err = zipCloseFileInZip (file); + } + +#ifndef NO_ADDFILEINEXISTINGZIP + if (global_comment==NULL) + global_comment = zi->globalcomment; +#endif + + centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); + + if (err==ZIP_OK) + { + linkedlist_datablock_internal* ldi = zi->central_dir.first_block; + while (ldi!=NULL) + { + if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) + { + if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block) + err = ZIP_ERRNO; + } + + size_centraldir += ldi->filled_in_this_block; + ldi = ldi->next_datablock; + } + } + free_linkedlist(&(zi->central_dir)); + + pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; + if(pos >= 0xffffffff || zi->number_entry > 0xFFFF) + { + ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream); + Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); + + Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos); + } + + if (err==ZIP_OK) + err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); + + if(err == ZIP_OK) + err = Write_GlobalComment(zi, global_comment); + + if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0) + if (err == ZIP_OK) + err = ZIP_ERRNO; + +#ifndef NO_ADDFILEINEXISTINGZIP + TRYFREE(zi->globalcomment); +#endif + TRYFREE(zi); + + return err; +} + +extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader) +{ + char* p = pData; + int size = 0; + char* pNewHeader; + char* pTmp; + short header; + short dataSize; + + int retVal = ZIP_OK; + + if(pData == NULL || *dataLen < 4) + return ZIP_PARAMERROR; + + pNewHeader = (char*)ALLOC(*dataLen); + pTmp = pNewHeader; + + while(p < (pData + *dataLen)) + { + header = *(short*)p; + dataSize = *(((short*)p)+1); + + if( header == sHeader ) // Header found. + { + p += dataSize + 4; // skip it. do not copy to temp buffer + } + else + { + // Extra Info block should not be removed, So copy it to the temp buffer. + memcpy(pTmp, p, dataSize + 4); + p += dataSize + 4; + size += dataSize + 4; + } + + } + + if(size < *dataLen) + { + // clean old extra info block. + memset(pData,0, *dataLen); + + // copy the new extra info block over the old + if(size > 0) + memcpy(pData, pNewHeader, size); + + // set the new extra info size + *dataLen = size; + + retVal = ZIP_OK; + } + else + retVal = ZIP_ERRNO; + + TRYFREE(pNewHeader); + + return retVal; +} diff --git a/third_party/zlib/v1_2_11/contrib/minizip/zip.h b/third_party/zlib/v1_2_11/contrib/minizip/zip.h new file mode 100644 index 0000000..8aaebb6 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/minizip/zip.h @@ -0,0 +1,362 @@ +/* zip.h -- IO on .zip files using zlib + Version 1.1, February 14h, 2010 + part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) + + Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) + + Modifications for Zip64 support + Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) + + For more info read MiniZip_info.txt + + --------------------------------------------------------------------------- + + Condition of use and distribution are the same than zlib : + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + --------------------------------------------------------------------------- + + Changes + + See header of zip.h + +*/ + +#ifndef _zip12_H +#define _zip12_H + +#ifdef __cplusplus +extern "C" { +#endif + +//#define HAVE_BZIP2 + +#ifndef _ZLIB_H +#include "zlib.h" +#endif + +#ifndef _ZLIBIOAPI_H +#include "ioapi.h" +#endif + +#ifdef HAVE_BZIP2 +#include "bzlib.h" +#endif + +#define Z_BZIP2ED 12 + +#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) +/* like the STRICT of WIN32, we define a pointer that cannot be converted + from (void*) without cast */ +typedef struct TagzipFile__ { int unused; } zipFile__; +typedef zipFile__ *zipFile; +#else +typedef voidp zipFile; +#endif + +#define ZIP_OK (0) +#define ZIP_EOF (0) +#define ZIP_ERRNO (Z_ERRNO) +#define ZIP_PARAMERROR (-102) +#define ZIP_BADZIPFILE (-103) +#define ZIP_INTERNALERROR (-104) + +#ifndef DEF_MEM_LEVEL +# if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +# else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +# endif +#endif +/* default memLevel */ + +/* tm_zip contain date/time info */ +typedef struct tm_zip_s +{ + uInt tm_sec; /* seconds after the minute - [0,59] */ + uInt tm_min; /* minutes after the hour - [0,59] */ + uInt tm_hour; /* hours since midnight - [0,23] */ + uInt tm_mday; /* day of the month - [1,31] */ + uInt tm_mon; /* months since January - [0,11] */ + uInt tm_year; /* years - [1980..2044] */ +} tm_zip; + +typedef struct +{ + tm_zip tmz_date; /* date in understandable format */ + uLong dosDate; /* if dos_date == 0, tmu_date is used */ +/* uLong flag; */ /* general purpose bit flag 2 bytes */ + + uLong internal_fa; /* internal file attributes 2 bytes */ + uLong external_fa; /* external file attributes 4 bytes */ +} zip_fileinfo; + +typedef const char* zipcharpc; + + +#define APPEND_STATUS_CREATE (0) +#define APPEND_STATUS_CREATEAFTER (1) +#define APPEND_STATUS_ADDINZIP (2) + +extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); +extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append)); +/* + Create a zipfile. + pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on + an Unix computer "zlib/zlib113.zip". + if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip + will be created at the end of the file. + (useful if the file contain a self extractor code) + if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will + add files in existing zip (be sure you don't add file that doesn't exist) + If the zipfile cannot be opened, the return value is NULL. + Else, the return value is a zipFile Handle, usable with other function + of this zip package. +*/ + +/* Note : there is no delete function into a zipfile. + If you want delete file into a zipfile, you must open a zipfile, and create another + Of couse, you can use RAW reading and writing to copy the file you did not want delte +*/ + +extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, + int append, + zipcharpc* globalcomment, + zlib_filefunc_def* pzlib_filefunc_def)); + +extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname, + int append, + zipcharpc* globalcomment, + zlib_filefunc64_def* pzlib_filefunc_def)); + +extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level)); + +extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int zip64)); + +/* + Open a file in the ZIP for writing. + filename : the filename in zip (if NULL, '-' without quote will be used + *zipfi contain supplemental information + if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local + contains the extrafield data the the local header + if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global + contains the extrafield data the the local header + if comment != NULL, comment contain the comment string + method contain the compression method (0 for store, Z_DEFLATED for deflate) + level contain the level of compression (can be Z_DEFAULT_COMPRESSION) + zip64 is set to 1 if a zip64 extended information block should be added to the local file header. + this MUST be '1' if the uncompressed size is >= 0xffffffff. + +*/ + + +extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw)); + + +extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int zip64)); +/* + Same than zipOpenNewFileInZip, except if raw=1, we write raw file + */ + +extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting)); + +extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + int zip64 + )); + +/* + Same than zipOpenNewFileInZip2, except + windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 + password : crypting password (NULL for no crypting) + crcForCrypting : crc of file to compress (needed for crypting) + */ + +extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase + )); + + +extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file, + const char* filename, + const zip_fileinfo* zipfi, + const void* extrafield_local, + uInt size_extrafield_local, + const void* extrafield_global, + uInt size_extrafield_global, + const char* comment, + int method, + int level, + int raw, + int windowBits, + int memLevel, + int strategy, + const char* password, + uLong crcForCrypting, + uLong versionMadeBy, + uLong flagBase, + int zip64 + )); +/* + Same than zipOpenNewFileInZip4, except + versionMadeBy : value for Version made by field + flag : value for flag field (compression level info will be added) + */ + + +extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, + const void* buf, + unsigned len)); +/* + Write data in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); +/* + Close the current file in the zipfile +*/ + +extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, + uLong uncompressed_size, + uLong crc32)); + +extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file, + ZPOS64_T uncompressed_size, + uLong crc32)); + +/* + Close the current file in the zipfile, for file opened with + parameter raw=1 in zipOpenNewFileInZip2 + uncompressed_size and crc32 are value for the uncompressed size +*/ + +extern int ZEXPORT zipClose OF((zipFile file, + const char* global_comment)); +/* + Close the zipfile +*/ + + +extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader)); +/* + zipRemoveExtraInfoBlock - Added by Mathias Svensson + + Remove extra information block from a extra information data for the local file header or central directory header + + It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode. + + 0x0001 is the signature header for the ZIP64 extra information blocks + + usage. + Remove ZIP64 Extra information from a central director extra field data + zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001); + + Remove ZIP64 Extra information from a Local File Header extra field data + zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001); +*/ + +#ifdef __cplusplus +} +#endif + +#endif /* _zip64_H */ diff --git a/third_party/zlib/v1_2_11/contrib/pascal/example.pas b/third_party/zlib/v1_2_11/contrib/pascal/example.pas new file mode 100644 index 0000000..5518b36 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/pascal/example.pas @@ -0,0 +1,599 @@ +(* example.c -- usage example of the zlib compression library + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Pascal translation + * Copyright (C) 1998 by Jacques Nomssi Nzali. + * For conditions of distribution and use, see copyright notice in readme.txt + * + * Adaptation to the zlibpas interface + * Copyright (C) 2003 by Cosmin Truta. + * For conditions of distribution and use, see copyright notice in readme.txt + *) + +program example; + +{$DEFINE TEST_COMPRESS} +{DO NOT $DEFINE TEST_GZIO} +{$DEFINE TEST_DEFLATE} +{$DEFINE TEST_INFLATE} +{$DEFINE TEST_FLUSH} +{$DEFINE TEST_SYNC} +{$DEFINE TEST_DICT} + +uses SysUtils, zlibpas; + +const TESTFILE = 'foo.gz'; + +(* "hello world" would be more standard, but the repeated "hello" + * stresses the compression code better, sorry... + *) +const hello: PChar = 'hello, hello!'; + +const dictionary: PChar = 'hello'; + +var dictId: LongInt; (* Adler32 value of the dictionary *) + +procedure CHECK_ERR(err: Integer; msg: String); +begin + if err <> Z_OK then + begin + WriteLn(msg, ' error: ', err); + Halt(1); + end; +end; + +procedure EXIT_ERR(const msg: String); +begin + WriteLn('Error: ', msg); + Halt(1); +end; + +(* =========================================================================== + * Test compress and uncompress + *) +{$IFDEF TEST_COMPRESS} +procedure test_compress(compr: Pointer; comprLen: LongInt; + uncompr: Pointer; uncomprLen: LongInt); +var err: Integer; + len: LongInt; +begin + len := StrLen(hello)+1; + + err := compress(compr, comprLen, hello, len); + CHECK_ERR(err, 'compress'); + + StrCopy(PChar(uncompr), 'garbage'); + + err := uncompress(uncompr, uncomprLen, compr, comprLen); + CHECK_ERR(err, 'uncompress'); + + if StrComp(PChar(uncompr), hello) <> 0 then + EXIT_ERR('bad uncompress') + else + WriteLn('uncompress(): ', PChar(uncompr)); +end; +{$ENDIF} + +(* =========================================================================== + * Test read/write of .gz files + *) +{$IFDEF TEST_GZIO} +procedure test_gzio(const fname: PChar; (* compressed file name *) + uncompr: Pointer; + uncomprLen: LongInt); +var err: Integer; + len: Integer; + zfile: gzFile; + pos: LongInt; +begin + len := StrLen(hello)+1; + + zfile := gzopen(fname, 'wb'); + if zfile = NIL then + begin + WriteLn('gzopen error'); + Halt(1); + end; + gzputc(zfile, 'h'); + if gzputs(zfile, 'ello') <> 4 then + begin + WriteLn('gzputs err: ', gzerror(zfile, err)); + Halt(1); + end; + {$IFDEF GZ_FORMAT_STRING} + if gzprintf(zfile, ', %s!', 'hello') <> 8 then + begin + WriteLn('gzprintf err: ', gzerror(zfile, err)); + Halt(1); + end; + {$ELSE} + if gzputs(zfile, ', hello!') <> 8 then + begin + WriteLn('gzputs err: ', gzerror(zfile, err)); + Halt(1); + end; + {$ENDIF} + gzseek(zfile, 1, SEEK_CUR); (* add one zero byte *) + gzclose(zfile); + + zfile := gzopen(fname, 'rb'); + if zfile = NIL then + begin + WriteLn('gzopen error'); + Halt(1); + end; + + StrCopy(PChar(uncompr), 'garbage'); + + if gzread(zfile, uncompr, uncomprLen) <> len then + begin + WriteLn('gzread err: ', gzerror(zfile, err)); + Halt(1); + end; + if StrComp(PChar(uncompr), hello) <> 0 then + begin + WriteLn('bad gzread: ', PChar(uncompr)); + Halt(1); + end + else + WriteLn('gzread(): ', PChar(uncompr)); + + pos := gzseek(zfile, -8, SEEK_CUR); + if (pos <> 6) or (gztell(zfile) <> pos) then + begin + WriteLn('gzseek error, pos=', pos, ', gztell=', gztell(zfile)); + Halt(1); + end; + + if gzgetc(zfile) <> ' ' then + begin + WriteLn('gzgetc error'); + Halt(1); + end; + + if gzungetc(' ', zfile) <> ' ' then + begin + WriteLn('gzungetc error'); + Halt(1); + end; + + gzgets(zfile, PChar(uncompr), uncomprLen); + uncomprLen := StrLen(PChar(uncompr)); + if uncomprLen <> 7 then (* " hello!" *) + begin + WriteLn('gzgets err after gzseek: ', gzerror(zfile, err)); + Halt(1); + end; + if StrComp(PChar(uncompr), hello + 6) <> 0 then + begin + WriteLn('bad gzgets after gzseek'); + Halt(1); + end + else + WriteLn('gzgets() after gzseek: ', PChar(uncompr)); + + gzclose(zfile); +end; +{$ENDIF} + +(* =========================================================================== + * Test deflate with small buffers + *) +{$IFDEF TEST_DEFLATE} +procedure test_deflate(compr: Pointer; comprLen: LongInt); +var c_stream: z_stream; (* compression stream *) + err: Integer; + len: LongInt; +begin + len := StrLen(hello)+1; + + c_stream.zalloc := NIL; + c_stream.zfree := NIL; + c_stream.opaque := NIL; + + err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, 'deflateInit'); + + c_stream.next_in := hello; + c_stream.next_out := compr; + + while (c_stream.total_in <> len) and + (c_stream.total_out < comprLen) do + begin + c_stream.avail_out := 1; { force small buffers } + c_stream.avail_in := 1; + err := deflate(c_stream, Z_NO_FLUSH); + CHECK_ERR(err, 'deflate'); + end; + + (* Finish the stream, still forcing small buffers: *) + while TRUE do + begin + c_stream.avail_out := 1; + err := deflate(c_stream, Z_FINISH); + if err = Z_STREAM_END then + break; + CHECK_ERR(err, 'deflate'); + end; + + err := deflateEnd(c_stream); + CHECK_ERR(err, 'deflateEnd'); +end; +{$ENDIF} + +(* =========================================================================== + * Test inflate with small buffers + *) +{$IFDEF TEST_INFLATE} +procedure test_inflate(compr: Pointer; comprLen : LongInt; + uncompr: Pointer; uncomprLen : LongInt); +var err: Integer; + d_stream: z_stream; (* decompression stream *) +begin + StrCopy(PChar(uncompr), 'garbage'); + + d_stream.zalloc := NIL; + d_stream.zfree := NIL; + d_stream.opaque := NIL; + + d_stream.next_in := compr; + d_stream.avail_in := 0; + d_stream.next_out := uncompr; + + err := inflateInit(d_stream); + CHECK_ERR(err, 'inflateInit'); + + while (d_stream.total_out < uncomprLen) and + (d_stream.total_in < comprLen) do + begin + d_stream.avail_out := 1; (* force small buffers *) + d_stream.avail_in := 1; + err := inflate(d_stream, Z_NO_FLUSH); + if err = Z_STREAM_END then + break; + CHECK_ERR(err, 'inflate'); + end; + + err := inflateEnd(d_stream); + CHECK_ERR(err, 'inflateEnd'); + + if StrComp(PChar(uncompr), hello) <> 0 then + EXIT_ERR('bad inflate') + else + WriteLn('inflate(): ', PChar(uncompr)); +end; +{$ENDIF} + +(* =========================================================================== + * Test deflate with large buffers and dynamic change of compression level + *) +{$IFDEF TEST_DEFLATE} +procedure test_large_deflate(compr: Pointer; comprLen: LongInt; + uncompr: Pointer; uncomprLen: LongInt); +var c_stream: z_stream; (* compression stream *) + err: Integer; +begin + c_stream.zalloc := NIL; + c_stream.zfree := NIL; + c_stream.opaque := NIL; + + err := deflateInit(c_stream, Z_BEST_SPEED); + CHECK_ERR(err, 'deflateInit'); + + c_stream.next_out := compr; + c_stream.avail_out := Integer(comprLen); + + (* At this point, uncompr is still mostly zeroes, so it should compress + * very well: + *) + c_stream.next_in := uncompr; + c_stream.avail_in := Integer(uncomprLen); + err := deflate(c_stream, Z_NO_FLUSH); + CHECK_ERR(err, 'deflate'); + if c_stream.avail_in <> 0 then + EXIT_ERR('deflate not greedy'); + + (* Feed in already compressed data and switch to no compression: *) + deflateParams(c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); + c_stream.next_in := compr; + c_stream.avail_in := Integer(comprLen div 2); + err := deflate(c_stream, Z_NO_FLUSH); + CHECK_ERR(err, 'deflate'); + + (* Switch back to compressing mode: *) + deflateParams(c_stream, Z_BEST_COMPRESSION, Z_FILTERED); + c_stream.next_in := uncompr; + c_stream.avail_in := Integer(uncomprLen); + err := deflate(c_stream, Z_NO_FLUSH); + CHECK_ERR(err, 'deflate'); + + err := deflate(c_stream, Z_FINISH); + if err <> Z_STREAM_END then + EXIT_ERR('deflate should report Z_STREAM_END'); + + err := deflateEnd(c_stream); + CHECK_ERR(err, 'deflateEnd'); +end; +{$ENDIF} + +(* =========================================================================== + * Test inflate with large buffers + *) +{$IFDEF TEST_INFLATE} +procedure test_large_inflate(compr: Pointer; comprLen: LongInt; + uncompr: Pointer; uncomprLen: LongInt); +var err: Integer; + d_stream: z_stream; (* decompression stream *) +begin + StrCopy(PChar(uncompr), 'garbage'); + + d_stream.zalloc := NIL; + d_stream.zfree := NIL; + d_stream.opaque := NIL; + + d_stream.next_in := compr; + d_stream.avail_in := Integer(comprLen); + + err := inflateInit(d_stream); + CHECK_ERR(err, 'inflateInit'); + + while TRUE do + begin + d_stream.next_out := uncompr; (* discard the output *) + d_stream.avail_out := Integer(uncomprLen); + err := inflate(d_stream, Z_NO_FLUSH); + if err = Z_STREAM_END then + break; + CHECK_ERR(err, 'large inflate'); + end; + + err := inflateEnd(d_stream); + CHECK_ERR(err, 'inflateEnd'); + + if d_stream.total_out <> 2 * uncomprLen + comprLen div 2 then + begin + WriteLn('bad large inflate: ', d_stream.total_out); + Halt(1); + end + else + WriteLn('large_inflate(): OK'); +end; +{$ENDIF} + +(* =========================================================================== + * Test deflate with full flush + *) +{$IFDEF TEST_FLUSH} +procedure test_flush(compr: Pointer; var comprLen : LongInt); +var c_stream: z_stream; (* compression stream *) + err: Integer; + len: Integer; +begin + len := StrLen(hello)+1; + + c_stream.zalloc := NIL; + c_stream.zfree := NIL; + c_stream.opaque := NIL; + + err := deflateInit(c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, 'deflateInit'); + + c_stream.next_in := hello; + c_stream.next_out := compr; + c_stream.avail_in := 3; + c_stream.avail_out := Integer(comprLen); + err := deflate(c_stream, Z_FULL_FLUSH); + CHECK_ERR(err, 'deflate'); + + Inc(PByteArray(compr)^[3]); (* force an error in first compressed block *) + c_stream.avail_in := len - 3; + + err := deflate(c_stream, Z_FINISH); + if err <> Z_STREAM_END then + CHECK_ERR(err, 'deflate'); + + err := deflateEnd(c_stream); + CHECK_ERR(err, 'deflateEnd'); + + comprLen := c_stream.total_out; +end; +{$ENDIF} + +(* =========================================================================== + * Test inflateSync() + *) +{$IFDEF TEST_SYNC} +procedure test_sync(compr: Pointer; comprLen: LongInt; + uncompr: Pointer; uncomprLen : LongInt); +var err: Integer; + d_stream: z_stream; (* decompression stream *) +begin + StrCopy(PChar(uncompr), 'garbage'); + + d_stream.zalloc := NIL; + d_stream.zfree := NIL; + d_stream.opaque := NIL; + + d_stream.next_in := compr; + d_stream.avail_in := 2; (* just read the zlib header *) + + err := inflateInit(d_stream); + CHECK_ERR(err, 'inflateInit'); + + d_stream.next_out := uncompr; + d_stream.avail_out := Integer(uncomprLen); + + inflate(d_stream, Z_NO_FLUSH); + CHECK_ERR(err, 'inflate'); + + d_stream.avail_in := Integer(comprLen-2); (* read all compressed data *) + err := inflateSync(d_stream); (* but skip the damaged part *) + CHECK_ERR(err, 'inflateSync'); + + err := inflate(d_stream, Z_FINISH); + if err <> Z_DATA_ERROR then + EXIT_ERR('inflate should report DATA_ERROR'); + (* Because of incorrect adler32 *) + + err := inflateEnd(d_stream); + CHECK_ERR(err, 'inflateEnd'); + + WriteLn('after inflateSync(): hel', PChar(uncompr)); +end; +{$ENDIF} + +(* =========================================================================== + * Test deflate with preset dictionary + *) +{$IFDEF TEST_DICT} +procedure test_dict_deflate(compr: Pointer; comprLen: LongInt); +var c_stream: z_stream; (* compression stream *) + err: Integer; +begin + c_stream.zalloc := NIL; + c_stream.zfree := NIL; + c_stream.opaque := NIL; + + err := deflateInit(c_stream, Z_BEST_COMPRESSION); + CHECK_ERR(err, 'deflateInit'); + + err := deflateSetDictionary(c_stream, dictionary, StrLen(dictionary)); + CHECK_ERR(err, 'deflateSetDictionary'); + + dictId := c_stream.adler; + c_stream.next_out := compr; + c_stream.avail_out := Integer(comprLen); + + c_stream.next_in := hello; + c_stream.avail_in := StrLen(hello)+1; + + err := deflate(c_stream, Z_FINISH); + if err <> Z_STREAM_END then + EXIT_ERR('deflate should report Z_STREAM_END'); + + err := deflateEnd(c_stream); + CHECK_ERR(err, 'deflateEnd'); +end; +{$ENDIF} + +(* =========================================================================== + * Test inflate with a preset dictionary + *) +{$IFDEF TEST_DICT} +procedure test_dict_inflate(compr: Pointer; comprLen: LongInt; + uncompr: Pointer; uncomprLen: LongInt); +var err: Integer; + d_stream: z_stream; (* decompression stream *) +begin + StrCopy(PChar(uncompr), 'garbage'); + + d_stream.zalloc := NIL; + d_stream.zfree := NIL; + d_stream.opaque := NIL; + + d_stream.next_in := compr; + d_stream.avail_in := Integer(comprLen); + + err := inflateInit(d_stream); + CHECK_ERR(err, 'inflateInit'); + + d_stream.next_out := uncompr; + d_stream.avail_out := Integer(uncomprLen); + + while TRUE do + begin + err := inflate(d_stream, Z_NO_FLUSH); + if err = Z_STREAM_END then + break; + if err = Z_NEED_DICT then + begin + if d_stream.adler <> dictId then + EXIT_ERR('unexpected dictionary'); + err := inflateSetDictionary(d_stream, dictionary, StrLen(dictionary)); + end; + CHECK_ERR(err, 'inflate with dict'); + end; + + err := inflateEnd(d_stream); + CHECK_ERR(err, 'inflateEnd'); + + if StrComp(PChar(uncompr), hello) <> 0 then + EXIT_ERR('bad inflate with dict') + else + WriteLn('inflate with dictionary: ', PChar(uncompr)); +end; +{$ENDIF} + +var compr, uncompr: Pointer; + comprLen, uncomprLen: LongInt; + +begin + if zlibVersion^ <> ZLIB_VERSION[1] then + EXIT_ERR('Incompatible zlib version'); + + WriteLn('zlib version: ', zlibVersion); + WriteLn('zlib compile flags: ', Format('0x%x', [zlibCompileFlags])); + + comprLen := 10000 * SizeOf(Integer); (* don't overflow on MSDOS *) + uncomprLen := comprLen; + GetMem(compr, comprLen); + GetMem(uncompr, uncomprLen); + if (compr = NIL) or (uncompr = NIL) then + EXIT_ERR('Out of memory'); + (* compr and uncompr are cleared to avoid reading uninitialized + * data and to ensure that uncompr compresses well. + *) + FillChar(compr^, comprLen, 0); + FillChar(uncompr^, uncomprLen, 0); + + {$IFDEF TEST_COMPRESS} + WriteLn('** Testing compress'); + test_compress(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + + {$IFDEF TEST_GZIO} + WriteLn('** Testing gzio'); + if ParamCount >= 1 then + test_gzio(ParamStr(1), uncompr, uncomprLen) + else + test_gzio(TESTFILE, uncompr, uncomprLen); + {$ENDIF} + + {$IFDEF TEST_DEFLATE} + WriteLn('** Testing deflate with small buffers'); + test_deflate(compr, comprLen); + {$ENDIF} + {$IFDEF TEST_INFLATE} + WriteLn('** Testing inflate with small buffers'); + test_inflate(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + + {$IFDEF TEST_DEFLATE} + WriteLn('** Testing deflate with large buffers'); + test_large_deflate(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + {$IFDEF TEST_INFLATE} + WriteLn('** Testing inflate with large buffers'); + test_large_inflate(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + + {$IFDEF TEST_FLUSH} + WriteLn('** Testing deflate with full flush'); + test_flush(compr, comprLen); + {$ENDIF} + {$IFDEF TEST_SYNC} + WriteLn('** Testing inflateSync'); + test_sync(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + comprLen := uncomprLen; + + {$IFDEF TEST_DICT} + WriteLn('** Testing deflate and inflate with preset dictionary'); + test_dict_deflate(compr, comprLen); + test_dict_inflate(compr, comprLen, uncompr, uncomprLen); + {$ENDIF} + + FreeMem(compr, comprLen); + FreeMem(uncompr, uncomprLen); +end. diff --git a/third_party/zlib/v1_2_11/contrib/pascal/readme.txt b/third_party/zlib/v1_2_11/contrib/pascal/readme.txt new file mode 100644 index 0000000..60e87c8 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/pascal/readme.txt @@ -0,0 +1,76 @@ + +This directory contains a Pascal (Delphi, Kylix) interface to the +zlib data compression library. + + +Directory listing +================= + +zlibd32.mak makefile for Borland C++ +example.pas usage example of zlib +zlibpas.pas the Pascal interface to zlib +readme.txt this file + + +Compatibility notes +=================== + +- Although the name "zlib" would have been more normal for the + zlibpas unit, this name is already taken by Borland's ZLib unit. + This is somehow unfortunate, because that unit is not a genuine + interface to the full-fledged zlib functionality, but a suite of + class wrappers around zlib streams. Other essential features, + such as checksums, are missing. + It would have been more appropriate for that unit to have a name + like "ZStreams", or something similar. + +- The C and zlib-supplied types int, uInt, long, uLong, etc. are + translated directly into Pascal types of similar sizes (Integer, + LongInt, etc.), to avoid namespace pollution. In particular, + there is no conversion of unsigned int into a Pascal unsigned + integer. The Word type is non-portable and has the same size + (16 bits) both in a 16-bit and in a 32-bit environment, unlike + Integer. Even if there is a 32-bit Cardinal type, there is no + real need for unsigned int in zlib under a 32-bit environment. + +- Except for the callbacks, the zlib function interfaces are + assuming the calling convention normally used in Pascal + (__pascal for DOS and Windows16, __fastcall for Windows32). + Since the cdecl keyword is used, the old Turbo Pascal does + not work with this interface. + +- The gz* function interfaces are not translated, to avoid + interfacing problems with the C runtime library. Besides, + gzprintf(gzFile file, const char *format, ...) + cannot be translated into Pascal. + + +Legal issues +============ + +The zlibpas interface is: + Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler. + Copyright (C) 1998 by Bob Dellaca. + Copyright (C) 2003 by Cosmin Truta. + +The example program is: + Copyright (C) 1995-2003 by Jean-loup Gailly. + Copyright (C) 1998,1999,2000 by Jacques Nomssi Nzali. + Copyright (C) 2003 by Cosmin Truta. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + diff --git a/third_party/zlib/v1_2_11/contrib/pascal/zlibd32.mak b/third_party/zlib/v1_2_11/contrib/pascal/zlibd32.mak new file mode 100644 index 0000000..9bb00b7 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/pascal/zlibd32.mak @@ -0,0 +1,99 @@ +# Makefile for zlib +# For use with Delphi and C++ Builder under Win32 +# Updated for zlib 1.2.x by Cosmin Truta + +# ------------ Borland C++ ------------ + +# This project uses the Delphi (fastcall/register) calling convention: +LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl + +CC = bcc32 +LD = bcc32 +AR = tlib +# do not use "-pr" in CFLAGS +CFLAGS = -a -d -k- -O2 $(LOC) +LDFLAGS = + + +# variables +ZLIB_LIB = zlib.lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj +OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj +OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(CFLAGS) $*.c + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + +minigzip.obj: test/minigzip.c zlib.h zconf.h + + +# For the sake of the old Borland make, +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) + -del $(ZLIB_LIB) + $(AR) $(ZLIB_LIB) $(OBJP1) + $(AR) $(ZLIB_LIB) $(OBJP2) + + +# testing +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) + + +# cleanup +clean: + -del *.obj + -del *.exe + -del *.lib + -del *.tds + -del zlib.bak + -del foo.gz + diff --git a/third_party/zlib/v1_2_11/contrib/pascal/zlibpas.pas b/third_party/zlib/v1_2_11/contrib/pascal/zlibpas.pas new file mode 100644 index 0000000..a0dff11 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/pascal/zlibpas.pas @@ -0,0 +1,276 @@ +(* zlibpas -- Pascal interface to the zlib data compression library + * + * Copyright (C) 2003 Cosmin Truta. + * Derived from original sources by Bob Dellaca. + * For conditions of distribution and use, see copyright notice in readme.txt + *) + +unit zlibpas; + +interface + +const + ZLIB_VERSION = '1.2.11'; + ZLIB_VERNUM = $12a0; + +type + alloc_func = function(opaque: Pointer; items, size: Integer): Pointer; + cdecl; + free_func = procedure(opaque, address: Pointer); + cdecl; + + in_func = function(opaque: Pointer; var buf: PByte): Integer; + cdecl; + out_func = function(opaque: Pointer; buf: PByte; size: Integer): Integer; + cdecl; + + z_streamp = ^z_stream; + z_stream = packed record + next_in: PChar; (* next input byte *) + avail_in: Integer; (* number of bytes available at next_in *) + total_in: LongInt; (* total nb of input bytes read so far *) + + next_out: PChar; (* next output byte should be put there *) + avail_out: Integer; (* remaining free space at next_out *) + total_out: LongInt; (* total nb of bytes output so far *) + + msg: PChar; (* last error message, NULL if no error *) + state: Pointer; (* not visible by applications *) + + zalloc: alloc_func; (* used to allocate the internal state *) + zfree: free_func; (* used to free the internal state *) + opaque: Pointer; (* private data object passed to zalloc and zfree *) + + data_type: Integer; (* best guess about the data type: ascii or binary *) + adler: LongInt; (* adler32 value of the uncompressed data *) + reserved: LongInt; (* reserved for future use *) + end; + + gz_headerp = ^gz_header; + gz_header = packed record + text: Integer; (* true if compressed data believed to be text *) + time: LongInt; (* modification time *) + xflags: Integer; (* extra flags (not used when writing a gzip file) *) + os: Integer; (* operating system *) + extra: PChar; (* pointer to extra field or Z_NULL if none *) + extra_len: Integer; (* extra field length (valid if extra != Z_NULL) *) + extra_max: Integer; (* space at extra (only when reading header) *) + name: PChar; (* pointer to zero-terminated file name or Z_NULL *) + name_max: Integer; (* space at name (only when reading header) *) + comment: PChar; (* pointer to zero-terminated comment or Z_NULL *) + comm_max: Integer; (* space at comment (only when reading header) *) + hcrc: Integer; (* true if there was or will be a header crc *) + done: Integer; (* true when done reading gzip header *) + end; + +(* constants *) +const + Z_NO_FLUSH = 0; + Z_PARTIAL_FLUSH = 1; + Z_SYNC_FLUSH = 2; + Z_FULL_FLUSH = 3; + Z_FINISH = 4; + Z_BLOCK = 5; + Z_TREES = 6; + + Z_OK = 0; + Z_STREAM_END = 1; + Z_NEED_DICT = 2; + Z_ERRNO = -1; + Z_STREAM_ERROR = -2; + Z_DATA_ERROR = -3; + Z_MEM_ERROR = -4; + Z_BUF_ERROR = -5; + Z_VERSION_ERROR = -6; + + Z_NO_COMPRESSION = 0; + Z_BEST_SPEED = 1; + Z_BEST_COMPRESSION = 9; + Z_DEFAULT_COMPRESSION = -1; + + Z_FILTERED = 1; + Z_HUFFMAN_ONLY = 2; + Z_RLE = 3; + Z_FIXED = 4; + Z_DEFAULT_STRATEGY = 0; + + Z_BINARY = 0; + Z_TEXT = 1; + Z_ASCII = 1; + Z_UNKNOWN = 2; + + Z_DEFLATED = 8; + +(* basic functions *) +function zlibVersion: PChar; +function deflateInit(var strm: z_stream; level: Integer): Integer; +function deflate(var strm: z_stream; flush: Integer): Integer; +function deflateEnd(var strm: z_stream): Integer; +function inflateInit(var strm: z_stream): Integer; +function inflate(var strm: z_stream; flush: Integer): Integer; +function inflateEnd(var strm: z_stream): Integer; + +(* advanced functions *) +function deflateInit2(var strm: z_stream; level, method, windowBits, + memLevel, strategy: Integer): Integer; +function deflateSetDictionary(var strm: z_stream; const dictionary: PChar; + dictLength: Integer): Integer; +function deflateCopy(var dest, source: z_stream): Integer; +function deflateReset(var strm: z_stream): Integer; +function deflateParams(var strm: z_stream; level, strategy: Integer): Integer; +function deflateTune(var strm: z_stream; good_length, max_lazy, nice_length, max_chain: Integer): Integer; +function deflateBound(var strm: z_stream; sourceLen: LongInt): LongInt; +function deflatePending(var strm: z_stream; var pending: Integer; var bits: Integer): Integer; +function deflatePrime(var strm: z_stream; bits, value: Integer): Integer; +function deflateSetHeader(var strm: z_stream; head: gz_header): Integer; +function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; +function inflateSetDictionary(var strm: z_stream; const dictionary: PChar; + dictLength: Integer): Integer; +function inflateSync(var strm: z_stream): Integer; +function inflateCopy(var dest, source: z_stream): Integer; +function inflateReset(var strm: z_stream): Integer; +function inflateReset2(var strm: z_stream; windowBits: Integer): Integer; +function inflatePrime(var strm: z_stream; bits, value: Integer): Integer; +function inflateMark(var strm: z_stream): LongInt; +function inflateGetHeader(var strm: z_stream; var head: gz_header): Integer; +function inflateBackInit(var strm: z_stream; + windowBits: Integer; window: PChar): Integer; +function inflateBack(var strm: z_stream; in_fn: in_func; in_desc: Pointer; + out_fn: out_func; out_desc: Pointer): Integer; +function inflateBackEnd(var strm: z_stream): Integer; +function zlibCompileFlags: LongInt; + +(* utility functions *) +function compress(dest: PChar; var destLen: LongInt; + const source: PChar; sourceLen: LongInt): Integer; +function compress2(dest: PChar; var destLen: LongInt; + const source: PChar; sourceLen: LongInt; + level: Integer): Integer; +function compressBound(sourceLen: LongInt): LongInt; +function uncompress(dest: PChar; var destLen: LongInt; + const source: PChar; sourceLen: LongInt): Integer; + +(* checksum functions *) +function adler32(adler: LongInt; const buf: PChar; len: Integer): LongInt; +function adler32_combine(adler1, adler2, len2: LongInt): LongInt; +function crc32(crc: LongInt; const buf: PChar; len: Integer): LongInt; +function crc32_combine(crc1, crc2, len2: LongInt): LongInt; + +(* various hacks, don't look :) *) +function deflateInit_(var strm: z_stream; level: Integer; + const version: PChar; stream_size: Integer): Integer; +function inflateInit_(var strm: z_stream; const version: PChar; + stream_size: Integer): Integer; +function deflateInit2_(var strm: z_stream; + level, method, windowBits, memLevel, strategy: Integer; + const version: PChar; stream_size: Integer): Integer; +function inflateInit2_(var strm: z_stream; windowBits: Integer; + const version: PChar; stream_size: Integer): Integer; +function inflateBackInit_(var strm: z_stream; + windowBits: Integer; window: PChar; + const version: PChar; stream_size: Integer): Integer; + + +implementation + +{$L adler32.obj} +{$L compress.obj} +{$L crc32.obj} +{$L deflate.obj} +{$L infback.obj} +{$L inffast.obj} +{$L inflate.obj} +{$L inftrees.obj} +{$L trees.obj} +{$L uncompr.obj} +{$L zutil.obj} + +function adler32; external; +function adler32_combine; external; +function compress; external; +function compress2; external; +function compressBound; external; +function crc32; external; +function crc32_combine; external; +function deflate; external; +function deflateBound; external; +function deflateCopy; external; +function deflateEnd; external; +function deflateInit_; external; +function deflateInit2_; external; +function deflateParams; external; +function deflatePending; external; +function deflatePrime; external; +function deflateReset; external; +function deflateSetDictionary; external; +function deflateSetHeader; external; +function deflateTune; external; +function inflate; external; +function inflateBack; external; +function inflateBackEnd; external; +function inflateBackInit_; external; +function inflateCopy; external; +function inflateEnd; external; +function inflateGetHeader; external; +function inflateInit_; external; +function inflateInit2_; external; +function inflateMark; external; +function inflatePrime; external; +function inflateReset; external; +function inflateReset2; external; +function inflateSetDictionary; external; +function inflateSync; external; +function uncompress; external; +function zlibCompileFlags; external; +function zlibVersion; external; + +function deflateInit(var strm: z_stream; level: Integer): Integer; +begin + Result := deflateInit_(strm, level, ZLIB_VERSION, sizeof(z_stream)); +end; + +function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel, + strategy: Integer): Integer; +begin + Result := deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + ZLIB_VERSION, sizeof(z_stream)); +end; + +function inflateInit(var strm: z_stream): Integer; +begin + Result := inflateInit_(strm, ZLIB_VERSION, sizeof(z_stream)); +end; + +function inflateInit2(var strm: z_stream; windowBits: Integer): Integer; +begin + Result := inflateInit2_(strm, windowBits, ZLIB_VERSION, sizeof(z_stream)); +end; + +function inflateBackInit(var strm: z_stream; + windowBits: Integer; window: PChar): Integer; +begin + Result := inflateBackInit_(strm, windowBits, window, + ZLIB_VERSION, sizeof(z_stream)); +end; + +function _malloc(Size: Integer): Pointer; cdecl; +begin + GetMem(Result, Size); +end; + +procedure _free(Block: Pointer); cdecl; +begin + FreeMem(Block); +end; + +procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; +begin + FillChar(P^, count, B); +end; + +procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; +begin + Move(source^, dest^, count); +end; + +end. diff --git a/third_party/zlib/v1_2_11/contrib/puff/Makefile b/third_party/zlib/v1_2_11/contrib/puff/Makefile new file mode 100644 index 0000000..0e2594c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/puff/Makefile @@ -0,0 +1,42 @@ +CFLAGS=-O + +puff: puff.o pufftest.o + +puff.o: puff.h + +pufftest.o: puff.h + +test: puff + puff zeros.raw + +puft: puff.c puff.h pufftest.o + cc -fprofile-arcs -ftest-coverage -o puft puff.c pufftest.o + +# puff full coverage test (should say 100%) +cov: puft + @rm -f *.gcov *.gcda + @puft -w zeros.raw 2>&1 | cat > /dev/null + @echo '04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 + @echo '00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 + @echo '00 00 00 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 254 + @echo '00 01 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 + @echo '01 01 00 fe ff 0a' | xxd -r -p | puft -f 2>&1 | cat > /dev/null + @echo '02 7e ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 + @echo '02' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 + @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 2 + @echo '04 80 49 92 24 49 92 24 71 ff ff 93 11 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 249 + @echo '04 c0 81 08 00 00 00 00 20 7f eb 0b 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 + @echo '0b 00 00' | xxd -r -p | puft -f 2>&1 | cat > /dev/null + @echo '1a 07' | xxd -r -p | puft 2> /dev/null || test $$? -eq 246 + @echo '0c c0 81 00 00 00 00 00 90 ff 6b 04' | xxd -r -p | puft 2> /dev/null || test $$? -eq 245 + @puft -f zeros.raw 2>&1 | cat > /dev/null + @echo 'fc 00 00' | xxd -r -p | puft 2> /dev/null || test $$? -eq 253 + @echo '04 00 fe ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 252 + @echo '04 00 24 49' | xxd -r -p | puft 2> /dev/null || test $$? -eq 251 + @echo '04 80 49 92 24 49 92 24 0f b4 ff ff c3 84' | xxd -r -p | puft 2> /dev/null || test $$? -eq 248 + @echo '04 00 24 e9 ff ff' | xxd -r -p | puft 2> /dev/null || test $$? -eq 250 + @echo '04 00 24 e9 ff 6d' | xxd -r -p | puft 2> /dev/null || test $$? -eq 247 + @gcov -n puff.c + +clean: + rm -f puff puft *.o *.gc* diff --git a/third_party/zlib/v1_2_11/contrib/puff/README b/third_party/zlib/v1_2_11/contrib/puff/README new file mode 100644 index 0000000..bbc4cb5 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/puff/README @@ -0,0 +1,63 @@ +Puff -- A Simple Inflate +3 Mar 2003 +Mark Adler +madler@alumni.caltech.edu + +What this is -- + +puff.c provides the routine puff() to decompress the deflate data format. It +does so more slowly than zlib, but the code is about one-fifth the size of the +inflate code in zlib, and written to be very easy to read. + +Why I wrote this -- + +puff.c was written to document the deflate format unambiguously, by virtue of +being working C code. It is meant to supplement RFC 1951, which formally +describes the deflate format. I have received many questions on details of the +deflate format, and I hope that reading this code will answer those questions. +puff.c is heavily commented with details of the deflate format, especially +those little nooks and cranies of the format that might not be obvious from a +specification. + +puff.c may also be useful in applications where code size or memory usage is a +very limited resource, and speed is not as important. + +How to use it -- + +Well, most likely you should just be reading puff.c and using zlib for actual +applications, but if you must ... + +Include puff.h in your code, which provides this prototype: + +int puff(unsigned char *dest, /* pointer to destination pointer */ + unsigned long *destlen, /* amount of output space */ + unsigned char *source, /* pointer to source data pointer */ + unsigned long *sourcelen); /* amount of input available */ + +Then you can call puff() to decompress a deflate stream that is in memory in +its entirety at source, to a sufficiently sized block of memory for the +decompressed data at dest. puff() is the only external symbol in puff.c The +only C library functions that puff.c needs are setjmp() and longjmp(), which +are used to simplify error checking in the code to improve readabilty. puff.c +does no memory allocation, and uses less than 2K bytes off of the stack. + +If destlen is not enough space for the uncompressed data, then inflate will +return an error without writing more than destlen bytes. Note that this means +that in order to decompress the deflate data successfully, you need to know +the size of the uncompressed data ahead of time. + +If needed, puff() can determine the size of the uncompressed data with no +output space. This is done by passing dest equal to (unsigned char *)0. Then +the initial value of *destlen is ignored and *destlen is set to the length of +the uncompressed data. So if the size of the uncompressed data is not known, +then two passes of puff() can be used--first to determine the size, and second +to do the actual inflation after allocating the appropriate memory. Not +pretty, but it works. (This is one of the reasons you should be using zlib.) + +The deflate format is self-terminating. If the deflate stream does not end +in *sourcelen bytes, puff() will return an error without reading at or past +endsource. + +On return, *sourcelen is updated to the amount of input data consumed, and +*destlen is updated to the size of the uncompressed data. See the comments +in puff.c for the possible return codes for puff(). diff --git a/third_party/zlib/v1_2_11/contrib/puff/puff.c b/third_party/zlib/v1_2_11/contrib/puff/puff.c new file mode 100644 index 0000000..c6c90d7 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/puff/puff.c @@ -0,0 +1,840 @@ +/* + * puff.c + * Copyright (C) 2002-2013 Mark Adler + * For conditions of distribution and use, see copyright notice in puff.h + * version 2.3, 21 Jan 2013 + * + * puff.c is a simple inflate written to be an unambiguous way to specify the + * deflate format. It is not written for speed but rather simplicity. As a + * side benefit, this code might actually be useful when small code is more + * important than speed, such as bootstrap applications. For typical deflate + * data, zlib's inflate() is about four times as fast as puff(). zlib's + * inflate compiles to around 20K on my machine, whereas puff.c compiles to + * around 4K on my machine (a PowerPC using GNU cc). If the faster decode() + * function here is used, then puff() is only twice as slow as zlib's + * inflate(). + * + * All dynamically allocated memory comes from the stack. The stack required + * is less than 2K bytes. This code is compatible with 16-bit int's and + * assumes that long's are at least 32 bits. puff.c uses the short data type, + * assumed to be 16 bits, for arrays in order to conserve memory. The code + * works whether integers are stored big endian or little endian. + * + * In the comments below are "Format notes" that describe the inflate process + * and document some of the less obvious aspects of the format. This source + * code is meant to supplement RFC 1951, which formally describes the deflate + * format: + * + * http://www.zlib.org/rfc-deflate.html + */ + +/* + * Change history: + * + * 1.0 10 Feb 2002 - First version + * 1.1 17 Feb 2002 - Clarifications of some comments and notes + * - Update puff() dest and source pointers on negative + * errors to facilitate debugging deflators + * - Remove longest from struct huffman -- not needed + * - Simplify offs[] index in construct() + * - Add input size and checking, using longjmp() to + * maintain easy readability + * - Use short data type for large arrays + * - Use pointers instead of long to specify source and + * destination sizes to avoid arbitrary 4 GB limits + * 1.2 17 Mar 2002 - Add faster version of decode(), doubles speed (!), + * but leave simple version for readabilty + * - Make sure invalid distances detected if pointers + * are 16 bits + * - Fix fixed codes table error + * - Provide a scanning mode for determining size of + * uncompressed data + * 1.3 20 Mar 2002 - Go back to lengths for puff() parameters [Gailly] + * - Add a puff.h file for the interface + * - Add braces in puff() for else do [Gailly] + * - Use indexes instead of pointers for readability + * 1.4 31 Mar 2002 - Simplify construct() code set check + * - Fix some comments + * - Add FIXLCODES #define + * 1.5 6 Apr 2002 - Minor comment fixes + * 1.6 7 Aug 2002 - Minor format changes + * 1.7 3 Mar 2003 - Added test code for distribution + * - Added zlib-like license + * 1.8 9 Jan 2004 - Added some comments on no distance codes case + * 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland] + * - Catch missing end-of-block symbol error + * 2.0 25 Jul 2008 - Add #define to permit distance too far back + * - Add option in TEST code for puff to write the data + * - Add option in TEST code to skip input bytes + * - Allow TEST code to read from piped stdin + * 2.1 4 Apr 2010 - Avoid variable initialization for happier compilers + * - Avoid unsigned comparisons for even happier compilers + * 2.2 25 Apr 2010 - Fix bug in variable initializations [Oberhumer] + * - Add const where appropriate [Oberhumer] + * - Split if's and ?'s for coverage testing + * - Break out test code to separate file + * - Move NIL to puff.h + * - Allow incomplete code only if single code length is 1 + * - Add full code coverage test to Makefile + * 2.3 21 Jan 2013 - Check for invalid code length codes in dynamic blocks + */ + +#include /* for setjmp(), longjmp(), and jmp_buf */ +#include "puff.h" /* prototype for puff() */ + +#define local static /* for local function definitions */ + +/* + * Maximums for allocations and loops. It is not useful to change these -- + * they are fixed by the deflate format. + */ +#define MAXBITS 15 /* maximum bits in a code */ +#define MAXLCODES 286 /* maximum number of literal/length codes */ +#define MAXDCODES 30 /* maximum number of distance codes */ +#define MAXCODES (MAXLCODES+MAXDCODES) /* maximum codes lengths to read */ +#define FIXLCODES 288 /* number of fixed literal/length codes */ + +/* input and output state */ +struct state { + /* output state */ + unsigned char *out; /* output buffer */ + unsigned long outlen; /* available space at out */ + unsigned long outcnt; /* bytes written to out so far */ + + /* input state */ + const unsigned char *in; /* input buffer */ + unsigned long inlen; /* available input at in */ + unsigned long incnt; /* bytes read so far */ + int bitbuf; /* bit buffer */ + int bitcnt; /* number of bits in bit buffer */ + + /* input limit error return state for bits() and decode() */ + jmp_buf env; +}; + +/* + * Return need bits from the input stream. This always leaves less than + * eight bits in the buffer. bits() works properly for need == 0. + * + * Format notes: + * + * - Bits are stored in bytes from the least significant bit to the most + * significant bit. Therefore bits are dropped from the bottom of the bit + * buffer, using shift right, and new bytes are appended to the top of the + * bit buffer, using shift left. + */ +local int bits(struct state *s, int need) +{ + long val; /* bit accumulator (can use up to 20 bits) */ + + /* load at least need bits into val */ + val = s->bitbuf; + while (s->bitcnt < need) { + if (s->incnt == s->inlen) + longjmp(s->env, 1); /* out of input */ + val |= (long)(s->in[s->incnt++]) << s->bitcnt; /* load eight bits */ + s->bitcnt += 8; + } + + /* drop need bits and update buffer, always zero to seven bits left */ + s->bitbuf = (int)(val >> need); + s->bitcnt -= need; + + /* return need bits, zeroing the bits above that */ + return (int)(val & ((1L << need) - 1)); +} + +/* + * Process a stored block. + * + * Format notes: + * + * - After the two-bit stored block type (00), the stored block length and + * stored bytes are byte-aligned for fast copying. Therefore any leftover + * bits in the byte that has the last bit of the type, as many as seven, are + * discarded. The value of the discarded bits are not defined and should not + * be checked against any expectation. + * + * - The second inverted copy of the stored block length does not have to be + * checked, but it's probably a good idea to do so anyway. + * + * - A stored block can have zero length. This is sometimes used to byte-align + * subsets of the compressed data for random access or partial recovery. + */ +local int stored(struct state *s) +{ + unsigned len; /* length of stored block */ + + /* discard leftover bits from current byte (assumes s->bitcnt < 8) */ + s->bitbuf = 0; + s->bitcnt = 0; + + /* get length and check against its one's complement */ + if (s->incnt + 4 > s->inlen) + return 2; /* not enough input */ + len = s->in[s->incnt++]; + len |= s->in[s->incnt++] << 8; + if (s->in[s->incnt++] != (~len & 0xff) || + s->in[s->incnt++] != ((~len >> 8) & 0xff)) + return -2; /* didn't match complement! */ + + /* copy len bytes from in to out */ + if (s->incnt + len > s->inlen) + return 2; /* not enough input */ + if (s->out != NIL) { + if (s->outcnt + len > s->outlen) + return 1; /* not enough output space */ + while (len--) + s->out[s->outcnt++] = s->in[s->incnt++]; + } + else { /* just scanning */ + s->outcnt += len; + s->incnt += len; + } + + /* done with a valid stored block */ + return 0; +} + +/* + * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of + * each length, which for a canonical code are stepped through in order. + * symbol[] are the symbol values in canonical order, where the number of + * entries is the sum of the counts in count[]. The decoding process can be + * seen in the function decode() below. + */ +struct huffman { + short *count; /* number of symbols of each length */ + short *symbol; /* canonically ordered symbols */ +}; + +/* + * Decode a code from the stream s using huffman table h. Return the symbol or + * a negative value if there is an error. If all of the lengths are zero, i.e. + * an empty code, or if the code is incomplete and an invalid code is received, + * then -10 is returned after reading MAXBITS bits. + * + * Format notes: + * + * - The codes as stored in the compressed data are bit-reversed relative to + * a simple integer ordering of codes of the same lengths. Hence below the + * bits are pulled from the compressed data one at a time and used to + * build the code value reversed from what is in the stream in order to + * permit simple integer comparisons for decoding. A table-based decoding + * scheme (as used in zlib) does not need to do this reversal. + * + * - The first code for the shortest length is all zeros. Subsequent codes of + * the same length are simply integer increments of the previous code. When + * moving up a length, a zero bit is appended to the code. For a complete + * code, the last code of the longest length will be all ones. + * + * - Incomplete codes are handled by this decoder, since they are permitted + * in the deflate format. See the format notes for fixed() and dynamic(). + */ +#ifdef SLOW +local int decode(struct state *s, const struct huffman *h) +{ + int len; /* current number of bits in code */ + int code; /* len bits being decoded */ + int first; /* first code of length len */ + int count; /* number of codes of length len */ + int index; /* index of first code of length len in symbol table */ + + code = first = index = 0; + for (len = 1; len <= MAXBITS; len++) { + code |= bits(s, 1); /* get next bit */ + count = h->count[len]; + if (code - count < first) /* if length len, return symbol */ + return h->symbol[index + (code - first)]; + index += count; /* else update for next length */ + first += count; + first <<= 1; + code <<= 1; + } + return -10; /* ran out of codes */ +} + +/* + * A faster version of decode() for real applications of this code. It's not + * as readable, but it makes puff() twice as fast. And it only makes the code + * a few percent larger. + */ +#else /* !SLOW */ +local int decode(struct state *s, const struct huffman *h) +{ + int len; /* current number of bits in code */ + int code; /* len bits being decoded */ + int first; /* first code of length len */ + int count; /* number of codes of length len */ + int index; /* index of first code of length len in symbol table */ + int bitbuf; /* bits from stream */ + int left; /* bits left in next or left to process */ + short *next; /* next number of codes */ + + bitbuf = s->bitbuf; + left = s->bitcnt; + code = first = index = 0; + len = 1; + next = h->count + 1; + while (1) { + while (left--) { + code |= bitbuf & 1; + bitbuf >>= 1; + count = *next++; + if (code - count < first) { /* if length len, return symbol */ + s->bitbuf = bitbuf; + s->bitcnt = (s->bitcnt - len) & 7; + return h->symbol[index + (code - first)]; + } + index += count; /* else update for next length */ + first += count; + first <<= 1; + code <<= 1; + len++; + } + left = (MAXBITS+1) - len; + if (left == 0) + break; + if (s->incnt == s->inlen) + longjmp(s->env, 1); /* out of input */ + bitbuf = s->in[s->incnt++]; + if (left > 8) + left = 8; + } + return -10; /* ran out of codes */ +} +#endif /* SLOW */ + +/* + * Given the list of code lengths length[0..n-1] representing a canonical + * Huffman code for n symbols, construct the tables required to decode those + * codes. Those tables are the number of codes of each length, and the symbols + * sorted by length, retaining their original order within each length. The + * return value is zero for a complete code set, negative for an over- + * subscribed code set, and positive for an incomplete code set. The tables + * can be used if the return value is zero or positive, but they cannot be used + * if the return value is negative. If the return value is zero, it is not + * possible for decode() using that table to return an error--any stream of + * enough bits will resolve to a symbol. If the return value is positive, then + * it is possible for decode() using that table to return an error for received + * codes past the end of the incomplete lengths. + * + * Not used by decode(), but used for error checking, h->count[0] is the number + * of the n symbols not in the code. So n - h->count[0] is the number of + * codes. This is useful for checking for incomplete codes that have more than + * one symbol, which is an error in a dynamic block. + * + * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS + * This is assured by the construction of the length arrays in dynamic() and + * fixed() and is not verified by construct(). + * + * Format notes: + * + * - Permitted and expected examples of incomplete codes are one of the fixed + * codes and any code with a single symbol which in deflate is coded as one + * bit instead of zero bits. See the format notes for fixed() and dynamic(). + * + * - Within a given code length, the symbols are kept in ascending order for + * the code bits definition. + */ +local int construct(struct huffman *h, const short *length, int n) +{ + int symbol; /* current symbol when stepping through length[] */ + int len; /* current length when stepping through h->count[] */ + int left; /* number of possible codes left of current length */ + short offs[MAXBITS+1]; /* offsets in symbol table for each length */ + + /* count number of codes of each length */ + for (len = 0; len <= MAXBITS; len++) + h->count[len] = 0; + for (symbol = 0; symbol < n; symbol++) + (h->count[length[symbol]])++; /* assumes lengths are within bounds */ + if (h->count[0] == n) /* no codes! */ + return 0; /* complete, but decode() will fail */ + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; /* one possible code of zero length */ + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; /* one more bit, double codes left */ + left -= h->count[len]; /* deduct count from possible codes */ + if (left < 0) + return left; /* over-subscribed--return negative */ + } /* left > 0 means incomplete */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + h->count[len]; + + /* + * put symbols in table sorted by length, by symbol order within each + * length + */ + for (symbol = 0; symbol < n; symbol++) + if (length[symbol] != 0) + h->symbol[offs[length[symbol]]++] = symbol; + + /* return zero for complete set, positive for incomplete set */ + return left; +} + +/* + * Decode literal/length and distance codes until an end-of-block code. + * + * Format notes: + * + * - Compressed data that is after the block type if fixed or after the code + * description if dynamic is a combination of literals and length/distance + * pairs terminated by and end-of-block code. Literals are simply Huffman + * coded bytes. A length/distance pair is a coded length followed by a + * coded distance to represent a string that occurs earlier in the + * uncompressed data that occurs again at the current location. + * + * - Literals, lengths, and the end-of-block code are combined into a single + * code of up to 286 symbols. They are 256 literals (0..255), 29 length + * symbols (257..285), and the end-of-block symbol (256). + * + * - There are 256 possible lengths (3..258), and so 29 symbols are not enough + * to represent all of those. Lengths 3..10 and 258 are in fact represented + * by just a length symbol. Lengths 11..257 are represented as a symbol and + * some number of extra bits that are added as an integer to the base length + * of the length symbol. The number of extra bits is determined by the base + * length symbol. These are in the static arrays below, lens[] for the base + * lengths and lext[] for the corresponding number of extra bits. + * + * - The reason that 258 gets its own symbol is that the longest length is used + * often in highly redundant files. Note that 258 can also be coded as the + * base value 227 plus the maximum extra value of 31. While a good deflate + * should never do this, it is not an error, and should be decoded properly. + * + * - If a length is decoded, including its extra bits if any, then it is + * followed a distance code. There are up to 30 distance symbols. Again + * there are many more possible distances (1..32768), so extra bits are added + * to a base value represented by the symbol. The distances 1..4 get their + * own symbol, but the rest require extra bits. The base distances and + * corresponding number of extra bits are below in the static arrays dist[] + * and dext[]. + * + * - Literal bytes are simply written to the output. A length/distance pair is + * an instruction to copy previously uncompressed bytes to the output. The + * copy is from distance bytes back in the output stream, copying for length + * bytes. + * + * - Distances pointing before the beginning of the output data are not + * permitted. + * + * - Overlapped copies, where the length is greater than the distance, are + * allowed and common. For example, a distance of one and a length of 258 + * simply copies the last byte 258 times. A distance of four and a length of + * twelve copies the last four bytes three times. A simple forward copy + * ignoring whether the length is greater than the distance or not implements + * this correctly. You should not use memcpy() since its behavior is not + * defined for overlapped arrays. You should not use memmove() or bcopy() + * since though their behavior -is- defined for overlapping arrays, it is + * defined to do the wrong thing in this case. + */ +local int codes(struct state *s, + const struct huffman *lencode, + const struct huffman *distcode) +{ + int symbol; /* decoded symbol */ + int len; /* length for copy */ + unsigned dist; /* distance for copy */ + static const short lens[29] = { /* Size base for length codes 257..285 */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static const short lext[29] = { /* Extra bits for length codes 257..285 */ + 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, 0}; + static const short dists[30] = { /* Offset base for distance codes 0..29 */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577}; + static const short dext[30] = { /* Extra bits for distance codes 0..29 */ + 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}; + + /* decode literals and length/distance pairs */ + do { + symbol = decode(s, lencode); + if (symbol < 0) + return symbol; /* invalid symbol */ + if (symbol < 256) { /* literal: symbol is the byte */ + /* write out the literal */ + if (s->out != NIL) { + if (s->outcnt == s->outlen) + return 1; + s->out[s->outcnt] = symbol; + } + s->outcnt++; + } + else if (symbol > 256) { /* length */ + /* get and compute length */ + symbol -= 257; + if (symbol >= 29) + return -10; /* invalid fixed code */ + len = lens[symbol] + bits(s, lext[symbol]); + + /* get and check distance */ + symbol = decode(s, distcode); + if (symbol < 0) + return symbol; /* invalid symbol */ + dist = dists[symbol] + bits(s, dext[symbol]); +#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (dist > s->outcnt) + return -11; /* distance too far back */ +#endif + + /* copy length bytes from distance bytes back */ + if (s->out != NIL) { + if (s->outcnt + len > s->outlen) + return 1; + while (len--) { + s->out[s->outcnt] = +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + dist > s->outcnt ? + 0 : +#endif + s->out[s->outcnt - dist]; + s->outcnt++; + } + } + else + s->outcnt += len; + } + } while (symbol != 256); /* end of block symbol */ + + /* done with a valid fixed or dynamic block */ + return 0; +} + +/* + * Process a fixed codes block. + * + * Format notes: + * + * - This block type can be useful for compressing small amounts of data for + * which the size of the code descriptions in a dynamic block exceeds the + * benefit of custom codes for that block. For fixed codes, no bits are + * spent on code descriptions. Instead the code lengths for literal/length + * codes and distance codes are fixed. The specific lengths for each symbol + * can be seen in the "for" loops below. + * + * - The literal/length code is complete, but has two symbols that are invalid + * and should result in an error if received. This cannot be implemented + * simply as an incomplete code since those two symbols are in the "middle" + * of the code. They are eight bits long and the longest literal/length\ + * code is nine bits. Therefore the code must be constructed with those + * symbols, and the invalid symbols must be detected after decoding. + * + * - The fixed distance codes also have two invalid symbols that should result + * in an error if received. Since all of the distance codes are the same + * length, this can be implemented as an incomplete code. Then the invalid + * codes are detected while decoding. + */ +local int fixed(struct state *s) +{ + static int virgin = 1; + static short lencnt[MAXBITS+1], lensym[FIXLCODES]; + static short distcnt[MAXBITS+1], distsym[MAXDCODES]; + static struct huffman lencode, distcode; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + int symbol; + short lengths[FIXLCODES]; + + /* construct lencode and distcode */ + lencode.count = lencnt; + lencode.symbol = lensym; + distcode.count = distcnt; + distcode.symbol = distsym; + + /* literal/length table */ + for (symbol = 0; symbol < 144; symbol++) + lengths[symbol] = 8; + for (; symbol < 256; symbol++) + lengths[symbol] = 9; + for (; symbol < 280; symbol++) + lengths[symbol] = 7; + for (; symbol < FIXLCODES; symbol++) + lengths[symbol] = 8; + construct(&lencode, lengths, FIXLCODES); + + /* distance table */ + for (symbol = 0; symbol < MAXDCODES; symbol++) + lengths[symbol] = 5; + construct(&distcode, lengths, MAXDCODES); + + /* do this just once */ + virgin = 0; + } + + /* decode data until end-of-block code */ + return codes(s, &lencode, &distcode); +} + +/* + * Process a dynamic codes block. + * + * Format notes: + * + * - A dynamic block starts with a description of the literal/length and + * distance codes for that block. New dynamic blocks allow the compressor to + * rapidly adapt to changing data with new codes optimized for that data. + * + * - The codes used by the deflate format are "canonical", which means that + * the actual bits of the codes are generated in an unambiguous way simply + * from the number of bits in each code. Therefore the code descriptions + * are simply a list of code lengths for each symbol. + * + * - The code lengths are stored in order for the symbols, so lengths are + * provided for each of the literal/length symbols, and for each of the + * distance symbols. + * + * - If a symbol is not used in the block, this is represented by a zero as + * as the code length. This does not mean a zero-length code, but rather + * that no code should be created for this symbol. There is no way in the + * deflate format to represent a zero-length code. + * + * - The maximum number of bits in a code is 15, so the possible lengths for + * any code are 1..15. + * + * - The fact that a length of zero is not permitted for a code has an + * interesting consequence. Normally if only one symbol is used for a given + * code, then in fact that code could be represented with zero bits. However + * in deflate, that code has to be at least one bit. So for example, if + * only a single distance base symbol appears in a block, then it will be + * represented by a single code of length one, in particular one 0 bit. This + * is an incomplete code, since if a 1 bit is received, it has no meaning, + * and should result in an error. So incomplete distance codes of one symbol + * should be permitted, and the receipt of invalid codes should be handled. + * + * - It is also possible to have a single literal/length code, but that code + * must be the end-of-block code, since every dynamic block has one. This + * is not the most efficient way to create an empty block (an empty fixed + * block is fewer bits), but it is allowed by the format. So incomplete + * literal/length codes of one symbol should also be permitted. + * + * - If there are only literal codes and no lengths, then there are no distance + * codes. This is represented by one distance code with zero bits. + * + * - The list of up to 286 length/literal lengths and up to 30 distance lengths + * are themselves compressed using Huffman codes and run-length encoding. In + * the list of code lengths, a 0 symbol means no code, a 1..15 symbol means + * that length, and the symbols 16, 17, and 18 are run-length instructions. + * Each of 16, 17, and 18 are follwed by extra bits to define the length of + * the run. 16 copies the last length 3 to 6 times. 17 represents 3 to 10 + * zero lengths, and 18 represents 11 to 138 zero lengths. Unused symbols + * are common, hence the special coding for zero lengths. + * + * - The symbols for 0..18 are Huffman coded, and so that code must be + * described first. This is simply a sequence of up to 19 three-bit values + * representing no code (0) or the code length for that symbol (1..7). + * + * - A dynamic block starts with three fixed-size counts from which is computed + * the number of literal/length code lengths, the number of distance code + * lengths, and the number of code length code lengths (ok, you come up with + * a better name!) in the code descriptions. For the literal/length and + * distance codes, lengths after those provided are considered zero, i.e. no + * code. The code length code lengths are received in a permuted order (see + * the order[] array below) to make a short code length code length list more + * likely. As it turns out, very short and very long codes are less likely + * to be seen in a dynamic code description, hence what may appear initially + * to be a peculiar ordering. + * + * - Given the number of literal/length code lengths (nlen) and distance code + * lengths (ndist), then they are treated as one long list of nlen + ndist + * code lengths. Therefore run-length coding can and often does cross the + * boundary between the two sets of lengths. + * + * - So to summarize, the code description at the start of a dynamic block is + * three counts for the number of code lengths for the literal/length codes, + * the distance codes, and the code length codes. This is followed by the + * code length code lengths, three bits each. This is used to construct the + * code length code which is used to read the remainder of the lengths. Then + * the literal/length code lengths and distance lengths are read as a single + * set of lengths using the code length codes. Codes are constructed from + * the resulting two sets of lengths, and then finally you can start + * decoding actual compressed data in the block. + * + * - For reference, a "typical" size for the code description in a dynamic + * block is around 80 bytes. + */ +local int dynamic(struct state *s) +{ + int nlen, ndist, ncode; /* number of lengths in descriptor */ + int index; /* index of lengths[] */ + int err; /* construct() return value */ + short lengths[MAXCODES]; /* descriptor code lengths */ + short lencnt[MAXBITS+1], lensym[MAXLCODES]; /* lencode memory */ + short distcnt[MAXBITS+1], distsym[MAXDCODES]; /* distcode memory */ + struct huffman lencode, distcode; /* length and distance codes */ + static const short order[19] = /* permutation of code length codes */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* construct lencode and distcode */ + lencode.count = lencnt; + lencode.symbol = lensym; + distcode.count = distcnt; + distcode.symbol = distsym; + + /* get number of lengths in each table, check lengths */ + nlen = bits(s, 5) + 257; + ndist = bits(s, 5) + 1; + ncode = bits(s, 4) + 4; + if (nlen > MAXLCODES || ndist > MAXDCODES) + return -3; /* bad counts */ + + /* read code length code lengths (really), missing lengths are zero */ + for (index = 0; index < ncode; index++) + lengths[order[index]] = bits(s, 3); + for (; index < 19; index++) + lengths[order[index]] = 0; + + /* build huffman table for code lengths codes (use lencode temporarily) */ + err = construct(&lencode, lengths, 19); + if (err != 0) /* require complete code set here */ + return -4; + + /* read length/literal and distance code length tables */ + index = 0; + while (index < nlen + ndist) { + int symbol; /* decoded value */ + int len; /* last length to repeat */ + + symbol = decode(s, &lencode); + if (symbol < 0) + return symbol; /* invalid symbol */ + if (symbol < 16) /* length in 0..15 */ + lengths[index++] = symbol; + else { /* repeat instruction */ + len = 0; /* assume repeating zeros */ + if (symbol == 16) { /* repeat last length 3..6 times */ + if (index == 0) + return -5; /* no last length! */ + len = lengths[index - 1]; /* last length */ + symbol = 3 + bits(s, 2); + } + else if (symbol == 17) /* repeat zero 3..10 times */ + symbol = 3 + bits(s, 3); + else /* == 18, repeat zero 11..138 times */ + symbol = 11 + bits(s, 7); + if (index + symbol > nlen + ndist) + return -6; /* too many lengths! */ + while (symbol--) /* repeat last or zero symbol times */ + lengths[index++] = len; + } + } + + /* check for end-of-block code -- there better be one! */ + if (lengths[256] == 0) + return -9; + + /* build huffman table for literal/length codes */ + err = construct(&lencode, lengths, nlen); + if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) + return -7; /* incomplete code ok only for single length 1 code */ + + /* build huffman table for distance codes */ + err = construct(&distcode, lengths + nlen, ndist); + if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) + return -8; /* incomplete code ok only for single length 1 code */ + + /* decode data until end-of-block code */ + return codes(s, &lencode, &distcode); +} + +/* + * Inflate source to dest. On return, destlen and sourcelen are updated to the + * size of the uncompressed data and the size of the deflate data respectively. + * On success, the return value of puff() is zero. If there is an error in the + * source data, i.e. it is not in the deflate format, then a negative value is + * returned. If there is not enough input available or there is not enough + * output space, then a positive error is returned. In that case, destlen and + * sourcelen are not updated to facilitate retrying from the beginning with the + * provision of more input data or more output space. In the case of invalid + * inflate data (a negative error), the dest and source pointers are updated to + * facilitate the debugging of deflators. + * + * puff() also has a mode to determine the size of the uncompressed output with + * no output written. For this dest must be (unsigned char *)0. In this case, + * the input value of *destlen is ignored, and on return *destlen is set to the + * size of the uncompressed output. + * + * The return codes are: + * + * 2: available inflate data did not terminate + * 1: output space exhausted before completing inflate + * 0: successful inflate + * -1: invalid block type (type == 3) + * -2: stored block length did not match one's complement + * -3: dynamic block code description: too many length or distance codes + * -4: dynamic block code description: code lengths codes incomplete + * -5: dynamic block code description: repeat lengths with no first length + * -6: dynamic block code description: repeat more than specified lengths + * -7: dynamic block code description: invalid literal/length code lengths + * -8: dynamic block code description: invalid distance code lengths + * -9: dynamic block code description: missing end-of-block code + * -10: invalid literal/length or distance code in fixed or dynamic block + * -11: distance is too far back in fixed or dynamic block + * + * Format notes: + * + * - Three bits are read for each block to determine the kind of block and + * whether or not it is the last block. Then the block is decoded and the + * process repeated if it was not the last block. + * + * - The leftover bits in the last byte of the deflate data after the last + * block (if it was a fixed or dynamic block) are undefined and have no + * expected values to check. + */ +int puff(unsigned char *dest, /* pointer to destination pointer */ + unsigned long *destlen, /* amount of output space */ + const unsigned char *source, /* pointer to source data pointer */ + unsigned long *sourcelen) /* amount of input available */ +{ + struct state s; /* input/output state */ + int last, type; /* block information */ + int err; /* return value */ + + /* initialize output state */ + s.out = dest; + s.outlen = *destlen; /* ignored if dest is NIL */ + s.outcnt = 0; + + /* initialize input state */ + s.in = source; + s.inlen = *sourcelen; + s.incnt = 0; + s.bitbuf = 0; + s.bitcnt = 0; + + /* return if bits() or decode() tries to read past available input */ + if (setjmp(s.env) != 0) /* if came back here via longjmp() */ + err = 2; /* then skip do-loop, return error */ + else { + /* process blocks until last block or error */ + do { + last = bits(&s, 1); /* one if last block */ + type = bits(&s, 2); /* block type 0..3 */ + err = type == 0 ? + stored(&s) : + (type == 1 ? + fixed(&s) : + (type == 2 ? + dynamic(&s) : + -1)); /* type == 3, invalid */ + if (err != 0) + break; /* return with error */ + } while (!last); + } + + /* update the lengths and return */ + if (err <= 0) { + *destlen = s.outcnt; + *sourcelen = s.incnt; + } + return err; +} diff --git a/third_party/zlib/v1_2_11/contrib/puff/puff.h b/third_party/zlib/v1_2_11/contrib/puff/puff.h new file mode 100644 index 0000000..e23a245 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/puff/puff.h @@ -0,0 +1,35 @@ +/* puff.h + Copyright (C) 2002-2013 Mark Adler, all rights reserved + version 2.3, 21 Jan 2013 + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Mark Adler madler@alumni.caltech.edu + */ + + +/* + * See puff.c for purpose and usage. + */ +#ifndef NIL +# define NIL ((unsigned char *)0) /* for no output option */ +#endif + +int puff(unsigned char *dest, /* pointer to destination pointer */ + unsigned long *destlen, /* amount of output space */ + const unsigned char *source, /* pointer to source data pointer */ + unsigned long *sourcelen); /* amount of input available */ diff --git a/third_party/zlib/v1_2_11/contrib/puff/pufftest.c b/third_party/zlib/v1_2_11/contrib/puff/pufftest.c new file mode 100644 index 0000000..7764814 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/puff/pufftest.c @@ -0,0 +1,165 @@ +/* + * pufftest.c + * Copyright (C) 2002-2013 Mark Adler + * For conditions of distribution and use, see copyright notice in puff.h + * version 2.3, 21 Jan 2013 + */ + +/* Example of how to use puff(). + + Usage: puff [-w] [-f] [-nnn] file + ... | puff [-w] [-f] [-nnn] + + where file is the input file with deflate data, nnn is the number of bytes + of input to skip before inflating (e.g. to skip a zlib or gzip header), and + -w is used to write the decompressed data to stdout. -f is for coverage + testing, and causes pufftest to fail with not enough output space (-f does + a write like -w, so -w is not required). */ + +#include +#include +#include "puff.h" + +#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) +# include +# include +# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif + +#define local static + +/* Return size times approximately the cube root of 2, keeping the result as 1, + 3, or 5 times a power of 2 -- the result is always > size, until the result + is the maximum value of an unsigned long, where it remains. This is useful + to keep reallocations less than ~33% over the actual data. */ +local size_t bythirds(size_t size) +{ + int n; + size_t m; + + m = size; + for (n = 0; m; n++) + m >>= 1; + if (n < 3) + return size + 1; + n -= 3; + m = size >> n; + m += m == 6 ? 2 : 1; + m <<= n; + return m > size ? m : (size_t)(-1); +} + +/* Read the input file *name, or stdin if name is NULL, into allocated memory. + Reallocate to larger buffers until the entire file is read in. Return a + pointer to the allocated data, or NULL if there was a memory allocation + failure. *len is the number of bytes of data read from the input file (even + if load() returns NULL). If the input file was empty or could not be opened + or read, *len is zero. */ +local void *load(const char *name, size_t *len) +{ + size_t size; + void *buf, *swap; + FILE *in; + + *len = 0; + buf = malloc(size = 4096); + if (buf == NULL) + return NULL; + in = name == NULL ? stdin : fopen(name, "rb"); + if (in != NULL) { + for (;;) { + *len += fread((char *)buf + *len, 1, size - *len, in); + if (*len < size) break; + size = bythirds(size); + if (size == *len || (swap = realloc(buf, size)) == NULL) { + free(buf); + buf = NULL; + break; + } + buf = swap; + } + fclose(in); + } + return buf; +} + +int main(int argc, char **argv) +{ + int ret, put = 0, fail = 0; + unsigned skip = 0; + char *arg, *name = NULL; + unsigned char *source = NULL, *dest; + size_t len = 0; + unsigned long sourcelen, destlen; + + /* process arguments */ + while (arg = *++argv, --argc) + if (arg[0] == '-') { + if (arg[1] == 'w' && arg[2] == 0) + put = 1; + else if (arg[1] == 'f' && arg[2] == 0) + fail = 1, put = 1; + else if (arg[1] >= '0' && arg[1] <= '9') + skip = (unsigned)atoi(arg + 1); + else { + fprintf(stderr, "invalid option %s\n", arg); + return 3; + } + } + else if (name != NULL) { + fprintf(stderr, "only one file name allowed\n"); + return 3; + } + else + name = arg; + source = load(name, &len); + if (source == NULL) { + fprintf(stderr, "memory allocation failure\n"); + return 4; + } + if (len == 0) { + fprintf(stderr, "could not read %s, or it was empty\n", + name == NULL ? "" : name); + free(source); + return 3; + } + if (skip >= len) { + fprintf(stderr, "skip request of %d leaves no input\n", skip); + free(source); + return 3; + } + + /* test inflate data with offset skip */ + len -= skip; + sourcelen = (unsigned long)len; + ret = puff(NIL, &destlen, source + skip, &sourcelen); + if (ret) + fprintf(stderr, "puff() failed with return code %d\n", ret); + else { + fprintf(stderr, "puff() succeeded uncompressing %lu bytes\n", destlen); + if (sourcelen < len) fprintf(stderr, "%lu compressed bytes unused\n", + len - sourcelen); + } + + /* if requested, inflate again and write decompressd data to stdout */ + if (put && ret == 0) { + if (fail) + destlen >>= 1; + dest = malloc(destlen); + if (dest == NULL) { + fprintf(stderr, "memory allocation failure\n"); + free(source); + return 4; + } + puff(dest, &destlen, source + skip, &sourcelen); + SET_BINARY_MODE(stdout); + fwrite(dest, 1, destlen, stdout); + free(dest); + } + + /* clean up */ + free(source); + return ret; +} diff --git a/third_party/zlib/v1_2_11/contrib/puff/zeros.raw b/third_party/zlib/v1_2_11/contrib/puff/zeros.raw new file mode 100644 index 0000000..0a90e76 Binary files /dev/null and b/third_party/zlib/v1_2_11/contrib/puff/zeros.raw differ diff --git a/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.c b/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.c new file mode 100644 index 0000000..5f659de --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.c @@ -0,0 +1,275 @@ +#include +#include +#include + +#include "zlib.h" + + +void MyDoMinus64(LARGE_INTEGER *R,LARGE_INTEGER A,LARGE_INTEGER B) +{ + R->HighPart = A.HighPart - B.HighPart; + if (A.LowPart >= B.LowPart) + R->LowPart = A.LowPart - B.LowPart; + else + { + R->LowPart = A.LowPart - B.LowPart; + R->HighPart --; + } +} + +#ifdef _M_X64 +// see http://msdn2.microsoft.com/library/twchhe95(en-us,vs.80).aspx for __rdtsc +unsigned __int64 __rdtsc(void); +void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) +{ + // printf("rdtsc = %I64x\n",__rdtsc()); + pbeginTime64->QuadPart=__rdtsc(); +} + +LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) +{ + LARGE_INTEGER LIres; + unsigned _int64 res=__rdtsc()-((unsigned _int64)(beginTime64.QuadPart)); + LIres.QuadPart=res; + // printf("rdtsc = %I64x\n",__rdtsc()); + return LIres; +} +#else +#ifdef _M_IX86 +void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) +{ + DWORD dwEdx,dwEax; + _asm + { + rdtsc + mov dwEax,eax + mov dwEdx,edx + } + pbeginTime64->LowPart=dwEax; + pbeginTime64->HighPart=dwEdx; +} + +void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) +{ + myGetRDTSC32(pbeginTime64); +} + +LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) +{ + LARGE_INTEGER LIres,endTime64; + myGetRDTSC32(&endTime64); + + LIres.LowPart=LIres.HighPart=0; + MyDoMinus64(&LIres,endTime64,beginTime64); + return LIres; +} +#else +void myGetRDTSC32(LARGE_INTEGER * pbeginTime64) +{ +} + +void BeginCountRdtsc(LARGE_INTEGER * pbeginTime64) +{ +} + +LARGE_INTEGER GetResRdtsc(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) +{ + LARGE_INTEGER lr; + lr.QuadPart=0; + return lr; +} +#endif +#endif + +void BeginCountPerfCounter(LARGE_INTEGER * pbeginTime64,BOOL fComputeTimeQueryPerf) +{ + if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(pbeginTime64))) + { + pbeginTime64->LowPart = GetTickCount(); + pbeginTime64->HighPart = 0; + } +} + +DWORD GetMsecSincePerfCounter(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPerf) +{ + LARGE_INTEGER endTime64,ticksPerSecond,ticks; + DWORDLONG ticksShifted,tickSecShifted; + DWORD dwLog=16+0; + DWORD dwRet; + if ((!fComputeTimeQueryPerf) || (!QueryPerformanceCounter(&endTime64))) + dwRet = (GetTickCount() - beginTime64.LowPart)*1; + else + { + MyDoMinus64(&ticks,endTime64,beginTime64); + QueryPerformanceFrequency(&ticksPerSecond); + + + { + ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog); + tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog); + + } + + dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted)); + dwRet *=1; + } + return dwRet; +} + +int ReadFileMemory(const char* filename,long* plFileSize,unsigned char** pFilePtr) +{ + FILE* stream; + unsigned char* ptr; + int retVal=1; + stream=fopen(filename, "rb"); + if (stream==NULL) + return 0; + + fseek(stream,0,SEEK_END); + + *plFileSize=ftell(stream); + fseek(stream,0,SEEK_SET); + ptr=malloc((*plFileSize)+1); + if (ptr==NULL) + retVal=0; + else + { + if (fread(ptr, 1, *plFileSize,stream) != (*plFileSize)) + retVal=0; + } + fclose(stream); + *pFilePtr=ptr; + return retVal; +} + +int main(int argc, char *argv[]) +{ + int BlockSizeCompress=0x8000; + int BlockSizeUncompress=0x8000; + int cprLevel=Z_DEFAULT_COMPRESSION ; + long lFileSize; + unsigned char* FilePtr; + long lBufferSizeCpr; + long lBufferSizeUncpr; + long lCompressedSize=0; + unsigned char* CprPtr; + unsigned char* UncprPtr; + long lSizeCpr,lSizeUncpr; + DWORD dwGetTick,dwMsecQP; + LARGE_INTEGER li_qp,li_rdtsc,dwResRdtsc; + + if (argc<=1) + { + printf("run TestZlib [BlockSizeCompress] [BlockSizeUncompress] [compres. level]\n"); + return 0; + } + + if (ReadFileMemory(argv[1],&lFileSize,&FilePtr)==0) + { + printf("error reading %s\n",argv[1]); + return 1; + } + else printf("file %s read, %u bytes\n",argv[1],lFileSize); + + if (argc>=3) + BlockSizeCompress=atol(argv[2]); + + if (argc>=4) + BlockSizeUncompress=atol(argv[3]); + + if (argc>=5) + cprLevel=(int)atol(argv[4]); + + lBufferSizeCpr = lFileSize + (lFileSize/0x10) + 0x200; + lBufferSizeUncpr = lBufferSizeCpr; + + CprPtr=(unsigned char*)malloc(lBufferSizeCpr + BlockSizeCompress); + + BeginCountPerfCounter(&li_qp,TRUE); + dwGetTick=GetTickCount(); + BeginCountRdtsc(&li_rdtsc); + { + z_stream zcpr; + int ret=Z_OK; + long lOrigToDo = lFileSize; + long lOrigDone = 0; + int step=0; + memset(&zcpr,0,sizeof(z_stream)); + deflateInit(&zcpr,cprLevel); + + zcpr.next_in = FilePtr; + zcpr.next_out = CprPtr; + + + do + { + long all_read_before = zcpr.total_in; + zcpr.avail_in = min(lOrigToDo,BlockSizeCompress); + zcpr.avail_out = BlockSizeCompress; + ret=deflate(&zcpr,(zcpr.avail_in==lOrigToDo) ? Z_FINISH : Z_SYNC_FLUSH); + lOrigDone += (zcpr.total_in-all_read_before); + lOrigToDo -= (zcpr.total_in-all_read_before); + step++; + } while (ret==Z_OK); + + lSizeCpr=zcpr.total_out; + deflateEnd(&zcpr); + dwGetTick=GetTickCount()-dwGetTick; + dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); + dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); + printf("total compress size = %u, in %u step\n",lSizeCpr,step); + printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); + printf("defcpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); + printf("defcpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); + } + + CprPtr=(unsigned char*)realloc(CprPtr,lSizeCpr); + UncprPtr=(unsigned char*)malloc(lBufferSizeUncpr + BlockSizeUncompress); + + BeginCountPerfCounter(&li_qp,TRUE); + dwGetTick=GetTickCount(); + BeginCountRdtsc(&li_rdtsc); + { + z_stream zcpr; + int ret=Z_OK; + long lOrigToDo = lSizeCpr; + long lOrigDone = 0; + int step=0; + memset(&zcpr,0,sizeof(z_stream)); + inflateInit(&zcpr); + + zcpr.next_in = CprPtr; + zcpr.next_out = UncprPtr; + + + do + { + long all_read_before = zcpr.total_in; + zcpr.avail_in = min(lOrigToDo,BlockSizeUncompress); + zcpr.avail_out = BlockSizeUncompress; + ret=inflate(&zcpr,Z_SYNC_FLUSH); + lOrigDone += (zcpr.total_in-all_read_before); + lOrigToDo -= (zcpr.total_in-all_read_before); + step++; + } while (ret==Z_OK); + + lSizeUncpr=zcpr.total_out; + inflateEnd(&zcpr); + dwGetTick=GetTickCount()-dwGetTick; + dwMsecQP=GetMsecSincePerfCounter(li_qp,TRUE); + dwResRdtsc=GetResRdtsc(li_rdtsc,TRUE); + printf("total uncompress size = %u, in %u step\n",lSizeUncpr,step); + printf("time = %u msec = %f sec\n",dwGetTick,dwGetTick/(double)1000.); + printf("uncpr time QP = %u msec = %f sec\n",dwMsecQP,dwMsecQP/(double)1000.); + printf("uncpr result rdtsc = %I64x\n\n",dwResRdtsc.QuadPart); + } + + if (lSizeUncpr==lFileSize) + { + if (memcmp(FilePtr,UncprPtr,lFileSize)==0) + printf("compare ok\n"); + + } + + return 0; +} diff --git a/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.txt b/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.txt new file mode 100644 index 0000000..62258f1 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/testzlib/testzlib.txt @@ -0,0 +1,10 @@ +To build testzLib with Visual Studio 2005: + +copy to a directory file from : +- root of zLib tree +- contrib/testzlib +- contrib/masmx86 +- contrib/masmx64 +- contrib/vstudio/vc7 + +and open testzlib8.sln \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/untgz/Makefile b/third_party/zlib/v1_2_11/contrib/untgz/Makefile new file mode 100644 index 0000000..b54266f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/untgz/Makefile @@ -0,0 +1,14 @@ +CC=cc +CFLAGS=-g + +untgz: untgz.o ../../libz.a + $(CC) $(CFLAGS) -o untgz untgz.o -L../.. -lz + +untgz.o: untgz.c ../../zlib.h + $(CC) $(CFLAGS) -c -I../.. untgz.c + +../../libz.a: + cd ../..; ./configure; make + +clean: + rm -f untgz untgz.o *~ diff --git a/third_party/zlib/v1_2_11/contrib/untgz/Makefile.msc b/third_party/zlib/v1_2_11/contrib/untgz/Makefile.msc new file mode 100644 index 0000000..77b8602 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/untgz/Makefile.msc @@ -0,0 +1,17 @@ +CC=cl +CFLAGS=-MD + +untgz.exe: untgz.obj ..\..\zlib.lib + $(CC) $(CFLAGS) untgz.obj ..\..\zlib.lib + +untgz.obj: untgz.c ..\..\zlib.h + $(CC) $(CFLAGS) -c -I..\.. untgz.c + +..\..\zlib.lib: + cd ..\.. + $(MAKE) -f win32\makefile.msc + cd contrib\untgz + +clean: + -del untgz.obj + -del untgz.exe diff --git a/third_party/zlib/v1_2_11/contrib/untgz/untgz.c b/third_party/zlib/v1_2_11/contrib/untgz/untgz.c new file mode 100644 index 0000000..2c391e5 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/untgz/untgz.c @@ -0,0 +1,674 @@ +/* + * untgz.c -- Display contents and extract files from a gzip'd TAR file + * + * written by Pedro A. Aranda Gutierrez + * adaptation to Unix by Jean-loup Gailly + * various fixes by Cosmin Truta + */ + +#include +#include +#include +#include +#include + +#include "zlib.h" + +#ifdef unix +# include +#else +# include +# include +#endif + +#ifdef WIN32 +#include +# ifndef F_OK +# define F_OK 0 +# endif +# define mkdir(dirname,mode) _mkdir(dirname) +# ifdef _MSC_VER +# define access(path,mode) _access(path,mode) +# define chmod(path,mode) _chmod(path,mode) +# define strdup(str) _strdup(str) +# endif +#else +# include +#endif + + +/* values used in typeflag field */ + +#define REGTYPE '0' /* regular file */ +#define AREGTYPE '\0' /* regular file */ +#define LNKTYPE '1' /* link */ +#define SYMTYPE '2' /* reserved */ +#define CHRTYPE '3' /* character special */ +#define BLKTYPE '4' /* block special */ +#define DIRTYPE '5' /* directory */ +#define FIFOTYPE '6' /* FIFO special */ +#define CONTTYPE '7' /* reserved */ + +/* GNU tar extensions */ + +#define GNUTYPE_DUMPDIR 'D' /* file names from dumped directory */ +#define GNUTYPE_LONGLINK 'K' /* long link name */ +#define GNUTYPE_LONGNAME 'L' /* long file name */ +#define GNUTYPE_MULTIVOL 'M' /* continuation of file from another volume */ +#define GNUTYPE_NAMES 'N' /* file name that does not fit into main hdr */ +#define GNUTYPE_SPARSE 'S' /* sparse file */ +#define GNUTYPE_VOLHDR 'V' /* tape/volume header */ + + +/* tar header */ + +#define BLOCKSIZE 512 +#define SHORTNAMESIZE 100 + +struct tar_header +{ /* byte offset */ + char name[100]; /* 0 */ + char mode[8]; /* 100 */ + char uid[8]; /* 108 */ + char gid[8]; /* 116 */ + char size[12]; /* 124 */ + char mtime[12]; /* 136 */ + char chksum[8]; /* 148 */ + char typeflag; /* 156 */ + char linkname[100]; /* 157 */ + char magic[6]; /* 257 */ + char version[2]; /* 263 */ + char uname[32]; /* 265 */ + char gname[32]; /* 297 */ + char devmajor[8]; /* 329 */ + char devminor[8]; /* 337 */ + char prefix[155]; /* 345 */ + /* 500 */ +}; + +union tar_buffer +{ + char buffer[BLOCKSIZE]; + struct tar_header header; +}; + +struct attr_item +{ + struct attr_item *next; + char *fname; + int mode; + time_t time; +}; + +enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID }; + +char *TGZfname OF((const char *)); +void TGZnotfound OF((const char *)); + +int getoct OF((char *, int)); +char *strtime OF((time_t *)); +int setfiletime OF((char *, time_t)); +void push_attr OF((struct attr_item **, char *, int, time_t)); +void restore_attr OF((struct attr_item **)); + +int ExprMatch OF((char *, char *)); + +int makedir OF((char *)); +int matchname OF((int, int, char **, char *)); + +void error OF((const char *)); +int tar OF((gzFile, int, int, int, char **)); + +void help OF((int)); +int main OF((int, char **)); + +char *prog; + +const char *TGZsuffix[] = { "\0", ".tar", ".tar.gz", ".taz", ".tgz", NULL }; + +/* return the file name of the TGZ archive */ +/* or NULL if it does not exist */ + +char *TGZfname (const char *arcname) +{ + static char buffer[1024]; + int origlen,i; + + strcpy(buffer,arcname); + origlen = strlen(buffer); + + for (i=0; TGZsuffix[i]; i++) + { + strcpy(buffer+origlen,TGZsuffix[i]); + if (access(buffer,F_OK) == 0) + return buffer; + } + return NULL; +} + + +/* error message for the filename */ + +void TGZnotfound (const char *arcname) +{ + int i; + + fprintf(stderr,"%s: Couldn't find ",prog); + for (i=0;TGZsuffix[i];i++) + fprintf(stderr,(TGZsuffix[i+1]) ? "%s%s, " : "or %s%s\n", + arcname, + TGZsuffix[i]); + exit(1); +} + + +/* convert octal digits to int */ +/* on error return -1 */ + +int getoct (char *p,int width) +{ + int result = 0; + char c; + + while (width--) + { + c = *p++; + if (c == 0) + break; + if (c == ' ') + continue; + if (c < '0' || c > '7') + return -1; + result = result * 8 + (c - '0'); + } + return result; +} + + +/* convert time_t to string */ +/* use the "YYYY/MM/DD hh:mm:ss" format */ + +char *strtime (time_t *t) +{ + struct tm *local; + static char result[32]; + + local = localtime(t); + sprintf(result,"%4d/%02d/%02d %02d:%02d:%02d", + local->tm_year+1900, local->tm_mon+1, local->tm_mday, + local->tm_hour, local->tm_min, local->tm_sec); + return result; +} + + +/* set file time */ + +int setfiletime (char *fname,time_t ftime) +{ +#ifdef WIN32 + static int isWinNT = -1; + SYSTEMTIME st; + FILETIME locft, modft; + struct tm *loctm; + HANDLE hFile; + int result; + + loctm = localtime(&ftime); + if (loctm == NULL) + return -1; + + st.wYear = (WORD)loctm->tm_year + 1900; + st.wMonth = (WORD)loctm->tm_mon + 1; + st.wDayOfWeek = (WORD)loctm->tm_wday; + st.wDay = (WORD)loctm->tm_mday; + st.wHour = (WORD)loctm->tm_hour; + st.wMinute = (WORD)loctm->tm_min; + st.wSecond = (WORD)loctm->tm_sec; + st.wMilliseconds = 0; + if (!SystemTimeToFileTime(&st, &locft) || + !LocalFileTimeToFileTime(&locft, &modft)) + return -1; + + if (isWinNT < 0) + isWinNT = (GetVersion() < 0x80000000) ? 1 : 0; + hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, + (isWinNT ? FILE_FLAG_BACKUP_SEMANTICS : 0), + NULL); + if (hFile == INVALID_HANDLE_VALUE) + return -1; + result = SetFileTime(hFile, NULL, NULL, &modft) ? 0 : -1; + CloseHandle(hFile); + return result; +#else + struct utimbuf settime; + + settime.actime = settime.modtime = ftime; + return utime(fname,&settime); +#endif +} + + +/* push file attributes */ + +void push_attr(struct attr_item **list,char *fname,int mode,time_t time) +{ + struct attr_item *item; + + item = (struct attr_item *)malloc(sizeof(struct attr_item)); + if (item == NULL) + error("Out of memory"); + item->fname = strdup(fname); + item->mode = mode; + item->time = time; + item->next = *list; + *list = item; +} + + +/* restore file attributes */ + +void restore_attr(struct attr_item **list) +{ + struct attr_item *item, *prev; + + for (item = *list; item != NULL; ) + { + setfiletime(item->fname,item->time); + chmod(item->fname,item->mode); + prev = item; + item = item->next; + free(prev); + } + *list = NULL; +} + + +/* match regular expression */ + +#define ISSPECIAL(c) (((c) == '*') || ((c) == '/')) + +int ExprMatch (char *string,char *expr) +{ + while (1) + { + if (ISSPECIAL(*expr)) + { + if (*expr == '/') + { + if (*string != '\\' && *string != '/') + return 0; + string ++; expr++; + } + else if (*expr == '*') + { + if (*expr ++ == 0) + return 1; + while (*++string != *expr) + if (*string == 0) + return 0; + } + } + else + { + if (*string != *expr) + return 0; + if (*expr++ == 0) + return 1; + string++; + } + } +} + + +/* recursive mkdir */ +/* abort on ENOENT; ignore other errors like "directory already exists" */ +/* return 1 if OK */ +/* 0 on error */ + +int makedir (char *newdir) +{ + char *buffer = strdup(newdir); + char *p; + int len = strlen(buffer); + + if (len <= 0) { + free(buffer); + return 0; + } + if (buffer[len-1] == '/') { + buffer[len-1] = '\0'; + } + if (mkdir(buffer, 0755) == 0) + { + free(buffer); + return 1; + } + + p = buffer+1; + while (1) + { + char hold; + + while(*p && *p != '\\' && *p != '/') + p++; + hold = *p; + *p = 0; + if ((mkdir(buffer, 0755) == -1) && (errno == ENOENT)) + { + fprintf(stderr,"%s: Couldn't create directory %s\n",prog,buffer); + free(buffer); + return 0; + } + if (hold == 0) + break; + *p++ = hold; + } + free(buffer); + return 1; +} + + +int matchname (int arg,int argc,char **argv,char *fname) +{ + if (arg == argc) /* no arguments given (untgz tgzarchive) */ + return 1; + + while (arg < argc) + if (ExprMatch(fname,argv[arg++])) + return 1; + + return 0; /* ignore this for the moment being */ +} + + +/* tar file list or extract */ + +int tar (gzFile in,int action,int arg,int argc,char **argv) +{ + union tar_buffer buffer; + int len; + int err; + int getheader = 1; + int remaining = 0; + FILE *outfile = NULL; + char fname[BLOCKSIZE]; + int tarmode; + time_t tartime; + struct attr_item *attributes = NULL; + + if (action == TGZ_LIST) + printf(" date time size file\n" + " ---------- -------- --------- -------------------------------------\n"); + while (1) + { + len = gzread(in, &buffer, BLOCKSIZE); + if (len < 0) + error(gzerror(in, &err)); + /* + * Always expect complete blocks to process + * the tar information. + */ + if (len != BLOCKSIZE) + { + action = TGZ_INVALID; /* force error exit */ + remaining = 0; /* force I/O cleanup */ + } + + /* + * If we have to get a tar header + */ + if (getheader >= 1) + { + /* + * if we met the end of the tar + * or the end-of-tar block, + * we are done + */ + if (len == 0 || buffer.header.name[0] == 0) + break; + + tarmode = getoct(buffer.header.mode,8); + tartime = (time_t)getoct(buffer.header.mtime,12); + if (tarmode == -1 || tartime == (time_t)-1) + { + buffer.header.name[0] = 0; + action = TGZ_INVALID; + } + + if (getheader == 1) + { + strncpy(fname,buffer.header.name,SHORTNAMESIZE); + if (fname[SHORTNAMESIZE-1] != 0) + fname[SHORTNAMESIZE] = 0; + } + else + { + /* + * The file name is longer than SHORTNAMESIZE + */ + if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0) + error("bad long name"); + getheader = 1; + } + + /* + * Act according to the type flag + */ + switch (buffer.header.typeflag) + { + case DIRTYPE: + if (action == TGZ_LIST) + printf(" %s %s\n",strtime(&tartime),fname); + if (action == TGZ_EXTRACT) + { + makedir(fname); + push_attr(&attributes,fname,tarmode,tartime); + } + break; + case REGTYPE: + case AREGTYPE: + remaining = getoct(buffer.header.size,12); + if (remaining == -1) + { + action = TGZ_INVALID; + break; + } + if (action == TGZ_LIST) + printf(" %s %9d %s\n",strtime(&tartime),remaining,fname); + else if (action == TGZ_EXTRACT) + { + if (matchname(arg,argc,argv,fname)) + { + outfile = fopen(fname,"wb"); + if (outfile == NULL) { + /* try creating directory */ + char *p = strrchr(fname, '/'); + if (p != NULL) { + *p = '\0'; + makedir(fname); + *p = '/'; + outfile = fopen(fname,"wb"); + } + } + if (outfile != NULL) + printf("Extracting %s\n",fname); + else + fprintf(stderr, "%s: Couldn't create %s",prog,fname); + } + else + outfile = NULL; + } + getheader = 0; + break; + case GNUTYPE_LONGLINK: + case GNUTYPE_LONGNAME: + remaining = getoct(buffer.header.size,12); + if (remaining < 0 || remaining >= BLOCKSIZE) + { + action = TGZ_INVALID; + break; + } + len = gzread(in, fname, BLOCKSIZE); + if (len < 0) + error(gzerror(in, &err)); + if (fname[BLOCKSIZE-1] != 0 || (int)strlen(fname) > remaining) + { + action = TGZ_INVALID; + break; + } + getheader = 2; + break; + default: + if (action == TGZ_LIST) + printf(" %s <---> %s\n",strtime(&tartime),fname); + break; + } + } + else + { + unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining; + + if (outfile != NULL) + { + if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) + { + fprintf(stderr, + "%s: Error writing %s -- skipping\n",prog,fname); + fclose(outfile); + outfile = NULL; + remove(fname); + } + } + remaining -= bytes; + } + + if (remaining == 0) + { + getheader = 1; + if (outfile != NULL) + { + fclose(outfile); + outfile = NULL; + if (action != TGZ_INVALID) + push_attr(&attributes,fname,tarmode,tartime); + } + } + + /* + * Abandon if errors are found + */ + if (action == TGZ_INVALID) + { + error("broken archive"); + break; + } + } + + /* + * Restore file modes and time stamps + */ + restore_attr(&attributes); + + if (gzclose(in) != Z_OK) + error("failed gzclose"); + + return 0; +} + + +/* ============================================================ */ + +void help(int exitval) +{ + printf("untgz version 0.2.1\n" + " using zlib version %s\n\n", + zlibVersion()); + printf("Usage: untgz file.tgz extract all files\n" + " untgz file.tgz fname ... extract selected files\n" + " untgz -l file.tgz list archive contents\n" + " untgz -h display this help\n"); + exit(exitval); +} + +void error(const char *msg) +{ + fprintf(stderr, "%s: %s\n", prog, msg); + exit(1); +} + + +/* ============================================================ */ + +#if defined(WIN32) && defined(__GNUC__) +int _CRT_glob = 0; /* disable argument globbing in MinGW */ +#endif + +int main(int argc,char **argv) +{ + int action = TGZ_EXTRACT; + int arg = 1; + char *TGZfile; + gzFile *f; + + prog = strrchr(argv[0],'\\'); + if (prog == NULL) + { + prog = strrchr(argv[0],'/'); + if (prog == NULL) + { + prog = strrchr(argv[0],':'); + if (prog == NULL) + prog = argv[0]; + else + prog++; + } + else + prog++; + } + else + prog++; + + if (argc == 1) + help(0); + + if (strcmp(argv[arg],"-l") == 0) + { + action = TGZ_LIST; + if (argc == ++arg) + help(0); + } + else if (strcmp(argv[arg],"-h") == 0) + { + help(0); + } + + if ((TGZfile = TGZfname(argv[arg])) == NULL) + TGZnotfound(argv[arg]); + + ++arg; + if ((action == TGZ_LIST) && (arg != argc)) + help(1); + +/* + * Process the TGZ file + */ + switch(action) + { + case TGZ_LIST: + case TGZ_EXTRACT: + f = gzopen(TGZfile,"rb"); + if (f == NULL) + { + fprintf(stderr,"%s: Couldn't gzopen %s\n",prog,TGZfile); + return 1; + } + exit(tar(f, action, arg, argc, argv)); + break; + + default: + error("Unknown option"); + exit(1); + } + + return 0; +} diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/readme.txt b/third_party/zlib/v1_2_11/contrib/vstudio/readme.txt new file mode 100644 index 0000000..f67eae8 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/readme.txt @@ -0,0 +1,78 @@ +Building instructions for the DLL versions of Zlib 1.2.11 +======================================================== + +This directory contains projects that build zlib and minizip using +Microsoft Visual C++ 9.0/10.0. + +You don't need to build these projects yourself. You can download the +binaries from: + http://www.winimage.com/zLibDll + +More information can be found at this site. + + + + + +Build instructions for Visual Studio 2008 (32 bits or 64 bits) +-------------------------------------------------------------- +- Decompress current zlib, including all contrib/* files +- Compile assembly code (with Visual Studio Command Prompt) by running: + bld_ml64.bat (in contrib\masmx64) + bld_ml32.bat (in contrib\masmx86) +- Open contrib\vstudio\vc9\zlibvc.sln with Microsoft Visual C++ 2008 +- Or run: vcbuild /rebuild contrib\vstudio\vc9\zlibvc.sln "Release|Win32" + +Build instructions for Visual Studio 2010 (32 bits or 64 bits) +-------------------------------------------------------------- +- Decompress current zlib, including all contrib/* files +- Open contrib\vstudio\vc10\zlibvc.sln with Microsoft Visual C++ 2010 + +Build instructions for Visual Studio 2012 (32 bits or 64 bits) +-------------------------------------------------------------- +- Decompress current zlib, including all contrib/* files +- Open contrib\vstudio\vc11\zlibvc.sln with Microsoft Visual C++ 2012 + +Build instructions for Visual Studio 2013 (32 bits or 64 bits) +-------------------------------------------------------------- +- Decompress current zlib, including all contrib/* files +- Open contrib\vstudio\vc12\zlibvc.sln with Microsoft Visual C++ 2013 + +Build instructions for Visual Studio 2015 (32 bits or 64 bits) +-------------------------------------------------------------- +- Decompress current zlib, including all contrib/* files +- Open contrib\vstudio\vc14\zlibvc.sln with Microsoft Visual C++ 2015 + + +Important +--------- +- To use zlibwapi.dll in your application, you must define the + macro ZLIB_WINAPI when compiling your application's source files. + + +Additional notes +---------------- +- This DLL, named zlibwapi.dll, is compatible to the old zlib.dll built + by Gilles Vollant from the zlib 1.1.x sources, and distributed at + http://www.winimage.com/zLibDll + It uses the WINAPI calling convention for the exported functions, and + includes the minizip functionality. If your application needs that + particular build of zlib.dll, you can rename zlibwapi.dll to zlib.dll. + +- The new DLL was renamed because there exist several incompatible + versions of zlib.dll on the Internet. + +- There is also an official DLL build of zlib, named zlib1.dll. This one + is exporting the functions using the CDECL convention. See the file + win32\DLL_FAQ.txt found in this zlib distribution. + +- There used to be a ZLIB_DLL macro in zlib 1.1.x, but now this symbol + has a slightly different effect. To avoid compatibility problems, do + not define it here. + + +Gilles Vollant +info@winimage.com + +Visual Studio 2013 and 2015 Projects from Sean Hunt +seandhunt_7@yahoo.com diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj new file mode 100644 index 0000000..74e15c9 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj @@ -0,0 +1,310 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694382A} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + true + false + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + false + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + true + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + true + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + false + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebug + false + + + $(IntDir) + Level3 + EditAndContinue + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj.filters new file mode 100644 index 0000000..0b2a3de --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/miniunz.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {048af943-022b-4db6-beeb-a54c34774ee2} + cpp;c;cxx;def;odl;idl;hpj;bat;asm + + + {c1d600d2-888f-4aea-b73e-8b0dd9befa0c} + h;hpp;hxx;hm;inl;inc + + + {0844199a-966b-4f19-81db-1e0125e141b9} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj new file mode 100644 index 0000000..917e156 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj @@ -0,0 +1,307 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + true + false + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + false + x64\$(Configuration)\ + x64\$(Configuration)\ + true + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + true + false + x64\$(Configuration)\ + x64\$(Configuration)\ + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebug + false + + + $(IntDir) + Level3 + EditAndContinue + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj.filters new file mode 100644 index 0000000..dd73cd3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/minizip.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {c0419b40-bf50-40da-b153-ff74215b79de} + cpp;c;cxx;def;odl;idl;hpj;bat;asm + + + {bb87b070-735b-478e-92ce-7383abb2f36c} + h;hpp;hxx;hm;inl;inc + + + {f46ab6a6-548f-43cb-ae96-681abb5bd5db} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj new file mode 100644 index 0000000..9088d17 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj @@ -0,0 +1,420 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B} + testzlib + Win32Proj + + + + Application + MultiByte + true + + + Application + MultiByte + true + + + Application + MultiByte + + + Application + MultiByte + true + + + Application + MultiByte + true + + + Application + MultiByte + + + Application + true + + + Application + true + + + Application + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + true + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + true + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebug + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + EditAndContinue + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDebugDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + %(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj.filters new file mode 100644 index 0000000..249daa8 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlib.vcxproj.filters @@ -0,0 +1,58 @@ + + + + + {c1f6a2e3-5da5-4955-8653-310d3efe05a9} + cpp;c;cxx;def;odl;idl;hpj;bat;asm + + + {c2aaffdc-2c95-4d6f-8466-4bec5890af2c} + h;hpp;hxx;hm;inl;inc + + + {c274fe07-05f2-461c-964b-f6341e4e7eb5} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj new file mode 100644 index 0000000..bcb08ff --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj @@ -0,0 +1,310 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694366A} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + true + false + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + false + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + true + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + true + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + false + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebug + false + + + $(IntDir) + Level3 + EditAndContinue + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj.filters new file mode 100644 index 0000000..53a8693 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/testzlibdll.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {fa61a89f-93fc-4c89-b29e-36224b7592f4} + cpp;c;cxx;def;odl;idl;hpj;bat;asm + + + {d4b85da0-2ba2-4934-b57f-e2584e3848ee} + h;hpp;hxx;hm;inl;inc + + + {e573e075-00bd-4a7d-bd67-a8cc9bfc5aca} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlib.rc b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlib.rc new file mode 100644 index 0000000..fee177a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlib.rc @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1, 2, 11, 0 + PRODUCTVERSION 1, 2, 11, 0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" + VALUE "FileVersion", "1.2.11\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlibwapi.dll\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj new file mode 100644 index 0000000..b9f2bbe --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj @@ -0,0 +1,473 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8} + + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + + + MultiThreadedDebug + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + Itanium + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj.filters new file mode 100644 index 0000000..c8c7f7e --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibstat.vcxproj.filters @@ -0,0 +1,77 @@ + + + + + {174213f6-7f66-4ae8-a3a8-a1e0a1e6ffdd} + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Source Files + + + + + Source Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.def b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.def new file mode 100644 index 0000000..54e683d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.def @@ -0,0 +1,153 @@ +LIBRARY +; zlib data compression and ZIP file I/O library + +VERSION 1.2 + +EXPORTS + adler32 @1 + compress @2 + crc32 @3 + deflate @4 + deflateCopy @5 + deflateEnd @6 + deflateInit2_ @7 + deflateInit_ @8 + deflateParams @9 + deflateReset @10 + deflateSetDictionary @11 + gzclose @12 + gzdopen @13 + gzerror @14 + gzflush @15 + gzopen @16 + gzread @17 + gzwrite @18 + inflate @19 + inflateEnd @20 + inflateInit2_ @21 + inflateInit_ @22 + inflateReset @23 + inflateSetDictionary @24 + inflateSync @25 + uncompress @26 + zlibVersion @27 + gzprintf @28 + gzputc @29 + gzgetc @30 + gzseek @31 + gzrewind @32 + gztell @33 + gzeof @34 + gzsetparams @35 + zError @36 + inflateSyncPoint @37 + get_crc_table @38 + compress2 @39 + gzputs @40 + gzgets @41 + inflateCopy @42 + inflateBackInit_ @43 + inflateBack @44 + inflateBackEnd @45 + compressBound @46 + deflateBound @47 + gzclearerr @48 + gzungetc @49 + zlibCompileFlags @50 + deflatePrime @51 + deflatePending @52 + + unzOpen @61 + unzClose @62 + unzGetGlobalInfo @63 + unzGetCurrentFileInfo @64 + unzGoToFirstFile @65 + unzGoToNextFile @66 + unzOpenCurrentFile @67 + unzReadCurrentFile @68 + unzOpenCurrentFile3 @69 + unztell @70 + unzeof @71 + unzCloseCurrentFile @72 + unzGetGlobalComment @73 + unzStringFileNameCompare @74 + unzLocateFile @75 + unzGetLocalExtrafield @76 + unzOpen2 @77 + unzOpenCurrentFile2 @78 + unzOpenCurrentFilePassword @79 + + zipOpen @80 + zipOpenNewFileInZip @81 + zipWriteInFileInZip @82 + zipCloseFileInZip @83 + zipClose @84 + zipOpenNewFileInZip2 @86 + zipCloseFileInZipRaw @87 + zipOpen2 @88 + zipOpenNewFileInZip3 @89 + + unzGetFilePos @100 + unzGoToFilePos @101 + + fill_win32_filefunc @110 + +; zlibwapi v1.2.4 added: + fill_win32_filefunc64 @111 + fill_win32_filefunc64A @112 + fill_win32_filefunc64W @113 + + unzOpen64 @120 + unzOpen2_64 @121 + unzGetGlobalInfo64 @122 + unzGetCurrentFileInfo64 @124 + unzGetCurrentFileZStreamPos64 @125 + unztell64 @126 + unzGetFilePos64 @127 + unzGoToFilePos64 @128 + + zipOpen64 @130 + zipOpen2_64 @131 + zipOpenNewFileInZip64 @132 + zipOpenNewFileInZip2_64 @133 + zipOpenNewFileInZip3_64 @134 + zipOpenNewFileInZip4_64 @135 + zipCloseFileInZipRaw64 @136 + +; zlib1 v1.2.4 added: + adler32_combine @140 + crc32_combine @142 + deflateSetHeader @144 + deflateTune @145 + gzbuffer @146 + gzclose_r @147 + gzclose_w @148 + gzdirect @149 + gzoffset @150 + inflateGetHeader @156 + inflateMark @157 + inflatePrime @158 + inflateReset2 @159 + inflateUndermine @160 + +; zlib1 v1.2.6 added: + gzgetc_ @161 + inflateResetKeep @163 + deflateResetKeep @164 + +; zlib1 v1.2.7 added: + gzopen_w @165 + +; zlib1 v1.2.8 added: + inflateGetDictionary @166 + gzvprintf @167 + +; zlib1 v1.2.9 added: + inflateCodesUsed @168 + inflateValidate @169 + uncompress2 @170 + gzfread @171 + gzfwrite @172 + deflateGetDictionary @173 + adler32_z @174 + crc32_z @175 diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.sln b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.sln new file mode 100644 index 0000000..6f6ffd5 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.sln @@ -0,0 +1,135 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Itanium = Debug|Itanium + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Itanium = Release|Itanium + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium + ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32 + ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.Build.0 = Debug|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.Build.0 = Release|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.Build.0 = Debug|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.Build.0 = Release|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.Build.0 = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.Build.0 = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj new file mode 100644 index 0000000..6ff9ddb --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj @@ -0,0 +1,657 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {8FD826F8-3739-44E6-8CC8-997122E53B8D} + + + + DynamicLibrary + false + true + + + DynamicLibrary + false + true + + + DynamicLibrary + false + + + DynamicLibrary + false + true + + + DynamicLibrary + false + true + + + DynamicLibrary + false + + + DynamicLibrary + false + true + + + DynamicLibrary + false + true + + + DynamicLibrary + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + true + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + true + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + true + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + zlibwapid + zlibwapi + zlibwapi + zlibwapid + zlibwapi + zlibwapi + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + + + MultiThreadedDebug + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + EditAndContinue + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + true + .\zlibvc.def + true + true + Windows + false + + + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + true + false + .\zlibvc.def + true + Windows + false + + + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + true + false + .\zlibvc.def + true + Windows + false + + + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + true + .\zlibvc.def + true + true + Windows + MachineX64 + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + true + false + .\zlibvc.def + true + Windows + MachineX64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + true + false + .\zlibvc.def + true + Windows + MachineX64 + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj.filters b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj.filters new file mode 100644 index 0000000..180b71c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc10/zlibvc.vcxproj.filters @@ -0,0 +1,118 @@ + + + + + {07934a85-8b61-443d-a0ee-b2eedb74f3cd} + cpp;c;cxx;rc;def;r;odl;hpj;bat;for;f90 + + + {1d99675b-433d-4a21-9e50-ed4ab8b19762} + h;hpp;hxx;hm;inl;fi;fd + + + {431c0958-fa71-44d0-9084-2d19d100c0cc} + ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Source Files + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/miniunz.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/miniunz.vcxproj new file mode 100644 index 0000000..8f9f20b --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/miniunz.vcxproj @@ -0,0 +1,314 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694382A} + Win32Proj + + + + Application + MultiByte + v110 + + + Application + Unicode + v110 + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + v110 + + + Application + MultiByte + v110 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + true + false + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + false + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + true + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + true + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + false + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/minizip.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/minizip.vcxproj new file mode 100644 index 0000000..c93d9e6 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/minizip.vcxproj @@ -0,0 +1,311 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B} + Win32Proj + + + + Application + MultiByte + v110 + + + Application + Unicode + v110 + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + v110 + + + Application + MultiByte + v110 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + true + false + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + false + x64\$(Configuration)\ + x64\$(Configuration)\ + true + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + true + false + x64\$(Configuration)\ + x64\$(Configuration)\ + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlib.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlib.vcxproj new file mode 100644 index 0000000..6d55954 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlib.vcxproj @@ -0,0 +1,426 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B} + testzlib + Win32Proj + + + + Application + MultiByte + true + v110 + + + Application + MultiByte + true + v110 + + + Application + Unicode + v110 + + + Application + MultiByte + true + + + Application + MultiByte + true + + + Application + MultiByte + + + Application + true + v110 + + + Application + true + v110 + + + Application + v110 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + true + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + true + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDebugDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + %(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlibdll.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlibdll.vcxproj new file mode 100644 index 0000000..9f20c78 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/testzlibdll.vcxproj @@ -0,0 +1,314 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694366A} + Win32Proj + + + + Application + MultiByte + v110 + + + Application + Unicode + v110 + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + v110 + + + Application + MultiByte + v110 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + true + false + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + false + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + true + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + true + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + false + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlib.rc b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlib.rc new file mode 100644 index 0000000..fee177a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlib.rc @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1, 2, 11, 0 + PRODUCTVERSION 1, 2, 11, 0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" + VALUE "FileVersion", "1.2.11\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlibwapi.dll\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibstat.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibstat.vcxproj new file mode 100644 index 0000000..806b76a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibstat.vcxproj @@ -0,0 +1,464 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8} + + + + StaticLibrary + false + v110 + + + StaticLibrary + false + v110 + + + StaticLibrary + false + v110 + Unicode + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + + + StaticLibrary + false + v110 + + + StaticLibrary + false + v110 + + + StaticLibrary + false + v110 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.def b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.def new file mode 100644 index 0000000..54e683d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.def @@ -0,0 +1,153 @@ +LIBRARY +; zlib data compression and ZIP file I/O library + +VERSION 1.2 + +EXPORTS + adler32 @1 + compress @2 + crc32 @3 + deflate @4 + deflateCopy @5 + deflateEnd @6 + deflateInit2_ @7 + deflateInit_ @8 + deflateParams @9 + deflateReset @10 + deflateSetDictionary @11 + gzclose @12 + gzdopen @13 + gzerror @14 + gzflush @15 + gzopen @16 + gzread @17 + gzwrite @18 + inflate @19 + inflateEnd @20 + inflateInit2_ @21 + inflateInit_ @22 + inflateReset @23 + inflateSetDictionary @24 + inflateSync @25 + uncompress @26 + zlibVersion @27 + gzprintf @28 + gzputc @29 + gzgetc @30 + gzseek @31 + gzrewind @32 + gztell @33 + gzeof @34 + gzsetparams @35 + zError @36 + inflateSyncPoint @37 + get_crc_table @38 + compress2 @39 + gzputs @40 + gzgets @41 + inflateCopy @42 + inflateBackInit_ @43 + inflateBack @44 + inflateBackEnd @45 + compressBound @46 + deflateBound @47 + gzclearerr @48 + gzungetc @49 + zlibCompileFlags @50 + deflatePrime @51 + deflatePending @52 + + unzOpen @61 + unzClose @62 + unzGetGlobalInfo @63 + unzGetCurrentFileInfo @64 + unzGoToFirstFile @65 + unzGoToNextFile @66 + unzOpenCurrentFile @67 + unzReadCurrentFile @68 + unzOpenCurrentFile3 @69 + unztell @70 + unzeof @71 + unzCloseCurrentFile @72 + unzGetGlobalComment @73 + unzStringFileNameCompare @74 + unzLocateFile @75 + unzGetLocalExtrafield @76 + unzOpen2 @77 + unzOpenCurrentFile2 @78 + unzOpenCurrentFilePassword @79 + + zipOpen @80 + zipOpenNewFileInZip @81 + zipWriteInFileInZip @82 + zipCloseFileInZip @83 + zipClose @84 + zipOpenNewFileInZip2 @86 + zipCloseFileInZipRaw @87 + zipOpen2 @88 + zipOpenNewFileInZip3 @89 + + unzGetFilePos @100 + unzGoToFilePos @101 + + fill_win32_filefunc @110 + +; zlibwapi v1.2.4 added: + fill_win32_filefunc64 @111 + fill_win32_filefunc64A @112 + fill_win32_filefunc64W @113 + + unzOpen64 @120 + unzOpen2_64 @121 + unzGetGlobalInfo64 @122 + unzGetCurrentFileInfo64 @124 + unzGetCurrentFileZStreamPos64 @125 + unztell64 @126 + unzGetFilePos64 @127 + unzGoToFilePos64 @128 + + zipOpen64 @130 + zipOpen2_64 @131 + zipOpenNewFileInZip64 @132 + zipOpenNewFileInZip2_64 @133 + zipOpenNewFileInZip3_64 @134 + zipOpenNewFileInZip4_64 @135 + zipCloseFileInZipRaw64 @136 + +; zlib1 v1.2.4 added: + adler32_combine @140 + crc32_combine @142 + deflateSetHeader @144 + deflateTune @145 + gzbuffer @146 + gzclose_r @147 + gzclose_w @148 + gzdirect @149 + gzoffset @150 + inflateGetHeader @156 + inflateMark @157 + inflatePrime @158 + inflateReset2 @159 + inflateUndermine @160 + +; zlib1 v1.2.6 added: + gzgetc_ @161 + inflateResetKeep @163 + deflateResetKeep @164 + +; zlib1 v1.2.7 added: + gzopen_w @165 + +; zlib1 v1.2.8 added: + inflateGetDictionary @166 + gzvprintf @167 + +; zlib1 v1.2.9 added: + inflateCodesUsed @168 + inflateValidate @169 + uncompress2 @170 + gzfread @171 + gzfwrite @172 + deflateGetDictionary @173 + adler32_z @174 + crc32_z @175 diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.sln b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.sln new file mode 100644 index 0000000..9fcbafd --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.sln @@ -0,0 +1,117 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Itanium = Debug|Itanium + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Itanium = Release|Itanium + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium + ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32 + ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.vcxproj new file mode 100644 index 0000000..c65b95f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc11/zlibvc.vcxproj @@ -0,0 +1,688 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {8FD826F8-3739-44E6-8CC8-997122E53B8D} + + + + DynamicLibrary + false + true + v110 + + + DynamicLibrary + false + true + v110 + + + DynamicLibrary + false + v110 + Unicode + + + DynamicLibrary + false + true + + + DynamicLibrary + false + true + + + DynamicLibrary + false + + + DynamicLibrary + false + true + v110 + + + DynamicLibrary + false + true + v110 + + + DynamicLibrary + false + v110 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + true + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + true + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + true + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\contrib\masmx64 +bld_ml64.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/miniunz.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/miniunz.vcxproj new file mode 100644 index 0000000..d88ac7f --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/miniunz.vcxproj @@ -0,0 +1,316 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694382A} + Win32Proj + + + + Application + MultiByte + v120 + + + Application + Unicode + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + true + false + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + false + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + true + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + true + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + false + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/minizip.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/minizip.vcxproj new file mode 100644 index 0000000..f1f239c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/minizip.vcxproj @@ -0,0 +1,313 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B} + Win32Proj + + + + Application + MultiByte + v120 + + + Application + Unicode + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + true + false + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + false + x64\$(Configuration)\ + x64\$(Configuration)\ + true + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + true + false + x64\$(Configuration)\ + x64\$(Configuration)\ + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlib.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlib.vcxproj new file mode 100644 index 0000000..64b2cbe --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlib.vcxproj @@ -0,0 +1,430 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B} + testzlib + Win32Proj + + + + Application + MultiByte + true + v120 + + + Application + MultiByte + true + v120 + + + Application + Unicode + v120 + + + Application + MultiByte + true + v120 + + + Application + MultiByte + true + v120 + + + Application + MultiByte + v120 + + + Application + true + v120 + + + Application + true + v120 + + + Application + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + true + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + true + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + false + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDebugDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + %(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlibdll.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlibdll.vcxproj new file mode 100644 index 0000000..c66573a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/testzlibdll.vcxproj @@ -0,0 +1,316 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694366A} + Win32Proj + + + + Application + MultiByte + v120 + + + Application + Unicode + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + Application + MultiByte + v120 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + true + false + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + false + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + true + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + true + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + false + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlib.rc b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlib.rc new file mode 100644 index 0000000..c4e4b01 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlib.rc @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1, 2, 11, 0 + PRODUCTVERSION 1, 2, 11, 0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" + VALUE "FileVersion", "1.2.11\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlibwapi.dll\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibstat.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibstat.vcxproj new file mode 100644 index 0000000..3fdee7c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibstat.vcxproj @@ -0,0 +1,467 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8} + + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + Unicode + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + StaticLibrary + false + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.def b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.def new file mode 100644 index 0000000..54e683d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.def @@ -0,0 +1,153 @@ +LIBRARY +; zlib data compression and ZIP file I/O library + +VERSION 1.2 + +EXPORTS + adler32 @1 + compress @2 + crc32 @3 + deflate @4 + deflateCopy @5 + deflateEnd @6 + deflateInit2_ @7 + deflateInit_ @8 + deflateParams @9 + deflateReset @10 + deflateSetDictionary @11 + gzclose @12 + gzdopen @13 + gzerror @14 + gzflush @15 + gzopen @16 + gzread @17 + gzwrite @18 + inflate @19 + inflateEnd @20 + inflateInit2_ @21 + inflateInit_ @22 + inflateReset @23 + inflateSetDictionary @24 + inflateSync @25 + uncompress @26 + zlibVersion @27 + gzprintf @28 + gzputc @29 + gzgetc @30 + gzseek @31 + gzrewind @32 + gztell @33 + gzeof @34 + gzsetparams @35 + zError @36 + inflateSyncPoint @37 + get_crc_table @38 + compress2 @39 + gzputs @40 + gzgets @41 + inflateCopy @42 + inflateBackInit_ @43 + inflateBack @44 + inflateBackEnd @45 + compressBound @46 + deflateBound @47 + gzclearerr @48 + gzungetc @49 + zlibCompileFlags @50 + deflatePrime @51 + deflatePending @52 + + unzOpen @61 + unzClose @62 + unzGetGlobalInfo @63 + unzGetCurrentFileInfo @64 + unzGoToFirstFile @65 + unzGoToNextFile @66 + unzOpenCurrentFile @67 + unzReadCurrentFile @68 + unzOpenCurrentFile3 @69 + unztell @70 + unzeof @71 + unzCloseCurrentFile @72 + unzGetGlobalComment @73 + unzStringFileNameCompare @74 + unzLocateFile @75 + unzGetLocalExtrafield @76 + unzOpen2 @77 + unzOpenCurrentFile2 @78 + unzOpenCurrentFilePassword @79 + + zipOpen @80 + zipOpenNewFileInZip @81 + zipWriteInFileInZip @82 + zipCloseFileInZip @83 + zipClose @84 + zipOpenNewFileInZip2 @86 + zipCloseFileInZipRaw @87 + zipOpen2 @88 + zipOpenNewFileInZip3 @89 + + unzGetFilePos @100 + unzGoToFilePos @101 + + fill_win32_filefunc @110 + +; zlibwapi v1.2.4 added: + fill_win32_filefunc64 @111 + fill_win32_filefunc64A @112 + fill_win32_filefunc64W @113 + + unzOpen64 @120 + unzOpen2_64 @121 + unzGetGlobalInfo64 @122 + unzGetCurrentFileInfo64 @124 + unzGetCurrentFileZStreamPos64 @125 + unztell64 @126 + unzGetFilePos64 @127 + unzGoToFilePos64 @128 + + zipOpen64 @130 + zipOpen2_64 @131 + zipOpenNewFileInZip64 @132 + zipOpenNewFileInZip2_64 @133 + zipOpenNewFileInZip3_64 @134 + zipOpenNewFileInZip4_64 @135 + zipCloseFileInZipRaw64 @136 + +; zlib1 v1.2.4 added: + adler32_combine @140 + crc32_combine @142 + deflateSetHeader @144 + deflateTune @145 + gzbuffer @146 + gzclose_r @147 + gzclose_w @148 + gzdirect @149 + gzoffset @150 + inflateGetHeader @156 + inflateMark @157 + inflatePrime @158 + inflateReset2 @159 + inflateUndermine @160 + +; zlib1 v1.2.6 added: + gzgetc_ @161 + inflateResetKeep @163 + deflateResetKeep @164 + +; zlib1 v1.2.7 added: + gzopen_w @165 + +; zlib1 v1.2.8 added: + inflateGetDictionary @166 + gzvprintf @167 + +; zlib1 v1.2.9 added: + inflateCodesUsed @168 + inflateValidate @169 + uncompress2 @170 + gzfread @171 + gzfwrite @172 + deflateGetDictionary @173 + adler32_z @174 + crc32_z @175 diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.sln b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.sln new file mode 100644 index 0000000..dcda229 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.sln @@ -0,0 +1,119 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.40629.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Itanium = Debug|Itanium + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Itanium = Release|Itanium + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium + ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32 + ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.vcxproj new file mode 100644 index 0000000..ab2b6c3 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc12/zlibvc.vcxproj @@ -0,0 +1,692 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {8FD826F8-3739-44E6-8CC8-997122E53B8D} + + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + v120 + Unicode + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + v120 + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + true + v120 + + + DynamicLibrary + false + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + true + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + true + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + true + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + false + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\contrib\masmx64 +bld_ml64.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/miniunz.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/miniunz.vcxproj new file mode 100644 index 0000000..9b5c075 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/miniunz.vcxproj @@ -0,0 +1,316 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694382A} + Win32Proj + + + + Application + MultiByte + v140 + + + Application + Unicode + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + true + false + x86\MiniUnzip$(Configuration)\ + x86\MiniUnzip$(Configuration)\Tmp\ + false + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + true + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + true + false + x64\MiniUnzip$(Configuration)\ + x64\MiniUnzip$(Configuration)\Tmp\ + false + false + ia64\MiniUnzip$(Configuration)\ + ia64\MiniUnzip$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + $(OutDir)miniunz.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)miniunz.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/minizip.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/minizip.vcxproj new file mode 100644 index 0000000..968a410 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/minizip.vcxproj @@ -0,0 +1,313 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B} + Win32Proj + + + + Application + MultiByte + v140 + + + Application + Unicode + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + true + false + x86\MiniZip$(Configuration)\ + x86\MiniZip$(Configuration)\Tmp\ + false + x64\$(Configuration)\ + x64\$(Configuration)\ + true + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + true + false + x64\$(Configuration)\ + x64\$(Configuration)\ + false + ia64\$(Configuration)\ + ia64\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + $(OutDir)minizip.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)minizip.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlib.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlib.vcxproj new file mode 100644 index 0000000..2c37125 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlib.vcxproj @@ -0,0 +1,430 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B} + testzlib + Win32Proj + + + + Application + MultiByte + true + v140 + + + Application + MultiByte + true + v140 + + + Application + Unicode + v140 + + + Application + MultiByte + true + v140 + + + Application + MultiByte + true + v140 + + + Application + MultiByte + v140 + + + Application + true + v140 + + + Application + true + v140 + + + Application + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + true + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x86\TestZlib$(Configuration)\ + x86\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + true + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + x64\TestZlib$(Configuration)\ + x64\TestZlib$(Configuration)\Tmp\ + false + ia64\TestZlib$(Configuration)\ + ia64\TestZlib$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)testzlib.exe + true + Console + true + true + false + + + MachineX86 + false + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDebugDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + Disabled + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_DEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + AssemblyAndSourceCode + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + %(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + ..\..\..;%(AdditionalIncludeDirectories) + ASMV;ASMINF;WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + Default + MultiThreadedDLL + false + $(IntDir) + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;NDEBUG;_CONSOLE;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + $(OutDir)testzlib.exe + true + Console + true + true + MachineIA64 + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlibdll.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlibdll.vcxproj new file mode 100644 index 0000000..d87474d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/testzlibdll.vcxproj @@ -0,0 +1,316 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {C52F9E7B-498A-42BE-8DB4-85A15694366A} + Win32Proj + + + + Application + MultiByte + v140 + + + Application + Unicode + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + Application + MultiByte + v140 + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + true + false + x86\TestZlibDll$(Configuration)\ + x86\TestZlibDll$(Configuration)\Tmp\ + false + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + true + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + true + false + x64\TestZlibDll$(Configuration)\ + x64\TestZlibDll$(Configuration)\Tmp\ + false + false + ia64\TestZlibDll$(Configuration)\ + ia64\TestZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + false + + + MachineX86 + + + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + Default + MultiThreaded + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x86\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineX64 + + + + + Itanium + + + Disabled + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + false + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllDebug\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + $(OutDir)testzlib.pdb + Console + MachineIA64 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + x64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineX64 + + + + + Itanium + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..;..\..\minizip;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ZLIB_WINAPI;NDEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions) + true + Default + MultiThreadedDLL + false + true + + + $(IntDir) + Level3 + ProgramDatabase + + + ia64\ZlibDllRelease\zlibwapi.lib;%(AdditionalDependencies) + $(OutDir)testzlibdll.exe + true + Console + true + true + MachineIA64 + + + + + + + + {8fd826f8-3739-44e6-8cc8-997122e53b8d} + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlib.rc b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlib.rc new file mode 100644 index 0000000..c4e4b01 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlib.rc @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1, 2, 11, 0 + PRODUCTVERSION 1, 2, 11, 0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" + VALUE "FileVersion", "1.2.11\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlibwapi.dll\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibstat.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibstat.vcxproj new file mode 100644 index 0000000..3e4b986 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibstat.vcxproj @@ -0,0 +1,467 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8} + + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + Unicode + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + StaticLibrary + false + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x86\ZlibStat$(Configuration)\ + x86\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + x64\ZlibStat$(Configuration)\ + x64\ZlibStat$(Configuration)\Tmp\ + ia64\ZlibStat$(Configuration)\ + ia64\ZlibStat$(Configuration)\Tmp\ + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:X86 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + OldStyle + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + X64 + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:AMD64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + Itanium + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + ZLIB_WINAPI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibstat.pch + $(IntDir) + $(IntDir) + $(OutDir) + Level3 + true + + + 0x040c + + + /MACHINE:IA64 /NODEFAULTLIB %(AdditionalOptions) + $(OutDir)zlibstat.lib + true + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.def b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.def new file mode 100644 index 0000000..54e683d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.def @@ -0,0 +1,153 @@ +LIBRARY +; zlib data compression and ZIP file I/O library + +VERSION 1.2 + +EXPORTS + adler32 @1 + compress @2 + crc32 @3 + deflate @4 + deflateCopy @5 + deflateEnd @6 + deflateInit2_ @7 + deflateInit_ @8 + deflateParams @9 + deflateReset @10 + deflateSetDictionary @11 + gzclose @12 + gzdopen @13 + gzerror @14 + gzflush @15 + gzopen @16 + gzread @17 + gzwrite @18 + inflate @19 + inflateEnd @20 + inflateInit2_ @21 + inflateInit_ @22 + inflateReset @23 + inflateSetDictionary @24 + inflateSync @25 + uncompress @26 + zlibVersion @27 + gzprintf @28 + gzputc @29 + gzgetc @30 + gzseek @31 + gzrewind @32 + gztell @33 + gzeof @34 + gzsetparams @35 + zError @36 + inflateSyncPoint @37 + get_crc_table @38 + compress2 @39 + gzputs @40 + gzgets @41 + inflateCopy @42 + inflateBackInit_ @43 + inflateBack @44 + inflateBackEnd @45 + compressBound @46 + deflateBound @47 + gzclearerr @48 + gzungetc @49 + zlibCompileFlags @50 + deflatePrime @51 + deflatePending @52 + + unzOpen @61 + unzClose @62 + unzGetGlobalInfo @63 + unzGetCurrentFileInfo @64 + unzGoToFirstFile @65 + unzGoToNextFile @66 + unzOpenCurrentFile @67 + unzReadCurrentFile @68 + unzOpenCurrentFile3 @69 + unztell @70 + unzeof @71 + unzCloseCurrentFile @72 + unzGetGlobalComment @73 + unzStringFileNameCompare @74 + unzLocateFile @75 + unzGetLocalExtrafield @76 + unzOpen2 @77 + unzOpenCurrentFile2 @78 + unzOpenCurrentFilePassword @79 + + zipOpen @80 + zipOpenNewFileInZip @81 + zipWriteInFileInZip @82 + zipCloseFileInZip @83 + zipClose @84 + zipOpenNewFileInZip2 @86 + zipCloseFileInZipRaw @87 + zipOpen2 @88 + zipOpenNewFileInZip3 @89 + + unzGetFilePos @100 + unzGoToFilePos @101 + + fill_win32_filefunc @110 + +; zlibwapi v1.2.4 added: + fill_win32_filefunc64 @111 + fill_win32_filefunc64A @112 + fill_win32_filefunc64W @113 + + unzOpen64 @120 + unzOpen2_64 @121 + unzGetGlobalInfo64 @122 + unzGetCurrentFileInfo64 @124 + unzGetCurrentFileZStreamPos64 @125 + unztell64 @126 + unzGetFilePos64 @127 + unzGoToFilePos64 @128 + + zipOpen64 @130 + zipOpen2_64 @131 + zipOpenNewFileInZip64 @132 + zipOpenNewFileInZip2_64 @133 + zipOpenNewFileInZip3_64 @134 + zipOpenNewFileInZip4_64 @135 + zipCloseFileInZipRaw64 @136 + +; zlib1 v1.2.4 added: + adler32_combine @140 + crc32_combine @142 + deflateSetHeader @144 + deflateTune @145 + gzbuffer @146 + gzclose_r @147 + gzclose_w @148 + gzdirect @149 + gzoffset @150 + inflateGetHeader @156 + inflateMark @157 + inflatePrime @158 + inflateReset2 @159 + inflateUndermine @160 + +; zlib1 v1.2.6 added: + gzgetc_ @161 + inflateResetKeep @163 + deflateResetKeep @164 + +; zlib1 v1.2.7 added: + gzopen_w @165 + +; zlib1 v1.2.8 added: + inflateGetDictionary @166 + gzvprintf @167 + +; zlib1 v1.2.9 added: + inflateCodesUsed @168 + inflateValidate @169 + uncompress2 @170 + gzfread @171 + gzfwrite @172 + deflateGetDictionary @173 + adler32_z @174 + crc32_z @175 diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.sln b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.sln new file mode 100644 index 0000000..6f4a107 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.sln @@ -0,0 +1,119 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Itanium = Debug|Itanium + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Itanium = Release|Itanium + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium + ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32 + ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.vcxproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.vcxproj new file mode 100644 index 0000000..f8f673c --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc14/zlibvc.vcxproj @@ -0,0 +1,692 @@ + + + + + Debug + Itanium + + + Debug + Win32 + + + Debug + x64 + + + ReleaseWithoutAsm + Itanium + + + ReleaseWithoutAsm + Win32 + + + ReleaseWithoutAsm + x64 + + + Release + Itanium + + + Release + Win32 + + + Release + x64 + + + + {8FD826F8-3739-44E6-8CC8-997122E53B8D} + + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + v140 + Unicode + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + v140 + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + true + v140 + + + DynamicLibrary + false + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30128.1 + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + true + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x86\ZlibDll$(Configuration)\ + x86\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + true + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + true + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + x64\ZlibDll$(Configuration)\ + x64\ZlibDll$(Configuration)\Tmp\ + false + false + ia64\ZlibDll$(Configuration)\ + ia64\ZlibDll$(Configuration)\Tmp\ + false + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + zlibwapi + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Win32 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;%(PreprocessorDefinitions) + true + + + MultiThreaded + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + /MACHINE:I386 %(AdditionalOptions) + ..\..\masmx86\match686.obj;..\..\masmx86\inffas32.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + false + + + $(OutDir)zlibwapi.lib + false + + + cd ..\..\masmx86 +bld_ml32.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\contrib\masmx64 +bld_ml64.bat + + + + + _DEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + Disabled + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + + + MultiThreadedDebugDLL + false + $(IntDir)zlibvc.pch + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + ProgramDatabase + + + _DEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + .\zlibvc.def + true + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + WIN32;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + X64 + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;ASMV;ASMINF;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + ..\..\masmx64\gvmat64.obj;..\..\masmx64\inffasx64.obj;%(AdditionalDependencies) + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineX64 + + + cd ..\..\masmx64 +bld_ml64.bat + + + + + NDEBUG;%(PreprocessorDefinitions) + true + true + Itanium + $(OutDir)zlibvc.tlb + + + OnlyExplicitInline + ..\..\..;..\..\masmx86;%(AdditionalIncludeDirectories) + _CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_WARNINGS;ZLIB_WINAPI;WIN64;%(PreprocessorDefinitions) + true + + + MultiThreadedDLL + false + true + $(IntDir)zlibvc.pch + All + $(IntDir) + $(IntDir) + $(OutDir) + + + Level3 + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x040c + + + $(OutDir)zlibwapi.dll + true + false + .\zlibvc.def + $(OutDir)zlibwapi.pdb + true + $(OutDir)zlibwapi.map + Windows + $(OutDir)zlibwapi.lib + MachineIA64 + + + + + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + %(AdditionalIncludeDirectories) + ZLIB_INTERNAL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/miniunz.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/miniunz.vcproj new file mode 100644 index 0000000..7da32b9 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/miniunz.vcproj @@ -0,0 +1,565 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/minizip.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/minizip.vcproj new file mode 100644 index 0000000..e57e07d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/minizip.vcproj @@ -0,0 +1,562 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlib.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlib.vcproj new file mode 100644 index 0000000..9cb0bf8 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlib.vcproj @@ -0,0 +1,852 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlibdll.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlibdll.vcproj new file mode 100644 index 0000000..b1ddde0 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/testzlibdll.vcproj @@ -0,0 +1,565 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlib.rc b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlib.rc new file mode 100644 index 0000000..fee177a --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlib.rc @@ -0,0 +1,32 @@ +#include + +#define IDR_VERSION1 1 +IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE + FILEVERSION 1, 2, 11, 0 + PRODUCTVERSION 1, 2, 11, 0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS_DOS_WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + + BEGIN + VALUE "FileDescription", "zlib data compression and ZIP file I/O library\0" + VALUE "FileVersion", "1.2.11\0" + VALUE "InternalName", "zlib\0" + VALUE "OriginalFilename", "zlibwapi.dll\0" + VALUE "ProductName", "ZLib.DLL\0" + VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibstat.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibstat.vcproj new file mode 100644 index 0000000..61c76c7 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibstat.vcproj @@ -0,0 +1,835 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.def b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.def new file mode 100644 index 0000000..54e683d --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.def @@ -0,0 +1,153 @@ +LIBRARY +; zlib data compression and ZIP file I/O library + +VERSION 1.2 + +EXPORTS + adler32 @1 + compress @2 + crc32 @3 + deflate @4 + deflateCopy @5 + deflateEnd @6 + deflateInit2_ @7 + deflateInit_ @8 + deflateParams @9 + deflateReset @10 + deflateSetDictionary @11 + gzclose @12 + gzdopen @13 + gzerror @14 + gzflush @15 + gzopen @16 + gzread @17 + gzwrite @18 + inflate @19 + inflateEnd @20 + inflateInit2_ @21 + inflateInit_ @22 + inflateReset @23 + inflateSetDictionary @24 + inflateSync @25 + uncompress @26 + zlibVersion @27 + gzprintf @28 + gzputc @29 + gzgetc @30 + gzseek @31 + gzrewind @32 + gztell @33 + gzeof @34 + gzsetparams @35 + zError @36 + inflateSyncPoint @37 + get_crc_table @38 + compress2 @39 + gzputs @40 + gzgets @41 + inflateCopy @42 + inflateBackInit_ @43 + inflateBack @44 + inflateBackEnd @45 + compressBound @46 + deflateBound @47 + gzclearerr @48 + gzungetc @49 + zlibCompileFlags @50 + deflatePrime @51 + deflatePending @52 + + unzOpen @61 + unzClose @62 + unzGetGlobalInfo @63 + unzGetCurrentFileInfo @64 + unzGoToFirstFile @65 + unzGoToNextFile @66 + unzOpenCurrentFile @67 + unzReadCurrentFile @68 + unzOpenCurrentFile3 @69 + unztell @70 + unzeof @71 + unzCloseCurrentFile @72 + unzGetGlobalComment @73 + unzStringFileNameCompare @74 + unzLocateFile @75 + unzGetLocalExtrafield @76 + unzOpen2 @77 + unzOpenCurrentFile2 @78 + unzOpenCurrentFilePassword @79 + + zipOpen @80 + zipOpenNewFileInZip @81 + zipWriteInFileInZip @82 + zipCloseFileInZip @83 + zipClose @84 + zipOpenNewFileInZip2 @86 + zipCloseFileInZipRaw @87 + zipOpen2 @88 + zipOpenNewFileInZip3 @89 + + unzGetFilePos @100 + unzGoToFilePos @101 + + fill_win32_filefunc @110 + +; zlibwapi v1.2.4 added: + fill_win32_filefunc64 @111 + fill_win32_filefunc64A @112 + fill_win32_filefunc64W @113 + + unzOpen64 @120 + unzOpen2_64 @121 + unzGetGlobalInfo64 @122 + unzGetCurrentFileInfo64 @124 + unzGetCurrentFileZStreamPos64 @125 + unztell64 @126 + unzGetFilePos64 @127 + unzGoToFilePos64 @128 + + zipOpen64 @130 + zipOpen2_64 @131 + zipOpenNewFileInZip64 @132 + zipOpenNewFileInZip2_64 @133 + zipOpenNewFileInZip3_64 @134 + zipOpenNewFileInZip4_64 @135 + zipCloseFileInZipRaw64 @136 + +; zlib1 v1.2.4 added: + adler32_combine @140 + crc32_combine @142 + deflateSetHeader @144 + deflateTune @145 + gzbuffer @146 + gzclose_r @147 + gzclose_w @148 + gzdirect @149 + gzoffset @150 + inflateGetHeader @156 + inflateMark @157 + inflatePrime @158 + inflateReset2 @159 + inflateUndermine @160 + +; zlib1 v1.2.6 added: + gzgetc_ @161 + inflateResetKeep @163 + deflateResetKeep @164 + +; zlib1 v1.2.7 added: + gzopen_w @165 + +; zlib1 v1.2.8 added: + inflateGetDictionary @166 + gzvprintf @167 + +; zlib1 v1.2.9 added: + inflateCodesUsed @168 + inflateValidate @169 + uncompress2 @170 + gzfread @171 + gzfwrite @172 + deflateGetDictionary @173 + adler32_z @174 + crc32_z @175 diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.sln b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.sln new file mode 100644 index 0000000..b482967 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.sln @@ -0,0 +1,144 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestZlibDll", "testzlibdll.vcproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}" + ProjectSection(ProjectDependencies) = postProject + {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}" + ProjectSection(ProjectDependencies) = postProject + {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}" + ProjectSection(ProjectDependencies) = postProject + {8FD826F8-3739-44E6-8CC8-997122E53B8D} = {8FD826F8-3739-44E6-8CC8-997122E53B8D} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Itanium = Debug|Itanium + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Itanium = Release|Itanium + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium + ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32 + ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.Build.0 = Debug|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.Build.0 = Release|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.Build.0 = Debug|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.Build.0 = Release|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = ReleaseWithoutAsm|Itanium + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64 + {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.Build.0 = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.Build.0 = Debug|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.Build.0 = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.Build.0 = Debug|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.Build.0 = Release|Itanium + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32 + {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.vcproj b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.vcproj new file mode 100644 index 0000000..c9a8947 --- /dev/null +++ b/third_party/zlib/v1_2_11/contrib/vstudio/vc9/zlibvc.vcproj @@ -0,0 +1,1156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/crc32.c b/third_party/zlib/v1_2_11/crc32.c new file mode 100644 index 0000000..9580440 --- /dev/null +++ b/third_party/zlib/v1_2_11/crc32.c @@ -0,0 +1,442 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, z_size_t)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, z_size_t)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32_z(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + return crc32_z(crc, buf, len); +} + +#ifdef BYFOUR + +/* + This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit + integer pointer type. This violates the strict aliasing rule, where a + compiler can assume, for optimization purposes, that two pointers to + fundamentally different types won't ever point to the same memory. This can + manifest as a problem only if one of the pointers is written to. This code + only reads from those pointers. So long as this code remains isolated in + this compilation unit, there won't be a problem. For this reason, this code + should not be copied and pasted into a compilation unit in which other code + writes to the buffer that is passed to these routines. + */ + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *buf4++; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/third_party/zlib/v1_2_11/crc32.h b/third_party/zlib/v1_2_11/crc32.h new file mode 100644 index 0000000..9e0c778 --- /dev/null +++ b/third_party/zlib/v1_2_11/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/third_party/zlib/v1_2_11/deflate.c b/third_party/zlib/v1_2_11/deflate.c new file mode 100644 index 0000000..1ec7614 --- /dev/null +++ b/third_party/zlib/v1_2_11/deflate.c @@ -0,0 +1,2163 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local int deflateStateCheck OF((z_streamp strm)); +local void slide_hash OF((deflate_state *s)); +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV +# pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef ZLIB_DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* =========================================================================== + * Slide the hash table when sliding the window down (could be avoided with 32 + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +local void slide_hash(s) + deflate_state *s; +{ + unsigned n, m; + Posf *p; + uInt wsize = s->w_size; + + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + } while (--n); + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif +} + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + s->status = INIT_STATE; /* to pass state test in deflateReset() */ + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = (uInt)windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = (uInt)memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +local int deflateStateCheck (strm) + z_streamp strm; +{ + deflate_state *s; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + s = strm->state; + if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE && +#ifdef GZIP + s->status != GZIP_STATE && +#endif + s->status != EXTRA_STATE && + s->status != NAME_STATE && + s->status != COMMENT_STATE && + s->status != HCRC_STATE && + s->status != BUSY_STATE && + s->status != FINISH_STATE)) + return 1; + return 0; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (deflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) + z_streamp strm; + Bytef *dictionary; + uInt *dictLength; +{ + deflate_state *s; + uInt len; + + if (deflateStateCheck(strm)) + return Z_STREAM_ERROR; + s = strm->state; + len = s->strstart + s->lookahead; + if (len > s->w_size) + len = s->w_size; + if (dictionary != Z_NULL && len) + zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len); + if (dictLength != Z_NULL) + *dictLength = len; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = +#ifdef GZIP + s->wrap == 2 ? GZIP_STATE : +#endif + s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (deflateStateCheck(strm) || strm->state->wrap != 2) + return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + s->high_water) { + /* Flush the last buffer: */ + int err = deflate(strm, Z_BLOCK); + if (err == Z_STREAM_ERROR) + return err; + if (strm->avail_out == 0) + return Z_BUF_ERROR; + } + if (s->level != level) { + if (s->level == 0 && s->matches != 0) { + if (s->matches == 1) + slide_hash(s); + else + CLEAR_HASH(s); + s->matches = 0; + } + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = (uInt)good_length; + s->max_lazy_match = (uInt)max_lazy; + s->nice_match = nice_length; + s->max_chain_length = (uInt)max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (deflateStateCheck(strm)) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; +#ifdef GZIP + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + Bytef *str; + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; +#endif + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output, except for + * some deflate_stored() output, goes through this function so some + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* =========================================================================== + * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1]. + */ +#define HCRC_UPDATE(beg) \ + do { \ + if (s->gzhead->hcrc && s->pending > (beg)) \ + strm->adler = crc32(strm->adler, s->pending_buf + (beg), \ + s->pending - (beg)); \ + } while (0) + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->avail_in != 0 && strm->next_in == Z_NULL) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + old_flush = s->last_flush; + s->last_flush = flush; + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Write the header */ + if (s->status == INIT_STATE) { + /* zlib header */ + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex; + while (s->pending + left > s->pending_buf_size) { + uInt copy = s->pending_buf_size - s->pending; + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, copy); + s->pending = s->pending_buf_size; + HCRC_UPDATE(beg); + s->gzindex += copy; + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + left -= copy; + } + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, left); + s->pending += left; + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + } + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) { + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + } + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#endif + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->level == 0 ? deflate_stored(s, flush) : + s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + + status = strm->state->status; + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (deflateStateCheck(source) || dest == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local unsigned read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = (int)s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef ZLIB_DEBUG + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* ZLIB_DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + unsigned n; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + slide_hash(s); + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* Maximum stored block length in deflate format (not including header). */ +#define MAX_STORED 65535 + +/* Minimum of a and b. */ +#define MIN(a, b) ((a) > (b) ? (b) : (a)) + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * + * In case deflateParams() is used to later switch to a non-zero compression + * level, s->matches (otherwise unused when storing) keeps track of the number + * of hash table slides to perform. If s->matches is 1, then one hash table + * slide will be done when switching. If s->matches is 2, the maximum value + * allowed here, then the hash table will be cleared, since two or more slides + * is the same as a clear. + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which + * maximizes the opportunites to have a single copy from next_in to next_out. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. + */ + unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size); + + /* Copy as many min_block or larger stored blocks directly to next_out as + * possible. If flushing, copy the remaining available input to next_out as + * stored blocks, if there is enough space. + */ + unsigned len, left, have, last = 0; + unsigned used = s->strm->avail_in; + do { + /* Set len to the maximum size block that we can copy directly with the + * available input data and output space. Set left to how much of that + * would be copied from what's left in the window. + */ + len = MAX_STORED; /* maximum deflate stored block length */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + if (s->strm->avail_out < have) /* need room for header */ + break; + /* maximum stored block length that will fit in avail_out: */ + have = s->strm->avail_out - have; + left = s->strstart - s->block_start; /* bytes left in window */ + if (len > (ulg)left + s->strm->avail_in) + len = left + s->strm->avail_in; /* limit len to the input */ + if (len > have) + len = have; /* limit len to the output */ + + /* If the stored block would be less than min_block in length, or if + * unable to copy all of the available input when flushing, then try + * copying to the window and the pending buffer instead. Also don't + * write an empty block when flushing -- deflate() does that. + */ + if (len < min_block && ((len == 0 && flush != Z_FINISH) || + flush == Z_NO_FLUSH || + len != left + s->strm->avail_in)) + break; + + /* Make a dummy stored block in pending to get the header bytes, + * including any pending bits. This also updates the debugging counts. + */ + last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; + _tr_stored_block(s, (char *)0, 0L, last); + + /* Replace the lengths in the dummy stored block with len. */ + s->pending_buf[s->pending - 4] = len; + s->pending_buf[s->pending - 3] = len >> 8; + s->pending_buf[s->pending - 2] = ~len; + s->pending_buf[s->pending - 1] = ~len >> 8; + + /* Write the stored block header bytes. */ + flush_pending(s->strm); + +#ifdef ZLIB_DEBUG + /* Update debugging counts for the data about to be copied. */ + s->compressed_len += len << 3; + s->bits_sent += len << 3; +#endif + + /* Copy uncompressed bytes from the window to next_out. */ + if (left) { + if (left > len) + left = len; + zmemcpy(s->strm->next_out, s->window + s->block_start, left); + s->strm->next_out += left; + s->strm->avail_out -= left; + s->strm->total_out += left; + s->block_start += left; + len -= left; + } + + /* Copy uncompressed bytes directly from next_in to next_out, updating + * the check value. + */ + if (len) { + read_buf(s->strm, s->strm->next_out, len); + s->strm->next_out += len; + s->strm->avail_out -= len; + s->strm->total_out += len; + } + } while (last == 0); + + /* Update the sliding window with the last s->w_size bytes of the copied + * data, or append all of the copied data to the existing window if less + * than s->w_size bytes were copied. Also update the number of bytes to + * insert in the hash tables, in the event that deflateParams() switches to + * a non-zero compression level. + */ + used -= s->strm->avail_in; /* number of input bytes directly copied */ + if (used) { + /* If any input was used, then no unused input remains in the window, + * therefore s->block_start == s->strstart. + */ + if (used >= s->w_size) { /* supplant the previous history */ + s->matches = 2; /* clear hash */ + zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); + s->strstart = s->w_size; + } + else { + if (s->window_size - s->strstart <= used) { + /* Slide the window down. */ + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + } + zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); + s->strstart += used; + } + s->block_start = s->strstart; + s->insert += MIN(used, s->w_size - s->insert); + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* If the last block was written to next_out, then done. */ + if (last) + return finish_done; + + /* If flushing and all input has been consumed, then done. */ + if (flush != Z_NO_FLUSH && flush != Z_FINISH && + s->strm->avail_in == 0 && (long)s->strstart == s->block_start) + return block_done; + + /* Fill the window with any remaining input. */ + have = s->window_size - s->strstart - 1; + if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) { + /* Slide the window down. */ + s->block_start -= s->w_size; + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + have += s->w_size; /* more space now */ + } + if (have > s->strm->avail_in) + have = s->strm->avail_in; + if (have) { + read_buf(s->strm, s->window + s->strstart, have); + s->strstart += have; + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* There was not enough avail_out to write a complete worthy or flushed + * stored block to next_out. Write a stored block to pending instead, if we + * have enough input for a worthy block, or if flushing and there is enough + * room for the remaining input as a stored block in the pending buffer. + */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + /* maximum stored block length that will fit in pending: */ + have = MIN(s->pending_buf_size - have, MAX_STORED); + min_block = MIN(have, s->w_size); + left = s->strstart - s->block_start; + if (left >= min_block || + ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && + s->strm->avail_in == 0 && left <= have)) { + len = MIN(left, have); + last = flush == Z_FINISH && s->strm->avail_in == 0 && + len == left ? 1 : 0; + _tr_stored_block(s, (charf *)s->window + s->block_start, len, last); + s->block_start += len; + flush_pending(s->strm); + } + + /* We've done all we can with the available input and output. */ + return last ? finish_started : need_more; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (uInt)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/third_party/zlib/v1_2_11/deflate.h b/third_party/zlib/v1_2_11/deflate.h new file mode 100644 index 0000000..23ecdd3 --- /dev/null +++ b/third_party/zlib/v1_2_11/deflate.h @@ -0,0 +1,349 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 /* zlib header -> BUSY_STATE */ +#ifdef GZIP +# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */ +#endif +#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */ +#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */ +#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */ +#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */ +#define BUSY_STATE 113 /* deflate -> FINISH_STATE */ +#define FINISH_STATE 666 /* stream complete */ +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + const static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + ulg pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef ZLIB_DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef ZLIB_DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (uch)(length); \ + ush dist = (ush)(distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/third_party/zlib/v1_2_11/doc/algorithm.txt b/third_party/zlib/v1_2_11/doc/algorithm.txt new file mode 100644 index 0000000..c97f495 --- /dev/null +++ b/third_party/zlib/v1_2_11/doc/algorithm.txt @@ -0,0 +1,209 @@ +1. Compression algorithm (deflate) + +The deflation algorithm used by gzip (also zip and zlib) is a variation of +LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in +the input data. The second occurrence of a string is replaced by a +pointer to the previous string, in the form of a pair (distance, +length). Distances are limited to 32K bytes, and lengths are limited +to 258 bytes. When a string does not occur anywhere in the previous +32K bytes, it is emitted as a sequence of literal bytes. (In this +description, `string' must be taken as an arbitrary sequence of bytes, +and is not restricted to printable characters.) + +Literals or match lengths are compressed with one Huffman tree, and +match distances are compressed with another tree. The trees are stored +in a compact form at the start of each block. The blocks can have any +size (except that the compressed data for one block must fit in +available memory). A block is terminated when deflate() determines that +it would be useful to start another block with fresh trees. (This is +somewhat similar to the behavior of LZW-based _compress_.) + +Duplicated strings are found using a hash table. All input strings of +length 3 are inserted in the hash table. A hash index is computed for +the next 3 bytes. If the hash chain for this index is not empty, all +strings in the chain are compared with the current input string, and +the longest match is selected. + +The hash chains are searched starting with the most recent strings, to +favor small distances and thus take advantage of the Huffman encoding. +The hash chains are singly linked. There are no deletions from the +hash chains, the algorithm simply discards matches that are too old. + +To avoid a worst-case situation, very long hash chains are arbitrarily +truncated at a certain length, determined by a runtime option (level +parameter of deflateInit). So deflate() does not always find the longest +possible match but generally finds a match which is long enough. + +deflate() also defers the selection of matches with a lazy evaluation +mechanism. After a match of length N has been found, deflate() searches for +a longer match at the next input byte. If a longer match is found, the +previous match is truncated to a length of one (thus producing a single +literal byte) and the process of lazy evaluation begins again. Otherwise, +the original match is kept, and the next match search is attempted only N +steps later. + +The lazy match evaluation is also subject to a runtime parameter. If +the current match is long enough, deflate() reduces the search for a longer +match, thus speeding up the whole process. If compression ratio is more +important than speed, deflate() attempts a complete second search even if +the first match is already long enough. + +The lazy match evaluation is not performed for the fastest compression +modes (level parameter 1 to 3). For these fast modes, new strings +are inserted in the hash table only when no match was found, or +when the match is not too long. This degrades the compression ratio +but saves time since there are both fewer insertions and fewer searches. + + +2. Decompression algorithm (inflate) + +2.1 Introduction + +The key question is how to represent a Huffman code (or any prefix code) so +that you can decode fast. The most important characteristic is that shorter +codes are much more common than longer codes, so pay attention to decoding the +short codes fast, and let the long codes take longer to decode. + +inflate() sets up a first level table that covers some number of bits of +input less than the length of longest code. It gets that many bits from the +stream, and looks it up in the table. The table will tell if the next +code is that many bits or less and how many, and if it is, it will tell +the value, else it will point to the next level table for which inflate() +grabs more bits and tries to decode a longer code. + +How many bits to make the first lookup is a tradeoff between the time it +takes to decode and the time it takes to build the table. If building the +table took no time (and if you had infinite memory), then there would only +be a first level table to cover all the way to the longest code. However, +building the table ends up taking a lot longer for more bits since short +codes are replicated many times in such a table. What inflate() does is +simply to make the number of bits in the first table a variable, and then +to set that variable for the maximum speed. + +For inflate, which has 286 possible codes for the literal/length tree, the size +of the first table is nine bits. Also the distance trees have 30 possible +values, and the size of the first table is six bits. Note that for each of +those cases, the table ended up one bit longer than the ``average'' code +length, i.e. the code length of an approximately flat code which would be a +little more than eight bits for 286 symbols and a little less than five bits +for 30 symbols. + + +2.2 More details on the inflate table lookup + +Ok, you want to know what this cleverly obfuscated inflate tree actually +looks like. You are correct that it's not a Huffman tree. It is simply a +lookup table for the first, let's say, nine bits of a Huffman symbol. The +symbol could be as short as one bit or as long as 15 bits. If a particular +symbol is shorter than nine bits, then that symbol's translation is duplicated +in all those entries that start with that symbol's bits. For example, if the +symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a +symbol is nine bits long, it appears in the table once. + +If the symbol is longer than nine bits, then that entry in the table points +to another similar table for the remaining bits. Again, there are duplicated +entries as needed. The idea is that most of the time the symbol will be short +and there will only be one table look up. (That's whole idea behind data +compression in the first place.) For the less frequent long symbols, there +will be two lookups. If you had a compression method with really long +symbols, you could have as many levels of lookups as is efficient. For +inflate, two is enough. + +So a table entry either points to another table (in which case nine bits in +the above example are gobbled), or it contains the translation for the symbol +and the number of bits to gobble. Then you start again with the next +ungobbled bit. + +You may wonder: why not just have one lookup table for how ever many bits the +longest symbol is? The reason is that if you do that, you end up spending +more time filling in duplicate symbol entries than you do actually decoding. +At least for deflate's output that generates new trees every several 10's of +kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code +would take too long if you're only decoding several thousand symbols. At the +other extreme, you could make a new table for every bit in the code. In fact, +that's essentially a Huffman tree. But then you spend too much time +traversing the tree while decoding, even for short symbols. + +So the number of bits for the first lookup table is a trade of the time to +fill out the table vs. the time spent looking at the second level and above of +the table. + +Here is an example, scaled down: + +The code being decoded, with 10 symbols, from 1 to 6 bits long: + +A: 0 +B: 10 +C: 1100 +D: 11010 +E: 11011 +F: 11100 +G: 11101 +H: 11110 +I: 111110 +J: 111111 + +Let's make the first table three bits long (eight entries): + +000: A,1 +001: A,1 +010: A,1 +011: A,1 +100: B,2 +101: B,2 +110: -> table X (gobble 3 bits) +111: -> table Y (gobble 3 bits) + +Each entry is what the bits decode as and how many bits that is, i.e. how +many bits to gobble. Or the entry points to another table, with the number of +bits to gobble implicit in the size of the table. + +Table X is two bits long since the longest code starting with 110 is five bits +long: + +00: C,1 +01: C,1 +10: D,2 +11: E,2 + +Table Y is three bits long since the longest code starting with 111 is six +bits long: + +000: F,2 +001: F,2 +010: G,2 +011: G,2 +100: H,2 +101: H,2 +110: I,3 +111: J,3 + +So what we have here are three tables with a total of 20 entries that had to +be constructed. That's compared to 64 entries for a single table. Or +compared to 16 entries for a Huffman tree (six two entry tables and one four +entry table). Assuming that the code ideally represents the probability of +the symbols, it takes on the average 1.25 lookups per symbol. That's compared +to one lookup for the single table, or 1.66 lookups per symbol for the +Huffman tree. + +There, I think that gives you a picture of what's going on. For inflate, the +meaning of a particular symbol is often more than just a letter. It can be a +byte (a "literal"), or it can be either a length or a distance which +indicates a base value and a number of bits to fetch after the code that is +added to the base value. Or it might be the special end-of-block code. The +data structures created in inftrees.c try to encode all that information +compactly in the tables. + + +Jean-loup Gailly Mark Adler +jloup@gzip.org madler@alumni.caltech.edu + + +References: + +[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data +Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3, +pp. 337-343. + +``DEFLATE Compressed Data Format Specification'' available in +http://tools.ietf.org/html/rfc1951 diff --git a/third_party/zlib/v1_2_11/doc/rfc1950.txt b/third_party/zlib/v1_2_11/doc/rfc1950.txt new file mode 100644 index 0000000..ce6428a --- /dev/null +++ b/third_party/zlib/v1_2_11/doc/rfc1950.txt @@ -0,0 +1,619 @@ + + + + + + +Network Working Group P. Deutsch +Request for Comments: 1950 Aladdin Enterprises +Category: Informational J-L. Gailly + Info-ZIP + May 1996 + + + ZLIB Compressed Data Format Specification version 3.3 + +Status of This Memo + + This memo provides information for the Internet community. This memo + does not specify an Internet standard of any kind. Distribution of + this memo is unlimited. + +IESG Note: + + The IESG takes no position on the validity of any Intellectual + Property Rights statements contained in this document. + +Notices + + Copyright (c) 1996 L. Peter Deutsch and Jean-Loup Gailly + + Permission is granted to copy and distribute this document for any + purpose and without charge, including translations into other + languages and incorporation into compilations, provided that the + copyright notice and this notice are preserved, and that any + substantive changes or deletions from the original are clearly + marked. + + A pointer to the latest version of this and related documentation in + HTML format can be found at the URL + . + +Abstract + + This specification defines a lossless compressed data format. The + data can be produced or consumed, even for an arbitrarily long + sequentially presented input data stream, using only an a priori + bounded amount of intermediate storage. The format presently uses + the DEFLATE compression method but can be easily extended to use + other compression methods. It can be implemented readily in a manner + not covered by patents. This specification also defines the ADLER-32 + checksum (an extension and improvement of the Fletcher checksum), + used for detection of data corruption, and provides an algorithm for + computing it. + + + + +Deutsch & Gailly Informational [Page 1] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + +Table of Contents + + 1. Introduction ................................................... 2 + 1.1. Purpose ................................................... 2 + 1.2. Intended audience ......................................... 3 + 1.3. Scope ..................................................... 3 + 1.4. Compliance ................................................ 3 + 1.5. Definitions of terms and conventions used ................ 3 + 1.6. Changes from previous versions ............................ 3 + 2. Detailed specification ......................................... 3 + 2.1. Overall conventions ....................................... 3 + 2.2. Data format ............................................... 4 + 2.3. Compliance ................................................ 7 + 3. References ..................................................... 7 + 4. Source code .................................................... 8 + 5. Security Considerations ........................................ 8 + 6. Acknowledgements ............................................... 8 + 7. Authors' Addresses ............................................. 8 + 8. Appendix: Rationale ............................................ 9 + 9. Appendix: Sample code ..........................................10 + +1. Introduction + + 1.1. Purpose + + The purpose of this specification is to define a lossless + compressed data format that: + + * Is independent of CPU type, operating system, file system, + and character set, and hence can be used for interchange; + + * Can be produced or consumed, even for an arbitrarily long + sequentially presented input data stream, using only an a + priori bounded amount of intermediate storage, and hence can + be used in data communications or similar structures such as + Unix filters; + + * Can use a number of different compression methods; + + * Can be implemented readily in a manner not covered by + patents, and hence can be practiced freely. + + The data format defined by this specification does not attempt to + allow random access to compressed data. + + + + + + + +Deutsch & Gailly Informational [Page 2] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + 1.2. Intended audience + + This specification is intended for use by implementors of software + to compress data into zlib format and/or decompress data from zlib + format. + + The text of the specification assumes a basic background in + programming at the level of bits and other primitive data + representations. + + 1.3. Scope + + The specification specifies a compressed data format that can be + used for in-memory compression of a sequence of arbitrary bytes. + + 1.4. Compliance + + Unless otherwise indicated below, a compliant decompressor must be + able to accept and decompress any data set that conforms to all + the specifications presented here; a compliant compressor must + produce data sets that conform to all the specifications presented + here. + + 1.5. Definitions of terms and conventions used + + byte: 8 bits stored or transmitted as a unit (same as an octet). + (For this specification, a byte is exactly 8 bits, even on + machines which store a character on a number of bits different + from 8.) See below, for the numbering of bits within a byte. + + 1.6. Changes from previous versions + + Version 3.1 was the first public release of this specification. + In version 3.2, some terminology was changed and the Adler-32 + sample code was rewritten for clarity. In version 3.3, the + support for a preset dictionary was introduced, and the + specification was converted to RFC style. + +2. Detailed specification + + 2.1. Overall conventions + + In the diagrams below, a box like this: + + +---+ + | | <-- the vertical bars might be missing + +---+ + + + + +Deutsch & Gailly Informational [Page 3] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + represents one byte; a box like this: + + +==============+ + | | + +==============+ + + represents a variable number of bytes. + + Bytes stored within a computer do not have a "bit order", since + they are always treated as a unit. However, a byte considered as + an integer between 0 and 255 does have a most- and least- + significant bit, and since we write numbers with the most- + significant digit on the left, we also write bytes with the most- + significant bit on the left. In the diagrams below, we number the + bits of a byte so that bit 0 is the least-significant bit, i.e., + the bits are numbered: + + +--------+ + |76543210| + +--------+ + + Within a computer, a number may occupy multiple bytes. All + multi-byte numbers in the format described here are stored with + the MOST-significant byte first (at the lower memory address). + For example, the decimal number 520 is stored as: + + 0 1 + +--------+--------+ + |00000010|00001000| + +--------+--------+ + ^ ^ + | | + | + less significant byte = 8 + + more significant byte = 2 x 256 + + 2.2. Data format + + A zlib stream has the following structure: + + 0 1 + +---+---+ + |CMF|FLG| (more-->) + +---+---+ + + + + + + + + +Deutsch & Gailly Informational [Page 4] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + (if FLG.FDICT set) + + 0 1 2 3 + +---+---+---+---+ + | DICTID | (more-->) + +---+---+---+---+ + + +=====================+---+---+---+---+ + |...compressed data...| ADLER32 | + +=====================+---+---+---+---+ + + Any data which may appear after ADLER32 are not part of the zlib + stream. + + CMF (Compression Method and flags) + This byte is divided into a 4-bit compression method and a 4- + bit information field depending on the compression method. + + bits 0 to 3 CM Compression method + bits 4 to 7 CINFO Compression info + + CM (Compression method) + This identifies the compression method used in the file. CM = 8 + denotes the "deflate" compression method with a window size up + to 32K. This is the method used by gzip and PNG (see + references [1] and [2] in Chapter 3, below, for the reference + documents). CM = 15 is reserved. It might be used in a future + version of this specification to indicate the presence of an + extra field before the compressed data. + + CINFO (Compression info) + For CM = 8, CINFO is the base-2 logarithm of the LZ77 window + size, minus eight (CINFO=7 indicates a 32K window size). Values + of CINFO above 7 are not allowed in this version of the + specification. CINFO is not defined in this specification for + CM not equal to 8. + + FLG (FLaGs) + This flag byte is divided as follows: + + bits 0 to 4 FCHECK (check bits for CMF and FLG) + bit 5 FDICT (preset dictionary) + bits 6 to 7 FLEVEL (compression level) + + The FCHECK value must be such that CMF and FLG, when viewed as + a 16-bit unsigned integer stored in MSB order (CMF*256 + FLG), + is a multiple of 31. + + + + +Deutsch & Gailly Informational [Page 5] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + FDICT (Preset dictionary) + If FDICT is set, a DICT dictionary identifier is present + immediately after the FLG byte. The dictionary is a sequence of + bytes which are initially fed to the compressor without + producing any compressed output. DICT is the Adler-32 checksum + of this sequence of bytes (see the definition of ADLER32 + below). The decompressor can use this identifier to determine + which dictionary has been used by the compressor. + + FLEVEL (Compression level) + These flags are available for use by specific compression + methods. The "deflate" method (CM = 8) sets these flags as + follows: + + 0 - compressor used fastest algorithm + 1 - compressor used fast algorithm + 2 - compressor used default algorithm + 3 - compressor used maximum compression, slowest algorithm + + The information in FLEVEL is not needed for decompression; it + is there to indicate if recompression might be worthwhile. + + compressed data + For compression method 8, the compressed data is stored in the + deflate compressed data format as described in the document + "DEFLATE Compressed Data Format Specification" by L. Peter + Deutsch. (See reference [3] in Chapter 3, below) + + Other compressed data formats are not specified in this version + of the zlib specification. + + ADLER32 (Adler-32 checksum) + This contains a checksum value of the uncompressed data + (excluding any dictionary data) computed according to Adler-32 + algorithm. This algorithm is a 32-bit extension and improvement + of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 + standard. See references [4] and [5] in Chapter 3, below) + + Adler-32 is composed of two sums accumulated per byte: s1 is + the sum of all bytes, s2 is the sum of all s1 values. Both sums + are done modulo 65521. s1 is initialized to 1, s2 to zero. The + Adler-32 checksum is stored as s2*65536 + s1 in most- + significant-byte first (network) order. + + + + + + + + +Deutsch & Gailly Informational [Page 6] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + 2.3. Compliance + + A compliant compressor must produce streams with correct CMF, FLG + and ADLER32, but need not support preset dictionaries. When the + zlib data format is used as part of another standard data format, + the compressor may use only preset dictionaries that are specified + by this other data format. If this other format does not use the + preset dictionary feature, the compressor must not set the FDICT + flag. + + A compliant decompressor must check CMF, FLG, and ADLER32, and + provide an error indication if any of these have incorrect values. + A compliant decompressor must give an error indication if CM is + not one of the values defined in this specification (only the + value 8 is permitted in this version), since another value could + indicate the presence of new features that would cause subsequent + data to be interpreted incorrectly. A compliant decompressor must + give an error indication if FDICT is set and DICTID is not the + identifier of a known preset dictionary. A decompressor may + ignore FLEVEL and still be compliant. When the zlib data format + is being used as a part of another standard format, a compliant + decompressor must support all the preset dictionaries specified by + the other format. When the other format does not use the preset + dictionary feature, a compliant decompressor must reject any + stream in which the FDICT flag is set. + +3. References + + [1] Deutsch, L.P.,"GZIP Compressed Data Format Specification", + available in ftp://ftp.uu.net/pub/archiving/zip/doc/ + + [2] Thomas Boutell, "PNG (Portable Network Graphics) specification", + available in ftp://ftp.uu.net/graphics/png/documents/ + + [3] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", + available in ftp://ftp.uu.net/pub/archiving/zip/doc/ + + [4] Fletcher, J. G., "An Arithmetic Checksum for Serial + Transmissions," IEEE Transactions on Communications, Vol. COM-30, + No. 1, January 1982, pp. 247-252. + + [5] ITU-T Recommendation X.224, Annex D, "Checksum Algorithms," + November, 1993, pp. 144, 145. (Available from + gopher://info.itu.ch). ITU-T X.244 is also the same as ISO 8073. + + + + + + + +Deutsch & Gailly Informational [Page 7] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + +4. Source code + + Source code for a C language implementation of a "zlib" compliant + library is available at ftp://ftp.uu.net/pub/archiving/zip/zlib/. + +5. Security Considerations + + A decoder that fails to check the ADLER32 checksum value may be + subject to undetected data corruption. + +6. Acknowledgements + + Trademarks cited in this document are the property of their + respective owners. + + Jean-Loup Gailly and Mark Adler designed the zlib format and wrote + the related software described in this specification. Glenn + Randers-Pehrson converted this document to RFC and HTML format. + +7. Authors' Addresses + + L. Peter Deutsch + Aladdin Enterprises + 203 Santa Margarita Ave. + Menlo Park, CA 94025 + + Phone: (415) 322-0103 (AM only) + FAX: (415) 322-1734 + EMail: + + + Jean-Loup Gailly + + EMail: + + Questions about the technical content of this specification can be + sent by email to + + Jean-Loup Gailly and + Mark Adler + + Editorial comments on this specification can be sent by email to + + L. Peter Deutsch and + Glenn Randers-Pehrson + + + + + + +Deutsch & Gailly Informational [Page 8] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + +8. Appendix: Rationale + + 8.1. Preset dictionaries + + A preset dictionary is specially useful to compress short input + sequences. The compressor can take advantage of the dictionary + context to encode the input in a more compact manner. The + decompressor can be initialized with the appropriate context by + virtually decompressing a compressed version of the dictionary + without producing any output. However for certain compression + algorithms such as the deflate algorithm this operation can be + achieved without actually performing any decompression. + + The compressor and the decompressor must use exactly the same + dictionary. The dictionary may be fixed or may be chosen among a + certain number of predefined dictionaries, according to the kind + of input data. The decompressor can determine which dictionary has + been chosen by the compressor by checking the dictionary + identifier. This document does not specify the contents of + predefined dictionaries, since the optimal dictionaries are + application specific. Standard data formats using this feature of + the zlib specification must precisely define the allowed + dictionaries. + + 8.2. The Adler-32 algorithm + + The Adler-32 algorithm is much faster than the CRC32 algorithm yet + still provides an extremely low probability of undetected errors. + + The modulo on unsigned long accumulators can be delayed for 5552 + bytes, so the modulo operation time is negligible. If the bytes + are a, b, c, the second sum is 3a + 2b + c + 3, and so is position + and order sensitive, unlike the first sum, which is just a + checksum. That 65521 is prime is important to avoid a possible + large class of two-byte errors that leave the check unchanged. + (The Fletcher checksum uses 255, which is not prime and which also + makes the Fletcher check insensitive to single byte changes 0 <-> + 255.) + + The sum s1 is initialized to 1 instead of zero to make the length + of the sequence part of s2, so that the length does not have to be + checked separately. (Any sequence of zeroes has a Fletcher + checksum of zero.) + + + + + + + + +Deutsch & Gailly Informational [Page 9] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + +9. Appendix: Sample code + + The following C code computes the Adler-32 checksum of a data buffer. + It is written for clarity, not for speed. The sample code is in the + ANSI C programming language. Non C users may find it easier to read + with these hints: + + & Bitwise AND operator. + >> Bitwise right shift operator. When applied to an + unsigned quantity, as here, right shift inserts zero bit(s) + at the left. + << Bitwise left shift operator. Left shift inserts zero + bit(s) at the right. + ++ "n++" increments the variable n. + % modulo operator: a % b is the remainder of a divided by b. + + #define BASE 65521 /* largest prime smaller than 65536 */ + + /* + Update a running Adler-32 checksum with the bytes buf[0..len-1] + and return the updated checksum. The Adler-32 checksum should be + initialized to 1. + + Usage example: + + unsigned long adler = 1L; + + while (read_buffer(buffer, length) != EOF) { + adler = update_adler32(adler, buffer, length); + } + if (adler != original_adler) error(); + */ + unsigned long update_adler32(unsigned long adler, + unsigned char *buf, int len) + { + unsigned long s1 = adler & 0xffff; + unsigned long s2 = (adler >> 16) & 0xffff; + int n; + + for (n = 0; n < len; n++) { + s1 = (s1 + buf[n]) % BASE; + s2 = (s2 + s1) % BASE; + } + return (s2 << 16) + s1; + } + + /* Return the adler32 of the bytes buf[0..len-1] */ + + + + +Deutsch & Gailly Informational [Page 10] + +RFC 1950 ZLIB Compressed Data Format Specification May 1996 + + + unsigned long adler32(unsigned char *buf, int len) + { + return update_adler32(1L, buf, len); + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Deutsch & Gailly Informational [Page 11] + diff --git a/third_party/zlib/v1_2_11/doc/rfc1951.txt b/third_party/zlib/v1_2_11/doc/rfc1951.txt new file mode 100644 index 0000000..403c8c7 --- /dev/null +++ b/third_party/zlib/v1_2_11/doc/rfc1951.txt @@ -0,0 +1,955 @@ + + + + + + +Network Working Group P. Deutsch +Request for Comments: 1951 Aladdin Enterprises +Category: Informational May 1996 + + + DEFLATE Compressed Data Format Specification version 1.3 + +Status of This Memo + + This memo provides information for the Internet community. This memo + does not specify an Internet standard of any kind. Distribution of + this memo is unlimited. + +IESG Note: + + The IESG takes no position on the validity of any Intellectual + Property Rights statements contained in this document. + +Notices + + Copyright (c) 1996 L. Peter Deutsch + + Permission is granted to copy and distribute this document for any + purpose and without charge, including translations into other + languages and incorporation into compilations, provided that the + copyright notice and this notice are preserved, and that any + substantive changes or deletions from the original are clearly + marked. + + A pointer to the latest version of this and related documentation in + HTML format can be found at the URL + . + +Abstract + + This specification defines a lossless compressed data format that + compresses data using a combination of the LZ77 algorithm and Huffman + coding, with efficiency comparable to the best currently available + general-purpose compression methods. The data can be produced or + consumed, even for an arbitrarily long sequentially presented input + data stream, using only an a priori bounded amount of intermediate + storage. The format can be implemented readily in a manner not + covered by patents. + + + + + + + + +Deutsch Informational [Page 1] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + +Table of Contents + + 1. Introduction ................................................... 2 + 1.1. Purpose ................................................... 2 + 1.2. Intended audience ......................................... 3 + 1.3. Scope ..................................................... 3 + 1.4. Compliance ................................................ 3 + 1.5. Definitions of terms and conventions used ................ 3 + 1.6. Changes from previous versions ............................ 4 + 2. Compressed representation overview ............................. 4 + 3. Detailed specification ......................................... 5 + 3.1. Overall conventions ....................................... 5 + 3.1.1. Packing into bytes .................................. 5 + 3.2. Compressed block format ................................... 6 + 3.2.1. Synopsis of prefix and Huffman coding ............... 6 + 3.2.2. Use of Huffman coding in the "deflate" format ....... 7 + 3.2.3. Details of block format ............................. 9 + 3.2.4. Non-compressed blocks (BTYPE=00) ................... 11 + 3.2.5. Compressed blocks (length and distance codes) ...... 11 + 3.2.6. Compression with fixed Huffman codes (BTYPE=01) .... 12 + 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) .. 13 + 3.3. Compliance ............................................... 14 + 4. Compression algorithm details ................................. 14 + 5. References .................................................... 16 + 6. Security Considerations ....................................... 16 + 7. Source code ................................................... 16 + 8. Acknowledgements .............................................. 16 + 9. Author's Address .............................................. 17 + +1. Introduction + + 1.1. Purpose + + The purpose of this specification is to define a lossless + compressed data format that: + * Is independent of CPU type, operating system, file system, + and character set, and hence can be used for interchange; + * Can be produced or consumed, even for an arbitrarily long + sequentially presented input data stream, using only an a + priori bounded amount of intermediate storage, and hence + can be used in data communications or similar structures + such as Unix filters; + * Compresses data with efficiency comparable to the best + currently available general-purpose compression methods, + and in particular considerably better than the "compress" + program; + * Can be implemented readily in a manner not covered by + patents, and hence can be practiced freely; + + + +Deutsch Informational [Page 2] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + * Is compatible with the file format produced by the current + widely used gzip utility, in that conforming decompressors + will be able to read data produced by the existing gzip + compressor. + + The data format defined by this specification does not attempt to: + + * Allow random access to compressed data; + * Compress specialized data (e.g., raster graphics) as well + as the best currently available specialized algorithms. + + A simple counting argument shows that no lossless compression + algorithm can compress every possible input data set. For the + format defined here, the worst case expansion is 5 bytes per 32K- + byte block, i.e., a size increase of 0.015% for large data sets. + English text usually compresses by a factor of 2.5 to 3; + executable files usually compress somewhat less; graphical data + such as raster images may compress much more. + + 1.2. Intended audience + + This specification is intended for use by implementors of software + to compress data into "deflate" format and/or decompress data from + "deflate" format. + + The text of the specification assumes a basic background in + programming at the level of bits and other primitive data + representations. Familiarity with the technique of Huffman coding + is helpful but not required. + + 1.3. Scope + + The specification specifies a method for representing a sequence + of bytes as a (usually shorter) sequence of bits, and a method for + packing the latter bit sequence into bytes. + + 1.4. Compliance + + Unless otherwise indicated below, a compliant decompressor must be + able to accept and decompress any data set that conforms to all + the specifications presented here; a compliant compressor must + produce data sets that conform to all the specifications presented + here. + + 1.5. Definitions of terms and conventions used + + Byte: 8 bits stored or transmitted as a unit (same as an octet). + For this specification, a byte is exactly 8 bits, even on machines + + + +Deutsch Informational [Page 3] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + which store a character on a number of bits different from eight. + See below, for the numbering of bits within a byte. + + String: a sequence of arbitrary bytes. + + 1.6. Changes from previous versions + + There have been no technical changes to the deflate format since + version 1.1 of this specification. In version 1.2, some + terminology was changed. Version 1.3 is a conversion of the + specification to RFC style. + +2. Compressed representation overview + + A compressed data set consists of a series of blocks, corresponding + to successive blocks of input data. The block sizes are arbitrary, + except that non-compressible blocks are limited to 65,535 bytes. + + Each block is compressed using a combination of the LZ77 algorithm + and Huffman coding. The Huffman trees for each block are independent + of those for previous or subsequent blocks; the LZ77 algorithm may + use a reference to a duplicated string occurring in a previous block, + up to 32K input bytes before. + + Each block consists of two parts: a pair of Huffman code trees that + describe the representation of the compressed data part, and a + compressed data part. (The Huffman trees themselves are compressed + using Huffman encoding.) The compressed data consists of a series of + elements of two types: literal bytes (of strings that have not been + detected as duplicated within the previous 32K input bytes), and + pointers to duplicated strings, where a pointer is represented as a + pair . The representation used in the + "deflate" format limits distances to 32K bytes and lengths to 258 + bytes, but does not limit the size of a block, except for + uncompressible blocks, which are limited as noted above. + + Each type of value (literals, distances, and lengths) in the + compressed data is represented using a Huffman code, using one code + tree for literals and lengths and a separate code tree for distances. + The code trees for each block appear in a compact form just before + the compressed data for that block. + + + + + + + + + + +Deutsch Informational [Page 4] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + +3. Detailed specification + + 3.1. Overall conventions In the diagrams below, a box like this: + + +---+ + | | <-- the vertical bars might be missing + +---+ + + represents one byte; a box like this: + + +==============+ + | | + +==============+ + + represents a variable number of bytes. + + Bytes stored within a computer do not have a "bit order", since + they are always treated as a unit. However, a byte considered as + an integer between 0 and 255 does have a most- and least- + significant bit, and since we write numbers with the most- + significant digit on the left, we also write bytes with the most- + significant bit on the left. In the diagrams below, we number the + bits of a byte so that bit 0 is the least-significant bit, i.e., + the bits are numbered: + + +--------+ + |76543210| + +--------+ + + Within a computer, a number may occupy multiple bytes. All + multi-byte numbers in the format described here are stored with + the least-significant byte first (at the lower memory address). + For example, the decimal number 520 is stored as: + + 0 1 + +--------+--------+ + |00001000|00000010| + +--------+--------+ + ^ ^ + | | + | + more significant byte = 2 x 256 + + less significant byte = 8 + + 3.1.1. Packing into bytes + + This document does not address the issue of the order in which + bits of a byte are transmitted on a bit-sequential medium, + since the final data format described here is byte- rather than + + + +Deutsch Informational [Page 5] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + bit-oriented. However, we describe the compressed block format + in below, as a sequence of data elements of various bit + lengths, not a sequence of bytes. We must therefore specify + how to pack these data elements into bytes to form the final + compressed byte sequence: + + * Data elements are packed into bytes in order of + increasing bit number within the byte, i.e., starting + with the least-significant bit of the byte. + * Data elements other than Huffman codes are packed + starting with the least-significant bit of the data + element. + * Huffman codes are packed starting with the most- + significant bit of the code. + + In other words, if one were to print out the compressed data as + a sequence of bytes, starting with the first byte at the + *right* margin and proceeding to the *left*, with the most- + significant bit of each byte on the left as usual, one would be + able to parse the result from right to left, with fixed-width + elements in the correct MSB-to-LSB order and Huffman codes in + bit-reversed order (i.e., with the first bit of the code in the + relative LSB position). + + 3.2. Compressed block format + + 3.2.1. Synopsis of prefix and Huffman coding + + Prefix coding represents symbols from an a priori known + alphabet by bit sequences (codes), one code for each symbol, in + a manner such that different symbols may be represented by bit + sequences of different lengths, but a parser can always parse + an encoded string unambiguously symbol-by-symbol. + + We define a prefix code in terms of a binary tree in which the + two edges descending from each non-leaf node are labeled 0 and + 1 and in which the leaf nodes correspond one-for-one with (are + labeled with) the symbols of the alphabet; then the code for a + symbol is the sequence of 0's and 1's on the edges leading from + the root to the leaf labeled with that symbol. For example: + + + + + + + + + + + +Deutsch Informational [Page 6] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + /\ Symbol Code + 0 1 ------ ---- + / \ A 00 + /\ B B 1 + 0 1 C 011 + / \ D 010 + A /\ + 0 1 + / \ + D C + + A parser can decode the next symbol from an encoded input + stream by walking down the tree from the root, at each step + choosing the edge corresponding to the next input bit. + + Given an alphabet with known symbol frequencies, the Huffman + algorithm allows the construction of an optimal prefix code + (one which represents strings with those symbol frequencies + using the fewest bits of any possible prefix codes for that + alphabet). Such a code is called a Huffman code. (See + reference [1] in Chapter 5, references for additional + information on Huffman codes.) + + Note that in the "deflate" format, the Huffman codes for the + various alphabets must not exceed certain maximum code lengths. + This constraint complicates the algorithm for computing code + lengths from symbol frequencies. Again, see Chapter 5, + references for details. + + 3.2.2. Use of Huffman coding in the "deflate" format + + The Huffman codes used for each alphabet in the "deflate" + format have two additional rules: + + * All codes of a given bit length have lexicographically + consecutive values, in the same order as the symbols + they represent; + + * Shorter codes lexicographically precede longer codes. + + + + + + + + + + + + +Deutsch Informational [Page 7] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + We could recode the example above to follow this rule as + follows, assuming that the order of the alphabet is ABCD: + + Symbol Code + ------ ---- + A 10 + B 0 + C 110 + D 111 + + I.e., 0 precedes 10 which precedes 11x, and 110 and 111 are + lexicographically consecutive. + + Given this rule, we can define the Huffman code for an alphabet + just by giving the bit lengths of the codes for each symbol of + the alphabet in order; this is sufficient to determine the + actual codes. In our example, the code is completely defined + by the sequence of bit lengths (2, 1, 3, 3). The following + algorithm generates the codes as integers, intended to be read + from most- to least-significant bit. The code lengths are + initially in tree[I].Len; the codes are produced in + tree[I].Code. + + 1) Count the number of codes for each code length. Let + bl_count[N] be the number of codes of length N, N >= 1. + + 2) Find the numerical value of the smallest code for each + code length: + + code = 0; + bl_count[0] = 0; + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits-1]) << 1; + next_code[bits] = code; + } + + 3) Assign numerical values to all codes, using consecutive + values for all codes of the same length with the base + values determined at step 2. Codes that are never used + (which have a bit length of zero) must not be assigned a + value. + + for (n = 0; n <= max_code; n++) { + len = tree[n].Len; + if (len != 0) { + tree[n].Code = next_code[len]; + next_code[len]++; + } + + + +Deutsch Informational [Page 8] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + } + + Example: + + Consider the alphabet ABCDEFGH, with bit lengths (3, 3, 3, 3, + 3, 2, 4, 4). After step 1, we have: + + N bl_count[N] + - ----------- + 2 1 + 3 5 + 4 2 + + Step 2 computes the following next_code values: + + N next_code[N] + - ------------ + 1 0 + 2 0 + 3 2 + 4 14 + + Step 3 produces the following code values: + + Symbol Length Code + ------ ------ ---- + A 3 010 + B 3 011 + C 3 100 + D 3 101 + E 3 110 + F 2 00 + G 4 1110 + H 4 1111 + + 3.2.3. Details of block format + + Each block of compressed data begins with 3 header bits + containing the following data: + + first bit BFINAL + next 2 bits BTYPE + + Note that the header bits do not necessarily begin on a byte + boundary, since a block does not necessarily occupy an integral + number of bytes. + + + + + +Deutsch Informational [Page 9] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + BFINAL is set if and only if this is the last block of the data + set. + + BTYPE specifies how the data are compressed, as follows: + + 00 - no compression + 01 - compressed with fixed Huffman codes + 10 - compressed with dynamic Huffman codes + 11 - reserved (error) + + The only difference between the two compressed cases is how the + Huffman codes for the literal/length and distance alphabets are + defined. + + In all cases, the decoding algorithm for the actual data is as + follows: + + do + read block header from input stream. + if stored with no compression + skip any remaining bits in current partially + processed byte + read LEN and NLEN (see next section) + copy LEN bytes of data to output + otherwise + if compressed with dynamic Huffman codes + read representation of code trees (see + subsection below) + loop (until end of block code recognized) + decode literal/length value from input stream + if value < 256 + copy value (literal byte) to output stream + otherwise + if value = end of block (256) + break from loop + otherwise (value = 257..285) + decode distance from input stream + + move backwards distance bytes in the output + stream, and copy length bytes from this + position to the output stream. + end loop + while not last block + + Note that a duplicated string reference may refer to a string + in a previous block; i.e., the backward distance may cross one + or more block boundaries. However a distance cannot refer past + the beginning of the output stream. (An application using a + + + +Deutsch Informational [Page 10] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + preset dictionary might discard part of the output stream; a + distance can refer to that part of the output stream anyway) + Note also that the referenced string may overlap the current + position; for example, if the last 2 bytes decoded have values + X and Y, a string reference with + adds X,Y,X,Y,X to the output stream. + + We now specify each compression method in turn. + + 3.2.4. Non-compressed blocks (BTYPE=00) + + Any bits of input up to the next byte boundary are ignored. + The rest of the block consists of the following information: + + 0 1 2 3 4... + +---+---+---+---+================================+ + | LEN | NLEN |... LEN bytes of literal data...| + +---+---+---+---+================================+ + + LEN is the number of data bytes in the block. NLEN is the + one's complement of LEN. + + 3.2.5. Compressed blocks (length and distance codes) + + As noted above, encoded data blocks in the "deflate" format + consist of sequences of symbols drawn from three conceptually + distinct alphabets: either literal bytes, from the alphabet of + byte values (0..255), or pairs, + where the length is drawn from (3..258) and the distance is + drawn from (1..32,768). In fact, the literal and length + alphabets are merged into a single alphabet (0..285), where + values 0..255 represent literal bytes, the value 256 indicates + end-of-block, and values 257..285 represent length codes + (possibly in conjunction with extra bits following the symbol + code) as follows: + + + + + + + + + + + + + + + + +Deutsch Informational [Page 11] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + Extra Extra Extra + Code Bits Length(s) Code Bits Lengths Code Bits Length(s) + ---- ---- ------ ---- ---- ------- ---- ---- ------- + 257 0 3 267 1 15,16 277 4 67-82 + 258 0 4 268 1 17,18 278 4 83-98 + 259 0 5 269 2 19-22 279 4 99-114 + 260 0 6 270 2 23-26 280 4 115-130 + 261 0 7 271 2 27-30 281 5 131-162 + 262 0 8 272 2 31-34 282 5 163-194 + 263 0 9 273 3 35-42 283 5 195-226 + 264 0 10 274 3 43-50 284 5 227-257 + 265 1 11,12 275 3 51-58 285 0 258 + 266 1 13,14 276 3 59-66 + + The extra bits should be interpreted as a machine integer + stored with the most-significant bit first, e.g., bits 1110 + represent the value 14. + + Extra Extra Extra + Code Bits Dist Code Bits Dist Code Bits Distance + ---- ---- ---- ---- ---- ------ ---- ---- -------- + 0 0 1 10 4 33-48 20 9 1025-1536 + 1 0 2 11 4 49-64 21 9 1537-2048 + 2 0 3 12 5 65-96 22 10 2049-3072 + 3 0 4 13 5 97-128 23 10 3073-4096 + 4 1 5,6 14 6 129-192 24 11 4097-6144 + 5 1 7,8 15 6 193-256 25 11 6145-8192 + 6 2 9-12 16 7 257-384 26 12 8193-12288 + 7 2 13-16 17 7 385-512 27 12 12289-16384 + 8 3 17-24 18 8 513-768 28 13 16385-24576 + 9 3 25-32 19 8 769-1024 29 13 24577-32768 + + 3.2.6. Compression with fixed Huffman codes (BTYPE=01) + + The Huffman codes for the two alphabets are fixed, and are not + represented explicitly in the data. The Huffman code lengths + for the literal/length alphabet are: + + Lit Value Bits Codes + --------- ---- ----- + 0 - 143 8 00110000 through + 10111111 + 144 - 255 9 110010000 through + 111111111 + 256 - 279 7 0000000 through + 0010111 + 280 - 287 8 11000000 through + 11000111 + + + +Deutsch Informational [Page 12] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + The code lengths are sufficient to generate the actual codes, + as described above; we show the codes in the table for added + clarity. Literal/length values 286-287 will never actually + occur in the compressed data, but participate in the code + construction. + + Distance codes 0-31 are represented by (fixed-length) 5-bit + codes, with possible additional bits as shown in the table + shown in Paragraph 3.2.5, above. Note that distance codes 30- + 31 will never actually occur in the compressed data. + + 3.2.7. Compression with dynamic Huffman codes (BTYPE=10) + + The Huffman codes for the two alphabets appear in the block + immediately after the header bits and before the actual + compressed data, first the literal/length code and then the + distance code. Each code is defined by a sequence of code + lengths, as discussed in Paragraph 3.2.2, above. For even + greater compactness, the code length sequences themselves are + compressed using a Huffman code. The alphabet for code lengths + is as follows: + + 0 - 15: Represent code lengths of 0 - 15 + 16: Copy the previous code length 3 - 6 times. + The next 2 bits indicate repeat length + (0 = 3, ... , 3 = 6) + Example: Codes 8, 16 (+2 bits 11), + 16 (+2 bits 10) will expand to + 12 code lengths of 8 (1 + 6 + 5) + 17: Repeat a code length of 0 for 3 - 10 times. + (3 bits of length) + 18: Repeat a code length of 0 for 11 - 138 times + (7 bits of length) + + A code length of 0 indicates that the corresponding symbol in + the literal/length or distance alphabet will not occur in the + block, and should not participate in the Huffman code + construction algorithm given earlier. If only one distance + code is used, it is encoded using one bit, not zero bits; in + this case there is a single code length of one, with one unused + code. One distance code of zero bits means that there are no + distance codes used at all (the data is all literals). + + We can now define the format of the block: + + 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) + 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) + 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) + + + +Deutsch Informational [Page 13] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + (HCLEN + 4) x 3 bits: code lengths for the code length + alphabet given just above, in the order: 16, 17, 18, + 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 + + These code lengths are interpreted as 3-bit integers + (0-7); as above, a code length of 0 means the + corresponding symbol (literal/length or distance code + length) is not used. + + HLIT + 257 code lengths for the literal/length alphabet, + encoded using the code length Huffman code + + HDIST + 1 code lengths for the distance alphabet, + encoded using the code length Huffman code + + The actual compressed data of the block, + encoded using the literal/length and distance Huffman + codes + + The literal/length symbol 256 (end of data), + encoded using the literal/length Huffman code + + The code length repeat codes can cross from HLIT + 257 to the + HDIST + 1 code lengths. In other words, all code lengths form + a single sequence of HLIT + HDIST + 258 values. + + 3.3. Compliance + + A compressor may limit further the ranges of values specified in + the previous section and still be compliant; for example, it may + limit the range of backward pointers to some value smaller than + 32K. Similarly, a compressor may limit the size of blocks so that + a compressible block fits in memory. + + A compliant decompressor must accept the full range of possible + values defined in the previous section, and must accept blocks of + arbitrary size. + +4. Compression algorithm details + + While it is the intent of this document to define the "deflate" + compressed data format without reference to any particular + compression algorithm, the format is related to the compressed + formats produced by LZ77 (Lempel-Ziv 1977, see reference [2] below); + since many variations of LZ77 are patented, it is strongly + recommended that the implementor of a compressor follow the general + algorithm presented here, which is known not to be patented per se. + The material in this section is not part of the definition of the + + + +Deutsch Informational [Page 14] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + + specification per se, and a compressor need not follow it in order to + be compliant. + + The compressor terminates a block when it determines that starting a + new block with fresh trees would be useful, or when the block size + fills up the compressor's block buffer. + + The compressor uses a chained hash table to find duplicated strings, + using a hash function that operates on 3-byte sequences. At any + given point during compression, let XYZ be the next 3 input bytes to + be examined (not necessarily all different, of course). First, the + compressor examines the hash chain for XYZ. If the chain is empty, + the compressor simply writes out X as a literal byte and advances one + byte in the input. If the hash chain is not empty, indicating that + the sequence XYZ (or, if we are unlucky, some other 3 bytes with the + same hash function value) has occurred recently, the compressor + compares all strings on the XYZ hash chain with the actual input data + sequence starting at the current point, and selects the longest + match. + + The compressor searches the hash chains starting with the most recent + strings, to favor small distances and thus take advantage of the + Huffman encoding. The hash chains are singly linked. There are no + deletions from the hash chains; the algorithm simply discards matches + that are too old. To avoid a worst-case situation, very long hash + chains are arbitrarily truncated at a certain length, determined by a + run-time parameter. + + To improve overall compression, the compressor optionally defers the + selection of matches ("lazy matching"): after a match of length N has + been found, the compressor searches for a longer match starting at + the next input byte. If it finds a longer match, it truncates the + previous match to a length of one (thus producing a single literal + byte) and then emits the longer match. Otherwise, it emits the + original match, and, as described above, advances N bytes before + continuing. + + Run-time parameters also control this "lazy match" procedure. If + compression ratio is most important, the compressor attempts a + complete second search regardless of the length of the first match. + In the normal case, if the current match is "long enough", the + compressor reduces the search for a longer match, thus speeding up + the process. If speed is most important, the compressor inserts new + strings in the hash table only when no match was found, or when the + match is not "too long". This degrades the compression ratio but + saves time since there are both fewer insertions and fewer searches. + + + + + +Deutsch Informational [Page 15] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + +5. References + + [1] Huffman, D. A., "A Method for the Construction of Minimum + Redundancy Codes", Proceedings of the Institute of Radio + Engineers, September 1952, Volume 40, Number 9, pp. 1098-1101. + + [2] Ziv J., Lempel A., "A Universal Algorithm for Sequential Data + Compression", IEEE Transactions on Information Theory, Vol. 23, + No. 3, pp. 337-343. + + [3] Gailly, J.-L., and Adler, M., ZLIB documentation and sources, + available in ftp://ftp.uu.net/pub/archiving/zip/doc/ + + [4] Gailly, J.-L., and Adler, M., GZIP documentation and sources, + available as gzip-*.tar in ftp://prep.ai.mit.edu/pub/gnu/ + + [5] Schwartz, E. S., and Kallick, B. "Generating a canonical prefix + encoding." Comm. ACM, 7,3 (Mar. 1964), pp. 166-169. + + [6] Hirschberg and Lelewer, "Efficient decoding of prefix codes," + Comm. ACM, 33,4, April 1990, pp. 449-459. + +6. Security Considerations + + Any data compression method involves the reduction of redundancy in + the data. Consequently, any corruption of the data is likely to have + severe effects and be difficult to correct. Uncompressed text, on + the other hand, will probably still be readable despite the presence + of some corrupted bytes. + + It is recommended that systems using this data format provide some + means of validating the integrity of the compressed data. See + reference [3], for example. + +7. Source code + + Source code for a C language implementation of a "deflate" compliant + compressor and decompressor is available within the zlib package at + ftp://ftp.uu.net/pub/archiving/zip/zlib/. + +8. Acknowledgements + + Trademarks cited in this document are the property of their + respective owners. + + Phil Katz designed the deflate format. Jean-Loup Gailly and Mark + Adler wrote the related software described in this specification. + Glenn Randers-Pehrson converted this document to RFC and HTML format. + + + +Deutsch Informational [Page 16] + +RFC 1951 DEFLATE Compressed Data Format Specification May 1996 + + +9. Author's Address + + L. Peter Deutsch + Aladdin Enterprises + 203 Santa Margarita Ave. + Menlo Park, CA 94025 + + Phone: (415) 322-0103 (AM only) + FAX: (415) 322-1734 + EMail: + + Questions about the technical content of this specification can be + sent by email to: + + Jean-Loup Gailly and + Mark Adler + + Editorial comments on this specification can be sent by email to: + + L. Peter Deutsch and + Glenn Randers-Pehrson + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Deutsch Informational [Page 17] + diff --git a/third_party/zlib/v1_2_11/doc/rfc1952.txt b/third_party/zlib/v1_2_11/doc/rfc1952.txt new file mode 100644 index 0000000..a8e51b4 --- /dev/null +++ b/third_party/zlib/v1_2_11/doc/rfc1952.txt @@ -0,0 +1,675 @@ + + + + + + +Network Working Group P. Deutsch +Request for Comments: 1952 Aladdin Enterprises +Category: Informational May 1996 + + + GZIP file format specification version 4.3 + +Status of This Memo + + This memo provides information for the Internet community. This memo + does not specify an Internet standard of any kind. Distribution of + this memo is unlimited. + +IESG Note: + + The IESG takes no position on the validity of any Intellectual + Property Rights statements contained in this document. + +Notices + + Copyright (c) 1996 L. Peter Deutsch + + Permission is granted to copy and distribute this document for any + purpose and without charge, including translations into other + languages and incorporation into compilations, provided that the + copyright notice and this notice are preserved, and that any + substantive changes or deletions from the original are clearly + marked. + + A pointer to the latest version of this and related documentation in + HTML format can be found at the URL + . + +Abstract + + This specification defines a lossless compressed data format that is + compatible with the widely used GZIP utility. The format includes a + cyclic redundancy check value for detecting data corruption. The + format presently uses the DEFLATE method of compression but can be + easily extended to use other compression methods. The format can be + implemented readily in a manner not covered by patents. + + + + + + + + + + +Deutsch Informational [Page 1] + +RFC 1952 GZIP File Format Specification May 1996 + + +Table of Contents + + 1. Introduction ................................................... 2 + 1.1. Purpose ................................................... 2 + 1.2. Intended audience ......................................... 3 + 1.3. Scope ..................................................... 3 + 1.4. Compliance ................................................ 3 + 1.5. Definitions of terms and conventions used ................. 3 + 1.6. Changes from previous versions ............................ 3 + 2. Detailed specification ......................................... 4 + 2.1. Overall conventions ....................................... 4 + 2.2. File format ............................................... 5 + 2.3. Member format ............................................. 5 + 2.3.1. Member header and trailer ........................... 6 + 2.3.1.1. Extra field ................................... 8 + 2.3.1.2. Compliance .................................... 9 + 3. References .................................................. 9 + 4. Security Considerations .................................... 10 + 5. Acknowledgements ........................................... 10 + 6. Author's Address ........................................... 10 + 7. Appendix: Jean-Loup Gailly's gzip utility .................. 11 + 8. Appendix: Sample CRC Code .................................. 11 + +1. Introduction + + 1.1. Purpose + + The purpose of this specification is to define a lossless + compressed data format that: + + * Is independent of CPU type, operating system, file system, + and character set, and hence can be used for interchange; + * Can compress or decompress a data stream (as opposed to a + randomly accessible file) to produce another data stream, + using only an a priori bounded amount of intermediate + storage, and hence can be used in data communications or + similar structures such as Unix filters; + * Compresses data with efficiency comparable to the best + currently available general-purpose compression methods, + and in particular considerably better than the "compress" + program; + * Can be implemented readily in a manner not covered by + patents, and hence can be practiced freely; + * Is compatible with the file format produced by the current + widely used gzip utility, in that conforming decompressors + will be able to read data produced by the existing gzip + compressor. + + + + +Deutsch Informational [Page 2] + +RFC 1952 GZIP File Format Specification May 1996 + + + The data format defined by this specification does not attempt to: + + * Provide random access to compressed data; + * Compress specialized data (e.g., raster graphics) as well as + the best currently available specialized algorithms. + + 1.2. Intended audience + + This specification is intended for use by implementors of software + to compress data into gzip format and/or decompress data from gzip + format. + + The text of the specification assumes a basic background in + programming at the level of bits and other primitive data + representations. + + 1.3. Scope + + The specification specifies a compression method and a file format + (the latter assuming only that a file can store a sequence of + arbitrary bytes). It does not specify any particular interface to + a file system or anything about character sets or encodings + (except for file names and comments, which are optional). + + 1.4. Compliance + + Unless otherwise indicated below, a compliant decompressor must be + able to accept and decompress any file that conforms to all the + specifications presented here; a compliant compressor must produce + files that conform to all the specifications presented here. The + material in the appendices is not part of the specification per se + and is not relevant to compliance. + + 1.5. Definitions of terms and conventions used + + byte: 8 bits stored or transmitted as a unit (same as an octet). + (For this specification, a byte is exactly 8 bits, even on + machines which store a character on a number of bits different + from 8.) See below for the numbering of bits within a byte. + + 1.6. Changes from previous versions + + There have been no technical changes to the gzip format since + version 4.1 of this specification. In version 4.2, some + terminology was changed, and the sample CRC code was rewritten for + clarity and to eliminate the requirement for the caller to do pre- + and post-conditioning. Version 4.3 is a conversion of the + specification to RFC style. + + + +Deutsch Informational [Page 3] + +RFC 1952 GZIP File Format Specification May 1996 + + +2. Detailed specification + + 2.1. Overall conventions + + In the diagrams below, a box like this: + + +---+ + | | <-- the vertical bars might be missing + +---+ + + represents one byte; a box like this: + + +==============+ + | | + +==============+ + + represents a variable number of bytes. + + Bytes stored within a computer do not have a "bit order", since + they are always treated as a unit. However, a byte considered as + an integer between 0 and 255 does have a most- and least- + significant bit, and since we write numbers with the most- + significant digit on the left, we also write bytes with the most- + significant bit on the left. In the diagrams below, we number the + bits of a byte so that bit 0 is the least-significant bit, i.e., + the bits are numbered: + + +--------+ + |76543210| + +--------+ + + This document does not address the issue of the order in which + bits of a byte are transmitted on a bit-sequential medium, since + the data format described here is byte- rather than bit-oriented. + + Within a computer, a number may occupy multiple bytes. All + multi-byte numbers in the format described here are stored with + the least-significant byte first (at the lower memory address). + For example, the decimal number 520 is stored as: + + 0 1 + +--------+--------+ + |00001000|00000010| + +--------+--------+ + ^ ^ + | | + | + more significant byte = 2 x 256 + + less significant byte = 8 + + + +Deutsch Informational [Page 4] + +RFC 1952 GZIP File Format Specification May 1996 + + + 2.2. File format + + A gzip file consists of a series of "members" (compressed data + sets). The format of each member is specified in the following + section. The members simply appear one after another in the file, + with no additional information before, between, or after them. + + 2.3. Member format + + Each member has the following structure: + + +---+---+---+---+---+---+---+---+---+---+ + |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) + +---+---+---+---+---+---+---+---+---+---+ + + (if FLG.FEXTRA set) + + +---+---+=================================+ + | XLEN |...XLEN bytes of "extra field"...| (more-->) + +---+---+=================================+ + + (if FLG.FNAME set) + + +=========================================+ + |...original file name, zero-terminated...| (more-->) + +=========================================+ + + (if FLG.FCOMMENT set) + + +===================================+ + |...file comment, zero-terminated...| (more-->) + +===================================+ + + (if FLG.FHCRC set) + + +---+---+ + | CRC16 | + +---+---+ + + +=======================+ + |...compressed blocks...| (more-->) + +=======================+ + + 0 1 2 3 4 5 6 7 + +---+---+---+---+---+---+---+---+ + | CRC32 | ISIZE | + +---+---+---+---+---+---+---+---+ + + + + +Deutsch Informational [Page 5] + +RFC 1952 GZIP File Format Specification May 1996 + + + 2.3.1. Member header and trailer + + ID1 (IDentification 1) + ID2 (IDentification 2) + These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 + (0x8b, \213), to identify the file as being in gzip format. + + CM (Compression Method) + This identifies the compression method used in the file. CM + = 0-7 are reserved. CM = 8 denotes the "deflate" + compression method, which is the one customarily used by + gzip and which is documented elsewhere. + + FLG (FLaGs) + This flag byte is divided into individual bits as follows: + + bit 0 FTEXT + bit 1 FHCRC + bit 2 FEXTRA + bit 3 FNAME + bit 4 FCOMMENT + bit 5 reserved + bit 6 reserved + bit 7 reserved + + If FTEXT is set, the file is probably ASCII text. This is + an optional indication, which the compressor may set by + checking a small amount of the input data to see whether any + non-ASCII characters are present. In case of doubt, FTEXT + is cleared, indicating binary data. For systems which have + different file formats for ascii text and binary data, the + decompressor can use FTEXT to choose the appropriate format. + We deliberately do not specify the algorithm used to set + this bit, since a compressor always has the option of + leaving it cleared and a decompressor always has the option + of ignoring it and letting some other program handle issues + of data conversion. + + If FHCRC is set, a CRC16 for the gzip header is present, + immediately before the compressed data. The CRC16 consists + of the two least significant bytes of the CRC32 for all + bytes of the gzip header up to and not including the CRC16. + [The FHCRC bit was never set by versions of gzip up to + 1.2.4, even though it was documented with a different + meaning in gzip 1.2.4.] + + If FEXTRA is set, optional extra fields are present, as + described in a following section. + + + +Deutsch Informational [Page 6] + +RFC 1952 GZIP File Format Specification May 1996 + + + If FNAME is set, an original file name is present, + terminated by a zero byte. The name must consist of ISO + 8859-1 (LATIN-1) characters; on operating systems using + EBCDIC or any other character set for file names, the name + must be translated to the ISO LATIN-1 character set. This + is the original name of the file being compressed, with any + directory components removed, and, if the file being + compressed is on a file system with case insensitive names, + forced to lower case. There is no original file name if the + data was compressed from a source other than a named file; + for example, if the source was stdin on a Unix system, there + is no file name. + + If FCOMMENT is set, a zero-terminated file comment is + present. This comment is not interpreted; it is only + intended for human consumption. The comment must consist of + ISO 8859-1 (LATIN-1) characters. Line breaks should be + denoted by a single line feed character (10 decimal). + + Reserved FLG bits must be zero. + + MTIME (Modification TIME) + This gives the most recent modification time of the original + file being compressed. The time is in Unix format, i.e., + seconds since 00:00:00 GMT, Jan. 1, 1970. (Note that this + may cause problems for MS-DOS and other systems that use + local rather than Universal time.) If the compressed data + did not come from a file, MTIME is set to the time at which + compression started. MTIME = 0 means no time stamp is + available. + + XFL (eXtra FLags) + These flags are available for use by specific compression + methods. The "deflate" method (CM = 8) sets these flags as + follows: + + XFL = 2 - compressor used maximum compression, + slowest algorithm + XFL = 4 - compressor used fastest algorithm + + OS (Operating System) + This identifies the type of file system on which compression + took place. This may be useful in determining end-of-line + convention for text files. The currently defined values are + as follows: + + + + + + +Deutsch Informational [Page 7] + +RFC 1952 GZIP File Format Specification May 1996 + + + 0 - FAT filesystem (MS-DOS, OS/2, NT/Win32) + 1 - Amiga + 2 - VMS (or OpenVMS) + 3 - Unix + 4 - VM/CMS + 5 - Atari TOS + 6 - HPFS filesystem (OS/2, NT) + 7 - Macintosh + 8 - Z-System + 9 - CP/M + 10 - TOPS-20 + 11 - NTFS filesystem (NT) + 12 - QDOS + 13 - Acorn RISCOS + 255 - unknown + + XLEN (eXtra LENgth) + If FLG.FEXTRA is set, this gives the length of the optional + extra field. See below for details. + + CRC32 (CRC-32) + This contains a Cyclic Redundancy Check value of the + uncompressed data computed according to CRC-32 algorithm + used in the ISO 3309 standard and in section 8.1.1.6.2 of + ITU-T recommendation V.42. (See http://www.iso.ch for + ordering ISO documents. See gopher://info.itu.ch for an + online version of ITU-T V.42.) + + ISIZE (Input SIZE) + This contains the size of the original (uncompressed) input + data modulo 2^32. + + 2.3.1.1. Extra field + + If the FLG.FEXTRA bit is set, an "extra field" is present in + the header, with total length XLEN bytes. It consists of a + series of subfields, each of the form: + + +---+---+---+---+==================================+ + |SI1|SI2| LEN |... LEN bytes of subfield data ...| + +---+---+---+---+==================================+ + + SI1 and SI2 provide a subfield ID, typically two ASCII letters + with some mnemonic value. Jean-Loup Gailly + is maintaining a registry of subfield + IDs; please send him any subfield ID you wish to use. Subfield + IDs with SI2 = 0 are reserved for future use. The following + IDs are currently defined: + + + +Deutsch Informational [Page 8] + +RFC 1952 GZIP File Format Specification May 1996 + + + SI1 SI2 Data + ---------- ---------- ---- + 0x41 ('A') 0x70 ('P') Apollo file type information + + LEN gives the length of the subfield data, excluding the 4 + initial bytes. + + 2.3.1.2. Compliance + + A compliant compressor must produce files with correct ID1, + ID2, CM, CRC32, and ISIZE, but may set all the other fields in + the fixed-length part of the header to default values (255 for + OS, 0 for all others). The compressor must set all reserved + bits to zero. + + A compliant decompressor must check ID1, ID2, and CM, and + provide an error indication if any of these have incorrect + values. It must examine FEXTRA/XLEN, FNAME, FCOMMENT and FHCRC + at least so it can skip over the optional fields if they are + present. It need not examine any other part of the header or + trailer; in particular, a decompressor may ignore FTEXT and OS + and always produce binary output, and still be compliant. A + compliant decompressor must give an error indication if any + reserved bit is non-zero, since such a bit could indicate the + presence of a new field that would cause subsequent data to be + interpreted incorrectly. + +3. References + + [1] "Information Processing - 8-bit single-byte coded graphic + character sets - Part 1: Latin alphabet No.1" (ISO 8859-1:1987). + The ISO 8859-1 (Latin-1) character set is a superset of 7-bit + ASCII. Files defining this character set are available as + iso_8859-1.* in ftp://ftp.uu.net/graphics/png/documents/ + + [2] ISO 3309 + + [3] ITU-T recommendation V.42 + + [4] Deutsch, L.P.,"DEFLATE Compressed Data Format Specification", + available in ftp://ftp.uu.net/pub/archiving/zip/doc/ + + [5] Gailly, J.-L., GZIP documentation, available as gzip-*.tar in + ftp://prep.ai.mit.edu/pub/gnu/ + + [6] Sarwate, D.V., "Computation of Cyclic Redundancy Checks via Table + Look-Up", Communications of the ACM, 31(8), pp.1008-1013. + + + + +Deutsch Informational [Page 9] + +RFC 1952 GZIP File Format Specification May 1996 + + + [7] Schwaderer, W.D., "CRC Calculation", April 85 PC Tech Journal, + pp.118-133. + + [8] ftp://ftp.adelaide.edu.au/pub/rocksoft/papers/crc_v3.txt, + describing the CRC concept. + +4. Security Considerations + + Any data compression method involves the reduction of redundancy in + the data. Consequently, any corruption of the data is likely to have + severe effects and be difficult to correct. Uncompressed text, on + the other hand, will probably still be readable despite the presence + of some corrupted bytes. + + It is recommended that systems using this data format provide some + means of validating the integrity of the compressed data, such as by + setting and checking the CRC-32 check value. + +5. Acknowledgements + + Trademarks cited in this document are the property of their + respective owners. + + Jean-Loup Gailly designed the gzip format and wrote, with Mark Adler, + the related software described in this specification. Glenn + Randers-Pehrson converted this document to RFC and HTML format. + +6. Author's Address + + L. Peter Deutsch + Aladdin Enterprises + 203 Santa Margarita Ave. + Menlo Park, CA 94025 + + Phone: (415) 322-0103 (AM only) + FAX: (415) 322-1734 + EMail: + + Questions about the technical content of this specification can be + sent by email to: + + Jean-Loup Gailly and + Mark Adler + + Editorial comments on this specification can be sent by email to: + + L. Peter Deutsch and + Glenn Randers-Pehrson + + + +Deutsch Informational [Page 10] + +RFC 1952 GZIP File Format Specification May 1996 + + +7. Appendix: Jean-Loup Gailly's gzip utility + + The most widely used implementation of gzip compression, and the + original documentation on which this specification is based, were + created by Jean-Loup Gailly . Since this + implementation is a de facto standard, we mention some more of its + features here. Again, the material in this section is not part of + the specification per se, and implementations need not follow it to + be compliant. + + When compressing or decompressing a file, gzip preserves the + protection, ownership, and modification time attributes on the local + file system, since there is no provision for representing protection + attributes in the gzip file format itself. Since the file format + includes a modification time, the gzip decompressor provides a + command line switch that assigns the modification time from the file, + rather than the local modification time of the compressed input, to + the decompressed output. + +8. Appendix: Sample CRC Code + + The following sample code represents a practical implementation of + the CRC (Cyclic Redundancy Check). (See also ISO 3309 and ITU-T V.42 + for a formal specification.) + + The sample code is in the ANSI C programming language. Non C users + may find it easier to read with these hints: + + & Bitwise AND operator. + ^ Bitwise exclusive-OR operator. + >> Bitwise right shift operator. When applied to an + unsigned quantity, as here, right shift inserts zero + bit(s) at the left. + ! Logical NOT operator. + ++ "n++" increments the variable n. + 0xNNN 0x introduces a hexadecimal (base 16) constant. + Suffix L indicates a long value (at least 32 bits). + + /* Table of CRCs of all 8-bit messages. */ + unsigned long crc_table[256]; + + /* Flag: has the table been computed? Initially false. */ + int crc_table_computed = 0; + + /* Make the table for a fast CRC. */ + void make_crc_table(void) + { + unsigned long c; + + + +Deutsch Informational [Page 11] + +RFC 1952 GZIP File Format Specification May 1996 + + + int n, k; + for (n = 0; n < 256; n++) { + c = (unsigned long) n; + for (k = 0; k < 8; k++) { + if (c & 1) { + c = 0xedb88320L ^ (c >> 1); + } else { + c = c >> 1; + } + } + crc_table[n] = c; + } + crc_table_computed = 1; + } + + /* + Update a running crc with the bytes buf[0..len-1] and return + the updated crc. The crc should be initialized to zero. Pre- and + post-conditioning (one's complement) is performed within this + function so it shouldn't be done by the caller. Usage example: + + unsigned long crc = 0L; + + while (read_buffer(buffer, length) != EOF) { + crc = update_crc(crc, buffer, length); + } + if (crc != original_crc) error(); + */ + unsigned long update_crc(unsigned long crc, + unsigned char *buf, int len) + { + unsigned long c = crc ^ 0xffffffffL; + int n; + + if (!crc_table_computed) + make_crc_table(); + for (n = 0; n < len; n++) { + c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); + } + return c ^ 0xffffffffL; + } + + /* Return the CRC of the bytes buf[0..len-1]. */ + unsigned long crc(unsigned char *buf, int len) + { + return update_crc(0L, buf, len); + } + + + + +Deutsch Informational [Page 12] + diff --git a/third_party/zlib/v1_2_11/doc/txtvsbin.txt b/third_party/zlib/v1_2_11/doc/txtvsbin.txt new file mode 100644 index 0000000..3d0f063 --- /dev/null +++ b/third_party/zlib/v1_2_11/doc/txtvsbin.txt @@ -0,0 +1,107 @@ +A Fast Method for Identifying Plain Text Files +============================================== + + +Introduction +------------ + +Given a file coming from an unknown source, it is sometimes desirable +to find out whether the format of that file is plain text. Although +this may appear like a simple task, a fully accurate detection of the +file type requires heavy-duty semantic analysis on the file contents. +It is, however, possible to obtain satisfactory results by employing +various heuristics. + +Previous versions of PKZip and other zip-compatible compression tools +were using a crude detection scheme: if more than 80% (4/5) of the bytes +found in a certain buffer are within the range [7..127], the file is +labeled as plain text, otherwise it is labeled as binary. A prominent +limitation of this scheme is the restriction to Latin-based alphabets. +Other alphabets, like Greek, Cyrillic or Asian, make extensive use of +the bytes within the range [128..255], and texts using these alphabets +are most often misidentified by this scheme; in other words, the rate +of false negatives is sometimes too high, which means that the recall +is low. Another weakness of this scheme is a reduced precision, due to +the false positives that may occur when binary files containing large +amounts of textual characters are misidentified as plain text. + +In this article we propose a new, simple detection scheme that features +a much increased precision and a near-100% recall. This scheme is +designed to work on ASCII, Unicode and other ASCII-derived alphabets, +and it handles single-byte encodings (ISO-8859, MacRoman, KOI8, etc.) +and variable-sized encodings (ISO-2022, UTF-8, etc.). Wider encodings +(UCS-2/UTF-16 and UCS-4/UTF-32) are not handled, however. + + +The Algorithm +------------- + +The algorithm works by dividing the set of bytecodes [0..255] into three +categories: +- The white list of textual bytecodes: + 9 (TAB), 10 (LF), 13 (CR), 32 (SPACE) to 255. +- The gray list of tolerated bytecodes: + 7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB), 27 (ESC). +- The black list of undesired, non-textual bytecodes: + 0 (NUL) to 6, 14 to 31. + +If a file contains at least one byte that belongs to the white list and +no byte that belongs to the black list, then the file is categorized as +plain text; otherwise, it is categorized as binary. (The boundary case, +when the file is empty, automatically falls into the latter category.) + + +Rationale +--------- + +The idea behind this algorithm relies on two observations. + +The first observation is that, although the full range of 7-bit codes +[0..127] is properly specified by the ASCII standard, most control +characters in the range [0..31] are not used in practice. The only +widely-used, almost universally-portable control codes are 9 (TAB), +10 (LF) and 13 (CR). There are a few more control codes that are +recognized on a reduced range of platforms and text viewers/editors: +7 (BEL), 8 (BS), 11 (VT), 12 (FF), 26 (SUB) and 27 (ESC); but these +codes are rarely (if ever) used alone, without being accompanied by +some printable text. Even the newer, portable text formats such as +XML avoid using control characters outside the list mentioned here. + +The second observation is that most of the binary files tend to contain +control characters, especially 0 (NUL). Even though the older text +detection schemes observe the presence of non-ASCII codes from the range +[128..255], the precision rarely has to suffer if this upper range is +labeled as textual, because the files that are genuinely binary tend to +contain both control characters and codes from the upper range. On the +other hand, the upper range needs to be labeled as textual, because it +is used by virtually all ASCII extensions. In particular, this range is +used for encoding non-Latin scripts. + +Since there is no counting involved, other than simply observing the +presence or the absence of some byte values, the algorithm produces +consistent results, regardless what alphabet encoding is being used. +(If counting were involved, it could be possible to obtain different +results on a text encoded, say, using ISO-8859-16 versus UTF-8.) + +There is an extra category of plain text files that are "polluted" with +one or more black-listed codes, either by mistake or by peculiar design +considerations. In such cases, a scheme that tolerates a small fraction +of black-listed codes would provide an increased recall (i.e. more true +positives). This, however, incurs a reduced precision overall, since +false positives are more likely to appear in binary files that contain +large chunks of textual data. Furthermore, "polluted" plain text should +be regarded as binary by general-purpose text detection schemes, because +general-purpose text processing algorithms might not be applicable. +Under this premise, it is safe to say that our detection method provides +a near-100% recall. + +Experiments have been run on many files coming from various platforms +and applications. We tried plain text files, system logs, source code, +formatted office documents, compiled object code, etc. The results +confirm the optimistic assumptions about the capabilities of this +algorithm. + + +-- +Cosmin Truta +Last updated: 2006-May-28 diff --git a/third_party/zlib/v1_2_11/examples/README.examples b/third_party/zlib/v1_2_11/examples/README.examples new file mode 100644 index 0000000..56a3171 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/README.examples @@ -0,0 +1,49 @@ +This directory contains examples of the use of zlib and other relevant +programs and documentation. + +enough.c + calculation and justification of ENOUGH parameter in inftrees.h + - calculates the maximum table space used in inflate tree + construction over all possible Huffman codes + +fitblk.c + compress just enough input to nearly fill a requested output size + - zlib isn't designed to do this, but fitblk does it anyway + +gun.c + uncompress a gzip file + - illustrates the use of inflateBack() for high speed file-to-file + decompression using call-back functions + - is approximately twice as fast as gzip -d + - also provides Unix uncompress functionality, again twice as fast + +gzappend.c + append to a gzip file + - illustrates the use of the Z_BLOCK flush parameter for inflate() + - illustrates the use of deflatePrime() to start at any bit + +gzjoin.c + join gzip files without recalculating the crc or recompressing + - illustrates the use of the Z_BLOCK flush parameter for inflate() + - illustrates the use of crc32_combine() + +gzlog.c +gzlog.h + efficiently and robustly maintain a message log file in gzip format + - illustrates use of raw deflate, Z_PARTIAL_FLUSH, deflatePrime(), + and deflateSetDictionary() + - illustrates use of a gzip header extra field + +zlib_how.html + painfully comprehensive description of zpipe.c (see below) + - describes in excruciating detail the use of deflate() and inflate() + +zpipe.c + reads and writes zlib streams from stdin to stdout + - illustrates the proper use of deflate() and inflate() + - deeply commented in zlib_how.html (see above) + +zran.c + index a zlib or gzip stream and randomly access it + - illustrates the use of Z_BLOCK, inflatePrime(), and + inflateSetDictionary() to provide random access diff --git a/third_party/zlib/v1_2_11/examples/enough.c b/third_party/zlib/v1_2_11/examples/enough.c new file mode 100644 index 0000000..b991144 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/enough.c @@ -0,0 +1,572 @@ +/* enough.c -- determine the maximum size of inflate's Huffman code tables over + * all possible valid and complete Huffman codes, subject to a length limit. + * Copyright (C) 2007, 2008, 2012 Mark Adler + * Version 1.4 18 August 2012 Mark Adler + */ + +/* Version history: + 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4) + 1.1 4 Jan 2007 Use faster incremental table usage computation + Prune examine() search on previously visited states + 1.2 5 Jan 2007 Comments clean up + As inflate does, decrease root for short codes + Refuse cases where inflate would increase root + 1.3 17 Feb 2008 Add argument for initial root table size + Fix bug for initial root table size == max - 1 + Use a macro to compute the history index + 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!) + Clean up comparisons of different types + Clean up code indentation + */ + +/* + Examine all possible Huffman codes for a given number of symbols and a + maximum code length in bits to determine the maximum table size for zilb's + inflate. Only complete Huffman codes are counted. + + Two codes are considered distinct if the vectors of the number of codes per + length are not identical. So permutations of the symbol assignments result + in the same code for the counting, as do permutations of the assignments of + the bit values to the codes (i.e. only canonical codes are counted). + + We build a code from shorter to longer lengths, determining how many symbols + are coded at each length. At each step, we have how many symbols remain to + be coded, what the last code length used was, and how many bit patterns of + that length remain unused. Then we add one to the code length and double the + number of unused patterns to graduate to the next code length. We then + assign all portions of the remaining symbols to that code length that + preserve the properties of a correct and eventually complete code. Those + properties are: we cannot use more bit patterns than are available; and when + all the symbols are used, there are exactly zero possible bit patterns + remaining. + + The inflate Huffman decoding algorithm uses two-level lookup tables for + speed. There is a single first-level table to decode codes up to root bits + in length (root == 9 in the current inflate implementation). The table + has 1 << root entries and is indexed by the next root bits of input. Codes + shorter than root bits have replicated table entries, so that the correct + entry is pointed to regardless of the bits that follow the short code. If + the code is longer than root bits, then the table entry points to a second- + level table. The size of that table is determined by the longest code with + that root-bit prefix. If that longest code has length len, then the table + has size 1 << (len - root), to index the remaining bits in that set of + codes. Each subsequent root-bit prefix then has its own sub-table. The + total number of table entries required by the code is calculated + incrementally as the number of codes at each bit length is populated. When + all of the codes are shorter than root bits, then root is reduced to the + longest code length, resulting in a single, smaller, one-level table. + + The inflate algorithm also provides for small values of root (relative to + the log2 of the number of symbols), where the shortest code has more bits + than root. In that case, root is increased to the length of the shortest + code. This program, by design, does not handle that case, so it is verified + that the number of symbols is less than 2^(root + 1). + + In order to speed up the examination (by about ten orders of magnitude for + the default arguments), the intermediate states in the build-up of a code + are remembered and previously visited branches are pruned. The memory + required for this will increase rapidly with the total number of symbols and + the maximum code length in bits. However this is a very small price to pay + for the vast speedup. + + First, all of the possible Huffman codes are counted, and reachable + intermediate states are noted by a non-zero count in a saved-results array. + Second, the intermediate states that lead to (root + 1) bit or longer codes + are used to look at all sub-codes from those junctures for their inflate + memory usage. (The amount of memory used is not affected by the number of + codes of root bits or less in length.) Third, the visited states in the + construction of those sub-codes and the associated calculation of the table + size is recalled in order to avoid recalculating from the same juncture. + Beginning the code examination at (root + 1) bit codes, which is enabled by + identifying the reachable nodes, accounts for about six of the orders of + magnitude of improvement for the default arguments. About another four + orders of magnitude come from not revisiting previous states. Out of + approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes + need to be examined to cover all of the possible table memory usage cases + for the default arguments of 286 symbols limited to 15-bit codes. + + Note that an unsigned long long type is used for counting. It is quite easy + to exceed the capacity of an eight-byte integer with a large number of + symbols and a large maximum code length, so multiple-precision arithmetic + would need to replace the unsigned long long arithmetic in that case. This + program will abort if an overflow occurs. The big_t type identifies where + the counting takes place. + + An unsigned long long type is also used for calculating the number of + possible codes remaining at the maximum length. This limits the maximum + code length to the number of bits in a long long minus the number of bits + needed to represent the symbols in a flat code. The code_t type identifies + where the bit pattern counting takes place. + */ + +#include +#include +#include +#include + +#define local static + +/* special data types */ +typedef unsigned long long big_t; /* type for code counting */ +typedef unsigned long long code_t; /* type for bit pattern counting */ +struct tab { /* type for been here check */ + size_t len; /* length of bit vector in char's */ + char *vec; /* allocated bit vector */ +}; + +/* The array for saving results, num[], is indexed with this triplet: + + syms: number of symbols remaining to code + left: number of available bit patterns at length len + len: number of bits in the codes currently being assigned + + Those indices are constrained thusly when saving results: + + syms: 3..totsym (totsym == total symbols to code) + left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6) + len: 1..max - 1 (max == maximum code length in bits) + + syms == 2 is not saved since that immediately leads to a single code. left + must be even, since it represents the number of available bit patterns at + the current length, which is double the number at the previous length. + left ends at syms-1 since left == syms immediately results in a single code. + (left > sym is not allowed since that would result in an incomplete code.) + len is less than max, since the code completes immediately when len == max. + + The offset into the array is calculated for the three indices with the + first one (syms) being outermost, and the last one (len) being innermost. + We build the array with length max-1 lists for the len index, with syms-3 + of those for each symbol. There are totsym-2 of those, with each one + varying in length as a function of sym. See the calculation of index in + count() for the index, and the calculation of size in main() for the size + of the array. + + For the deflate example of 286 symbols limited to 15-bit codes, the array + has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than + half of the space allocated for saved results is actually used -- not all + possible triplets are reached in the generation of valid Huffman codes. + */ + +/* The array for tracking visited states, done[], is itself indexed identically + to the num[] array as described above for the (syms, left, len) triplet. + Each element in the array is further indexed by the (mem, rem) doublet, + where mem is the amount of inflate table space used so far, and rem is the + remaining unused entries in the current inflate sub-table. Each indexed + element is simply one bit indicating whether the state has been visited or + not. Since the ranges for mem and rem are not known a priori, each bit + vector is of a variable size, and grows as needed to accommodate the visited + states. mem and rem are used to calculate a single index in a triangular + array. Since the range of mem is expected in the default case to be about + ten times larger than the range of rem, the array is skewed to reduce the + memory usage, with eight times the range for mem than for rem. See the + calculations for offset and bit in beenhere() for the details. + + For the deflate example of 286 symbols limited to 15-bit codes, the bit + vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[] + array itself. + */ + +/* Globals to avoid propagating constants or constant pointers recursively */ +local int max; /* maximum allowed bit length for the codes */ +local int root; /* size of base code table in bits */ +local int large; /* largest code table so far */ +local size_t size; /* number of elements in num and done */ +local int *code; /* number of symbols assigned to each bit length */ +local big_t *num; /* saved results array for code counting */ +local struct tab *done; /* states already evaluated array */ + +/* Index function for num[] and done[] */ +#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1) + +/* Free allocated space. Uses globals code, num, and done. */ +local void cleanup(void) +{ + size_t n; + + if (done != NULL) { + for (n = 0; n < size; n++) + if (done[n].len) + free(done[n].vec); + free(done); + } + if (num != NULL) + free(num); + if (code != NULL) + free(code); +} + +/* Return the number of possible Huffman codes using bit patterns of lengths + len through max inclusive, coding syms symbols, with left bit patterns of + length len unused -- return -1 if there is an overflow in the counting. + Keep a record of previous results in num to prevent repeating the same + calculation. Uses the globals max and num. */ +local big_t count(int syms, int len, int left) +{ + big_t sum; /* number of possible codes from this juncture */ + big_t got; /* value returned from count() */ + int least; /* least number of syms to use at this juncture */ + int most; /* most number of syms to use at this juncture */ + int use; /* number of bit patterns to use in next call */ + size_t index; /* index of this case in *num */ + + /* see if only one possible code */ + if (syms == left) + return 1; + + /* note and verify the expected state */ + assert(syms > left && left > 0 && len < max); + + /* see if we've done this one already */ + index = INDEX(syms, left, len); + got = num[index]; + if (got) + return got; /* we have -- return the saved result */ + + /* we need to use at least this many bit patterns so that the code won't be + incomplete at the next length (more bit patterns than symbols) */ + least = (left << 1) - syms; + if (least < 0) + least = 0; + + /* we can use at most this many bit patterns, lest there not be enough + available for the remaining symbols at the maximum length (if there were + no limit to the code length, this would become: most = left - 1) */ + most = (((code_t)left << (max - len)) - syms) / + (((code_t)1 << (max - len)) - 1); + + /* count all possible codes from this juncture and add them up */ + sum = 0; + for (use = least; use <= most; use++) { + got = count(syms - use, len + 1, (left - use) << 1); + sum += got; + if (got == (big_t)0 - 1 || sum < got) /* overflow */ + return (big_t)0 - 1; + } + + /* verify that all recursive calls are productive */ + assert(sum != 0); + + /* save the result and return it */ + num[index] = sum; + return sum; +} + +/* Return true if we've been here before, set to true if not. Set a bit in a + bit vector to indicate visiting this state. Each (syms,len,left) state + has a variable size bit vector indexed by (mem,rem). The bit vector is + lengthened if needed to allow setting the (mem,rem) bit. */ +local int beenhere(int syms, int len, int left, int mem, int rem) +{ + size_t index; /* index for this state's bit vector */ + size_t offset; /* offset in this state's bit vector */ + int bit; /* mask for this state's bit */ + size_t length; /* length of the bit vector in bytes */ + char *vector; /* new or enlarged bit vector */ + + /* point to vector for (syms,left,len), bit in vector for (mem,rem) */ + index = INDEX(syms, left, len); + mem -= 1 << root; + offset = (mem >> 3) + rem; + offset = ((offset * (offset + 1)) >> 1) + rem; + bit = 1 << (mem & 7); + + /* see if we've been here */ + length = done[index].len; + if (offset < length && (done[index].vec[offset] & bit) != 0) + return 1; /* done this! */ + + /* we haven't been here before -- set the bit to show we have now */ + + /* see if we need to lengthen the vector in order to set the bit */ + if (length <= offset) { + /* if we have one already, enlarge it, zero out the appended space */ + if (length) { + do { + length <<= 1; + } while (length <= offset); + vector = realloc(done[index].vec, length); + if (vector != NULL) + memset(vector + done[index].len, 0, length - done[index].len); + } + + /* otherwise we need to make a new vector and zero it out */ + else { + length = 1 << (len - root); + while (length <= offset) + length <<= 1; + vector = calloc(length, sizeof(char)); + } + + /* in either case, bail if we can't get the memory */ + if (vector == NULL) { + fputs("abort: unable to allocate enough memory\n", stderr); + cleanup(); + exit(1); + } + + /* install the new vector */ + done[index].len = length; + done[index].vec = vector; + } + + /* set the bit */ + done[index].vec[offset] |= bit; + return 0; +} + +/* Examine all possible codes from the given node (syms, len, left). Compute + the amount of memory required to build inflate's decoding tables, where the + number of code structures used so far is mem, and the number remaining in + the current sub-table is rem. Uses the globals max, code, root, large, and + done. */ +local void examine(int syms, int len, int left, int mem, int rem) +{ + int least; /* least number of syms to use at this juncture */ + int most; /* most number of syms to use at this juncture */ + int use; /* number of bit patterns to use in next call */ + + /* see if we have a complete code */ + if (syms == left) { + /* set the last code entry */ + code[len] = left; + + /* complete computation of memory used by this code */ + while (rem < left) { + left -= rem; + rem = 1 << (len - root); + mem += rem; + } + assert(rem == left); + + /* if this is a new maximum, show the entries used and the sub-code */ + if (mem > large) { + large = mem; + printf("max %d: ", mem); + for (use = root + 1; use <= max; use++) + if (code[use]) + printf("%d[%d] ", code[use], use); + putchar('\n'); + fflush(stdout); + } + + /* remove entries as we drop back down in the recursion */ + code[len] = 0; + return; + } + + /* prune the tree if we can */ + if (beenhere(syms, len, left, mem, rem)) + return; + + /* we need to use at least this many bit patterns so that the code won't be + incomplete at the next length (more bit patterns than symbols) */ + least = (left << 1) - syms; + if (least < 0) + least = 0; + + /* we can use at most this many bit patterns, lest there not be enough + available for the remaining symbols at the maximum length (if there were + no limit to the code length, this would become: most = left - 1) */ + most = (((code_t)left << (max - len)) - syms) / + (((code_t)1 << (max - len)) - 1); + + /* occupy least table spaces, creating new sub-tables as needed */ + use = least; + while (rem < use) { + use -= rem; + rem = 1 << (len - root); + mem += rem; + } + rem -= use; + + /* examine codes from here, updating table space as we go */ + for (use = least; use <= most; use++) { + code[len] = use; + examine(syms - use, len + 1, (left - use) << 1, + mem + (rem ? 1 << (len - root) : 0), rem << 1); + if (rem == 0) { + rem = 1 << (len - root); + mem += rem; + } + rem--; + } + + /* remove entries as we drop back down in the recursion */ + code[len] = 0; +} + +/* Look at all sub-codes starting with root + 1 bits. Look at only the valid + intermediate code states (syms, left, len). For each completed code, + calculate the amount of memory required by inflate to build the decoding + tables. Find the maximum amount of memory required and show the code that + requires that maximum. Uses the globals max, root, and num. */ +local void enough(int syms) +{ + int n; /* number of remaing symbols for this node */ + int left; /* number of unused bit patterns at this length */ + size_t index; /* index of this case in *num */ + + /* clear code */ + for (n = 0; n <= max; n++) + code[n] = 0; + + /* look at all (root + 1) bit and longer codes */ + large = 1 << root; /* base table */ + if (root < max) /* otherwise, there's only a base table */ + for (n = 3; n <= syms; n++) + for (left = 2; left < n; left += 2) + { + /* look at all reachable (root + 1) bit nodes, and the + resulting codes (complete at root + 2 or more) */ + index = INDEX(n, left, root + 1); + if (root + 1 < max && num[index]) /* reachable node */ + examine(n, root + 1, left, 1 << root, 0); + + /* also look at root bit codes with completions at root + 1 + bits (not saved in num, since complete), just in case */ + if (num[index - 1] && n <= left << 1) + examine((n - left) << 1, root + 1, (n - left) << 1, + 1 << root, 0); + } + + /* done */ + printf("done: maximum of %d table entries\n", large); +} + +/* + Examine and show the total number of possible Huffman codes for a given + maximum number of symbols, initial root table size, and maximum code length + in bits -- those are the command arguments in that order. The default + values are 286, 9, and 15 respectively, for the deflate literal/length code. + The possible codes are counted for each number of coded symbols from two to + the maximum. The counts for each of those and the total number of codes are + shown. The maximum number of inflate table entires is then calculated + across all possible codes. Each new maximum number of table entries and the + associated sub-code (starting at root + 1 == 10 bits) is shown. + + To count and examine Huffman codes that are not length-limited, provide a + maximum length equal to the number of symbols minus one. + + For the deflate literal/length code, use "enough". For the deflate distance + code, use "enough 30 6". + + This uses the %llu printf format to print big_t numbers, which assumes that + big_t is an unsigned long long. If the big_t type is changed (for example + to a multiple precision type), the method of printing will also need to be + updated. + */ +int main(int argc, char **argv) +{ + int syms; /* total number of symbols to code */ + int n; /* number of symbols to code for this run */ + big_t got; /* return value of count() */ + big_t sum; /* accumulated number of codes over n */ + code_t word; /* for counting bits in code_t */ + + /* set up globals for cleanup() */ + code = NULL; + num = NULL; + done = NULL; + + /* get arguments -- default to the deflate literal/length code */ + syms = 286; + root = 9; + max = 15; + if (argc > 1) { + syms = atoi(argv[1]); + if (argc > 2) { + root = atoi(argv[2]); + if (argc > 3) + max = atoi(argv[3]); + } + } + if (argc > 4 || syms < 2 || root < 1 || max < 1) { + fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n", + stderr); + return 1; + } + + /* if not restricting the code length, the longest is syms - 1 */ + if (max > syms - 1) + max = syms - 1; + + /* determine the number of bits in a code_t */ + for (n = 0, word = 1; word; n++, word <<= 1) + ; + + /* make sure that the calculation of most will not overflow */ + if (max > n || (code_t)(syms - 2) >= (((code_t)0 - 1) >> (max - 1))) { + fputs("abort: code length too long for internal types\n", stderr); + return 1; + } + + /* reject impossible code requests */ + if ((code_t)(syms - 1) > ((code_t)1 << max) - 1) { + fprintf(stderr, "%d symbols cannot be coded in %d bits\n", + syms, max); + return 1; + } + + /* allocate code vector */ + code = calloc(max + 1, sizeof(int)); + if (code == NULL) { + fputs("abort: unable to allocate enough memory\n", stderr); + return 1; + } + + /* determine size of saved results array, checking for overflows, + allocate and clear the array (set all to zero with calloc()) */ + if (syms == 2) /* iff max == 1 */ + num = NULL; /* won't be saving any results */ + else { + size = syms >> 1; + if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) || + (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) || + (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) || + (num = calloc(size, sizeof(big_t))) == NULL) { + fputs("abort: unable to allocate enough memory\n", stderr); + cleanup(); + return 1; + } + } + + /* count possible codes for all numbers of symbols, add up counts */ + sum = 0; + for (n = 2; n <= syms; n++) { + got = count(n, 1, 2); + sum += got; + if (got == (big_t)0 - 1 || sum < got) { /* overflow */ + fputs("abort: can't count that high!\n", stderr); + cleanup(); + return 1; + } + printf("%llu %d-codes\n", got, n); + } + printf("%llu total codes for 2 to %d symbols", sum, syms); + if (max < syms - 1) + printf(" (%d-bit length limit)\n", max); + else + puts(" (no length limit)"); + + /* allocate and clear done array for beenhere() */ + if (syms == 2) + done = NULL; + else if (size > ((size_t)0 - 1) / sizeof(struct tab) || + (done = calloc(size, sizeof(struct tab))) == NULL) { + fputs("abort: unable to allocate enough memory\n", stderr); + cleanup(); + return 1; + } + + /* find and show maximum inflate table usage */ + if (root > max) /* reduce root to max length */ + root = max; + if ((code_t)syms < ((code_t)1 << (root + 1))) + enough(syms); + else + puts("cannot handle minimum code lengths > root"); + + /* done */ + cleanup(); + return 0; +} diff --git a/third_party/zlib/v1_2_11/examples/fitblk.c b/third_party/zlib/v1_2_11/examples/fitblk.c new file mode 100644 index 0000000..c61de5c --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/fitblk.c @@ -0,0 +1,233 @@ +/* fitblk.c: example of fitting compressed output to a specified size + Not copyrighted -- provided to the public domain + Version 1.1 25 November 2004 Mark Adler */ + +/* Version history: + 1.0 24 Nov 2004 First version + 1.1 25 Nov 2004 Change deflateInit2() to deflateInit() + Use fixed-size, stack-allocated raw buffers + Simplify code moving compression to subroutines + Use assert() for internal errors + Add detailed description of approach + */ + +/* Approach to just fitting a requested compressed size: + + fitblk performs three compression passes on a portion of the input + data in order to determine how much of that input will compress to + nearly the requested output block size. The first pass generates + enough deflate blocks to produce output to fill the requested + output size plus a specfied excess amount (see the EXCESS define + below). The last deflate block may go quite a bit past that, but + is discarded. The second pass decompresses and recompresses just + the compressed data that fit in the requested plus excess sized + buffer. The deflate process is terminated after that amount of + input, which is less than the amount consumed on the first pass. + The last deflate block of the result will be of a comparable size + to the final product, so that the header for that deflate block and + the compression ratio for that block will be about the same as in + the final product. The third compression pass decompresses the + result of the second step, but only the compressed data up to the + requested size minus an amount to allow the compressed stream to + complete (see the MARGIN define below). That will result in a + final compressed stream whose length is less than or equal to the + requested size. Assuming sufficient input and a requested size + greater than a few hundred bytes, the shortfall will typically be + less than ten bytes. + + If the input is short enough that the first compression completes + before filling the requested output size, then that compressed + stream is return with no recompression. + + EXCESS is chosen to be just greater than the shortfall seen in a + two pass approach similar to the above. That shortfall is due to + the last deflate block compressing more efficiently with a smaller + header on the second pass. EXCESS is set to be large enough so + that there is enough uncompressed data for the second pass to fill + out the requested size, and small enough so that the final deflate + block of the second pass will be close in size to the final deflate + block of the third and final pass. MARGIN is chosen to be just + large enough to assure that the final compression has enough room + to complete in all cases. + */ + +#include +#include +#include +#include "zlib.h" + +#define local static + +/* print nastygram and leave */ +local void quit(char *why) +{ + fprintf(stderr, "fitblk abort: %s\n", why); + exit(1); +} + +#define RAWLEN 4096 /* intermediate uncompressed buffer size */ + +/* compress from file to def until provided buffer is full or end of + input reached; return last deflate() return value, or Z_ERRNO if + there was read error on the file */ +local int partcompress(FILE *in, z_streamp def) +{ + int ret, flush; + unsigned char raw[RAWLEN]; + + flush = Z_NO_FLUSH; + do { + def->avail_in = fread(raw, 1, RAWLEN, in); + if (ferror(in)) + return Z_ERRNO; + def->next_in = raw; + if (feof(in)) + flush = Z_FINISH; + ret = deflate(def, flush); + assert(ret != Z_STREAM_ERROR); + } while (def->avail_out != 0 && flush == Z_NO_FLUSH); + return ret; +} + +/* recompress from inf's input to def's output; the input for inf and + the output for def are set in those structures before calling; + return last deflate() return value, or Z_MEM_ERROR if inflate() + was not able to allocate enough memory when it needed to */ +local int recompress(z_streamp inf, z_streamp def) +{ + int ret, flush; + unsigned char raw[RAWLEN]; + + flush = Z_NO_FLUSH; + do { + /* decompress */ + inf->avail_out = RAWLEN; + inf->next_out = raw; + ret = inflate(inf, Z_NO_FLUSH); + assert(ret != Z_STREAM_ERROR && ret != Z_DATA_ERROR && + ret != Z_NEED_DICT); + if (ret == Z_MEM_ERROR) + return ret; + + /* compress what was decompresed until done or no room */ + def->avail_in = RAWLEN - inf->avail_out; + def->next_in = raw; + if (inf->avail_out != 0) + flush = Z_FINISH; + ret = deflate(def, flush); + assert(ret != Z_STREAM_ERROR); + } while (ret != Z_STREAM_END && def->avail_out != 0); + return ret; +} + +#define EXCESS 256 /* empirically determined stream overage */ +#define MARGIN 8 /* amount to back off for completion */ + +/* compress from stdin to fixed-size block on stdout */ +int main(int argc, char **argv) +{ + int ret; /* return code */ + unsigned size; /* requested fixed output block size */ + unsigned have; /* bytes written by deflate() call */ + unsigned char *blk; /* intermediate and final stream */ + unsigned char *tmp; /* close to desired size stream */ + z_stream def, inf; /* zlib deflate and inflate states */ + + /* get requested output size */ + if (argc != 2) + quit("need one argument: size of output block"); + ret = strtol(argv[1], argv + 1, 10); + if (argv[1][0] != 0) + quit("argument must be a number"); + if (ret < 8) /* 8 is minimum zlib stream size */ + quit("need positive size of 8 or greater"); + size = (unsigned)ret; + + /* allocate memory for buffers and compression engine */ + blk = malloc(size + EXCESS); + def.zalloc = Z_NULL; + def.zfree = Z_NULL; + def.opaque = Z_NULL; + ret = deflateInit(&def, Z_DEFAULT_COMPRESSION); + if (ret != Z_OK || blk == NULL) + quit("out of memory"); + + /* compress from stdin until output full, or no more input */ + def.avail_out = size + EXCESS; + def.next_out = blk; + ret = partcompress(stdin, &def); + if (ret == Z_ERRNO) + quit("error reading input"); + + /* if it all fit, then size was undersubscribed -- done! */ + if (ret == Z_STREAM_END && def.avail_out >= EXCESS) { + /* write block to stdout */ + have = size + EXCESS - def.avail_out; + if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) + quit("error writing output"); + + /* clean up and print results to stderr */ + ret = deflateEnd(&def); + assert(ret != Z_STREAM_ERROR); + free(blk); + fprintf(stderr, + "%u bytes unused out of %u requested (all input)\n", + size - have, size); + return 0; + } + + /* it didn't all fit -- set up for recompression */ + inf.zalloc = Z_NULL; + inf.zfree = Z_NULL; + inf.opaque = Z_NULL; + inf.avail_in = 0; + inf.next_in = Z_NULL; + ret = inflateInit(&inf); + tmp = malloc(size + EXCESS); + if (ret != Z_OK || tmp == NULL) + quit("out of memory"); + ret = deflateReset(&def); + assert(ret != Z_STREAM_ERROR); + + /* do first recompression close to the right amount */ + inf.avail_in = size + EXCESS; + inf.next_in = blk; + def.avail_out = size + EXCESS; + def.next_out = tmp; + ret = recompress(&inf, &def); + if (ret == Z_MEM_ERROR) + quit("out of memory"); + + /* set up for next reocmpression */ + ret = inflateReset(&inf); + assert(ret != Z_STREAM_ERROR); + ret = deflateReset(&def); + assert(ret != Z_STREAM_ERROR); + + /* do second and final recompression (third compression) */ + inf.avail_in = size - MARGIN; /* assure stream will complete */ + inf.next_in = tmp; + def.avail_out = size; + def.next_out = blk; + ret = recompress(&inf, &def); + if (ret == Z_MEM_ERROR) + quit("out of memory"); + assert(ret == Z_STREAM_END); /* otherwise MARGIN too small */ + + /* done -- write block to stdout */ + have = size - def.avail_out; + if (fwrite(blk, 1, have, stdout) != have || ferror(stdout)) + quit("error writing output"); + + /* clean up and print results to stderr */ + free(tmp); + ret = inflateEnd(&inf); + assert(ret != Z_STREAM_ERROR); + ret = deflateEnd(&def); + assert(ret != Z_STREAM_ERROR); + free(blk); + fprintf(stderr, + "%u bytes unused out of %u requested (%lu input)\n", + size - have, size, def.total_in); + return 0; +} diff --git a/third_party/zlib/v1_2_11/examples/gun.c b/third_party/zlib/v1_2_11/examples/gun.c new file mode 100644 index 0000000..be44fa5 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/gun.c @@ -0,0 +1,702 @@ +/* gun.c -- simple gunzip to give an example of the use of inflateBack() + * Copyright (C) 2003, 2005, 2008, 2010, 2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + Version 1.7 12 August 2012 Mark Adler */ + +/* Version history: + 1.0 16 Feb 2003 First version for testing of inflateBack() + 1.1 21 Feb 2005 Decompress concatenated gzip streams + Remove use of "this" variable (C++ keyword) + Fix return value for in() + Improve allocation failure checking + Add typecasting for void * structures + Add -h option for command version and usage + Add a bunch of comments + 1.2 20 Mar 2005 Add Unix compress (LZW) decompression + Copy file attributes from input file to output file + 1.3 12 Jun 2005 Add casts for error messages [Oberhumer] + 1.4 8 Dec 2006 LZW decompression speed improvements + 1.5 9 Feb 2008 Avoid warning in latest version of gcc + 1.6 17 Jan 2010 Avoid signed/unsigned comparison warnings + 1.7 12 Aug 2012 Update for z_const usage in zlib 1.2.8 + */ + +/* + gun [ -t ] [ name ... ] + + decompresses the data in the named gzip files. If no arguments are given, + gun will decompress from stdin to stdout. The names must end in .gz, -gz, + .z, -z, _z, or .Z. The uncompressed data will be written to a file name + with the suffix stripped. On success, the original file is deleted. On + failure, the output file is deleted. For most failures, the command will + continue to process the remaining names on the command line. A memory + allocation failure will abort the command. If -t is specified, then the + listed files or stdin will be tested as gzip files for integrity (without + checking for a proper suffix), no output will be written, and no files + will be deleted. + + Like gzip, gun allows concatenated gzip streams and will decompress them, + writing all of the uncompressed data to the output. Unlike gzip, gun allows + an empty file on input, and will produce no error writing an empty output + file. + + gun will also decompress files made by Unix compress, which uses LZW + compression. These files are automatically detected by virtue of their + magic header bytes. Since the end of Unix compress stream is marked by the + end-of-file, they cannot be concantenated. If a Unix compress stream is + encountered in an input file, it is the last stream in that file. + + Like gunzip and uncompress, the file attributes of the original compressed + file are maintained in the final uncompressed file, to the extent that the + user permissions allow it. + + On my Mac OS X PowerPC G4, gun is almost twice as fast as gunzip (version + 1.2.4) is on the same file, when gun is linked with zlib 1.2.2. Also the + LZW decompression provided by gun is about twice as fast as the standard + Unix uncompress command. + */ + +/* external functions and related types and constants */ +#include /* fprintf() */ +#include /* malloc(), free() */ +#include /* strerror(), strcmp(), strlen(), memcpy() */ +#include /* errno */ +#include /* open() */ +#include /* read(), write(), close(), chown(), unlink() */ +#include +#include /* stat(), chmod() */ +#include /* utime() */ +#include "zlib.h" /* inflateBackInit(), inflateBack(), */ + /* inflateBackEnd(), crc32() */ + +/* function declaration */ +#define local static + +/* buffer constants */ +#define SIZE 32768U /* input and output buffer sizes */ +#define PIECE 16384 /* limits i/o chunks for 16-bit int case */ + +/* structure for infback() to pass to input function in() -- it maintains the + input file and a buffer of size SIZE */ +struct ind { + int infile; + unsigned char *inbuf; +}; + +/* Load input buffer, assumed to be empty, and return bytes loaded and a + pointer to them. read() is called until the buffer is full, or until it + returns end-of-file or error. Return 0 on error. */ +local unsigned in(void *in_desc, z_const unsigned char **buf) +{ + int ret; + unsigned len; + unsigned char *next; + struct ind *me = (struct ind *)in_desc; + + next = me->inbuf; + *buf = next; + len = 0; + do { + ret = PIECE; + if ((unsigned)ret > SIZE - len) + ret = (int)(SIZE - len); + ret = (int)read(me->infile, next, ret); + if (ret == -1) { + len = 0; + break; + } + next += ret; + len += ret; + } while (ret != 0 && len < SIZE); + return len; +} + +/* structure for infback() to pass to output function out() -- it maintains the + output file, a running CRC-32 check on the output and the total number of + bytes output, both for checking against the gzip trailer. (The length in + the gzip trailer is stored modulo 2^32, so it's ok if a long is 32 bits and + the output is greater than 4 GB.) */ +struct outd { + int outfile; + int check; /* true if checking crc and total */ + unsigned long crc; + unsigned long total; +}; + +/* Write output buffer and update the CRC-32 and total bytes written. write() + is called until all of the output is written or an error is encountered. + On success out() returns 0. For a write failure, out() returns 1. If the + output file descriptor is -1, then nothing is written. + */ +local int out(void *out_desc, unsigned char *buf, unsigned len) +{ + int ret; + struct outd *me = (struct outd *)out_desc; + + if (me->check) { + me->crc = crc32(me->crc, buf, len); + me->total += len; + } + if (me->outfile != -1) + do { + ret = PIECE; + if ((unsigned)ret > len) + ret = (int)len; + ret = (int)write(me->outfile, buf, ret); + if (ret == -1) + return 1; + buf += ret; + len -= ret; + } while (len != 0); + return 0; +} + +/* next input byte macro for use inside lunpipe() and gunpipe() */ +#define NEXT() (have ? 0 : (have = in(indp, &next)), \ + last = have ? (have--, (int)(*next++)) : -1) + +/* memory for gunpipe() and lunpipe() -- + the first 256 entries of prefix[] and suffix[] are never used, could + have offset the index, but it's faster to waste the memory */ +unsigned char inbuf[SIZE]; /* input buffer */ +unsigned char outbuf[SIZE]; /* output buffer */ +unsigned short prefix[65536]; /* index to LZW prefix string */ +unsigned char suffix[65536]; /* one-character LZW suffix */ +unsigned char match[65280 + 2]; /* buffer for reversed match or gzip + 32K sliding window */ + +/* throw out what's left in the current bits byte buffer (this is a vestigial + aspect of the compressed data format derived from an implementation that + made use of a special VAX machine instruction!) */ +#define FLUSHCODE() \ + do { \ + left = 0; \ + rem = 0; \ + if (chunk > have) { \ + chunk -= have; \ + have = 0; \ + if (NEXT() == -1) \ + break; \ + chunk--; \ + if (chunk > have) { \ + chunk = have = 0; \ + break; \ + } \ + } \ + have -= chunk; \ + next += chunk; \ + chunk = 0; \ + } while (0) + +/* Decompress a compress (LZW) file from indp to outfile. The compress magic + header (two bytes) has already been read and verified. There are have bytes + of buffered input at next. strm is used for passing error information back + to gunpipe(). + + lunpipe() will return Z_OK on success, Z_BUF_ERROR for an unexpected end of + file, read error, or write error (a write error indicated by strm->next_in + not equal to Z_NULL), or Z_DATA_ERROR for invalid input. + */ +local int lunpipe(unsigned have, z_const unsigned char *next, struct ind *indp, + int outfile, z_stream *strm) +{ + int last; /* last byte read by NEXT(), or -1 if EOF */ + unsigned chunk; /* bytes left in current chunk */ + int left; /* bits left in rem */ + unsigned rem; /* unused bits from input */ + int bits; /* current bits per code */ + unsigned code; /* code, table traversal index */ + unsigned mask; /* mask for current bits codes */ + int max; /* maximum bits per code for this stream */ + unsigned flags; /* compress flags, then block compress flag */ + unsigned end; /* last valid entry in prefix/suffix tables */ + unsigned temp; /* current code */ + unsigned prev; /* previous code */ + unsigned final; /* last character written for previous code */ + unsigned stack; /* next position for reversed string */ + unsigned outcnt; /* bytes in output buffer */ + struct outd outd; /* output structure */ + unsigned char *p; + + /* set up output */ + outd.outfile = outfile; + outd.check = 0; + + /* process remainder of compress header -- a flags byte */ + flags = NEXT(); + if (last == -1) + return Z_BUF_ERROR; + if (flags & 0x60) { + strm->msg = (char *)"unknown lzw flags set"; + return Z_DATA_ERROR; + } + max = flags & 0x1f; + if (max < 9 || max > 16) { + strm->msg = (char *)"lzw bits out of range"; + return Z_DATA_ERROR; + } + if (max == 9) /* 9 doesn't really mean 9 */ + max = 10; + flags &= 0x80; /* true if block compress */ + + /* clear table */ + bits = 9; + mask = 0x1ff; + end = flags ? 256 : 255; + + /* set up: get first 9-bit code, which is the first decompressed byte, but + don't create a table entry until the next code */ + if (NEXT() == -1) /* no compressed data is ok */ + return Z_OK; + final = prev = (unsigned)last; /* low 8 bits of code */ + if (NEXT() == -1) /* missing a bit */ + return Z_BUF_ERROR; + if (last & 1) { /* code must be < 256 */ + strm->msg = (char *)"invalid lzw code"; + return Z_DATA_ERROR; + } + rem = (unsigned)last >> 1; /* remaining 7 bits */ + left = 7; + chunk = bits - 2; /* 7 bytes left in this chunk */ + outbuf[0] = (unsigned char)final; /* write first decompressed byte */ + outcnt = 1; + + /* decode codes */ + stack = 0; + for (;;) { + /* if the table will be full after this, increment the code size */ + if (end >= mask && bits < max) { + FLUSHCODE(); + bits++; + mask <<= 1; + mask++; + } + + /* get a code of length bits */ + if (chunk == 0) /* decrement chunk modulo bits */ + chunk = bits; + code = rem; /* low bits of code */ + if (NEXT() == -1) { /* EOF is end of compressed data */ + /* write remaining buffered output */ + if (outcnt && out(&outd, outbuf, outcnt)) { + strm->next_in = outbuf; /* signal write error */ + return Z_BUF_ERROR; + } + return Z_OK; + } + code += (unsigned)last << left; /* middle (or high) bits of code */ + left += 8; + chunk--; + if (bits > left) { /* need more bits */ + if (NEXT() == -1) /* can't end in middle of code */ + return Z_BUF_ERROR; + code += (unsigned)last << left; /* high bits of code */ + left += 8; + chunk--; + } + code &= mask; /* mask to current code length */ + left -= bits; /* number of unused bits */ + rem = (unsigned)last >> (8 - left); /* unused bits from last byte */ + + /* process clear code (256) */ + if (code == 256 && flags) { + FLUSHCODE(); + bits = 9; /* initialize bits and mask */ + mask = 0x1ff; + end = 255; /* empty table */ + continue; /* get next code */ + } + + /* special code to reuse last match */ + temp = code; /* save the current code */ + if (code > end) { + /* Be picky on the allowed code here, and make sure that the code + we drop through (prev) will be a valid index so that random + input does not cause an exception. The code != end + 1 check is + empirically derived, and not checked in the original uncompress + code. If this ever causes a problem, that check could be safely + removed. Leaving this check in greatly improves gun's ability + to detect random or corrupted input after a compress header. + In any case, the prev > end check must be retained. */ + if (code != end + 1 || prev > end) { + strm->msg = (char *)"invalid lzw code"; + return Z_DATA_ERROR; + } + match[stack++] = (unsigned char)final; + code = prev; + } + + /* walk through linked list to generate output in reverse order */ + p = match + stack; + while (code >= 256) { + *p++ = suffix[code]; + code = prefix[code]; + } + stack = p - match; + match[stack++] = (unsigned char)code; + final = code; + + /* link new table entry */ + if (end < mask) { + end++; + prefix[end] = (unsigned short)prev; + suffix[end] = (unsigned char)final; + } + + /* set previous code for next iteration */ + prev = temp; + + /* write output in forward order */ + while (stack > SIZE - outcnt) { + while (outcnt < SIZE) + outbuf[outcnt++] = match[--stack]; + if (out(&outd, outbuf, outcnt)) { + strm->next_in = outbuf; /* signal write error */ + return Z_BUF_ERROR; + } + outcnt = 0; + } + p = match + stack; + do { + outbuf[outcnt++] = *--p; + } while (p > match); + stack = 0; + + /* loop for next code with final and prev as the last match, rem and + left provide the first 0..7 bits of the next code, end is the last + valid table entry */ + } +} + +/* Decompress a gzip file from infile to outfile. strm is assumed to have been + successfully initialized with inflateBackInit(). The input file may consist + of a series of gzip streams, in which case all of them will be decompressed + to the output file. If outfile is -1, then the gzip stream(s) integrity is + checked and nothing is written. + + The return value is a zlib error code: Z_MEM_ERROR if out of memory, + Z_DATA_ERROR if the header or the compressed data is invalid, or if the + trailer CRC-32 check or length doesn't match, Z_BUF_ERROR if the input ends + prematurely or a write error occurs, or Z_ERRNO if junk (not a another gzip + stream) follows a valid gzip stream. + */ +local int gunpipe(z_stream *strm, int infile, int outfile) +{ + int ret, first, last; + unsigned have, flags, len; + z_const unsigned char *next = NULL; + struct ind ind, *indp; + struct outd outd; + + /* setup input buffer */ + ind.infile = infile; + ind.inbuf = inbuf; + indp = &ind; + + /* decompress concatenated gzip streams */ + have = 0; /* no input data read in yet */ + first = 1; /* looking for first gzip header */ + strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ + for (;;) { + /* look for the two magic header bytes for a gzip stream */ + if (NEXT() == -1) { + ret = Z_OK; + break; /* empty gzip stream is ok */ + } + if (last != 31 || (NEXT() != 139 && last != 157)) { + strm->msg = (char *)"incorrect header check"; + ret = first ? Z_DATA_ERROR : Z_ERRNO; + break; /* not a gzip or compress header */ + } + first = 0; /* next non-header is junk */ + + /* process a compress (LZW) file -- can't be concatenated after this */ + if (last == 157) { + ret = lunpipe(have, next, indp, outfile, strm); + break; + } + + /* process remainder of gzip header */ + ret = Z_BUF_ERROR; + if (NEXT() != 8) { /* only deflate method allowed */ + if (last == -1) break; + strm->msg = (char *)"unknown compression method"; + ret = Z_DATA_ERROR; + break; + } + flags = NEXT(); /* header flags */ + NEXT(); /* discard mod time, xflgs, os */ + NEXT(); + NEXT(); + NEXT(); + NEXT(); + NEXT(); + if (last == -1) break; + if (flags & 0xe0) { + strm->msg = (char *)"unknown header flags set"; + ret = Z_DATA_ERROR; + break; + } + if (flags & 4) { /* extra field */ + len = NEXT(); + len += (unsigned)(NEXT()) << 8; + if (last == -1) break; + while (len > have) { + len -= have; + have = 0; + if (NEXT() == -1) break; + len--; + } + if (last == -1) break; + have -= len; + next += len; + } + if (flags & 8) /* file name */ + while (NEXT() != 0 && last != -1) + ; + if (flags & 16) /* comment */ + while (NEXT() != 0 && last != -1) + ; + if (flags & 2) { /* header crc */ + NEXT(); + NEXT(); + } + if (last == -1) break; + + /* set up output */ + outd.outfile = outfile; + outd.check = 1; + outd.crc = crc32(0L, Z_NULL, 0); + outd.total = 0; + + /* decompress data to output */ + strm->next_in = next; + strm->avail_in = have; + ret = inflateBack(strm, in, indp, out, &outd); + if (ret != Z_STREAM_END) break; + next = strm->next_in; + have = strm->avail_in; + strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */ + + /* check trailer */ + ret = Z_BUF_ERROR; + if (NEXT() != (int)(outd.crc & 0xff) || + NEXT() != (int)((outd.crc >> 8) & 0xff) || + NEXT() != (int)((outd.crc >> 16) & 0xff) || + NEXT() != (int)((outd.crc >> 24) & 0xff)) { + /* crc error */ + if (last != -1) { + strm->msg = (char *)"incorrect data check"; + ret = Z_DATA_ERROR; + } + break; + } + if (NEXT() != (int)(outd.total & 0xff) || + NEXT() != (int)((outd.total >> 8) & 0xff) || + NEXT() != (int)((outd.total >> 16) & 0xff) || + NEXT() != (int)((outd.total >> 24) & 0xff)) { + /* length error */ + if (last != -1) { + strm->msg = (char *)"incorrect length check"; + ret = Z_DATA_ERROR; + } + break; + } + + /* go back and look for another gzip stream */ + } + + /* clean up and return */ + return ret; +} + +/* Copy file attributes, from -> to, as best we can. This is best effort, so + no errors are reported. The mode bits, including suid, sgid, and the sticky + bit are copied (if allowed), the owner's user id and group id are copied + (again if allowed), and the access and modify times are copied. */ +local void copymeta(char *from, char *to) +{ + struct stat was; + struct utimbuf when; + + /* get all of from's Unix meta data, return if not a regular file */ + if (stat(from, &was) != 0 || (was.st_mode & S_IFMT) != S_IFREG) + return; + + /* set to's mode bits, ignore errors */ + (void)chmod(to, was.st_mode & 07777); + + /* copy owner's user and group, ignore errors */ + (void)chown(to, was.st_uid, was.st_gid); + + /* copy access and modify times, ignore errors */ + when.actime = was.st_atime; + when.modtime = was.st_mtime; + (void)utime(to, &when); +} + +/* Decompress the file inname to the file outnname, of if test is true, just + decompress without writing and check the gzip trailer for integrity. If + inname is NULL or an empty string, read from stdin. If outname is NULL or + an empty string, write to stdout. strm is a pre-initialized inflateBack + structure. When appropriate, copy the file attributes from inname to + outname. + + gunzip() returns 1 if there is an out-of-memory error or an unexpected + return code from gunpipe(). Otherwise it returns 0. + */ +local int gunzip(z_stream *strm, char *inname, char *outname, int test) +{ + int ret; + int infile, outfile; + + /* open files */ + if (inname == NULL || *inname == 0) { + inname = "-"; + infile = 0; /* stdin */ + } + else { + infile = open(inname, O_RDONLY, 0); + if (infile == -1) { + fprintf(stderr, "gun cannot open %s\n", inname); + return 0; + } + } + if (test) + outfile = -1; + else if (outname == NULL || *outname == 0) { + outname = "-"; + outfile = 1; /* stdout */ + } + else { + outfile = open(outname, O_CREAT | O_TRUNC | O_WRONLY, 0666); + if (outfile == -1) { + close(infile); + fprintf(stderr, "gun cannot create %s\n", outname); + return 0; + } + } + errno = 0; + + /* decompress */ + ret = gunpipe(strm, infile, outfile); + if (outfile > 2) close(outfile); + if (infile > 2) close(infile); + + /* interpret result */ + switch (ret) { + case Z_OK: + case Z_ERRNO: + if (infile > 2 && outfile > 2) { + copymeta(inname, outname); /* copy attributes */ + unlink(inname); + } + if (ret == Z_ERRNO) + fprintf(stderr, "gun warning: trailing garbage ignored in %s\n", + inname); + break; + case Z_DATA_ERROR: + if (outfile > 2) unlink(outname); + fprintf(stderr, "gun data error on %s: %s\n", inname, strm->msg); + break; + case Z_MEM_ERROR: + if (outfile > 2) unlink(outname); + fprintf(stderr, "gun out of memory error--aborting\n"); + return 1; + case Z_BUF_ERROR: + if (outfile > 2) unlink(outname); + if (strm->next_in != Z_NULL) { + fprintf(stderr, "gun write error on %s: %s\n", + outname, strerror(errno)); + } + else if (errno) { + fprintf(stderr, "gun read error on %s: %s\n", + inname, strerror(errno)); + } + else { + fprintf(stderr, "gun unexpected end of file on %s\n", + inname); + } + break; + default: + if (outfile > 2) unlink(outname); + fprintf(stderr, "gun internal error--aborting\n"); + return 1; + } + return 0; +} + +/* Process the gun command line arguments. See the command syntax near the + beginning of this source file. */ +int main(int argc, char **argv) +{ + int ret, len, test; + char *outname; + unsigned char *window; + z_stream strm; + + /* initialize inflateBack state for repeated use */ + window = match; /* reuse LZW match buffer */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + ret = inflateBackInit(&strm, 15, window); + if (ret != Z_OK) { + fprintf(stderr, "gun out of memory error--aborting\n"); + return 1; + } + + /* decompress each file to the same name with the suffix removed */ + argc--; + argv++; + test = 0; + if (argc && strcmp(*argv, "-h") == 0) { + fprintf(stderr, "gun 1.6 (17 Jan 2010)\n"); + fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n"); + fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n"); + return 0; + } + if (argc && strcmp(*argv, "-t") == 0) { + test = 1; + argc--; + argv++; + } + if (argc) + do { + if (test) + outname = NULL; + else { + len = (int)strlen(*argv); + if (strcmp(*argv + len - 3, ".gz") == 0 || + strcmp(*argv + len - 3, "-gz") == 0) + len -= 3; + else if (strcmp(*argv + len - 2, ".z") == 0 || + strcmp(*argv + len - 2, "-z") == 0 || + strcmp(*argv + len - 2, "_z") == 0 || + strcmp(*argv + len - 2, ".Z") == 0) + len -= 2; + else { + fprintf(stderr, "gun error: no gz type on %s--skipping\n", + *argv); + continue; + } + outname = malloc(len + 1); + if (outname == NULL) { + fprintf(stderr, "gun out of memory error--aborting\n"); + ret = 1; + break; + } + memcpy(outname, *argv, len); + outname[len] = 0; + } + ret = gunzip(&strm, *argv, outname, test); + if (outname != NULL) free(outname); + if (ret) break; + } while (argv++, --argc); + else + ret = gunzip(&strm, NULL, NULL, test); + + /* clean up */ + inflateBackEnd(&strm); + return ret; +} diff --git a/third_party/zlib/v1_2_11/examples/gzappend.c b/third_party/zlib/v1_2_11/examples/gzappend.c new file mode 100644 index 0000000..662dec3 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/gzappend.c @@ -0,0 +1,504 @@ +/* gzappend -- command to append to a gzip file + + Copyright (C) 2003, 2012 Mark Adler, all rights reserved + version 1.2, 11 Oct 2012 + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Mark Adler madler@alumni.caltech.edu + */ + +/* + * Change history: + * + * 1.0 19 Oct 2003 - First version + * 1.1 4 Nov 2003 - Expand and clarify some comments and notes + * - Add version and copyright to help + * - Send help to stdout instead of stderr + * - Add some preemptive typecasts + * - Add L to constants in lseek() calls + * - Remove some debugging information in error messages + * - Use new data_type definition for zlib 1.2.1 + * - Simplfy and unify file operations + * - Finish off gzip file in gztack() + * - Use deflatePrime() instead of adding empty blocks + * - Keep gzip file clean on appended file read errors + * - Use in-place rotate instead of auxiliary buffer + * (Why you ask? Because it was fun to write!) + * 1.2 11 Oct 2012 - Fix for proper z_const usage + * - Check for input buffer malloc failure + */ + +/* + gzappend takes a gzip file and appends to it, compressing files from the + command line or data from stdin. The gzip file is written to directly, to + avoid copying that file, in case it's large. Note that this results in the + unfriendly behavior that if gzappend fails, the gzip file is corrupted. + + This program was written to illustrate the use of the new Z_BLOCK option of + zlib 1.2.x's inflate() function. This option returns from inflate() at each + block boundary to facilitate locating and modifying the last block bit at + the start of the final deflate block. Also whether using Z_BLOCK or not, + another required feature of zlib 1.2.x is that inflate() now provides the + number of unusued bits in the last input byte used. gzappend will not work + with versions of zlib earlier than 1.2.1. + + gzappend first decompresses the gzip file internally, discarding all but + the last 32K of uncompressed data, and noting the location of the last block + bit and the number of unused bits in the last byte of the compressed data. + The gzip trailer containing the CRC-32 and length of the uncompressed data + is verified. This trailer will be later overwritten. + + Then the last block bit is cleared by seeking back in the file and rewriting + the byte that contains it. Seeking forward, the last byte of the compressed + data is saved along with the number of unused bits to initialize deflate. + + A deflate process is initialized, using the last 32K of the uncompressed + data from the gzip file to initialize the dictionary. If the total + uncompressed data was less than 32K, then all of it is used to initialize + the dictionary. The deflate output bit buffer is also initialized with the + last bits from the original deflate stream. From here on, the data to + append is simply compressed using deflate, and written to the gzip file. + When that is complete, the new CRC-32 and uncompressed length are written + as the trailer of the gzip file. + */ + +#include +#include +#include +#include +#include +#include "zlib.h" + +#define local static +#define LGCHUNK 14 +#define CHUNK (1U << LGCHUNK) +#define DSIZE 32768U + +/* print an error message and terminate with extreme prejudice */ +local void bye(char *msg1, char *msg2) +{ + fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2); + exit(1); +} + +/* return the greatest common divisor of a and b using Euclid's algorithm, + modified to be fast when one argument much greater than the other, and + coded to avoid unnecessary swapping */ +local unsigned gcd(unsigned a, unsigned b) +{ + unsigned c; + + while (a && b) + if (a > b) { + c = b; + while (a - c >= c) + c <<= 1; + a -= c; + } + else { + c = a; + while (b - c >= c) + c <<= 1; + b -= c; + } + return a + b; +} + +/* rotate list[0..len-1] left by rot positions, in place */ +local void rotate(unsigned char *list, unsigned len, unsigned rot) +{ + unsigned char tmp; + unsigned cycles; + unsigned char *start, *last, *to, *from; + + /* normalize rot and handle degenerate cases */ + if (len < 2) return; + if (rot >= len) rot %= len; + if (rot == 0) return; + + /* pointer to last entry in list */ + last = list + (len - 1); + + /* do simple left shift by one */ + if (rot == 1) { + tmp = *list; + memcpy(list, list + 1, len - 1); + *last = tmp; + return; + } + + /* do simple right shift by one */ + if (rot == len - 1) { + tmp = *last; + memmove(list + 1, list, len - 1); + *list = tmp; + return; + } + + /* otherwise do rotate as a set of cycles in place */ + cycles = gcd(len, rot); /* number of cycles */ + do { + start = from = list + cycles; /* start index is arbitrary */ + tmp = *from; /* save entry to be overwritten */ + for (;;) { + to = from; /* next step in cycle */ + from += rot; /* go right rot positions */ + if (from > last) from -= len; /* (pointer better not wrap) */ + if (from == start) break; /* all but one shifted */ + *to = *from; /* shift left */ + } + *to = tmp; /* complete the circle */ + } while (--cycles); +} + +/* structure for gzip file read operations */ +typedef struct { + int fd; /* file descriptor */ + int size; /* 1 << size is bytes in buf */ + unsigned left; /* bytes available at next */ + unsigned char *buf; /* buffer */ + z_const unsigned char *next; /* next byte in buffer */ + char *name; /* file name for error messages */ +} file; + +/* reload buffer */ +local int readin(file *in) +{ + int len; + + len = read(in->fd, in->buf, 1 << in->size); + if (len == -1) bye("error reading ", in->name); + in->left = (unsigned)len; + in->next = in->buf; + return len; +} + +/* read from file in, exit if end-of-file */ +local int readmore(file *in) +{ + if (readin(in) == 0) bye("unexpected end of ", in->name); + return 0; +} + +#define read1(in) (in->left == 0 ? readmore(in) : 0, \ + in->left--, *(in->next)++) + +/* skip over n bytes of in */ +local void skip(file *in, unsigned n) +{ + unsigned bypass; + + if (n > in->left) { + n -= in->left; + bypass = n & ~((1U << in->size) - 1); + if (bypass) { + if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1) + bye("seeking ", in->name); + n -= bypass; + } + readmore(in); + if (n > in->left) + bye("unexpected end of ", in->name); + } + in->left -= n; + in->next += n; +} + +/* read a four-byte unsigned integer, little-endian, from in */ +unsigned long read4(file *in) +{ + unsigned long val; + + val = read1(in); + val += (unsigned)read1(in) << 8; + val += (unsigned long)read1(in) << 16; + val += (unsigned long)read1(in) << 24; + return val; +} + +/* skip over gzip header */ +local void gzheader(file *in) +{ + int flags; + unsigned n; + + if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file"); + if (read1(in) != 8) bye("unknown compression method in", in->name); + flags = read1(in); + if (flags & 0xe0) bye("unknown header flags set in", in->name); + skip(in, 6); + if (flags & 4) { + n = read1(in); + n += (unsigned)(read1(in)) << 8; + skip(in, n); + } + if (flags & 8) while (read1(in) != 0) ; + if (flags & 16) while (read1(in) != 0) ; + if (flags & 2) skip(in, 2); +} + +/* decompress gzip file "name", return strm with a deflate stream ready to + continue compression of the data in the gzip file, and return a file + descriptor pointing to where to write the compressed data -- the deflate + stream is initialized to compress using level "level" */ +local int gzscan(char *name, z_stream *strm, int level) +{ + int ret, lastbit, left, full; + unsigned have; + unsigned long crc, tot; + unsigned char *window; + off_t lastoff, end; + file gz; + + /* open gzip file */ + gz.name = name; + gz.fd = open(name, O_RDWR, 0); + if (gz.fd == -1) bye("cannot open ", name); + gz.buf = malloc(CHUNK); + if (gz.buf == NULL) bye("out of memory", ""); + gz.size = LGCHUNK; + gz.left = 0; + + /* skip gzip header */ + gzheader(&gz); + + /* prepare to decompress */ + window = malloc(DSIZE); + if (window == NULL) bye("out of memory", ""); + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = inflateInit2(strm, -15); + if (ret != Z_OK) bye("out of memory", " or library mismatch"); + + /* decompress the deflate stream, saving append information */ + lastbit = 0; + lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; + left = 0; + strm->avail_in = gz.left; + strm->next_in = gz.next; + crc = crc32(0L, Z_NULL, 0); + have = full = 0; + do { + /* if needed, get more input */ + if (strm->avail_in == 0) { + readmore(&gz); + strm->avail_in = gz.left; + strm->next_in = gz.next; + } + + /* set up output to next available section of sliding window */ + strm->avail_out = DSIZE - have; + strm->next_out = window + have; + + /* inflate and check for errors */ + ret = inflate(strm, Z_BLOCK); + if (ret == Z_STREAM_ERROR) bye("internal stream error!", ""); + if (ret == Z_MEM_ERROR) bye("out of memory", ""); + if (ret == Z_DATA_ERROR) + bye("invalid compressed data--format violated in", name); + + /* update crc and sliding window pointer */ + crc = crc32(crc, window + have, DSIZE - have - strm->avail_out); + if (strm->avail_out) + have = DSIZE - strm->avail_out; + else { + have = 0; + full = 1; + } + + /* process end of block */ + if (strm->data_type & 128) { + if (strm->data_type & 64) + left = strm->data_type & 0x1f; + else { + lastbit = strm->data_type & 0x1f; + lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in; + } + } + } while (ret != Z_STREAM_END); + inflateEnd(strm); + gz.left = strm->avail_in; + gz.next = strm->next_in; + + /* save the location of the end of the compressed data */ + end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; + + /* check gzip trailer and save total for deflate */ + if (crc != read4(&gz)) + bye("invalid compressed data--crc mismatch in ", name); + tot = strm->total_out; + if ((tot & 0xffffffffUL) != read4(&gz)) + bye("invalid compressed data--length mismatch in", name); + + /* if not at end of file, warn */ + if (gz.left || readin(&gz)) + fprintf(stderr, + "gzappend warning: junk at end of gzip file overwritten\n"); + + /* clear last block bit */ + lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET); + if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); + *gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7))); + lseek(gz.fd, -1L, SEEK_CUR); + if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name); + + /* if window wrapped, build dictionary from window by rotating */ + if (full) { + rotate(window, DSIZE, have); + have = DSIZE; + } + + /* set up deflate stream with window, crc, total_in, and leftover bits */ + ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); + if (ret != Z_OK) bye("out of memory", ""); + deflateSetDictionary(strm, window, have); + strm->adler = crc; + strm->total_in = tot; + if (left) { + lseek(gz.fd, --end, SEEK_SET); + if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); + deflatePrime(strm, 8 - left, *gz.buf); + } + lseek(gz.fd, end, SEEK_SET); + + /* clean up and return */ + free(window); + free(gz.buf); + return gz.fd; +} + +/* append file "name" to gzip file gd using deflate stream strm -- if last + is true, then finish off the deflate stream at the end */ +local void gztack(char *name, int gd, z_stream *strm, int last) +{ + int fd, len, ret; + unsigned left; + unsigned char *in, *out; + + /* open file to compress and append */ + fd = 0; + if (name != NULL) { + fd = open(name, O_RDONLY, 0); + if (fd == -1) + fprintf(stderr, "gzappend warning: %s not found, skipping ...\n", + name); + } + + /* allocate buffers */ + in = malloc(CHUNK); + out = malloc(CHUNK); + if (in == NULL || out == NULL) bye("out of memory", ""); + + /* compress input file and append to gzip file */ + do { + /* get more input */ + len = read(fd, in, CHUNK); + if (len == -1) { + fprintf(stderr, + "gzappend warning: error reading %s, skipping rest ...\n", + name); + len = 0; + } + strm->avail_in = (unsigned)len; + strm->next_in = in; + if (len) strm->adler = crc32(strm->adler, in, (unsigned)len); + + /* compress and write all available output */ + do { + strm->avail_out = CHUNK; + strm->next_out = out; + ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH); + left = CHUNK - strm->avail_out; + while (left) { + len = write(gd, out + CHUNK - strm->avail_out - left, left); + if (len == -1) bye("writing gzip file", ""); + left -= (unsigned)len; + } + } while (strm->avail_out == 0 && ret != Z_STREAM_END); + } while (len != 0); + + /* write trailer after last entry */ + if (last) { + deflateEnd(strm); + out[0] = (unsigned char)(strm->adler); + out[1] = (unsigned char)(strm->adler >> 8); + out[2] = (unsigned char)(strm->adler >> 16); + out[3] = (unsigned char)(strm->adler >> 24); + out[4] = (unsigned char)(strm->total_in); + out[5] = (unsigned char)(strm->total_in >> 8); + out[6] = (unsigned char)(strm->total_in >> 16); + out[7] = (unsigned char)(strm->total_in >> 24); + len = 8; + do { + ret = write(gd, out + 8 - len, len); + if (ret == -1) bye("writing gzip file", ""); + len -= ret; + } while (len); + close(gd); + } + + /* clean up and return */ + free(out); + free(in); + if (fd > 0) close(fd); +} + +/* process the compression level option if present, scan the gzip file, and + append the specified files, or append the data from stdin if no other file + names are provided on the command line -- the gzip file must be writable + and seekable */ +int main(int argc, char **argv) +{ + int gd, level; + z_stream strm; + + /* ignore command name */ + argc--; argv++; + + /* provide usage if no arguments */ + if (*argv == NULL) { + printf( + "gzappend 1.2 (11 Oct 2012) Copyright (C) 2003, 2012 Mark Adler\n" + ); + printf( + "usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n"); + return 0; + } + + /* set compression level */ + level = Z_DEFAULT_COMPRESSION; + if (argv[0][0] == '-') { + if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0) + bye("invalid compression level", ""); + level = argv[0][1] - '0'; + if (*++argv == NULL) bye("no gzip file name after options", ""); + } + + /* prepare to append to gzip file */ + gd = gzscan(*argv++, &strm, level); + + /* append files on command line, or from stdin if none */ + if (*argv == NULL) + gztack(NULL, gd, &strm, 1); + else + do { + gztack(*argv, gd, &strm, argv[1] == NULL); + } while (*++argv != NULL); + return 0; +} diff --git a/third_party/zlib/v1_2_11/examples/gzjoin.c b/third_party/zlib/v1_2_11/examples/gzjoin.c new file mode 100644 index 0000000..89e8098 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/gzjoin.c @@ -0,0 +1,449 @@ +/* gzjoin -- command to join gzip files into one gzip file + + Copyright (C) 2004, 2005, 2012 Mark Adler, all rights reserved + version 1.2, 14 Aug 2012 + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Mark Adler madler@alumni.caltech.edu + */ + +/* + * Change history: + * + * 1.0 11 Dec 2004 - First version + * 1.1 12 Jun 2005 - Changed ssize_t to long for portability + * 1.2 14 Aug 2012 - Clean up for z_const usage + */ + +/* + gzjoin takes one or more gzip files on the command line and writes out a + single gzip file that will uncompress to the concatenation of the + uncompressed data from the individual gzip files. gzjoin does this without + having to recompress any of the data and without having to calculate a new + crc32 for the concatenated uncompressed data. gzjoin does however have to + decompress all of the input data in order to find the bits in the compressed + data that need to be modified to concatenate the streams. + + gzjoin does not do an integrity check on the input gzip files other than + checking the gzip header and decompressing the compressed data. They are + otherwise assumed to be complete and correct. + + Each joint between gzip files removes at least 18 bytes of previous trailer + and subsequent header, and inserts an average of about three bytes to the + compressed data in order to connect the streams. The output gzip file + has a minimal ten-byte gzip header with no file name or modification time. + + This program was written to illustrate the use of the Z_BLOCK option of + inflate() and the crc32_combine() function. gzjoin will not compile with + versions of zlib earlier than 1.2.3. + */ + +#include /* fputs(), fprintf(), fwrite(), putc() */ +#include /* exit(), malloc(), free() */ +#include /* open() */ +#include /* close(), read(), lseek() */ +#include "zlib.h" + /* crc32(), crc32_combine(), inflateInit2(), inflate(), inflateEnd() */ + +#define local static + +/* exit with an error (return a value to allow use in an expression) */ +local int bail(char *why1, char *why2) +{ + fprintf(stderr, "gzjoin error: %s%s, output incomplete\n", why1, why2); + exit(1); + return 0; +} + +/* -- simple buffered file input with access to the buffer -- */ + +#define CHUNK 32768 /* must be a power of two and fit in unsigned */ + +/* bin buffered input file type */ +typedef struct { + char *name; /* name of file for error messages */ + int fd; /* file descriptor */ + unsigned left; /* bytes remaining at next */ + unsigned char *next; /* next byte to read */ + unsigned char *buf; /* allocated buffer of length CHUNK */ +} bin; + +/* close a buffered file and free allocated memory */ +local void bclose(bin *in) +{ + if (in != NULL) { + if (in->fd != -1) + close(in->fd); + if (in->buf != NULL) + free(in->buf); + free(in); + } +} + +/* open a buffered file for input, return a pointer to type bin, or NULL on + failure */ +local bin *bopen(char *name) +{ + bin *in; + + in = malloc(sizeof(bin)); + if (in == NULL) + return NULL; + in->buf = malloc(CHUNK); + in->fd = open(name, O_RDONLY, 0); + if (in->buf == NULL || in->fd == -1) { + bclose(in); + return NULL; + } + in->left = 0; + in->next = in->buf; + in->name = name; + return in; +} + +/* load buffer from file, return -1 on read error, 0 or 1 on success, with + 1 indicating that end-of-file was reached */ +local int bload(bin *in) +{ + long len; + + if (in == NULL) + return -1; + if (in->left != 0) + return 0; + in->next = in->buf; + do { + len = (long)read(in->fd, in->buf + in->left, CHUNK - in->left); + if (len < 0) + return -1; + in->left += (unsigned)len; + } while (len != 0 && in->left < CHUNK); + return len == 0 ? 1 : 0; +} + +/* get a byte from the file, bail if end of file */ +#define bget(in) (in->left ? 0 : bload(in), \ + in->left ? (in->left--, *(in->next)++) : \ + bail("unexpected end of file on ", in->name)) + +/* get a four-byte little-endian unsigned integer from file */ +local unsigned long bget4(bin *in) +{ + unsigned long val; + + val = bget(in); + val += (unsigned long)(bget(in)) << 8; + val += (unsigned long)(bget(in)) << 16; + val += (unsigned long)(bget(in)) << 24; + return val; +} + +/* skip bytes in file */ +local void bskip(bin *in, unsigned skip) +{ + /* check pointer */ + if (in == NULL) + return; + + /* easy case -- skip bytes in buffer */ + if (skip <= in->left) { + in->left -= skip; + in->next += skip; + return; + } + + /* skip what's in buffer, discard buffer contents */ + skip -= in->left; + in->left = 0; + + /* seek past multiples of CHUNK bytes */ + if (skip > CHUNK) { + unsigned left; + + left = skip & (CHUNK - 1); + if (left == 0) { + /* exact number of chunks: seek all the way minus one byte to check + for end-of-file with a read */ + lseek(in->fd, skip - 1, SEEK_CUR); + if (read(in->fd, in->buf, 1) != 1) + bail("unexpected end of file on ", in->name); + return; + } + + /* skip the integral chunks, update skip with remainder */ + lseek(in->fd, skip - left, SEEK_CUR); + skip = left; + } + + /* read more input and skip remainder */ + bload(in); + if (skip > in->left) + bail("unexpected end of file on ", in->name); + in->left -= skip; + in->next += skip; +} + +/* -- end of buffered input functions -- */ + +/* skip the gzip header from file in */ +local void gzhead(bin *in) +{ + int flags; + + /* verify gzip magic header and compression method */ + if (bget(in) != 0x1f || bget(in) != 0x8b || bget(in) != 8) + bail(in->name, " is not a valid gzip file"); + + /* get and verify flags */ + flags = bget(in); + if ((flags & 0xe0) != 0) + bail("unknown reserved bits set in ", in->name); + + /* skip modification time, extra flags, and os */ + bskip(in, 6); + + /* skip extra field if present */ + if (flags & 4) { + unsigned len; + + len = bget(in); + len += (unsigned)(bget(in)) << 8; + bskip(in, len); + } + + /* skip file name if present */ + if (flags & 8) + while (bget(in) != 0) + ; + + /* skip comment if present */ + if (flags & 16) + while (bget(in) != 0) + ; + + /* skip header crc if present */ + if (flags & 2) + bskip(in, 2); +} + +/* write a four-byte little-endian unsigned integer to out */ +local void put4(unsigned long val, FILE *out) +{ + putc(val & 0xff, out); + putc((val >> 8) & 0xff, out); + putc((val >> 16) & 0xff, out); + putc((val >> 24) & 0xff, out); +} + +/* Load up zlib stream from buffered input, bail if end of file */ +local void zpull(z_streamp strm, bin *in) +{ + if (in->left == 0) + bload(in); + if (in->left == 0) + bail("unexpected end of file on ", in->name); + strm->avail_in = in->left; + strm->next_in = in->next; +} + +/* Write header for gzip file to out and initialize trailer. */ +local void gzinit(unsigned long *crc, unsigned long *tot, FILE *out) +{ + fwrite("\x1f\x8b\x08\0\0\0\0\0\0\xff", 1, 10, out); + *crc = crc32(0L, Z_NULL, 0); + *tot = 0; +} + +/* Copy the compressed data from name, zeroing the last block bit of the last + block if clr is true, and adding empty blocks as needed to get to a byte + boundary. If clr is false, then the last block becomes the last block of + the output, and the gzip trailer is written. crc and tot maintains the + crc and length (modulo 2^32) of the output for the trailer. The resulting + gzip file is written to out. gzinit() must be called before the first call + of gzcopy() to write the gzip header and to initialize crc and tot. */ +local void gzcopy(char *name, int clr, unsigned long *crc, unsigned long *tot, + FILE *out) +{ + int ret; /* return value from zlib functions */ + int pos; /* where the "last block" bit is in byte */ + int last; /* true if processing the last block */ + bin *in; /* buffered input file */ + unsigned char *start; /* start of compressed data in buffer */ + unsigned char *junk; /* buffer for uncompressed data -- discarded */ + z_off_t len; /* length of uncompressed data (support > 4 GB) */ + z_stream strm; /* zlib inflate stream */ + + /* open gzip file and skip header */ + in = bopen(name); + if (in == NULL) + bail("could not open ", name); + gzhead(in); + + /* allocate buffer for uncompressed data and initialize raw inflate + stream */ + junk = malloc(CHUNK); + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, -15); + if (junk == NULL || ret != Z_OK) + bail("out of memory", ""); + + /* inflate and copy compressed data, clear last-block bit if requested */ + len = 0; + zpull(&strm, in); + start = in->next; + last = start[0] & 1; + if (last && clr) + start[0] &= ~1; + strm.avail_out = 0; + for (;;) { + /* if input used and output done, write used input and get more */ + if (strm.avail_in == 0 && strm.avail_out != 0) { + fwrite(start, 1, strm.next_in - start, out); + start = in->buf; + in->left = 0; + zpull(&strm, in); + } + + /* decompress -- return early when end-of-block reached */ + strm.avail_out = CHUNK; + strm.next_out = junk; + ret = inflate(&strm, Z_BLOCK); + switch (ret) { + case Z_MEM_ERROR: + bail("out of memory", ""); + case Z_DATA_ERROR: + bail("invalid compressed data in ", in->name); + } + + /* update length of uncompressed data */ + len += CHUNK - strm.avail_out; + + /* check for block boundary (only get this when block copied out) */ + if (strm.data_type & 128) { + /* if that was the last block, then done */ + if (last) + break; + + /* number of unused bits in last byte */ + pos = strm.data_type & 7; + + /* find the next last-block bit */ + if (pos != 0) { + /* next last-block bit is in last used byte */ + pos = 0x100 >> pos; + last = strm.next_in[-1] & pos; + if (last && clr) + in->buf[strm.next_in - in->buf - 1] &= ~pos; + } + else { + /* next last-block bit is in next unused byte */ + if (strm.avail_in == 0) { + /* don't have that byte yet -- get it */ + fwrite(start, 1, strm.next_in - start, out); + start = in->buf; + in->left = 0; + zpull(&strm, in); + } + last = strm.next_in[0] & 1; + if (last && clr) + in->buf[strm.next_in - in->buf] &= ~1; + } + } + } + + /* update buffer with unused input */ + in->left = strm.avail_in; + in->next = in->buf + (strm.next_in - in->buf); + + /* copy used input, write empty blocks to get to byte boundary */ + pos = strm.data_type & 7; + fwrite(start, 1, in->next - start - 1, out); + last = in->next[-1]; + if (pos == 0 || !clr) + /* already at byte boundary, or last file: write last byte */ + putc(last, out); + else { + /* append empty blocks to last byte */ + last &= ((0x100 >> pos) - 1); /* assure unused bits are zero */ + if (pos & 1) { + /* odd -- append an empty stored block */ + putc(last, out); + if (pos == 1) + putc(0, out); /* two more bits in block header */ + fwrite("\0\0\xff\xff", 1, 4, out); + } + else { + /* even -- append 1, 2, or 3 empty fixed blocks */ + switch (pos) { + case 6: + putc(last | 8, out); + last = 0; + case 4: + putc(last | 0x20, out); + last = 0; + case 2: + putc(last | 0x80, out); + putc(0, out); + } + } + } + + /* update crc and tot */ + *crc = crc32_combine(*crc, bget4(in), len); + *tot += (unsigned long)len; + + /* clean up */ + inflateEnd(&strm); + free(junk); + bclose(in); + + /* write trailer if this is the last gzip file */ + if (!clr) { + put4(*crc, out); + put4(*tot, out); + } +} + +/* join the gzip files on the command line, write result to stdout */ +int main(int argc, char **argv) +{ + unsigned long crc, tot; /* running crc and total uncompressed length */ + + /* skip command name */ + argc--; + argv++; + + /* show usage if no arguments */ + if (argc == 0) { + fputs("gzjoin usage: gzjoin f1.gz [f2.gz [f3.gz ...]] > fjoin.gz\n", + stderr); + return 0; + } + + /* join gzip files on command line and write to stdout */ + gzinit(&crc, &tot, stdout); + while (argc--) + gzcopy(*argv++, argc, &crc, &tot, stdout); + + /* done */ + return 0; +} diff --git a/third_party/zlib/v1_2_11/examples/gzlog.c b/third_party/zlib/v1_2_11/examples/gzlog.c new file mode 100644 index 0000000..b8c2927 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/gzlog.c @@ -0,0 +1,1059 @@ +/* + * gzlog.c + * Copyright (C) 2004, 2008, 2012, 2016 Mark Adler, all rights reserved + * For conditions of distribution and use, see copyright notice in gzlog.h + * version 2.2, 14 Aug 2012 + */ + +/* + gzlog provides a mechanism for frequently appending short strings to a gzip + file that is efficient both in execution time and compression ratio. The + strategy is to write the short strings in an uncompressed form to the end of + the gzip file, only compressing when the amount of uncompressed data has + reached a given threshold. + + gzlog also provides protection against interruptions in the process due to + system crashes. The status of the operation is recorded in an extra field + in the gzip file, and is only updated once the gzip file is brought to a + valid state. The last data to be appended or compressed is saved in an + auxiliary file, so that if the operation is interrupted, it can be completed + the next time an append operation is attempted. + + gzlog maintains another auxiliary file with the last 32K of data from the + compressed portion, which is preloaded for the compression of the subsequent + data. This minimizes the impact to the compression ratio of appending. + */ + +/* + Operations Concept: + + Files (log name "foo"): + foo.gz -- gzip file with the complete log + foo.add -- last message to append or last data to compress + foo.dict -- dictionary of the last 32K of data for next compression + foo.temp -- temporary dictionary file for compression after this one + foo.lock -- lock file for reading and writing the other files + foo.repairs -- log file for log file recovery operations (not compressed) + + gzip file structure: + - fixed-length (no file name) header with extra field (see below) + - compressed data ending initially with empty stored block + - uncompressed data filling out originally empty stored block and + subsequent stored blocks as needed (16K max each) + - gzip trailer + - no junk at end (no other gzip streams) + + When appending data, the information in the first three items above plus the + foo.add file are sufficient to recover an interrupted append operation. The + extra field has the necessary information to restore the start of the last + stored block and determine where to append the data in the foo.add file, as + well as the crc and length of the gzip data before the append operation. + + The foo.add file is created before the gzip file is marked for append, and + deleted after the gzip file is marked as complete. So if the append + operation is interrupted, the data to add will still be there. If due to + some external force, the foo.add file gets deleted between when the append + operation was interrupted and when recovery is attempted, the gzip file will + still be restored, but without the appended data. + + When compressing data, the information in the first two items above plus the + foo.add file are sufficient to recover an interrupted compress operation. + The extra field has the necessary information to find the end of the + compressed data, and contains both the crc and length of just the compressed + data and of the complete set of data including the contents of the foo.add + file. + + Again, the foo.add file is maintained during the compress operation in case + of an interruption. If in the unlikely event the foo.add file with the data + to be compressed is missing due to some external force, a gzip file with + just the previous compressed data will be reconstructed. In this case, all + of the data that was to be compressed is lost (approximately one megabyte). + This will not occur if all that happened was an interruption of the compress + operation. + + The third state that is marked is the replacement of the old dictionary with + the new dictionary after a compress operation. Once compression is + complete, the gzip file is marked as being in the replace state. This + completes the gzip file, so an interrupt after being so marked does not + result in recompression. Then the dictionary file is replaced, and the gzip + file is marked as completed. This state prevents the possibility of + restarting compression with the wrong dictionary file. + + All three operations are wrapped by a lock/unlock procedure. In order to + gain exclusive access to the log files, first a foo.lock file must be + exclusively created. When all operations are complete, the lock is + released by deleting the foo.lock file. If when attempting to create the + lock file, it already exists and the modify time of the lock file is more + than five minutes old (set by the PATIENCE define below), then the old + lock file is considered stale and deleted, and the exclusive creation of + the lock file is retried. To assure that there are no false assessments + of the staleness of the lock file, the operations periodically touch the + lock file to update the modified date. + + Following is the definition of the extra field with all of the information + required to enable the above append and compress operations and their + recovery if interrupted. Multi-byte values are stored little endian + (consistent with the gzip format). File pointers are eight bytes long. + The crc's and lengths for the gzip trailer are four bytes long. (Note that + the length at the end of a gzip file is used for error checking only, and + for large files is actually the length modulo 2^32.) The stored block + length is two bytes long. The gzip extra field two-byte identification is + "ap" for append. It is assumed that writing the extra field to the file is + an "atomic" operation. That is, either all of the extra field is written + to the file, or none of it is, if the operation is interrupted right at the + point of updating the extra field. This is a reasonable assumption, since + the extra field is within the first 52 bytes of the file, which is smaller + than any expected block size for a mass storage device (usually 512 bytes or + larger). + + Extra field (35 bytes): + - Pointer to first stored block length -- this points to the two-byte length + of the first stored block, which is followed by the two-byte, one's + complement of that length. The stored block length is preceded by the + three-bit header of the stored block, which is the actual start of the + stored block in the deflate format. See the bit offset field below. + - Pointer to the last stored block length. This is the same as above, but + for the last stored block of the uncompressed data in the gzip file. + Initially this is the same as the first stored block length pointer. + When the stored block gets to 16K (see the MAX_STORE define), then a new + stored block as added, at which point the last stored block length pointer + is different from the first stored block length pointer. When they are + different, the first bit of the last stored block header is eight bits, or + one byte back from the block length. + - Compressed data crc and length. This is the crc and length of the data + that is in the compressed portion of the deflate stream. These are used + only in the event that the foo.add file containing the data to compress is + lost after a compress operation is interrupted. + - Total data crc and length. This is the crc and length of all of the data + stored in the gzip file, compressed and uncompressed. It is used to + reconstruct the gzip trailer when compressing, as well as when recovering + interrupted operations. + - Final stored block length. This is used to quickly find where to append, + and allows the restoration of the original final stored block state when + an append operation is interrupted. + - First stored block start as the number of bits back from the final stored + block first length byte. This value is in the range of 3..10, and is + stored as the low three bits of the final byte of the extra field after + subtracting three (0..7). This allows the last-block bit of the stored + block header to be updated when a new stored block is added, for the case + when the first stored block and the last stored block are the same. (When + they are different, the numbers of bits back is known to be eight.) This + also allows for new compressed data to be appended to the old compressed + data in the compress operation, overwriting the previous first stored + block, or for the compressed data to be terminated and a valid gzip file + reconstructed on the off chance that a compression operation was + interrupted and the data to compress in the foo.add file was deleted. + - The operation in process. This is the next two bits in the last byte (the + bits under the mask 0x18). The are interpreted as 0: nothing in process, + 1: append in process, 2: compress in process, 3: replace in process. + - The top three bits of the last byte in the extra field are reserved and + are currently set to zero. + + Main procedure: + - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of + the system open() call. If the modify time of an existing lock file is + more than PATIENCE seconds old, then the lock file is deleted and the + exclusive create is retried. + - Load the extra field from the foo.gz file, and see if an operation was in + progress but not completed. If so, apply the recovery procedure below. + - Perform the append procedure with the provided data. + - If the uncompressed data in the foo.gz file is 1MB or more, apply the + compress procedure. + - Delete the foo.lock file. + + Append procedure: + - Put what to append in the foo.add file so that the operation can be + restarted if this procedure is interrupted. + - Mark the foo.gz extra field with the append operation in progress. + + Restore the original last-block bit and stored block length of the last + stored block from the information in the extra field, in case a previous + append operation was interrupted. + - Append the provided data to the last stored block, creating new stored + blocks as needed and updating the stored blocks last-block bits and + lengths. + - Update the crc and length with the new data, and write the gzip trailer. + - Write over the extra field (with a single write operation) with the new + pointers, lengths, and crc's, and mark the gzip file as not in process. + Though there is still a foo.add file, it will be ignored since nothing + is in process. If a foo.add file is leftover from a previously + completed operation, it is truncated when writing new data to it. + - Delete the foo.add file. + + Compress and replace procedures: + - Read all of the uncompressed data in the stored blocks in foo.gz and write + it to foo.add. Also write foo.temp with the last 32K of that data to + provide a dictionary for the next invocation of this procedure. + - Rewrite the extra field marking foo.gz with a compression in process. + * If there is no data provided to compress (due to a missing foo.add file + when recovering), reconstruct and truncate the foo.gz file to contain + only the previous compressed data and proceed to the step after the next + one. Otherwise ... + - Compress the data with the dictionary in foo.dict, and write to the + foo.gz file starting at the bit immediately following the last previously + compressed block. If there is no foo.dict, proceed anyway with the + compression at slightly reduced efficiency. (For the foo.dict file to be + missing requires some external failure beyond simply the interruption of + a compress operation.) During this process, the foo.lock file is + periodically touched to assure that that file is not considered stale by + another process before we're done. The deflation is terminated with a + non-last empty static block (10 bits long), that is then located and + written over by a last-bit-set empty stored block. + - Append the crc and length of the data in the gzip file (previously + calculated during the append operations). + - Write over the extra field with the updated stored block offsets, bits + back, crc's, and lengths, and mark foo.gz as in process for a replacement + of the dictionary. + @ Delete the foo.add file. + - Replace foo.dict with foo.temp. + - Write over the extra field, marking foo.gz as complete. + + Recovery procedure: + - If not a replace recovery, read in the foo.add file, and provide that data + to the appropriate recovery below. If there is no foo.add file, provide + a zero data length to the recovery. In that case, the append recovery + restores the foo.gz to the previous compressed + uncompressed data state. + For the the compress recovery, a missing foo.add file results in foo.gz + being restored to the previous compressed-only data state. + - Append recovery: + - Pick up append at + step above + - Compress recovery: + - Pick up compress at * step above + - Replace recovery: + - Pick up compress at @ step above + - Log the repair with a date stamp in foo.repairs + */ + +#include +#include /* rename, fopen, fprintf, fclose */ +#include /* malloc, free */ +#include /* strlen, strrchr, strcpy, strncpy, strcmp */ +#include /* open */ +#include /* lseek, read, write, close, unlink, sleep, */ + /* ftruncate, fsync */ +#include /* errno */ +#include /* time, ctime */ +#include /* stat */ +#include /* utimes */ +#include "zlib.h" /* crc32 */ + +#include "gzlog.h" /* header for external access */ + +#define local static +typedef unsigned int uint; +typedef unsigned long ulong; + +/* Macro for debugging to deterministically force recovery operations */ +#ifdef GZLOG_DEBUG + #include /* longjmp */ + jmp_buf gzlog_jump; /* where to go back to */ + int gzlog_bail = 0; /* which point to bail at (1..8) */ + int gzlog_count = -1; /* number of times through to wait */ +# define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \ + longjmp(gzlog_jump, gzlog_bail); } while (0) +#else +# define BAIL(n) +#endif + +/* how old the lock file can be in seconds before considering it stale */ +#define PATIENCE 300 + +/* maximum stored block size in Kbytes -- must be in 1..63 */ +#define MAX_STORE 16 + +/* number of stored Kbytes to trigger compression (must be >= 32 to allow + dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to + discard the stored block headers contribution of five bytes each) */ +#define TRIGGER 1024 + +/* size of a deflate dictionary (this cannot be changed) */ +#define DICT 32768U + +/* values for the operation (2 bits) */ +#define NO_OP 0 +#define APPEND_OP 1 +#define COMPRESS_OP 2 +#define REPLACE_OP 3 + +/* macros to extract little-endian integers from an unsigned byte buffer */ +#define PULL2(p) ((p)[0]+((uint)((p)[1])<<8)) +#define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16)) +#define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32)) + +/* macros to store integers into a byte buffer in little-endian order */ +#define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0) +#define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0) +#define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0) + +/* internal structure for log information */ +#define LOGID "\106\035\172" /* should be three non-zero characters */ +struct log { + char id[4]; /* contains LOGID to detect inadvertent overwrites */ + int fd; /* file descriptor for .gz file, opened read/write */ + char *path; /* allocated path, e.g. "/var/log/foo" or "foo" */ + char *end; /* end of path, for appending suffices such as ".gz" */ + off_t first; /* offset of first stored block first length byte */ + int back; /* location of first block id in bits back from first */ + uint stored; /* bytes currently in last stored block */ + off_t last; /* offset of last stored block first length byte */ + ulong ccrc; /* crc of compressed data */ + ulong clen; /* length (modulo 2^32) of compressed data */ + ulong tcrc; /* crc of total data */ + ulong tlen; /* length (modulo 2^32) of total data */ + time_t lock; /* last modify time of our lock file */ +}; + +/* gzip header for gzlog */ +local unsigned char log_gzhead[] = { + 0x1f, 0x8b, /* magic gzip id */ + 8, /* compression method is deflate */ + 4, /* there is an extra field (no file name) */ + 0, 0, 0, 0, /* no modification time provided */ + 0, 0xff, /* no extra flags, no OS specified */ + 39, 0, 'a', 'p', 35, 0 /* extra field with "ap" subfield */ + /* 35 is EXTRA, 39 is EXTRA + 4 */ +}; + +#define HEAD sizeof(log_gzhead) /* should be 16 */ + +/* initial gzip extra field content (52 == HEAD + EXTRA + 1) */ +local unsigned char log_gzext[] = { + 52, 0, 0, 0, 0, 0, 0, 0, /* offset of first stored block length */ + 52, 0, 0, 0, 0, 0, 0, 0, /* offset of last stored block length */ + 0, 0, 0, 0, 0, 0, 0, 0, /* compressed data crc and length */ + 0, 0, 0, 0, 0, 0, 0, 0, /* total data crc and length */ + 0, 0, /* final stored block data length */ + 5 /* op is NO_OP, last bit 8 bits back */ +}; + +#define EXTRA sizeof(log_gzext) /* should be 35 */ + +/* initial gzip data and trailer */ +local unsigned char log_gzbody[] = { + 1, 0, 0, 0xff, 0xff, /* empty stored block (last) */ + 0, 0, 0, 0, /* crc */ + 0, 0, 0, 0 /* uncompressed length */ +}; + +#define BODY sizeof(log_gzbody) + +/* Exclusively create foo.lock in order to negotiate exclusive access to the + foo.* files. If the modify time of an existing lock file is greater than + PATIENCE seconds in the past, then consider the lock file to have been + abandoned, delete it, and try the exclusive create again. Save the lock + file modify time for verification of ownership. Return 0 on success, or -1 + on failure, usually due to an access restriction or invalid path. Note that + if stat() or unlink() fails, it may be due to another process noticing the + abandoned lock file a smidge sooner and deleting it, so those are not + flagged as an error. */ +local int log_lock(struct log *log) +{ + int fd; + struct stat st; + + strcpy(log->end, ".lock"); + while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) { + if (errno != EEXIST) + return -1; + if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) { + unlink(log->path); + continue; + } + sleep(2); /* relinquish the CPU for two seconds while waiting */ + } + close(fd); + if (stat(log->path, &st) == 0) + log->lock = st.st_mtime; + return 0; +} + +/* Update the modify time of the lock file to now, in order to prevent another + task from thinking that the lock is stale. Save the lock file modify time + for verification of ownership. */ +local void log_touch(struct log *log) +{ + struct stat st; + + strcpy(log->end, ".lock"); + utimes(log->path, NULL); + if (stat(log->path, &st) == 0) + log->lock = st.st_mtime; +} + +/* Check the log file modify time against what is expected. Return true if + this is not our lock. If it is our lock, touch it to keep it. */ +local int log_check(struct log *log) +{ + struct stat st; + + strcpy(log->end, ".lock"); + if (stat(log->path, &st) || st.st_mtime != log->lock) + return 1; + log_touch(log); + return 0; +} + +/* Unlock a previously acquired lock, but only if it's ours. */ +local void log_unlock(struct log *log) +{ + if (log_check(log)) + return; + strcpy(log->end, ".lock"); + unlink(log->path); + log->lock = 0; +} + +/* Check the gzip header and read in the extra field, filling in the values in + the log structure. Return op on success or -1 if the gzip header was not as + expected. op is the current operation in progress last written to the extra + field. This assumes that the gzip file has already been opened, with the + file descriptor log->fd. */ +local int log_head(struct log *log) +{ + int op; + unsigned char buf[HEAD + EXTRA]; + + if (lseek(log->fd, 0, SEEK_SET) < 0 || + read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA || + memcmp(buf, log_gzhead, HEAD)) { + return -1; + } + log->first = PULL8(buf + HEAD); + log->last = PULL8(buf + HEAD + 8); + log->ccrc = PULL4(buf + HEAD + 16); + log->clen = PULL4(buf + HEAD + 20); + log->tcrc = PULL4(buf + HEAD + 24); + log->tlen = PULL4(buf + HEAD + 28); + log->stored = PULL2(buf + HEAD + 32); + log->back = 3 + (buf[HEAD + 34] & 7); + op = (buf[HEAD + 34] >> 3) & 3; + return op; +} + +/* Write over the extra field contents, marking the operation as op. Use fsync + to assure that the device is written to, and in the requested order. This + operation, and only this operation, is assumed to be atomic in order to + assure that the log is recoverable in the event of an interruption at any + point in the process. Return -1 if the write to foo.gz failed. */ +local int log_mark(struct log *log, int op) +{ + int ret; + unsigned char ext[EXTRA]; + + PUT8(ext, log->first); + PUT8(ext + 8, log->last); + PUT4(ext + 16, log->ccrc); + PUT4(ext + 20, log->clen); + PUT4(ext + 24, log->tcrc); + PUT4(ext + 28, log->tlen); + PUT2(ext + 32, log->stored); + ext[34] = log->back - 3 + (op << 3); + fsync(log->fd); + ret = lseek(log->fd, HEAD, SEEK_SET) < 0 || + write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0; + fsync(log->fd); + return ret; +} + +/* Rewrite the last block header bits and subsequent zero bits to get to a byte + boundary, setting the last block bit if last is true, and then write the + remainder of the stored block header (length and one's complement). Leave + the file pointer after the end of the last stored block data. Return -1 if + there is a read or write failure on the foo.gz file */ +local int log_last(struct log *log, int last) +{ + int back, len, mask; + unsigned char buf[6]; + + /* determine the locations of the bytes and bits to modify */ + back = log->last == log->first ? log->back : 8; + len = back > 8 ? 2 : 1; /* bytes back from log->last */ + mask = 0x80 >> ((back - 1) & 7); /* mask for block last-bit */ + + /* get the byte to modify (one or two back) into buf[0] -- don't need to + read the byte if the last-bit is eight bits back, since in that case + the entire byte will be modified */ + buf[0] = 0; + if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 || + read(log->fd, buf, 1) != 1)) + return -1; + + /* change the last-bit of the last stored block as requested -- note + that all bits above the last-bit are set to zero, per the type bits + of a stored block being 00 and per the convention that the bits to + bring the stream to a byte boundary are also zeros */ + buf[1] = 0; + buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0); + + /* write the modified stored block header and lengths, move the file + pointer to after the last stored block data */ + PUT2(buf + 2, log->stored); + PUT2(buf + 4, log->stored ^ 0xffff); + return lseek(log->fd, log->last - len, SEEK_SET) < 0 || + write(log->fd, buf + 2 - len, len + 4) != len + 4 || + lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0; +} + +/* Append len bytes from data to the locked and open log file. len may be zero + if recovering and no .add file was found. In that case, the previous state + of the foo.gz file is restored. The data is appended uncompressed in + deflate stored blocks. Return -1 if there was an error reading or writing + the foo.gz file. */ +local int log_append(struct log *log, unsigned char *data, size_t len) +{ + uint put; + off_t end; + unsigned char buf[8]; + + /* set the last block last-bit and length, in case recovering an + interrupted append, then position the file pointer to append to the + block */ + if (log_last(log, 1)) + return -1; + + /* append, adding stored blocks and updating the offset of the last stored + block as needed, and update the total crc and length */ + while (len) { + /* append as much as we can to the last block */ + put = (MAX_STORE << 10) - log->stored; + if (put > len) + put = (uint)len; + if (put) { + if (write(log->fd, data, put) != put) + return -1; + BAIL(1); + log->tcrc = crc32(log->tcrc, data, put); + log->tlen += put; + log->stored += put; + data += put; + len -= put; + } + + /* if we need to, add a new empty stored block */ + if (len) { + /* mark current block as not last */ + if (log_last(log, 0)) + return -1; + + /* point to new, empty stored block */ + log->last += 4 + log->stored + 1; + log->stored = 0; + } + + /* mark last block as last, update its length */ + if (log_last(log, 1)) + return -1; + BAIL(2); + } + + /* write the new crc and length trailer, and truncate just in case (could + be recovering from partial append with a missing foo.add file) */ + PUT4(buf, log->tcrc); + PUT4(buf + 4, log->tlen); + if (write(log->fd, buf, 8) != 8 || + (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) + return -1; + + /* write the extra field, marking the log file as done, delete .add file */ + if (log_mark(log, NO_OP)) + return -1; + strcpy(log->end, ".add"); + unlink(log->path); /* ignore error, since may not exist */ + return 0; +} + +/* Replace the foo.dict file with the foo.temp file. Also delete the foo.add + file, since the compress operation may have been interrupted before that was + done. Returns 1 if memory could not be allocated, or -1 if reading or + writing foo.gz fails, or if the rename fails for some reason other than + foo.temp not existing. foo.temp not existing is a permitted error, since + the replace operation may have been interrupted after the rename is done, + but before foo.gz is marked as complete. */ +local int log_replace(struct log *log) +{ + int ret; + char *dest; + + /* delete foo.add file */ + strcpy(log->end, ".add"); + unlink(log->path); /* ignore error, since may not exist */ + BAIL(3); + + /* rename foo.name to foo.dict, replacing foo.dict if it exists */ + strcpy(log->end, ".dict"); + dest = malloc(strlen(log->path) + 1); + if (dest == NULL) + return -2; + strcpy(dest, log->path); + strcpy(log->end, ".temp"); + ret = rename(log->path, dest); + free(dest); + if (ret && errno != ENOENT) + return -1; + BAIL(4); + + /* mark the foo.gz file as done */ + return log_mark(log, NO_OP); +} + +/* Compress the len bytes at data and append the compressed data to the + foo.gz deflate data immediately after the previous compressed data. This + overwrites the previous uncompressed data, which was stored in foo.add + and is the data provided in data[0..len-1]. If this operation is + interrupted, it picks up at the start of this routine, with the foo.add + file read in again. If there is no data to compress (len == 0), then we + simply terminate the foo.gz file after the previously compressed data, + appending a final empty stored block and the gzip trailer. Return -1 if + reading or writing the log.gz file failed, or -2 if there was a memory + allocation failure. */ +local int log_compress(struct log *log, unsigned char *data, size_t len) +{ + int fd; + uint got, max; + ssize_t dict; + off_t end; + z_stream strm; + unsigned char buf[DICT]; + + /* compress and append compressed data */ + if (len) { + /* set up for deflate, allocating memory */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, + Z_DEFAULT_STRATEGY) != Z_OK) + return -2; + + /* read in dictionary (last 32K of data that was compressed) */ + strcpy(log->end, ".dict"); + fd = open(log->path, O_RDONLY, 0); + if (fd >= 0) { + dict = read(fd, buf, DICT); + close(fd); + if (dict < 0) { + deflateEnd(&strm); + return -1; + } + if (dict) + deflateSetDictionary(&strm, buf, (uint)dict); + } + log_touch(log); + + /* prime deflate with last bits of previous block, position write + pointer to write those bits and overwrite what follows */ + if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1), + SEEK_SET) < 0 || + read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) { + deflateEnd(&strm); + return -1; + } + deflatePrime(&strm, (8 - log->back) & 7, *buf); + + /* compress, finishing with a partial non-last empty static block */ + strm.next_in = data; + max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */ + do { + strm.avail_in = len > max ? max : (uint)len; + len -= strm.avail_in; + do { + strm.avail_out = DICT; + strm.next_out = buf; + deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH); + got = DICT - strm.avail_out; + if (got && write(log->fd, buf, got) != got) { + deflateEnd(&strm); + return -1; + } + log_touch(log); + } while (strm.avail_out == 0); + } while (len); + deflateEnd(&strm); + BAIL(5); + + /* find start of empty static block -- scanning backwards the first one + bit is the second bit of the block, if the last byte is zero, then + we know the byte before that has a one in the top bit, since an + empty static block is ten bits long */ + if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 || + read(log->fd, buf, 1) != 1) + return -1; + log->first++; + if (*buf) { + log->back = 1; + while ((*buf & ((uint)1 << (8 - log->back++))) == 0) + ; /* guaranteed to terminate, since *buf != 0 */ + } + else + log->back = 10; + + /* update compressed crc and length */ + log->ccrc = log->tcrc; + log->clen = log->tlen; + } + else { + /* no data to compress -- fix up existing gzip stream */ + log->tcrc = log->ccrc; + log->tlen = log->clen; + } + + /* complete and truncate gzip stream */ + log->last = log->first; + log->stored = 0; + PUT4(buf, log->tcrc); + PUT4(buf + 4, log->tlen); + if (log_last(log, 1) || write(log->fd, buf, 8) != 8 || + (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) + return -1; + BAIL(6); + + /* mark as being in the replace operation */ + if (log_mark(log, REPLACE_OP)) + return -1; + + /* execute the replace operation and mark the file as done */ + return log_replace(log); +} + +/* log a repair record to the .repairs file */ +local void log_log(struct log *log, int op, char *record) +{ + time_t now; + FILE *rec; + + now = time(NULL); + strcpy(log->end, ".repairs"); + rec = fopen(log->path, "a"); + if (rec == NULL) + return; + fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ? + "append" : (op == COMPRESS_OP ? "compress" : "replace"), record); + fclose(rec); + return; +} + +/* Recover the interrupted operation op. First read foo.add for recovering an + append or compress operation. Return -1 if there was an error reading or + writing foo.gz or reading an existing foo.add, or -2 if there was a memory + allocation failure. */ +local int log_recover(struct log *log, int op) +{ + int fd, ret = 0; + unsigned char *data = NULL; + size_t len = 0; + struct stat st; + + /* log recovery */ + log_log(log, op, "start"); + + /* load foo.add file if expected and present */ + if (op == APPEND_OP || op == COMPRESS_OP) { + strcpy(log->end, ".add"); + if (stat(log->path, &st) == 0 && st.st_size) { + len = (size_t)(st.st_size); + if ((off_t)len != st.st_size || + (data = malloc(st.st_size)) == NULL) { + log_log(log, op, "allocation failure"); + return -2; + } + if ((fd = open(log->path, O_RDONLY, 0)) < 0) { + log_log(log, op, ".add file read failure"); + return -1; + } + ret = (size_t)read(fd, data, len) != len; + close(fd); + if (ret) { + log_log(log, op, ".add file read failure"); + return -1; + } + log_log(log, op, "loaded .add file"); + } + else + log_log(log, op, "missing .add file!"); + } + + /* recover the interrupted operation */ + switch (op) { + case APPEND_OP: + ret = log_append(log, data, len); + break; + case COMPRESS_OP: + ret = log_compress(log, data, len); + break; + case REPLACE_OP: + ret = log_replace(log); + } + + /* log status */ + log_log(log, op, ret ? "failure" : "complete"); + + /* clean up */ + if (data != NULL) + free(data); + return ret; +} + +/* Close the foo.gz file (if open) and release the lock. */ +local void log_close(struct log *log) +{ + if (log->fd >= 0) + close(log->fd); + log->fd = -1; + log_unlock(log); +} + +/* Open foo.gz, verify the header, and load the extra field contents, after + first creating the foo.lock file to gain exclusive access to the foo.* + files. If foo.gz does not exist or is empty, then write the initial header, + extra, and body content of an empty foo.gz log file. If there is an error + creating the lock file due to access restrictions, or an error reading or + writing the foo.gz file, or if the foo.gz file is not a proper log file for + this object (e.g. not a gzip file or does not contain the expected extra + field), then return true. If there is an error, the lock is released. + Otherwise, the lock is left in place. */ +local int log_open(struct log *log) +{ + int op; + + /* release open file resource if left over -- can occur if lock lost + between gzlog_open() and gzlog_write() */ + if (log->fd >= 0) + close(log->fd); + log->fd = -1; + + /* negotiate exclusive access */ + if (log_lock(log) < 0) + return -1; + + /* open the log file, foo.gz */ + strcpy(log->end, ".gz"); + log->fd = open(log->path, O_RDWR | O_CREAT, 0644); + if (log->fd < 0) { + log_close(log); + return -1; + } + + /* if new, initialize foo.gz with an empty log, delete old dictionary */ + if (lseek(log->fd, 0, SEEK_END) == 0) { + if (write(log->fd, log_gzhead, HEAD) != HEAD || + write(log->fd, log_gzext, EXTRA) != EXTRA || + write(log->fd, log_gzbody, BODY) != BODY) { + log_close(log); + return -1; + } + strcpy(log->end, ".dict"); + unlink(log->path); + } + + /* verify log file and load extra field information */ + if ((op = log_head(log)) < 0) { + log_close(log); + return -1; + } + + /* check for interrupted process and if so, recover */ + if (op != NO_OP && log_recover(log, op)) { + log_close(log); + return -1; + } + + /* touch the lock file to prevent another process from grabbing it */ + log_touch(log); + return 0; +} + +/* See gzlog.h for the description of the external methods below */ +gzlog *gzlog_open(char *path) +{ + size_t n; + struct log *log; + + /* check arguments */ + if (path == NULL || *path == 0) + return NULL; + + /* allocate and initialize log structure */ + log = malloc(sizeof(struct log)); + if (log == NULL) + return NULL; + strcpy(log->id, LOGID); + log->fd = -1; + + /* save path and end of path for name construction */ + n = strlen(path); + log->path = malloc(n + 9); /* allow for ".repairs" */ + if (log->path == NULL) { + free(log); + return NULL; + } + strcpy(log->path, path); + log->end = log->path + n; + + /* gain exclusive access and verify log file -- may perform a + recovery operation if needed */ + if (log_open(log)) { + free(log->path); + free(log); + return NULL; + } + + /* return pointer to log structure */ + return log; +} + +/* gzlog_compress() return values: + 0: all good + -1: file i/o error (usually access issue) + -2: memory allocation failure + -3: invalid log pointer argument */ +int gzlog_compress(gzlog *logd) +{ + int fd, ret; + uint block; + size_t len, next; + unsigned char *data, buf[5]; + struct log *log = logd; + + /* check arguments */ + if (log == NULL || strcmp(log->id, LOGID)) + return -3; + + /* see if we lost the lock -- if so get it again and reload the extra + field information (it probably changed), recover last operation if + necessary */ + if (log_check(log) && log_open(log)) + return -1; + + /* create space for uncompressed data */ + len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) + + log->stored; + if ((data = malloc(len)) == NULL) + return -2; + + /* do statement here is just a cheap trick for error handling */ + do { + /* read in the uncompressed data */ + if (lseek(log->fd, log->first - 1, SEEK_SET) < 0) + break; + next = 0; + while (next < len) { + if (read(log->fd, buf, 5) != 5) + break; + block = PULL2(buf + 1); + if (next + block > len || + read(log->fd, (char *)data + next, block) != block) + break; + next += block; + } + if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored) + break; + log_touch(log); + + /* write the uncompressed data to the .add file */ + strcpy(log->end, ".add"); + fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + break; + ret = (size_t)write(fd, data, len) != len; + if (ret | close(fd)) + break; + log_touch(log); + + /* write the dictionary for the next compress to the .temp file */ + strcpy(log->end, ".temp"); + fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + break; + next = DICT > len ? len : DICT; + ret = (size_t)write(fd, (char *)data + len - next, next) != next; + if (ret | close(fd)) + break; + log_touch(log); + + /* roll back to compressed data, mark the compress in progress */ + log->last = log->first; + log->stored = 0; + if (log_mark(log, COMPRESS_OP)) + break; + BAIL(7); + + /* compress and append the data (clears mark) */ + ret = log_compress(log, data, len); + free(data); + return ret; + } while (0); + + /* broke out of do above on i/o error */ + free(data); + return -1; +} + +/* gzlog_write() return values: + 0: all good + -1: file i/o error (usually access issue) + -2: memory allocation failure + -3: invalid log pointer argument */ +int gzlog_write(gzlog *logd, void *data, size_t len) +{ + int fd, ret; + struct log *log = logd; + + /* check arguments */ + if (log == NULL || strcmp(log->id, LOGID)) + return -3; + if (data == NULL || len <= 0) + return 0; + + /* see if we lost the lock -- if so get it again and reload the extra + field information (it probably changed), recover last operation if + necessary */ + if (log_check(log) && log_open(log)) + return -1; + + /* create and write .add file */ + strcpy(log->end, ".add"); + fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + return -1; + ret = (size_t)write(fd, data, len) != len; + if (ret | close(fd)) + return -1; + log_touch(log); + + /* mark log file with append in progress */ + if (log_mark(log, APPEND_OP)) + return -1; + BAIL(8); + + /* append data (clears mark) */ + if (log_append(log, data, len)) + return -1; + + /* check to see if it's time to compress -- if not, then done */ + if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER) + return 0; + + /* time to compress */ + return gzlog_compress(log); +} + +/* gzlog_close() return values: + 0: ok + -3: invalid log pointer argument */ +int gzlog_close(gzlog *logd) +{ + struct log *log = logd; + + /* check arguments */ + if (log == NULL || strcmp(log->id, LOGID)) + return -3; + + /* close the log file and release the lock */ + log_close(log); + + /* free structure and return */ + if (log->path != NULL) + free(log->path); + strcpy(log->id, "bad"); + free(log); + return 0; +} diff --git a/third_party/zlib/v1_2_11/examples/gzlog.h b/third_party/zlib/v1_2_11/examples/gzlog.h new file mode 100644 index 0000000..86f0cec --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/gzlog.h @@ -0,0 +1,91 @@ +/* gzlog.h + Copyright (C) 2004, 2008, 2012 Mark Adler, all rights reserved + version 2.2, 14 Aug 2012 + + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Mark Adler madler@alumni.caltech.edu + */ + +/* Version History: + 1.0 26 Nov 2004 First version + 2.0 25 Apr 2008 Complete redesign for recovery of interrupted operations + Interface changed slightly in that now path is a prefix + Compression now occurs as needed during gzlog_write() + gzlog_write() now always leaves the log file as valid gzip + 2.1 8 Jul 2012 Fix argument checks in gzlog_compress() and gzlog_write() + 2.2 14 Aug 2012 Clean up signed comparisons + */ + +/* + The gzlog object allows writing short messages to a gzipped log file, + opening the log file locked for small bursts, and then closing it. The log + object works by appending stored (uncompressed) data to the gzip file until + 1 MB has been accumulated. At that time, the stored data is compressed, and + replaces the uncompressed data in the file. The log file is truncated to + its new size at that time. After each write operation, the log file is a + valid gzip file that can decompressed to recover what was written. + + The gzlog operations can be interupted at any point due to an application or + system crash, and the log file will be recovered the next time the log is + opened with gzlog_open(). + */ + +#ifndef GZLOG_H +#define GZLOG_H + +/* gzlog object type */ +typedef void gzlog; + +/* Open a gzlog object, creating the log file if it does not exist. Return + NULL on error. Note that gzlog_open() could take a while to complete if it + has to wait to verify that a lock is stale (possibly for five minutes), or + if there is significant contention with other instantiations of this object + when locking the resource. path is the prefix of the file names created by + this object. If path is "foo", then the log file will be "foo.gz", and + other auxiliary files will be created and destroyed during the process: + "foo.dict" for a compression dictionary, "foo.temp" for a temporary (next) + dictionary, "foo.add" for data being added or compressed, "foo.lock" for the + lock file, and "foo.repairs" to log recovery operations performed due to + interrupted gzlog operations. A gzlog_open() followed by a gzlog_close() + will recover a previously interrupted operation, if any. */ +gzlog *gzlog_open(char *path); + +/* Write to a gzlog object. Return zero on success, -1 if there is a file i/o + error on any of the gzlog files (this should not happen if gzlog_open() + succeeded, unless the device has run out of space or leftover auxiliary + files have permissions or ownership that prevent their use), -2 if there is + a memory allocation failure, or -3 if the log argument is invalid (e.g. if + it was not created by gzlog_open()). This function will write data to the + file uncompressed, until 1 MB has been accumulated, at which time that data + will be compressed. The log file will be a valid gzip file upon successful + return. */ +int gzlog_write(gzlog *log, void *data, size_t len); + +/* Force compression of any uncompressed data in the log. This should be used + sparingly, if at all. The main application would be when a log file will + not be appended to again. If this is used to compress frequently while + appending, it will both significantly increase the execution time and + reduce the compression ratio. The return codes are the same as for + gzlog_write(). */ +int gzlog_compress(gzlog *log); + +/* Close a gzlog object. Return zero on success, -3 if the log argument is + invalid. The log object is freed, and so cannot be referenced again. */ +int gzlog_close(gzlog *log); + +#endif diff --git a/third_party/zlib/v1_2_11/examples/zlib_how.html b/third_party/zlib/v1_2_11/examples/zlib_how.html new file mode 100644 index 0000000..444ff1c --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/zlib_how.html @@ -0,0 +1,545 @@ + + + + +zlib Usage Example + + + +

zlib Usage Example

+We often get questions about how the deflate() and inflate() functions should be used. +Users wonder when they should provide more input, when they should use more output, +what to do with a Z_BUF_ERROR, how to make sure the process terminates properly, and +so on. So for those who have read zlib.h (a few times), and +would like further edification, below is an annotated example in C of simple routines to compress and decompress +from an input file to an output file using deflate() and inflate() respectively. The +annotations are interspersed between lines of the code. So please read between the lines. +We hope this helps explain some of the intricacies of zlib. +

+Without further adieu, here is the program zpipe.c: +


+/* zpipe.c: example of proper use of zlib's inflate() and deflate()
+   Not copyrighted -- provided to the public domain
+   Version 1.4  11 December 2005  Mark Adler */
+
+/* Version history:
+   1.0  30 Oct 2004  First version
+   1.1   8 Nov 2004  Add void casting for unused return values
+                     Use switch statement for inflate() return values
+   1.2   9 Nov 2004  Add assertions to document zlib guarantees
+   1.3   6 Apr 2005  Remove incorrect assertion in inf()
+   1.4  11 Dec 2005  Add hack to avoid MSDOS end-of-line conversions
+                     Avoid some compiler warnings for input and output buffers
+ */
+
+We now include the header files for the required definitions. From +stdio.h we use fopen(), fread(), fwrite(), +feof(), ferror(), and fclose() for file i/o, and +fputs() for error messages. From string.h we use +strcmp() for command line argument processing. +From assert.h we use the assert() macro. +From zlib.h +we use the basic compression functions deflateInit(), +deflate(), and deflateEnd(), and the basic decompression +functions inflateInit(), inflate(), and +inflateEnd(). +

+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include "zlib.h"
+
+This is an ugly hack required to avoid corruption of the input and output data on +Windows/MS-DOS systems. Without this, those systems would assume that the input and output +files are text, and try to convert the end-of-line characters from one standard to +another. That would corrupt binary data, and in particular would render the compressed data unusable. +This sets the input and output to binary which suppresses the end-of-line conversions. +SET_BINARY_MODE() will be used later on stdin and stdout, at the beginning of main(). +

+#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#  include <fcntl.h>
+#  include <io.h>
+#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+#  define SET_BINARY_MODE(file)
+#endif
+
+CHUNK is simply the buffer size for feeding data to and pulling data +from the zlib routines. Larger buffer sizes would be more efficient, +especially for inflate(). If the memory is available, buffers sizes +on the order of 128K or 256K bytes should be used. +

+#define CHUNK 16384
+
+The def() routine compresses data from an input file to an output file. The output data +will be in the zlib format, which is different from the gzip or zip +formats. The zlib format has a very small header of only two bytes to identify it as +a zlib stream and to provide decoding information, and a four-byte trailer with a fast +check value to verify the integrity of the uncompressed data after decoding. +

+/* Compress from file source to file dest until EOF on source.
+   def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_STREAM_ERROR if an invalid compression
+   level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
+   version of the library linked do not match, or Z_ERRNO if there is
+   an error reading or writing the files. */
+int def(FILE *source, FILE *dest, int level)
+{
+
+Here are the local variables for def(). ret will be used for zlib +return codes. flush will keep track of the current flushing state for deflate(), +which is either no flushing, or flush to completion after the end of the input file is reached. +have is the amount of data returned from deflate(). The strm structure +is used to pass information to and from the zlib routines, and to maintain the +deflate() state. in and out are the input and output buffers for +deflate(). +

+    int ret, flush;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+
+The first thing we do is to initialize the zlib state for compression using +deflateInit(). This must be done before the first use of deflate(). +The zalloc, zfree, and opaque fields in the strm +structure must be initialized before calling deflateInit(). Here they are +set to the zlib constant Z_NULL to request that zlib use +the default memory allocation routines. An application may also choose to provide +custom memory allocation routines here. deflateInit() will allocate on the +order of 256K bytes for the internal state. +(See zlib Technical Details.) +

+deflateInit() is called with a pointer to the structure to be initialized and +the compression level, which is an integer in the range of -1 to 9. Lower compression +levels result in faster execution, but less compression. Higher levels result in +greater compression, but slower execution. The zlib constant Z_DEFAULT_COMPRESSION, +equal to -1, +provides a good compromise between compression and speed and is equivalent to level 6. +Level 0 actually does no compression at all, and in fact expands the data slightly to produce +the zlib format (it is not a byte-for-byte copy of the input). +More advanced applications of zlib +may use deflateInit2() here instead. Such an application may want to reduce how +much memory will be used, at some price in compression. Or it may need to request a +gzip header and trailer instead of a zlib header and trailer, or raw +encoding with no header or trailer at all. +

+We must check the return value of deflateInit() against the zlib constant +Z_OK to make sure that it was able to +allocate memory for the internal state, and that the provided arguments were valid. +deflateInit() will also check that the version of zlib that the zlib.h +file came from matches the version of zlib actually linked with the program. This +is especially important for environments in which zlib is a shared library. +

+Note that an application can initialize multiple, independent zlib streams, which can +operate in parallel. The state information maintained in the structure allows the zlib +routines to be reentrant. +


+    /* allocate deflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    ret = deflateInit(&strm, level);
+    if (ret != Z_OK)
+        return ret;
+
+With the pleasantries out of the way, now we can get down to business. The outer do-loop +reads all of the input file and exits at the bottom of the loop once end-of-file is reached. +This loop contains the only call of deflate(). So we must make sure that all of the +input data has been processed and that all of the output data has been generated and consumed +before we fall out of the loop at the bottom. +

+    /* compress until end of file */
+    do {
+
+We start off by reading data from the input file. The number of bytes read is put directly +into avail_in, and a pointer to those bytes is put into next_in. We also +check to see if end-of-file on the input has been reached. If we are at the end of file, then flush is set to the +zlib constant Z_FINISH, which is later passed to deflate() to +indicate that this is the last chunk of input data to compress. We need to use feof() +to check for end-of-file as opposed to seeing if fewer than CHUNK bytes have been read. The +reason is that if the input file length is an exact multiple of CHUNK, we will miss +the fact that we got to the end-of-file, and not know to tell deflate() to finish +up the compressed stream. If we are not yet at the end of the input, then the zlib +constant Z_NO_FLUSH will be passed to deflate to indicate that we are still +in the middle of the uncompressed data. +

+If there is an error in reading from the input file, the process is aborted with +deflateEnd() being called to free the allocated zlib state before returning +the error. We wouldn't want a memory leak, now would we? deflateEnd() can be called +at any time after the state has been initialized. Once that's done, deflateInit() (or +deflateInit2()) would have to be called to start a new compression process. There is +no point here in checking the deflateEnd() return code. The deallocation can't fail. +


+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)deflateEnd(&strm);
+            return Z_ERRNO;
+        }
+        flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
+        strm.next_in = in;
+
+The inner do-loop passes our chunk of input data to deflate(), and then +keeps calling deflate() until it is done producing output. Once there is no more +new output, deflate() is guaranteed to have consumed all of the input, i.e., +avail_in will be zero. +

+        /* run deflate() on input until output buffer not full, finish
+           compression if all of source has been read in */
+        do {
+
+Output space is provided to deflate() by setting avail_out to the number +of available output bytes and next_out to a pointer to that space. +

+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+
+Now we call the compression engine itself, deflate(). It takes as many of the +avail_in bytes at next_in as it can process, and writes as many as +avail_out bytes to next_out. Those counters and pointers are then +updated past the input data consumed and the output data written. It is the amount of +output space available that may limit how much input is consumed. +Hence the inner loop to make sure that +all of the input is consumed by providing more output space each time. Since avail_in +and next_in are updated by deflate(), we don't have to mess with those +between deflate() calls until it's all used up. +

+The parameters to deflate() are a pointer to the strm structure containing +the input and output information and the internal compression engine state, and a parameter +indicating whether and how to flush data to the output. Normally deflate will consume +several K bytes of input data before producing any output (except for the header), in order +to accumulate statistics on the data for optimum compression. It will then put out a burst of +compressed data, and proceed to consume more input before the next burst. Eventually, +deflate() +must be told to terminate the stream, complete the compression with provided input data, and +write out the trailer check value. deflate() will continue to compress normally as long +as the flush parameter is Z_NO_FLUSH. Once the Z_FINISH parameter is provided, +deflate() will begin to complete the compressed output stream. However depending on how +much output space is provided, deflate() may have to be called several times until it +has provided the complete compressed stream, even after it has consumed all of the input. The flush +parameter must continue to be Z_FINISH for those subsequent calls. +

+There are other values of the flush parameter that are used in more advanced applications. You can +force deflate() to produce a burst of output that encodes all of the input data provided +so far, even if it wouldn't have otherwise, for example to control data latency on a link with +compressed data. You can also ask that deflate() do that as well as erase any history up to +that point so that what follows can be decompressed independently, for example for random access +applications. Both requests will degrade compression by an amount depending on how often such +requests are made. +

+deflate() has a return value that can indicate errors, yet we do not check it here. Why +not? Well, it turns out that deflate() can do no wrong here. Let's go through +deflate()'s return values and dispense with them one by one. The possible values are +Z_OK, Z_STREAM_END, Z_STREAM_ERROR, or Z_BUF_ERROR. Z_OK +is, well, ok. Z_STREAM_END is also ok and will be returned for the last call of +deflate(). This is already guaranteed by calling deflate() with Z_FINISH +until it has no more output. Z_STREAM_ERROR is only possible if the stream is not +initialized properly, but we did initialize it properly. There is no harm in checking for +Z_STREAM_ERROR here, for example to check for the possibility that some +other part of the application inadvertently clobbered the memory containing the zlib state. +Z_BUF_ERROR will be explained further below, but +suffice it to say that this is simply an indication that deflate() could not consume +more input or produce more output. deflate() can be called again with more output space +or more available input, which it will be in this code. +


+            ret = deflate(&strm, flush);    /* no bad return value */
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+
+Now we compute how much output deflate() provided on the last call, which is the +difference between how much space was provided before the call, and how much output space +is still available after the call. Then that data, if any, is written to the output file. +We can then reuse the output buffer for the next call of deflate(). Again if there +is a file i/o error, we call deflateEnd() before returning to avoid a memory leak. +

+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)deflateEnd(&strm);
+                return Z_ERRNO;
+            }
+
+The inner do-loop is repeated until the last deflate() call fails to fill the +provided output buffer. Then we know that deflate() has done as much as it can with +the provided input, and that all of that input has been consumed. We can then fall out of this +loop and reuse the input buffer. +

+The way we tell that deflate() has no more output is by seeing that it did not fill +the output buffer, leaving avail_out greater than zero. However suppose that +deflate() has no more output, but just so happened to exactly fill the output buffer! +avail_out is zero, and we can't tell that deflate() has done all it can. +As far as we know, deflate() +has more output for us. So we call it again. But now deflate() produces no output +at all, and avail_out remains unchanged as CHUNK. That deflate() call +wasn't able to do anything, either consume input or produce output, and so it returns +Z_BUF_ERROR. (See, I told you I'd cover this later.) However this is not a problem at +all. Now we finally have the desired indication that deflate() is really done, +and so we drop out of the inner loop to provide more input to deflate(). +

+With flush set to Z_FINISH, this final set of deflate() calls will +complete the output stream. Once that is done, subsequent calls of deflate() would return +Z_STREAM_ERROR if the flush parameter is not Z_FINISH, and do no more processing +until the state is reinitialized. +

+Some applications of zlib have two loops that call deflate() +instead of the single inner loop we have here. The first loop would call +without flushing and feed all of the data to deflate(). The second loop would call +deflate() with no more +data and the Z_FINISH parameter to complete the process. As you can see from this +example, that can be avoided by simply keeping track of the current flush state. +


+        } while (strm.avail_out == 0);
+        assert(strm.avail_in == 0);     /* all input will be used */
+
+Now we check to see if we have already processed all of the input file. That information was +saved in the flush variable, so we see if that was set to Z_FINISH. If so, +then we're done and we fall out of the outer loop. We're guaranteed to get Z_STREAM_END +from the last deflate() call, since we ran it until the last chunk of input was +consumed and all of the output was generated. +

+        /* done when last data in file processed */
+    } while (flush != Z_FINISH);
+    assert(ret == Z_STREAM_END);        /* stream will be complete */
+
+The process is complete, but we still need to deallocate the state to avoid a memory leak +(or rather more like a memory hemorrhage if you didn't do this). Then +finally we can return with a happy return value. +

+    /* clean up and return */
+    (void)deflateEnd(&strm);
+    return Z_OK;
+}
+
+Now we do the same thing for decompression in the inf() routine. inf() +decompresses what is hopefully a valid zlib stream from the input file and writes the +uncompressed data to the output file. Much of the discussion above for def() +applies to inf() as well, so the discussion here will focus on the differences between +the two. +

+/* Decompress from file source to file dest until stream ends or EOF.
+   inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
+   allocated for processing, Z_DATA_ERROR if the deflate data is
+   invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
+   the version of the library linked do not match, or Z_ERRNO if there
+   is an error reading or writing the files. */
+int inf(FILE *source, FILE *dest)
+{
+
+The local variables have the same functionality as they do for def(). The +only difference is that there is no flush variable, since inflate() +can tell from the zlib stream itself when the stream is complete. +

+    int ret;
+    unsigned have;
+    z_stream strm;
+    unsigned char in[CHUNK];
+    unsigned char out[CHUNK];
+
+The initialization of the state is the same, except that there is no compression level, +of course, and two more elements of the structure are initialized. avail_in +and next_in must be initialized before calling inflateInit(). This +is because the application has the option to provide the start of the zlib stream in +order for inflateInit() to have access to information about the compression +method to aid in memory allocation. In the current implementation of zlib +(up through versions 1.2.x), the method-dependent memory allocations are deferred to the first call of +inflate() anyway. However those fields must be initialized since later versions +of zlib that provide more compression methods may take advantage of this interface. +In any case, no decompression is performed by inflateInit(), so the +avail_out and next_out fields do not need to be initialized before calling. +

+Here avail_in is set to zero and next_in is set to Z_NULL to +indicate that no input data is being provided. +


+    /* allocate inflate state */
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.avail_in = 0;
+    strm.next_in = Z_NULL;
+    ret = inflateInit(&strm);
+    if (ret != Z_OK)
+        return ret;
+
+The outer do-loop decompresses input until inflate() indicates +that it has reached the end of the compressed data and has produced all of the uncompressed +output. This is in contrast to def() which processes all of the input file. +If end-of-file is reached before the compressed data self-terminates, then the compressed +data is incomplete and an error is returned. +

+    /* decompress until deflate stream ends or end of file */
+    do {
+
+We read input data and set the strm structure accordingly. If we've reached the +end of the input file, then we leave the outer loop and report an error, since the +compressed data is incomplete. Note that we may read more data than is eventually consumed +by inflate(), if the input file continues past the zlib stream. +For applications where zlib streams are embedded in other data, this routine would +need to be modified to return the unused data, or at least indicate how much of the input +data was not used, so the application would know where to pick up after the zlib stream. +

+        strm.avail_in = fread(in, 1, CHUNK, source);
+        if (ferror(source)) {
+            (void)inflateEnd(&strm);
+            return Z_ERRNO;
+        }
+        if (strm.avail_in == 0)
+            break;
+        strm.next_in = in;
+
+The inner do-loop has the same function it did in def(), which is to +keep calling inflate() until has generated all of the output it can with the +provided input. +

+        /* run inflate() on input until output buffer not full */
+        do {
+
+Just like in def(), the same output space is provided for each call of inflate(). +

+            strm.avail_out = CHUNK;
+            strm.next_out = out;
+
+Now we run the decompression engine itself. There is no need to adjust the flush parameter, since +the zlib format is self-terminating. The main difference here is that there are +return values that we need to pay attention to. Z_DATA_ERROR +indicates that inflate() detected an error in the zlib compressed data format, +which means that either the data is not a zlib stream to begin with, or that the data was +corrupted somewhere along the way since it was compressed. The other error to be processed is +Z_MEM_ERROR, which can occur since memory allocation is deferred until inflate() +needs it, unlike deflate(), whose memory is allocated at the start by deflateInit(). +

+Advanced applications may use +deflateSetDictionary() to prime deflate() with a set of likely data to improve the +first 32K or so of compression. This is noted in the zlib header, so inflate() +requests that that dictionary be provided before it can start to decompress. Without the dictionary, +correct decompression is not possible. For this routine, we have no idea what the dictionary is, +so the Z_NEED_DICT indication is converted to a Z_DATA_ERROR. +

+inflate() can also return Z_STREAM_ERROR, which should not be possible here, +but could be checked for as noted above for def(). Z_BUF_ERROR does not need to be +checked for here, for the same reasons noted for def(). Z_STREAM_END will be +checked for later. +


+            ret = inflate(&strm, Z_NO_FLUSH);
+            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
+            switch (ret) {
+            case Z_NEED_DICT:
+                ret = Z_DATA_ERROR;     /* and fall through */
+            case Z_DATA_ERROR:
+            case Z_MEM_ERROR:
+                (void)inflateEnd(&strm);
+                return ret;
+            }
+
+The output of inflate() is handled identically to that of deflate(). +

+            have = CHUNK - strm.avail_out;
+            if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
+                (void)inflateEnd(&strm);
+                return Z_ERRNO;
+            }
+
+The inner do-loop ends when inflate() has no more output as indicated +by not filling the output buffer, just as for deflate(). In this case, we cannot +assert that strm.avail_in will be zero, since the deflate stream may end before the file +does. +

+        } while (strm.avail_out == 0);
+
+The outer do-loop ends when inflate() reports that it has reached the +end of the input zlib stream, has completed the decompression and integrity +check, and has provided all of the output. This is indicated by the inflate() +return value Z_STREAM_END. The inner loop is guaranteed to leave ret +equal to Z_STREAM_END if the last chunk of the input file read contained the end +of the zlib stream. So if the return value is not Z_STREAM_END, the +loop continues to read more input. +

+        /* done when inflate() says it's done */
+    } while (ret != Z_STREAM_END);
+
+At this point, decompression successfully completed, or we broke out of the loop due to no +more data being available from the input file. If the last inflate() return value +is not Z_STREAM_END, then the zlib stream was incomplete and a data error +is returned. Otherwise, we return with a happy return value. Of course, inflateEnd() +is called first to avoid a memory leak. +

+    /* clean up and return */
+    (void)inflateEnd(&strm);
+    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
+}
+
+That ends the routines that directly use zlib. The following routines make this +a command-line program by running data through the above routines from stdin to +stdout, and handling any errors reported by def() or inf(). +

+zerr() is used to interpret the possible error codes from def() +and inf(), as detailed in their comments above, and print out an error message. +Note that these are only a subset of the possible return values from deflate() +and inflate(). +


+/* report a zlib or i/o error */
+void zerr(int ret)
+{
+    fputs("zpipe: ", stderr);
+    switch (ret) {
+    case Z_ERRNO:
+        if (ferror(stdin))
+            fputs("error reading stdin\n", stderr);
+        if (ferror(stdout))
+            fputs("error writing stdout\n", stderr);
+        break;
+    case Z_STREAM_ERROR:
+        fputs("invalid compression level\n", stderr);
+        break;
+    case Z_DATA_ERROR:
+        fputs("invalid or incomplete deflate data\n", stderr);
+        break;
+    case Z_MEM_ERROR:
+        fputs("out of memory\n", stderr);
+        break;
+    case Z_VERSION_ERROR:
+        fputs("zlib version mismatch!\n", stderr);
+    }
+}
+
+Here is the main() routine used to test def() and inf(). The +zpipe command is simply a compression pipe from stdin to stdout, if +no arguments are given, or it is a decompression pipe if zpipe -d is used. If any other +arguments are provided, no compression or decompression is performed. Instead a usage +message is displayed. Examples are zpipe < foo.txt > foo.txt.z to compress, and +zpipe -d < foo.txt.z > foo.txt to decompress. +

+/* compress or decompress from stdin to stdout */
+int main(int argc, char **argv)
+{
+    int ret;
+
+    /* avoid end-of-line conversions */
+    SET_BINARY_MODE(stdin);
+    SET_BINARY_MODE(stdout);
+
+    /* do compression if no arguments */
+    if (argc == 1) {
+        ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* do decompression if -d specified */
+    else if (argc == 2 && strcmp(argv[1], "-d") == 0) {
+        ret = inf(stdin, stdout);
+        if (ret != Z_OK)
+            zerr(ret);
+        return ret;
+    }
+
+    /* otherwise, report usage */
+    else {
+        fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr);
+        return 1;
+    }
+}
+
+
+Copyright (c) 2004, 2005 by Mark Adler
Last modified 11 December 2005
+ + diff --git a/third_party/zlib/v1_2_11/examples/zpipe.c b/third_party/zlib/v1_2_11/examples/zpipe.c new file mode 100644 index 0000000..83535d1 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/zpipe.c @@ -0,0 +1,205 @@ +/* zpipe.c: example of proper use of zlib's inflate() and deflate() + Not copyrighted -- provided to the public domain + Version 1.4 11 December 2005 Mark Adler */ + +/* Version history: + 1.0 30 Oct 2004 First version + 1.1 8 Nov 2004 Add void casting for unused return values + Use switch statement for inflate() return values + 1.2 9 Nov 2004 Add assertions to document zlib guarantees + 1.3 6 Apr 2005 Remove incorrect assertion in inf() + 1.4 11 Dec 2005 Add hack to avoid MSDOS end-of-line conversions + Avoid some compiler warnings for input and output buffers + */ + +#include +#include +#include +#include "zlib.h" + +#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) +# include +# include +# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif + +#define CHUNK 16384 + +/* Compress from file source to file dest until EOF on source. + def() returns Z_OK on success, Z_MEM_ERROR if memory could not be + allocated for processing, Z_STREAM_ERROR if an invalid compression + level is supplied, Z_VERSION_ERROR if the version of zlib.h and the + version of the library linked do not match, or Z_ERRNO if there is + an error reading or writing the files. */ +int def(FILE *source, FILE *dest, int level) +{ + int ret, flush; + unsigned have; + z_stream strm; + unsigned char in[CHUNK]; + unsigned char out[CHUNK]; + + /* allocate deflate state */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + ret = deflateInit(&strm, level); + if (ret != Z_OK) + return ret; + + /* compress until end of file */ + do { + strm.avail_in = fread(in, 1, CHUNK, source); + if (ferror(source)) { + (void)deflateEnd(&strm); + return Z_ERRNO; + } + flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; + strm.next_in = in; + + /* run deflate() on input until output buffer not full, finish + compression if all of source has been read in */ + do { + strm.avail_out = CHUNK; + strm.next_out = out; + ret = deflate(&strm, flush); /* no bad return value */ + assert(ret != Z_STREAM_ERROR); /* state not clobbered */ + have = CHUNK - strm.avail_out; + if (fwrite(out, 1, have, dest) != have || ferror(dest)) { + (void)deflateEnd(&strm); + return Z_ERRNO; + } + } while (strm.avail_out == 0); + assert(strm.avail_in == 0); /* all input will be used */ + + /* done when last data in file processed */ + } while (flush != Z_FINISH); + assert(ret == Z_STREAM_END); /* stream will be complete */ + + /* clean up and return */ + (void)deflateEnd(&strm); + return Z_OK; +} + +/* Decompress from file source to file dest until stream ends or EOF. + inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be + allocated for processing, Z_DATA_ERROR if the deflate data is + invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and + the version of the library linked do not match, or Z_ERRNO if there + is an error reading or writing the files. */ +int inf(FILE *source, FILE *dest) +{ + int ret; + unsigned have; + z_stream strm; + unsigned char in[CHUNK]; + unsigned char out[CHUNK]; + + /* allocate inflate state */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit(&strm); + if (ret != Z_OK) + return ret; + + /* decompress until deflate stream ends or end of file */ + do { + strm.avail_in = fread(in, 1, CHUNK, source); + if (ferror(source)) { + (void)inflateEnd(&strm); + return Z_ERRNO; + } + if (strm.avail_in == 0) + break; + strm.next_in = in; + + /* run inflate() on input until output buffer not full */ + do { + strm.avail_out = CHUNK; + strm.next_out = out; + ret = inflate(&strm, Z_NO_FLUSH); + assert(ret != Z_STREAM_ERROR); /* state not clobbered */ + switch (ret) { + case Z_NEED_DICT: + ret = Z_DATA_ERROR; /* and fall through */ + case Z_DATA_ERROR: + case Z_MEM_ERROR: + (void)inflateEnd(&strm); + return ret; + } + have = CHUNK - strm.avail_out; + if (fwrite(out, 1, have, dest) != have || ferror(dest)) { + (void)inflateEnd(&strm); + return Z_ERRNO; + } + } while (strm.avail_out == 0); + + /* done when inflate() says it's done */ + } while (ret != Z_STREAM_END); + + /* clean up and return */ + (void)inflateEnd(&strm); + return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; +} + +/* report a zlib or i/o error */ +void zerr(int ret) +{ + fputs("zpipe: ", stderr); + switch (ret) { + case Z_ERRNO: + if (ferror(stdin)) + fputs("error reading stdin\n", stderr); + if (ferror(stdout)) + fputs("error writing stdout\n", stderr); + break; + case Z_STREAM_ERROR: + fputs("invalid compression level\n", stderr); + break; + case Z_DATA_ERROR: + fputs("invalid or incomplete deflate data\n", stderr); + break; + case Z_MEM_ERROR: + fputs("out of memory\n", stderr); + break; + case Z_VERSION_ERROR: + fputs("zlib version mismatch!\n", stderr); + } +} + +/* compress or decompress from stdin to stdout */ +int main(int argc, char **argv) +{ + int ret; + + /* avoid end-of-line conversions */ + SET_BINARY_MODE(stdin); + SET_BINARY_MODE(stdout); + + /* do compression if no arguments */ + if (argc == 1) { + ret = def(stdin, stdout, Z_DEFAULT_COMPRESSION); + if (ret != Z_OK) + zerr(ret); + return ret; + } + + /* do decompression if -d specified */ + else if (argc == 2 && strcmp(argv[1], "-d") == 0) { + ret = inf(stdin, stdout); + if (ret != Z_OK) + zerr(ret); + return ret; + } + + /* otherwise, report usage */ + else { + fputs("zpipe usage: zpipe [-d] < source > dest\n", stderr); + return 1; + } +} diff --git a/third_party/zlib/v1_2_11/examples/zran.c b/third_party/zlib/v1_2_11/examples/zran.c new file mode 100644 index 0000000..4fec659 --- /dev/null +++ b/third_party/zlib/v1_2_11/examples/zran.c @@ -0,0 +1,409 @@ +/* zran.c -- example of zlib/gzip stream indexing and random access + * Copyright (C) 2005, 2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + Version 1.1 29 Sep 2012 Mark Adler */ + +/* Version History: + 1.0 29 May 2005 First version + 1.1 29 Sep 2012 Fix memory reallocation error + */ + +/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary() + for random access of a compressed file. A file containing a zlib or gzip + stream is provided on the command line. The compressed stream is decoded in + its entirety, and an index built with access points about every SPAN bytes + in the uncompressed output. The compressed file is left open, and can then + be read randomly, having to decompress on the average SPAN/2 uncompressed + bytes before getting to the desired block of data. + + An access point can be created at the start of any deflate block, by saving + the starting file offset and bit of that block, and the 32K bytes of + uncompressed data that precede that block. Also the uncompressed offset of + that block is saved to provide a referece for locating a desired starting + point in the uncompressed stream. build_index() works by decompressing the + input zlib or gzip stream a block at a time, and at the end of each block + deciding if enough uncompressed data has gone by to justify the creation of + a new access point. If so, that point is saved in a data structure that + grows as needed to accommodate the points. + + To use the index, an offset in the uncompressed data is provided, for which + the latest access point at or preceding that offset is located in the index. + The input file is positioned to the specified location in the index, and if + necessary the first few bits of the compressed data is read from the file. + inflate is initialized with those bits and the 32K of uncompressed data, and + the decompression then proceeds until the desired offset in the file is + reached. Then the decompression continues to read the desired uncompressed + data from the file. + + Another approach would be to generate the index on demand. In that case, + requests for random access reads from the compressed data would try to use + the index, but if a read far enough past the end of the index is required, + then further index entries would be generated and added. + + There is some fair bit of overhead to starting inflation for the random + access, mainly copying the 32K byte dictionary. So if small pieces of the + file are being accessed, it would make sense to implement a cache to hold + some lookahead and avoid many calls to extract() for small lengths. + + Another way to build an index would be to use inflateCopy(). That would + not be constrained to have access points at block boundaries, but requires + more memory per access point, and also cannot be saved to file due to the + use of pointers in the state. The approach here allows for storage of the + index in a file. + */ + +#include +#include +#include +#include "zlib.h" + +#define local static + +#define SPAN 1048576L /* desired distance between access points */ +#define WINSIZE 32768U /* sliding window size */ +#define CHUNK 16384 /* file input buffer size */ + +/* access point entry */ +struct point { + off_t out; /* corresponding offset in uncompressed data */ + off_t in; /* offset in input file of first full byte */ + int bits; /* number of bits (1-7) from byte at in - 1, or 0 */ + unsigned char window[WINSIZE]; /* preceding 32K of uncompressed data */ +}; + +/* access point list */ +struct access { + int have; /* number of list entries filled in */ + int size; /* number of list entries allocated */ + struct point *list; /* allocated list */ +}; + +/* Deallocate an index built by build_index() */ +local void free_index(struct access *index) +{ + if (index != NULL) { + free(index->list); + free(index); + } +} + +/* Add an entry to the access point list. If out of memory, deallocate the + existing list and return NULL. */ +local struct access *addpoint(struct access *index, int bits, + off_t in, off_t out, unsigned left, unsigned char *window) +{ + struct point *next; + + /* if list is empty, create it (start with eight points) */ + if (index == NULL) { + index = malloc(sizeof(struct access)); + if (index == NULL) return NULL; + index->list = malloc(sizeof(struct point) << 3); + if (index->list == NULL) { + free(index); + return NULL; + } + index->size = 8; + index->have = 0; + } + + /* if list is full, make it bigger */ + else if (index->have == index->size) { + index->size <<= 1; + next = realloc(index->list, sizeof(struct point) * index->size); + if (next == NULL) { + free_index(index); + return NULL; + } + index->list = next; + } + + /* fill in entry and increment how many we have */ + next = index->list + index->have; + next->bits = bits; + next->in = in; + next->out = out; + if (left) + memcpy(next->window, window + WINSIZE - left, left); + if (left < WINSIZE) + memcpy(next->window + left, window, WINSIZE - left); + index->have++; + + /* return list, possibly reallocated */ + return index; +} + +/* Make one entire pass through the compressed stream and build an index, with + access points about every span bytes of uncompressed output -- span is + chosen to balance the speed of random access against the memory requirements + of the list, about 32K bytes per access point. Note that data after the end + of the first zlib or gzip stream in the file is ignored. build_index() + returns the number of access points on success (>= 1), Z_MEM_ERROR for out + of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a + file read error. On success, *built points to the resulting index. */ +local int build_index(FILE *in, off_t span, struct access **built) +{ + int ret; + off_t totin, totout; /* our own total counters to avoid 4GB limit */ + off_t last; /* totout value of last access point */ + struct access *index; /* access points being generated */ + z_stream strm; + unsigned char input[CHUNK]; + unsigned char window[WINSIZE]; + + /* initialize inflate */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */ + if (ret != Z_OK) + return ret; + + /* inflate the input, maintain a sliding window, and build an index -- this + also validates the integrity of the compressed data using the check + information at the end of the gzip or zlib stream */ + totin = totout = last = 0; + index = NULL; /* will be allocated by first addpoint() */ + strm.avail_out = 0; + do { + /* get some compressed data from input file */ + strm.avail_in = fread(input, 1, CHUNK, in); + if (ferror(in)) { + ret = Z_ERRNO; + goto build_index_error; + } + if (strm.avail_in == 0) { + ret = Z_DATA_ERROR; + goto build_index_error; + } + strm.next_in = input; + + /* process all of that, or until end of stream */ + do { + /* reset sliding window if necessary */ + if (strm.avail_out == 0) { + strm.avail_out = WINSIZE; + strm.next_out = window; + } + + /* inflate until out of input, output, or at end of block -- + update the total input and output counters */ + totin += strm.avail_in; + totout += strm.avail_out; + ret = inflate(&strm, Z_BLOCK); /* return at end of block */ + totin -= strm.avail_in; + totout -= strm.avail_out; + if (ret == Z_NEED_DICT) + ret = Z_DATA_ERROR; + if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) + goto build_index_error; + if (ret == Z_STREAM_END) + break; + + /* if at end of block, consider adding an index entry (note that if + data_type indicates an end-of-block, then all of the + uncompressed data from that block has been delivered, and none + of the compressed data after that block has been consumed, + except for up to seven bits) -- the totout == 0 provides an + entry point after the zlib or gzip header, and assures that the + index always has at least one access point; we avoid creating an + access point after the last block by checking bit 6 of data_type + */ + if ((strm.data_type & 128) && !(strm.data_type & 64) && + (totout == 0 || totout - last > span)) { + index = addpoint(index, strm.data_type & 7, totin, + totout, strm.avail_out, window); + if (index == NULL) { + ret = Z_MEM_ERROR; + goto build_index_error; + } + last = totout; + } + } while (strm.avail_in != 0); + } while (ret != Z_STREAM_END); + + /* clean up and return index (release unused entries in list) */ + (void)inflateEnd(&strm); + index->list = realloc(index->list, sizeof(struct point) * index->have); + index->size = index->have; + *built = index; + return index->size; + + /* return error */ + build_index_error: + (void)inflateEnd(&strm); + if (index != NULL) + free_index(index); + return ret; +} + +/* Use the index to read len bytes from offset into buf, return bytes read or + negative for error (Z_DATA_ERROR or Z_MEM_ERROR). If data is requested past + the end of the uncompressed data, then extract() will return a value less + than len, indicating how much as actually read into buf. This function + should not return a data error unless the file was modified since the index + was generated. extract() may also return Z_ERRNO if there is an error on + reading or seeking the input file. */ +local int extract(FILE *in, struct access *index, off_t offset, + unsigned char *buf, int len) +{ + int ret, skip; + z_stream strm; + struct point *here; + unsigned char input[CHUNK]; + unsigned char discard[WINSIZE]; + + /* proceed only if something reasonable to do */ + if (len < 0) + return 0; + + /* find where in stream to start */ + here = index->list; + ret = index->have; + while (--ret && here[1].out <= offset) + here++; + + /* initialize file and inflate state to start there */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, -15); /* raw inflate */ + if (ret != Z_OK) + return ret; + ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET); + if (ret == -1) + goto extract_ret; + if (here->bits) { + ret = getc(in); + if (ret == -1) { + ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR; + goto extract_ret; + } + (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits)); + } + (void)inflateSetDictionary(&strm, here->window, WINSIZE); + + /* skip uncompressed bytes until offset reached, then satisfy request */ + offset -= here->out; + strm.avail_in = 0; + skip = 1; /* while skipping to offset */ + do { + /* define where to put uncompressed data, and how much */ + if (offset == 0 && skip) { /* at offset now */ + strm.avail_out = len; + strm.next_out = buf; + skip = 0; /* only do this once */ + } + if (offset > WINSIZE) { /* skip WINSIZE bytes */ + strm.avail_out = WINSIZE; + strm.next_out = discard; + offset -= WINSIZE; + } + else if (offset != 0) { /* last skip */ + strm.avail_out = (unsigned)offset; + strm.next_out = discard; + offset = 0; + } + + /* uncompress until avail_out filled, or end of stream */ + do { + if (strm.avail_in == 0) { + strm.avail_in = fread(input, 1, CHUNK, in); + if (ferror(in)) { + ret = Z_ERRNO; + goto extract_ret; + } + if (strm.avail_in == 0) { + ret = Z_DATA_ERROR; + goto extract_ret; + } + strm.next_in = input; + } + ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */ + if (ret == Z_NEED_DICT) + ret = Z_DATA_ERROR; + if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR) + goto extract_ret; + if (ret == Z_STREAM_END) + break; + } while (strm.avail_out != 0); + + /* if reach end of stream, then don't keep trying to get more */ + if (ret == Z_STREAM_END) + break; + + /* do until offset reached and requested data read, or stream ends */ + } while (skip); + + /* compute number of uncompressed bytes read after offset */ + ret = skip ? 0 : len - strm.avail_out; + + /* clean up and return bytes read or error */ + extract_ret: + (void)inflateEnd(&strm); + return ret; +} + +/* Demonstrate the use of build_index() and extract() by processing the file + provided on the command line, and the extracting 16K from about 2/3rds of + the way through the uncompressed output, and writing that to stdout. */ +int main(int argc, char **argv) +{ + int len; + off_t offset; + FILE *in; + struct access *index = NULL; + unsigned char buf[CHUNK]; + + /* open input file */ + if (argc != 2) { + fprintf(stderr, "usage: zran file.gz\n"); + return 1; + } + in = fopen(argv[1], "rb"); + if (in == NULL) { + fprintf(stderr, "zran: could not open %s for reading\n", argv[1]); + return 1; + } + + /* build index */ + len = build_index(in, SPAN, &index); + if (len < 0) { + fclose(in); + switch (len) { + case Z_MEM_ERROR: + fprintf(stderr, "zran: out of memory\n"); + break; + case Z_DATA_ERROR: + fprintf(stderr, "zran: compressed data error in %s\n", argv[1]); + break; + case Z_ERRNO: + fprintf(stderr, "zran: read error on %s\n", argv[1]); + break; + default: + fprintf(stderr, "zran: error %d while building index\n", len); + } + return 1; + } + fprintf(stderr, "zran: built index with %d access points\n", len); + + /* use index by reading some bytes from an arbitrary offset */ + offset = (index->list[index->have - 1].out << 1) / 3; + len = extract(in, index, offset, buf, CHUNK); + if (len < 0) + fprintf(stderr, "zran: extraction failed: %s error\n", + len == Z_MEM_ERROR ? "out of memory" : "input corrupted"); + else { + fwrite(buf, 1, len, stdout); + fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset); + } + + /* clean up and exit */ + free_index(index); + fclose(in); + return 0; +} diff --git a/third_party/zlib/v1_2_11/gzclose.c b/third_party/zlib/v1_2_11/gzclose.c new file mode 100644 index 0000000..caeb99a --- /dev/null +++ b/third_party/zlib/v1_2_11/gzclose.c @@ -0,0 +1,25 @@ +/* gzclose.c -- zlib gzclose() function + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +int ZEXPORT gzclose(file) + gzFile file; +{ +#ifndef NO_GZCOMPRESS + gz_statep state; + + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); +#else + return gzclose_r(file); +#endif +} diff --git a/third_party/zlib/v1_2_11/gzguts.h b/third_party/zlib/v1_2_11/gzguts.h new file mode 100644 index 0000000..990a4d2 --- /dev/null +++ b/third_party/zlib/v1_2_11/gzguts.h @@ -0,0 +1,218 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "zlib.h" +#ifdef STDC +# include +# include +# include +#endif + +#ifndef _POSIX_SOURCE +# define _POSIX_SOURCE +#endif +#include + +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# define WIDECHAR +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99), _snprintf does not guarantee + null termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#if defined(_MSC_VER) && _MSC_VER < 1900 +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer (double-sized when writing) */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/third_party/zlib/v1_2_11/gzlib.c b/third_party/zlib/v1_2_11/gzlib.c new file mode 100644 index 0000000..4105e6a --- /dev/null +++ b/third_party/zlib/v1_2_11/gzlib.c @@ -0,0 +1,637 @@ +/* gzlib.c -- zlib functions common to reading and writing gzip files + * Copyright (C) 2004-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__) +# define LSEEK _lseeki64 +#else +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define LSEEK lseek64 +#else +# define LSEEK lseek +#endif +#endif + +/* Local functions */ +local void gz_reset OF((gz_statep)); +local gzFile gz_open OF((const void *, int, const char *)); + +#if defined UNDER_CE + +/* Map the Windows error number in ERROR to a locale-dependent error message + string and return a pointer to it. Typically, the values for ERROR come + from GetLastError. + + The string pointed to shall not be modified by the application, but may be + overwritten by a subsequent call to gz_strwinerror + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +char ZLIB_INTERNAL *gz_strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +#endif /* UNDER_CE */ + +/* Reset gzip file state */ +local void gz_reset(state) + gz_statep state; +{ + state->x.have = 0; /* no output data available */ + if (state->mode == GZ_READ) { /* for reading ... */ + state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ + state->how = LOOK; /* look for gzip header */ + } + state->seek = 0; /* no seek request pending */ + gz_error(state, Z_OK, NULL); /* clear error */ + state->x.pos = 0; /* no uncompressed data yet */ + state->strm.avail_in = 0; /* no input data yet */ +} + +/* Open a gzip file either by name or file descriptor. */ +local gzFile gz_open(path, fd, mode) + const void *path; + int fd; + const char *mode; +{ + gz_statep state; + z_size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; + + /* allocate gzFile structure to return */ + state = (gz_statep)malloc(sizeof(gz_state)); + if (state == NULL) + return NULL; + state->size = 0; /* no buffers allocated yet */ + state->want = GZBUFSIZE; /* requested buffer size */ + state->msg = NULL; /* no error message yet */ + + /* interpret mode */ + state->mode = GZ_NONE; + state->level = Z_DEFAULT_COMPRESSION; + state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; + while (*mode) { + if (*mode >= '0' && *mode <= '9') + state->level = *mode - '0'; + else + switch (*mode) { + case 'r': + state->mode = GZ_READ; + break; +#ifndef NO_GZCOMPRESS + case 'w': + state->mode = GZ_WRITE; + break; + case 'a': + state->mode = GZ_APPEND; + break; +#endif + case '+': /* can't read and write at the same time */ + free(state); + return NULL; + case 'b': /* ignore -- will request binary anyway */ + break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif + case 'f': + state->strategy = Z_FILTERED; + break; + case 'h': + state->strategy = Z_HUFFMAN_ONLY; + break; + case 'R': + state->strategy = Z_RLE; + break; + case 'F': + state->strategy = Z_FIXED; + break; + case 'T': + state->direct = 1; + break; + default: /* could consider as an error, but just ignore */ + ; + } + mode++; + } + + /* must provide an "r", "w", or "a" */ + if (state->mode == GZ_NONE) { + free(state); + return NULL; + } + + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + + /* save the path name for error messages */ +#ifdef WIDECHAR + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (z_size_t)-1) + len = 0; + } + else +#endif + len = strlen((const char *)path); + state->path = (char *)malloc(len + 1); + if (state->path == NULL) { + free(state); + return NULL; + } +#ifdef WIDECHAR + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(state->path, len + 1, "%s", (const char *)path); +#else + strcpy(state->path, path); +#endif + + /* compute the flags for open() */ + oflag = +#ifdef O_LARGEFILE + O_LARGEFILE | +#endif +#ifdef O_BINARY + O_BINARY | +#endif +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef WIDECHAR + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open((const char *)path, oflag, 0666)); + if (state->fd == -1) { + free(state->path); + free(state); + return NULL; + } + if (state->mode == GZ_APPEND) { + LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */ + state->mode = GZ_WRITE; /* simplify later checks */ + } + + /* save the current position for rewinding (only if reading) */ + if (state->mode == GZ_READ) { + state->start = LSEEK(state->fd, 0, SEEK_CUR); + if (state->start == -1) state->start = 0; + } + + /* initialize stream */ + gz_reset(state); + + /* return stream */ + return (gzFile)state; +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen64(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzdopen(fd, mode) + int fd; + const char *mode; +{ + char *path; /* identifier for error messages */ + gzFile gz; + + if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) + return NULL; +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(path, 7 + 3 * sizeof(int), "", fd); +#else + sprintf(path, "", fd); /* for debugging */ +#endif + gz = gz_open(path, fd, mode); + free(path); + return gz; +} + +/* -- see zlib.h -- */ +#ifdef WIDECHAR +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzbuffer(file, size) + gzFile file; + unsigned size; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* make sure we haven't already allocated memory */ + if (state->size != 0) + return -1; + + /* check and set requested size */ + if ((size << 1) < size) + return -1; /* need to be able to double it */ + if (size < 2) + size = 2; /* need two bytes to check magic header */ + state->want = size; + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzrewind(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* back up and start over */ + if (LSEEK(state->fd, state->start, SEEK_SET) == -1) + return -1; + gz_reset(state); + return 0; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzseek64(file, offset, whence) + gzFile file; + z_off64_t offset; + int whence; +{ + unsigned n; + z_off64_t ret; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* check that there's no error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* can only seek from start or relative to current position */ + if (whence != SEEK_SET && whence != SEEK_CUR) + return -1; + + /* normalize offset to a SEEK_CUR specification */ + if (whence == SEEK_SET) + offset -= state->x.pos; + else if (state->seek) + offset += state->skip; + state->seek = 0; + + /* if within raw area while reading, just go there */ + if (state->mode == GZ_READ && state->how == COPY && + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); + if (ret == -1) + return -1; + state->x.have = 0; + state->eof = 0; + state->past = 0; + state->seek = 0; + gz_error(state, Z_OK, NULL); + state->strm.avail_in = 0; + state->x.pos += offset; + return state->x.pos; + } + + /* calculate skip amount, rewinding if needed for back seek when reading */ + if (offset < 0) { + if (state->mode != GZ_READ) /* writing -- can't go backwards */ + return -1; + offset += state->x.pos; + if (offset < 0) /* before start of file! */ + return -1; + if (gzrewind(file) == -1) /* rewind, then skip to offset */ + return -1; + } + + /* if reading, skip what's in output buffer (one less gzgetc() check) */ + if (state->mode == GZ_READ) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + offset -= n; + } + + /* request skip (if not zero) */ + if (offset) { + state->seek = 1; + state->skip = offset; + } + return state->x.pos + offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzseek(file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gztell64(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* return position */ + return state->x.pos + (state->seek ? state->skip : 0); +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gztell(file) + gzFile file; +{ + z_off64_t ret; + + ret = gztell64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzoffset64(file) + gzFile file; +{ + z_off64_t offset; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* compute and return effective offset in file */ + offset = LSEEK(state->fd, 0, SEEK_CUR); + if (offset == -1) + return -1; + if (state->mode == GZ_READ) /* reading */ + offset -= state->strm.avail_in; /* don't count buffered input */ + return offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzoffset(file) + gzFile file; +{ + z_off64_t ret; + + ret = gzoffset64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzeof(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return 0; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return 0; + + /* return end-of-file state */ + return state->mode == GZ_READ ? state->past : 0; +} + +/* -- see zlib.h -- */ +const char * ZEXPORT gzerror(file, errnum) + gzFile file; + int *errnum; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return NULL; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return NULL; + + /* return error information */ + if (errnum != NULL) + *errnum = state->err; + return state->err == Z_MEM_ERROR ? "out of memory" : + (state->msg == NULL ? "" : state->msg); +} + +/* -- see zlib.h -- */ +void ZEXPORT gzclearerr(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return; + + /* clear error and end-of-file */ + if (state->mode == GZ_READ) { + state->eof = 0; + state->past = 0; + } + gz_error(state, Z_OK, NULL); +} + +/* Create an error message in allocated memory and set state->err and + state->msg accordingly. Free any previous error message already there. Do + not try to free or allocate space if the error is Z_MEM_ERROR (out of + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +void ZLIB_INTERNAL gz_error(state, err, msg) + gz_statep state; + int err; + const char *msg; +{ + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) + free(state->msg); + state->msg = NULL; + } + + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + + /* set error code, and if no message, then done */ + state->err = err; + if (msg == NULL) + return; + + /* for an out of memory error, return literal string when requested */ + if (err == Z_MEM_ERROR) + return; + + /* construct error message with path */ + if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == + NULL) { + state->err = Z_MEM_ERROR; + return; + } +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, + "%s%s%s", state->path, ": ", msg); +#else + strcpy(state->msg, state->path); + strcat(state->msg, ": "); + strcat(state->msg, msg); +#endif +} + +#ifndef INT_MAX +/* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +unsigned ZLIB_INTERNAL gz_intmax() +{ + unsigned p, q; + + p = 1; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +} +#endif diff --git a/third_party/zlib/v1_2_11/gzread.c b/third_party/zlib/v1_2_11/gzread.c new file mode 100644 index 0000000..956b91e --- /dev/null +++ b/third_party/zlib/v1_2_11/gzread.c @@ -0,0 +1,654 @@ +/* gzread.c -- zlib functions for reading gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +local int gz_avail OF((gz_statep)); +local int gz_look OF((gz_statep)); +local int gz_decomp OF((gz_statep)); +local int gz_fetch OF((gz_statep)); +local int gz_skip OF((gz_statep, z_off64_t)); +local z_size_t gz_read OF((gz_statep, voidp, z_size_t)); + +/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +local int gz_load(state, buf, len, have) + gz_statep state; + unsigned char *buf; + unsigned len; + unsigned *have; +{ + int ret; + unsigned get, max = ((unsigned)-1 >> 2) + 1; + + *have = 0; + do { + get = len - *have; + if (get > max) + get = max; + ret = read(state->fd, buf + *have, get); + if (ret <= 0) + break; + *have += (unsigned)ret; + } while (*have < len); + if (ret < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (ret == 0) + state->eof = 1; + return 0; +} + +/* Load up input buffer and set eof flag if last data loaded -- return -1 on + error, 0 otherwise. Note that the eof flag is set when the end of the input + file is reached, even though there may be unused data in the buffer. Once + that data has been used, no more attempts will be made to read the file. + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ +local int gz_avail(state) + gz_statep state; +{ + unsigned got; + z_streamp strm = &(state->strm); + + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + if (state->eof == 0) { + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in; + unsigned const char *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) + return -1; + strm->avail_in += got; + strm->next_in = state->in; + } + return 0; +} + +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. + If this is the first time in, allocate required memory. state->how will be + left unchanged if there is no more input data available, will be set to COPY + if there is no gzip header and direct copying will be performed, or it will + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + /* allocate read buffers and inflate memory */ + if (state->size == 0) { + /* allocate buffers */ + state->in = (unsigned char *)malloc(state->want); + state->out = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL || state->out == NULL) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + state->size = state->want; + + /* allocate inflate memory */ + state->strm.zalloc = Z_NULL; + state->strm.zfree = Z_NULL; + state->strm.opaque = Z_NULL; + state->strm.avail_in = 0; + state->strm.next_in = Z_NULL; + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ + free(state->out); + free(state->in); + state->size = 0; + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } + + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; + } + + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; + } + + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; + if (strm->avail_in) { + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; + strm->avail_in = 0; + } + state->how = COPY; + state->direct = 1; + return 0; +} + +/* Decompress from input to the provided next_out and avail_out in the state. + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ +local int gz_decomp(state) + gz_statep state; +{ + int ret = Z_OK; + unsigned had; + z_streamp strm = &(state->strm); + + /* fill output buffer up to end of deflate stream */ + had = strm->avail_out; + do { + /* get more input for inflate() */ + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) { + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; + } + + /* decompress and handle errors */ + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { + gz_error(state, Z_STREAM_ERROR, + "internal error: inflate stream corrupt"); + return -1; + } + if (ret == Z_MEM_ERROR) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ + gz_error(state, Z_DATA_ERROR, + strm->msg == NULL ? "compressed data error" : strm->msg); + return -1; + } + } while (strm->avail_out && ret != Z_STREAM_END); + + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; + + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; + + /* good decompression */ + return 0; +} + +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. + Data is either copied from the input file or decompressed from the input + file depending on state->how. If state->how is LOOK, then a gzip header is + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; + return 0; + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); + return 0; +} + +/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +local int gz_skip(state, len) + gz_statep state; + z_off64_t len; +{ + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ + while (len) + /* skip over whatever is in output buffer */ + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + len -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) + break; + + /* need more data to skip -- load up output buffer */ + else { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + } + return 0; +} + +/* Read len bytes into buf from file, or less than len up to the end of the + input. Return the number of bytes read. If zero is returned, either the + end of file was reached, or there was an error. state->err must be + consulted in that case to determine which. */ +local z_size_t gz_read(state, buf, len) + gz_statep state; + voidp buf; + z_size_t len; +{ + z_size_t got; + unsigned n; + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return 0; + } + + /* get len bytes to buf, or less than len if at the end */ + got = 0; + do { + /* set n to the maximum amount of len that fits in an unsigned int */ + n = -1; + if (n > len) + n = len; + + /* first just try copying data from the output buffer */ + if (state->x.have) { + if (state->x.have < n) + n = state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) { + state->past = 1; /* tried to read past end */ + break; + } + + /* need output data -- for small len or new stream load up our output + buffer */ + else if (state->how == LOOK || n < (state->size << 1)) { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return 0; + continue; /* no progress yet -- go back to copy above */ + /* the copy above assures that we will leave with space in the + output buffer, allowing at least one gzungetc() to succeed */ + } + + /* large len -- read directly into user buffer */ + else if (state->how == COPY) { /* read directly */ + if (gz_load(state, (unsigned char *)buf, n, &n) == -1) + return 0; + } + + /* large len -- decompress directly into user buffer */ + else { /* state->how == GZIP */ + state->strm.avail_out = n; + state->strm.next_out = (unsigned char *)buf; + if (gz_decomp(state) == -1) + return 0; + n = state->x.have; + state->x.have = 0; + } + + /* update progress */ + len -= n; + buf = (char *)buf + n; + got += n; + state->x.pos += n; + } while (len); + + /* return number of bytes read into user buffer */ + return got; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzread(file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids a flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in an int"); + return -1; + } + + /* read len or fewer bytes to buf */ + len = gz_read(state, buf, len); + + /* check for an error */ + if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* return the number of bytes read (this is assured to fit in an int) */ + return (int)len; +} + +/* -- see zlib.h -- */ +z_size_t ZEXPORT gzfread(buf, size, nitems, file) + voidp buf; + z_size_t size; + z_size_t nitems; + gzFile file; +{ + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return 0; + + /* compute bytes to read -- error on overflow */ + len = nitems * size; + if (size && len / size != nitems) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); + return 0; + } + + /* read len or fewer bytes to buf, return the number of full items read */ + return len ? gz_read(state, buf, len) / size : 0; +} + +/* -- see zlib.h -- */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +#else +# undef gzgetc +#endif +int ZEXPORT gzgetc(file) + gzFile file; +{ + int ret; + unsigned char buf[1]; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* try output buffer (no need to check for skip request) */ + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; + } + + /* nothing there -- try gz_read() */ + ret = gz_read(state, buf, 1); + return ret < 1 ? -1 : buf[0]; +} + +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + +/* -- see zlib.h -- */ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* can't push EOF */ + if (c < 0) + return -1; + + /* if output buffer empty, put byte at end (allows more pushing) */ + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = (unsigned char)c; + state->x.pos--; + state->past = 0; + return c; + } + + /* if no room, give up (must have already done a gzungetc()) */ + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); + return -1; + } + + /* slide output data if needed and insert byte before existing data */ + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; + unsigned char *dest = state->out + (state->size << 1); + while (src > state->out) + *--dest = *--src; + state->x.next = dest; + } + state->x.have++; + state->x.next--; + state->x.next[0] = (unsigned char)c; + state->x.pos--; + state->past = 0; + return c; +} + +/* -- see zlib.h -- */ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + unsigned left, n; + char *str; + unsigned char *eol; + gz_statep state; + + /* check parameters and get internal structure */ + if (file == NULL || buf == NULL || len < 1) + return NULL; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return NULL; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return NULL; + } + + /* copy output bytes up to new line or len - 1, whichever comes first -- + append a terminating zero to the string (we don't check for a zero in + the contents, let the user worry about that) */ + str = buf; + left = (unsigned)len - 1; + if (left) do { + /* assure that something is in the output buffer */ + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ + } + + /* look for end-of-line in current output buffer */ + n = state->x.have > left ? left : state->x.have; + eol = (unsigned char *)memchr(state->x.next, '\n', n); + if (eol != NULL) + n = (unsigned)(eol - state->x.next) + 1; + + /* copy through end-of-line, or remainder if not found */ + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + left -= n; + buf += n; + } while (left && eol == NULL); + + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; + buf[0] = 0; + return str; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzdirect(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* if the state is not known, but we can find out, then do so (this is + mainly for right after a gzopen() or gzdopen()) */ + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); + + /* return 1 if transparent, 0 if processing a gzip stream */ + return state->direct; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_r(file) + gzFile file; +{ + int ret, err; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return Z_STREAM_ERROR; + + /* free memory and close file */ + if (state->size) { + inflateEnd(&(state->strm)); + free(state->out); + free(state->in); + } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; + gz_error(state, Z_OK, NULL); + free(state->path); + ret = close(state->fd); + free(state); + return ret ? Z_ERRNO : err; +} diff --git a/third_party/zlib/v1_2_11/gzwrite.c b/third_party/zlib/v1_2_11/gzwrite.c new file mode 100644 index 0000000..c7b5651 --- /dev/null +++ b/third_party/zlib/v1_2_11/gzwrite.c @@ -0,0 +1,665 @@ +/* gzwrite.c -- zlib functions for writing gzip files + * Copyright (C) 2004-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_init OF((gz_statep)); +local int gz_comp OF((gz_statep, int)); +local int gz_zero OF((gz_statep, z_off64_t)); +local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); + +/* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on a memory allocation failure, or 0 on + success. */ +local int gz_init(state) + gz_statep state; +{ + int ret; + z_streamp strm = &(state->strm); + + /* allocate input buffer (double size for gzprintf) */ + state->in = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = (unsigned char *)malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + strm->next_in = NULL; + } + + /* mark state as initialized */ + state->size = state->want; + + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } + return 0; +} + +/* Compress whatever is at avail_in and next_in and write to the output file. + Return -1 if there is an error writing to the output file or if gz_init() + fails to allocate memory, otherwise 0. flush is assumed to be a valid + deflate() flush value. If flush is Z_FINISH, then the deflate() state is + reset to start a new gzip stream. If gz->direct is true, then simply write + to the output file without compressing, and ignore flush. */ +local int gz_comp(state, flush) + gz_statep state; + int flush; +{ + int ret, writ; + unsigned have, put, max = ((unsigned)-1 >> 2) + 1; + z_streamp strm = &(state->strm); + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + + /* write directly if requested */ + if (state->direct) { + while (strm->avail_in) { + put = strm->avail_in > max ? max : strm->avail_in; + writ = write(state->fd, strm->next_in, put); + if (writ < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in -= (unsigned)writ; + strm->next_in += writ; + } + return 0; + } + + /* run deflate() on provided input until it produces no more output */ + ret = Z_OK; + do { + /* write out current buffer contents if full, or if flushing, but if + doing Z_FINISH then don't write until we get to Z_STREAM_END */ + if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && + (flush != Z_FINISH || ret == Z_STREAM_END))) { + while (strm->next_out > state->x.next) { + put = strm->next_out - state->x.next > (int)max ? max : + (unsigned)(strm->next_out - state->x.next); + writ = write(state->fd, state->x.next, put); + if (writ < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + state->x.next += writ; + } + if (strm->avail_out == 0) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = state->out; + } + } + + /* compress */ + have = strm->avail_out; + ret = deflate(strm, flush); + if (ret == Z_STREAM_ERROR) { + gz_error(state, Z_STREAM_ERROR, + "internal error: deflate stream corrupt"); + return -1; + } + have -= strm->avail_out; + } while (have); + + /* if that completed a deflate stream, allow another to start */ + if (flush == Z_FINISH) + deflateReset(strm); + + /* all done, no errors */ + return 0; +} + +/* Compress len zeros to output. Return -1 on a write error or memory + allocation failure by gz_comp(), or 0 on success. */ +local int gz_zero(state, len) + gz_statep state; + z_off64_t len; +{ + int first; + unsigned n; + z_streamp strm = &(state->strm); + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + + /* compress len zeros (len guaranteed > 0) */ + first = 1; + while (len) { + n = GT_OFF(state->size) || (z_off64_t)state->size > len ? + (unsigned)len : state->size; + if (first) { + memset(state->in, 0, n); + first = 0; + } + strm->avail_in = n; + strm->next_in = state->in; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + len -= n; + } + return 0; +} + +/* Write len bytes from buf to file. Return the number of bytes written. If + the returned value is less than len, then there was an error. */ +local z_size_t gz_write(state, buf, len) + gz_statep state; + voidpc buf; + z_size_t len; +{ + z_size_t put = len; + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* for small len, copy to input buffer, otherwise compress directly */ + if (len < state->size) { + /* copy to input buffer, compress when full */ + do { + unsigned have, copy; + + if (state->strm.avail_in == 0) + state->strm.next_in = state->in; + have = (unsigned)((state->strm.next_in + state->strm.avail_in) - + state->in); + copy = state->size - have; + if (copy > len) + copy = len; + memcpy(state->in + have, buf, copy); + state->strm.avail_in += copy; + state->x.pos += copy; + buf = (const char *)buf + copy; + len -= copy; + if (len && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } while (len); + } + else { + /* consume whatever's left in the input buffer */ + if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* directly compress user buffer to file */ + state->strm.next_in = (z_const Bytef *)buf; + do { + unsigned n = (unsigned)-1; + if (n > len) + n = len; + state->strm.avail_in = n; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + len -= n; + } while (len); + } + + /* input was all buffered or compressed */ + return put; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzwrite(file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids a flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return 0; + } + + /* write len bytes from buf (the return value will fit in an int) */ + return (int)gz_write(state, buf, len); +} + +/* -- see zlib.h -- */ +z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) + voidpc buf; + z_size_t size; + z_size_t nitems; + gzFile file; +{ + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* compute bytes to read -- error on overflow */ + len = nitems * size; + if (size && len / size != nitems) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); + return 0; + } + + /* write len bytes to buf, return the number of full items written */ + return len ? gz_write(state, buf, len) / size : 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned have; + unsigned char buf[1]; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* try writing to input buffer for speed (state->size == 0 if buffer not + initialized) */ + if (state->size) { + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + if (have < state->size) { + state->in[have] = (unsigned char)c; + strm->avail_in++; + state->x.pos++; + return c & 0xff; + } + } + + /* no room in buffer or not initialized, use gz_write() */ + buf[0] = (unsigned char)c; + if (gz_write(state, buf, 1) != 1) + return -1; + return c & 0xff; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputs(file, str) + gzFile file; + const char *str; +{ + int ret; + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* write string */ + len = strlen(str); + ret = gz_write(state, str, len); + return ret == 0 && len != 0 ? -1 : ret; +} + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +#include + +/* -- see zlib.h -- */ +int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) +{ + int len; + unsigned left; + char *next; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return state->err; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* do the printf() into the input buffer, put length in len -- the input + buffer is double-sized just for this function, so there is guaranteed to + be state->size bytes available after the current contents */ + if (strm->avail_in == 0) + strm->next_in = state->in; + next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in); + next[state->size - 1] = 0; +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(next, format, va); + for (len = 0; len < state->size; len++) + if (next[len] == 0) break; +# else + len = vsprintf(next, format, va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(next, state->size, format, va); + len = strlen(next); +# else + len = vsnprintf(next, state->size, format, va); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0) + return 0; + + /* update buffer and position, compress first half if past that */ + strm->avail_in += (unsigned)len; + state->x.pos += len; + if (strm->avail_in >= state->size) { + left = strm->avail_in - state->size; + strm->avail_in = state->size; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return state->err; + memcpy(state->in, state->in + state->size, left); + strm->next_in = state->in; + strm->avail_in = left; + } + return len; +} + +int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) +{ + va_list va; + int ret; + + va_start(va, format); + ret = gzvprintf(file, format, va); + va_end(va); + return ret; +} + +#else /* !STDC && !Z_HAVE_STDARG_H */ + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + unsigned len, left; + char *next; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return Z_STREAM_ERROR; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return state->error; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->error; + } + + /* do the printf() into the input buffer, put length in len -- the input + buffer is double-sized just for this function, so there is guaranteed to + be state->size bytes available after the current contents */ + if (strm->avail_in == 0) + strm->next_in = state->in; + next = (char *)(strm->next_in + strm->avail_in); + next[state->size - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, + a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < size; len++) + if (next[len] == 0) + break; +# else + len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, + a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(next); +# else + len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len == 0 || len >= state->size || next[state->size - 1] != 0) + return 0; + + /* update buffer and position, compress first half if past that */ + strm->avail_in += len; + state->x.pos += len; + if (strm->avail_in >= state->size) { + left = strm->avail_in - state->size; + strm->avail_in = state->size; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return state->err; + memcpy(state->in, state->in + state->size, left); + strm->next_in = state->in; + strm->avail_in = left; + } + return (int)len; +} + +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzflush(file, flush) + gzFile file; + int flush; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* check flush parameter */ + if (flush < 0 || flush > Z_FINISH) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* compress remaining data with requested flush */ + (void)gz_comp(state, flush); + return state->err; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzsetparams(file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ + if (level == state->level && strategy == state->strategy) + return Z_OK; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* change compression parameters for subsequent input */ + if (state->size) { + /* flush previous input with previous parameters before changing */ + if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1) + return state->err; + deflateParams(strm, level, strategy); + } + state->level = level; + state->strategy = strategy; + return Z_OK; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_w(file) + gzFile file; +{ + int ret = Z_OK; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing */ + if (state->mode != GZ_WRITE) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + ret = state->err; + } + + /* flush, free memory, and close file */ + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (state->size) { + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } + gz_error(state, Z_OK, NULL); + free(state->path); + if (close(state->fd) == -1) + ret = Z_ERRNO; + free(state); + return ret; +} diff --git a/third_party/zlib/v1_2_11/infback.c b/third_party/zlib/v1_2_11/infback.c new file mode 100644 index 0000000..59679ec --- /dev/null +++ b/third_party/zlib/v1_2_11/infback.c @@ -0,0 +1,640 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = (uInt)windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/third_party/zlib/v1_2_11/inffast.c b/third_party/zlib/v1_2_11/inffast.c new file mode 100644 index 0000000..0dbd1db --- /dev/null +++ b/third_party/zlib/v1_2_11/inffast.c @@ -0,0 +1,323 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - 5); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/third_party/zlib/v1_2_11/inffast.h b/third_party/zlib/v1_2_11/inffast.h new file mode 100644 index 0000000..e5c1aa4 --- /dev/null +++ b/third_party/zlib/v1_2_11/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/third_party/zlib/v1_2_11/inffixed.h b/third_party/zlib/v1_2_11/inffixed.h new file mode 100644 index 0000000..d628327 --- /dev/null +++ b/third_party/zlib/v1_2_11/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/third_party/zlib/v1_2_11/inflate.c b/third_party/zlib/v1_2_11/inflate.c new file mode 100644 index 0000000..ac333e8 --- /dev/null +++ b/third_party/zlib/v1_2_11/inflate.c @@ -0,0 +1,1561 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/third_party/zlib/v1_2_11/inflate.h b/third_party/zlib/v1_2_11/inflate.h new file mode 100644 index 0000000..a46cce6 --- /dev/null +++ b/third_party/zlib/v1_2_11/inflate.h @@ -0,0 +1,125 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD = 16180, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* State maintained between inflate() calls -- approximately 7K bytes, not + including the allocated sliding window, which is up to 32K bytes. */ +struct inflate_state { + z_streamp strm; /* pointer back to this zlib stream */ + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip, + bit 2 true to validate check value */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/third_party/zlib/v1_2_11/inftrees.c b/third_party/zlib/v1_2_11/inftrees.c new file mode 100644 index 0000000..2ea08fc --- /dev/null +++ b/third_party/zlib/v1_2_11/inftrees.c @@ -0,0 +1,304 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.11 Copyright 1995-2017 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + unsigned match; /* use base and extra for symbol >= match */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + match = 20; + break; + case LENS: + base = lbase; + extra = lext; + match = 257; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + match = 0; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if (work[sym] + 1U < match) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if (work[sym] >= match) { + here.op = (unsigned char)(extra[work[sym] - match]); + here.val = base[work[sym] - match]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/third_party/zlib/v1_2_11/inftrees.h b/third_party/zlib/v1_2_11/inftrees.h new file mode 100644 index 0000000..baa53a0 --- /dev/null +++ b/third_party/zlib/v1_2_11/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/third_party/zlib/v1_2_11/make_vms.com b/third_party/zlib/v1_2_11/make_vms.com new file mode 100644 index 0000000..65e9d0c --- /dev/null +++ b/third_party/zlib/v1_2_11/make_vms.com @@ -0,0 +1,867 @@ +$! make libz under VMS written by +$! Martin P.J. Zinser +$! +$! In case of problems with the install you might contact me at +$! zinser@zinser.no-ip.info(preferred) or +$! martin.zinser@eurexchange.com (work) +$! +$! Make procedure history for Zlib +$! +$!------------------------------------------------------------------------------ +$! Version history +$! 0.01 20060120 First version to receive a number +$! 0.02 20061008 Adapt to new Makefile.in +$! 0.03 20091224 Add support for large file check +$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite +$! 0.05 20100221 Exchange zlibdefs.h by zconf.h.in +$! 0.06 20120111 Fix missing amiss_err, update zconf_h.in, fix new exmples +$! subdir path, update module search in makefile.in +$! 0.07 20120115 Triggered by work done by Alexey Chupahin completly redesigned +$! shared image creation +$! 0.08 20120219 Make it work on VAX again, pre-load missing symbols to shared +$! image +$! 0.09 20120305 SMS. P1 sets builder ("MMK", "MMS", " " (built-in)). +$! "" -> automatic, preference: MMK, MMS, built-in. +$! +$ on error then goto err_exit +$! +$ true = 1 +$ false = 0 +$ tmpnam = "temp_" + f$getjpi("","pid") +$ tt = tmpnam + ".txt" +$ tc = tmpnam + ".c" +$ th = tmpnam + ".h" +$ define/nolog tconfig 'th' +$ its_decc = false +$ its_vaxc = false +$ its_gnuc = false +$ s_case = False +$! +$! Setup variables holding "config" information +$! +$ Make = "''p1'" +$ name = "Zlib" +$ version = "?.?.?" +$ v_string = "ZLIB_VERSION" +$ v_file = "zlib.h" +$ ccopt = "/include = []" +$ lopts = "" +$ dnsrl = "" +$ aconf_in_file = "zconf.h.in#zconf.h_in#zconf_h.in" +$ conf_check_string = "" +$ linkonly = false +$ optfile = name + ".opt" +$ mapfile = name + ".map" +$ libdefs = "" +$ vax = f$getsyi("HW_MODEL").lt.1024 +$ axp = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096 +$ ia64 = f$getsyi("HW_MODEL").ge.4096 +$! +$! 2012-03-05 SMS. +$! Why is this needed? And if it is needed, why not simply ".not. vax"? +$! +$!!! if axp .or. ia64 then set proc/parse=extended +$! +$ whoami = f$parse(f$environment("Procedure"),,,,"NO_CONCEAL") +$ mydef = F$parse(whoami,,,"DEVICE") +$ mydir = f$parse(whoami,,,"DIRECTORY") - "][" +$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type") +$! +$! Check for MMK/MMS +$! +$ if (Make .eqs. "") +$ then +$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS" +$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK" +$ else +$ Make = f$edit( Make, "trim") +$ endif +$! +$ gosub find_version +$! +$ open/write topt tmp.opt +$ open/write optf 'optfile' +$! +$ gosub check_opts +$! +$! Look for the compiler used +$! +$ gosub check_compiler +$ close topt +$ close optf +$! +$ if its_decc +$ then +$ ccopt = "/prefix=all" + ccopt +$ if f$trnlnm("SYS") .eqs. "" +$ then +$ if axp +$ then +$ define sys sys$library: +$ else +$ ccopt = "/decc" + ccopt +$ define sys decc$library_include: +$ endif +$ endif +$! +$! 2012-03-05 SMS. +$! Why /NAMES = AS_IS? Why not simply ".not. vax"? And why not on VAX? +$! +$ if axp .or. ia64 +$ then +$ ccopt = ccopt + "/name=as_is/opt=(inline=speed)" +$ s_case = true +$ endif +$ endif +$ if its_vaxc .or. its_gnuc +$ then +$ if f$trnlnm("SYS").eqs."" then define sys sys$library: +$ endif +$! +$! Build a fake configure input header +$! +$ open/write conf_hin config.hin +$ write conf_hin "#undef _LARGEFILE64_SOURCE" +$ close conf_hin +$! +$! +$ i = 0 +$FIND_ACONF: +$ fname = f$element(i,"#",aconf_in_file) +$ if fname .eqs. "#" then goto AMISS_ERR +$ if f$search(fname) .eqs. "" +$ then +$ i = i + 1 +$ goto find_aconf +$ endif +$ open/read/err=aconf_err aconf_in 'fname' +$ open/write aconf zconf.h +$ACONF_LOOP: +$ read/end_of_file=aconf_exit aconf_in line +$ work = f$edit(line, "compress,trim") +$ if f$extract(0,6,work) .nes. "#undef" +$ then +$ if f$extract(0,12,work) .nes. "#cmakedefine" +$ then +$ write aconf line +$ endif +$ else +$ cdef = f$element(1," ",work) +$ gosub check_config +$ endif +$ goto aconf_loop +$ACONF_EXIT: +$ write aconf "" +$ write aconf "/* VMS specifics added by make_vms.com: */" +$ write aconf "#define VMS 1" +$ write aconf "#include " +$ write aconf "#include " +$ write aconf "#ifdef _LARGEFILE" +$ write aconf "# define off64_t __off64_t" +$ write aconf "# define fopen64 fopen" +$ write aconf "# define fseeko64 fseeko" +$ write aconf "# define lseek64 lseek" +$ write aconf "# define ftello64 ftell" +$ write aconf "#endif" +$ write aconf "#if !defined( __VAX) && (__CRTL_VER >= 70312000)" +$ write aconf "# define HAVE_VSNPRINTF" +$ write aconf "#endif" +$ close aconf_in +$ close aconf +$ if f$search("''th'") .nes. "" then delete 'th';* +$! Build the thing plain or with mms +$! +$ write sys$output "Compiling Zlib sources ..." +$ if make.eqs."" +$ then +$ if (f$search( "example.obj;*") .nes. "") then delete example.obj;* +$ if (f$search( "minigzip.obj;*") .nes. "") then delete minigzip.obj;* +$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" - + adler32.c zlib.h zconf.h +$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" - + compress.c zlib.h zconf.h +$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" - + crc32.c zlib.h zconf.h +$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" - + deflate.c deflate.h zutil.h zlib.h zconf.h +$ CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" - + gzclose.c zutil.h zlib.h zconf.h +$ CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" - + gzlib.c zutil.h zlib.h zconf.h +$ CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" - + gzread.c zutil.h zlib.h zconf.h +$ CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" - + gzwrite.c zutil.h zlib.h zconf.h +$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" - + infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h +$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" - + inffast.c zutil.h zlib.h zconf.h inffast.h +$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" - + inflate.c zutil.h zlib.h zconf.h infblock.h +$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" - + inftrees.c zutil.h zlib.h zconf.h inftrees.h +$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" - + trees.c deflate.h zutil.h zlib.h zconf.h +$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" - + uncompr.c zlib.h zconf.h +$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" - + zutil.c zutil.h zlib.h zconf.h +$ write sys$output "Building Zlib ..." +$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ +$ write sys$output "Building example..." +$ CALL MAKE example.OBJ "CC ''CCOPT' [.test]example" - + [.test]example.c zlib.h zconf.h +$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb +$ write sys$output "Building minigzip..." +$ CALL MAKE minigzip.OBJ "CC ''CCOPT' [.test]minigzip" - + [.test]minigzip.c zlib.h zconf.h +$ call make minigzip.exe - + "LINK minigzip,libz.olb/lib" - + minigzip.obj libz.olb +$ else +$ gosub crea_mms +$ write sys$output "Make ''name' ''version' with ''Make' " +$ 'make' +$ endif +$! +$! Create shareable image +$! +$ gosub crea_olist +$ write sys$output "Creating libzshr.exe" +$ call map_2_shopt 'mapfile' 'optfile' +$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,'optfile'/opt +$ write sys$output "Zlib build completed" +$ delete/nolog tmp.opt;* +$ exit +$AMISS_ERR: +$ write sys$output "No source for config.hin found." +$ write sys$output "Tried any of ''aconf_in_file'" +$ goto err_exit +$CC_ERR: +$ write sys$output "C compiler required to build ''name'" +$ goto err_exit +$ERR_EXIT: +$ set message/facil/ident/sever/text +$ close/nolog optf +$ close/nolog topt +$ close/nolog aconf_in +$ close/nolog aconf +$ close/nolog out +$ close/nolog min +$ close/nolog mod +$ close/nolog h_in +$ write sys$output "Exiting..." +$ exit 2 +$! +$! +$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES +$ V = 'F$Verify(0) +$! P1 = What we are trying to make +$! P2 = Command to make it +$! P3 - P8 What it depends on +$ +$ If F$Search(P1) .Eqs. "" Then Goto Makeit +$ Time = F$CvTime(F$File(P1,"RDT")) +$arg=3 +$Loop: +$ Argument = P'arg +$ If Argument .Eqs. "" Then Goto Exit +$ El=0 +$Loop2: +$ File = F$Element(El," ",Argument) +$ If File .Eqs. " " Then Goto Endl +$ AFile = "" +$Loop3: +$ OFile = AFile +$ AFile = F$Search(File) +$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl +$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit +$ Goto Loop3 +$NextEL: +$ El = El + 1 +$ Goto Loop2 +$EndL: +$ arg=arg+1 +$ If arg .Le. 8 Then Goto Loop +$ Goto Exit +$ +$Makeit: +$ VV=F$VERIFY(0) +$ write sys$output P2 +$ 'P2 +$ VV='F$Verify(VV) +$Exit: +$ If V Then Set Verify +$ENDSUBROUTINE +$!------------------------------------------------------------------------------ +$! +$! Check command line options and set symbols accordingly +$! +$!------------------------------------------------------------------------------ +$! Version history +$! 0.01 20041206 First version to receive a number +$! 0.02 20060126 Add new "HELP" target +$ CHECK_OPTS: +$ i = 1 +$ OPT_LOOP: +$ if i .lt. 9 +$ then +$ cparm = f$edit(p'i',"upcase") +$! +$! Check if parameter actually contains something +$! +$ if f$edit(cparm,"trim") .nes. "" +$ then +$ if cparm .eqs. "DEBUG" +$ then +$ ccopt = ccopt + "/noopt/deb" +$ lopts = lopts + "/deb" +$ endif +$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm) +$ then +$ start = f$locate("=",cparm) + 1 +$ len = f$length(cparm) - start +$ ccopt = ccopt + f$extract(start,len,cparm) +$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) - + then s_case = true +$ endif +$ if cparm .eqs. "LINK" then linkonly = true +$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm) +$ then +$ start = f$locate("=",cparm) + 1 +$ len = f$length(cparm) - start +$ lopts = lopts + f$extract(start,len,cparm) +$ endif +$ if f$locate("CC=",cparm) .lt. f$length(cparm) +$ then +$ start = f$locate("=",cparm) + 1 +$ len = f$length(cparm) - start +$ cc_com = f$extract(start,len,cparm) + if (cc_com .nes. "DECC") .and. - + (cc_com .nes. "VAXC") .and. - + (cc_com .nes. "GNUC") +$ then +$ write sys$output "Unsupported compiler choice ''cc_com' ignored" +$ write sys$output "Use DECC, VAXC, or GNUC instead" +$ else +$ if cc_com .eqs. "DECC" then its_decc = true +$ if cc_com .eqs. "VAXC" then its_vaxc = true +$ if cc_com .eqs. "GNUC" then its_gnuc = true +$ endif +$ endif +$ if f$locate("MAKE=",cparm) .lt. f$length(cparm) +$ then +$ start = f$locate("=",cparm) + 1 +$ len = f$length(cparm) - start +$ mmks = f$extract(start,len,cparm) +$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS") +$ then +$ make = mmks +$ else +$ write sys$output "Unsupported make choice ''mmks' ignored" +$ write sys$output "Use MMK or MMS instead" +$ endif +$ endif +$ if cparm .eqs. "HELP" then gosub bhelp +$ endif +$ i = i + 1 +$ goto opt_loop +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! Look for the compiler used +$! +$! Version history +$! 0.01 20040223 First version to receive a number +$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists +$! 0.03 20060202 Extend handling of GNU C +$! 0.04 20090402 Compaq -> hp +$CHECK_COMPILER: +$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) +$ then +$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "") +$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "") +$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "") +$ endif +$! +$! Exit if no compiler available +$! +$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) +$ then goto CC_ERR +$ else +$ if its_decc +$ then +$ write sys$output "CC compiler check ... hp C" +$ if f$trnlnm("decc$no_rooted_search_lists") .nes. "" +$ then +$ dnrsl = f$trnlnm("decc$no_rooted_search_lists") +$ endif +$ define/nolog decc$no_rooted_search_lists 1 +$ else +$ if its_vaxc then write sys$output "CC compiler check ... VAX C" +$ if its_gnuc +$ then +$ write sys$output "CC compiler check ... GNU C" +$ if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib" +$ if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib" +$ cc = "gcc" +$ endif +$ if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share" +$ if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share" +$ endif +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! If MMS/MMK are available dump out the descrip.mms if required +$! +$CREA_MMS: +$ write sys$output "Creating descrip.mms..." +$ create descrip.mms +$ open/append out descrip.mms +$ copy sys$input: out +$ deck +# descrip.mms: MMS description file for building zlib on VMS +# written by Martin P.J. Zinser +# + +OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzlib.obj\ + gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\ + deflate.obj, trees.obj, zutil.obj, inflate.obj, \ + inftrees.obj, inffast.obj + +$ eod +$ write out "CFLAGS=", ccopt +$ write out "LOPTS=", lopts +$ write out "all : example.exe minigzip.exe libz.olb" +$ copy sys$input: out +$ deck + @ write sys$output " Example applications available" + +libz.olb : libz.olb($(OBJS)) + @ write sys$output " libz available" + +example.exe : example.obj libz.olb + link $(LOPTS) example,libz.olb/lib + +minigzip.exe : minigzip.obj libz.olb + link $(LOPTS) minigzip,libz.olb/lib + +clean : + delete *.obj;*,libz.olb;*,*.opt;*,*.exe;* + + +# Other dependencies. +adler32.obj : adler32.c zutil.h zlib.h zconf.h +compress.obj : compress.c zlib.h zconf.h +crc32.obj : crc32.c zutil.h zlib.h zconf.h +deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h +example.obj : [.test]example.c zlib.h zconf.h +gzclose.obj : gzclose.c zutil.h zlib.h zconf.h +gzlib.obj : gzlib.c zutil.h zlib.h zconf.h +gzread.obj : gzread.c zutil.h zlib.h zconf.h +gzwrite.obj : gzwrite.c zutil.h zlib.h zconf.h +inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h +inflate.obj : inflate.c zutil.h zlib.h zconf.h +inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h +minigzip.obj : [.test]minigzip.c zlib.h zconf.h +trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h +uncompr.obj : uncompr.c zlib.h zconf.h +zutil.obj : zutil.c zutil.h zlib.h zconf.h +infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h +$ eod +$ close out +$ return +$!------------------------------------------------------------------------------ +$! +$! Read list of core library sources from makefile.in and create options +$! needed to build shareable image +$! +$CREA_OLIST: +$ open/read min makefile.in +$ open/write mod modules.opt +$ src_check_list = "OBJZ =#OBJG =" +$MRLOOP: +$ read/end=mrdone min rec +$ i = 0 +$SRC_CHECK_LOOP: +$ src_check = f$element(i, "#", src_check_list) +$ i = i+1 +$ if src_check .eqs. "#" then goto mrloop +$ if (f$extract(0,6,rec) .nes. src_check) then goto src_check_loop +$ rec = rec - src_check +$ gosub extra_filnam +$ if (f$element(1,"\",rec) .eqs. "\") then goto mrloop +$MRSLOOP: +$ read/end=mrdone min rec +$ gosub extra_filnam +$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop +$MRDONE: +$ close min +$ close mod +$ return +$!------------------------------------------------------------------------------ +$! +$! Take record extracted in crea_olist and split it into single filenames +$! +$EXTRA_FILNAM: +$ myrec = f$edit(rec - "\", "trim,compress") +$ i = 0 +$FELOOP: +$ srcfil = f$element(i," ", myrec) +$ if (srcfil .nes. " ") +$ then +$ write mod f$parse(srcfil,,,"NAME"), ".obj" +$ i = i + 1 +$ goto feloop +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! Find current Zlib version number +$! +$FIND_VERSION: +$ open/read h_in 'v_file' +$hloop: +$ read/end=hdone h_in rec +$ rec = f$edit(rec,"TRIM") +$ if (f$extract(0,1,rec) .nes. "#") then goto hloop +$ rec = f$edit(rec - "#", "TRIM") +$ if f$element(0," ",rec) .nes. "define" then goto hloop +$ if f$element(1," ",rec) .eqs. v_string +$ then +$ version = 'f$element(2," ",rec)' +$ goto hdone +$ endif +$ goto hloop +$hdone: +$ close h_in +$ return +$!------------------------------------------------------------------------------ +$! +$CHECK_CONFIG: +$! +$ in_ldef = f$locate(cdef,libdefs) +$ if (in_ldef .lt. f$length(libdefs)) +$ then +$ write aconf "#define ''cdef' 1" +$ libdefs = f$extract(0,in_ldef,libdefs) + - + f$extract(in_ldef + f$length(cdef) + 1, - + f$length(libdefs) - in_ldef - f$length(cdef) - 1, - + libdefs) +$ else +$ if (f$type('cdef') .eqs. "INTEGER") +$ then +$ write aconf "#define ''cdef' ", 'cdef' +$ else +$ if (f$type('cdef') .eqs. "STRING") +$ then +$ write aconf "#define ''cdef' ", """", '''cdef'', """" +$ else +$ gosub check_cc_def +$ endif +$ endif +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! Check if this is a define relating to the properties of the C/C++ +$! compiler +$! +$ CHECK_CC_DEF: +$ if (cdef .eqs. "_LARGEFILE64_SOURCE") +$ then +$ copy sys$input: 'tc' +$ deck +#include "tconfig" +#define _LARGEFILE +#include + +int main(){ +FILE *fp; + fp = fopen("temp.txt","r"); + fseeko(fp,1,SEEK_SET); + fclose(fp); +} + +$ eod +$ test_inv = false +$ comm_h = false +$ gosub cc_prop_check +$ return +$ endif +$ write aconf "/* ", line, " */" +$ return +$!------------------------------------------------------------------------------ +$! +$! Check for properties of C/C++ compiler +$! +$! Version history +$! 0.01 20031020 First version to receive a number +$! 0.02 20031022 Added logic for defines with value +$! 0.03 20040309 Make sure local config file gets not deleted +$! 0.04 20041230 Also write include for configure run +$! 0.05 20050103 Add processing of "comment defines" +$CC_PROP_CHECK: +$ cc_prop = true +$ is_need = false +$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true) +$ if f$search(th) .eqs. "" then create 'th' +$ set message/nofac/noident/nosever/notext +$ on error then continue +$ cc 'tmpnam' +$ if .not. ($status) then cc_prop = false +$ on error then continue +$! The headers might lie about the capabilities of the RTL +$ link 'tmpnam',tmp.opt/opt +$ if .not. ($status) then cc_prop = false +$ set message/fac/ident/sever/text +$ on error then goto err_exit +$ delete/nolog 'tmpnam'.*;*/exclude='th' +$ if (cc_prop .and. .not. is_need) .or. - + (.not. cc_prop .and. is_need) +$ then +$ write sys$output "Checking for ''cdef'... yes" +$ if f$type('cdef_val'_yes) .nes. "" +$ then +$ if f$type('cdef_val'_yes) .eqs. "INTEGER" - + then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes) +$ if f$type('cdef_val'_yes) .eqs. "STRING" - + then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes) +$ else +$ call write_config f$fao("#define !AS 1",cdef) +$ endif +$ if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. - + (cdef .eqs. "_LARGEFILE64_SOURCE") then - + call write_config f$string("#define _LARGEFILE 1") +$ else +$ write sys$output "Checking for ''cdef'... no" +$ if (comm_h) +$ then + call write_config f$fao("/* !AS */",line) +$ else +$ if f$type('cdef_val'_no) .nes. "" +$ then +$ if f$type('cdef_val'_no) .eqs. "INTEGER" - + then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no) +$ if f$type('cdef_val'_no) .eqs. "STRING" - + then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no) +$ else +$ call write_config f$fao("#undef !AS",cdef) +$ endif +$ endif +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! Check for properties of C/C++ compiler with multiple result values +$! +$! Version history +$! 0.01 20040127 First version +$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05 +$CC_MPROP_CHECK: +$ cc_prop = true +$ i = 1 +$ idel = 1 +$ MT_LOOP: +$ if f$type(result_'i') .eqs. "STRING" +$ then +$ set message/nofac/noident/nosever/notext +$ on error then continue +$ cc 'tmpnam'_'i' +$ if .not. ($status) then cc_prop = false +$ on error then continue +$! The headers might lie about the capabilities of the RTL +$ link 'tmpnam'_'i',tmp.opt/opt +$ if .not. ($status) then cc_prop = false +$ set message/fac/ident/sever/text +$ on error then goto err_exit +$ delete/nolog 'tmpnam'_'i'.*;* +$ if (cc_prop) +$ then +$ write sys$output "Checking for ''cdef'... ", mdef_'i' +$ if f$type(mdef_'i') .eqs. "INTEGER" - + then call write_config f$fao("#define !AS !UL",cdef,mdef_'i') +$ if f$type('cdef_val'_yes) .eqs. "STRING" - + then call write_config f$fao("#define !AS !AS",cdef,mdef_'i') +$ goto msym_clean +$ else +$ i = i + 1 +$ goto mt_loop +$ endif +$ endif +$ write sys$output "Checking for ''cdef'... no" +$ call write_config f$fao("#undef !AS",cdef) +$ MSYM_CLEAN: +$ if (idel .le. msym_max) +$ then +$ delete/sym mdef_'idel' +$ idel = idel + 1 +$ goto msym_clean +$ endif +$ return +$!------------------------------------------------------------------------------ +$! +$! Write configuration to both permanent and temporary config file +$! +$! Version history +$! 0.01 20031029 First version to receive a number +$! +$WRITE_CONFIG: SUBROUTINE +$ write aconf 'p1' +$ open/append confh 'th' +$ write confh 'p1' +$ close confh +$ENDSUBROUTINE +$!------------------------------------------------------------------------------ +$! +$! Analyze the project map file and create the symbol vector for a shareable +$! image from it +$! +$! Version history +$! 0.01 20120128 First version +$! 0.02 20120226 Add pre-load logic +$! +$ MAP_2_SHOPT: Subroutine +$! +$ SAY := "WRITE_ SYS$OUTPUT" +$! +$ IF F$SEARCH("''P1'") .EQS. "" +$ THEN +$ SAY "MAP_2_SHOPT-E-NOSUCHFILE: Error, inputfile ''p1' not available" +$ goto exit_m2s +$ ENDIF +$ IF "''P2'" .EQS. "" +$ THEN +$ SAY "MAP_2_SHOPT: Error, no output file provided" +$ goto exit_m2s +$ ENDIF +$! +$ module1 = "deflate#deflateEnd#deflateInit_#deflateParams#deflateSetDictionary" +$ module2 = "gzclose#gzerror#gzgetc#gzgets#gzopen#gzprintf#gzputc#gzputs#gzread" +$ module3 = "gzseek#gztell#inflate#inflateEnd#inflateInit_#inflateSetDictionary" +$ module4 = "inflateSync#uncompress#zlibVersion#compress" +$ open/read map 'p1 +$ if axp .or. ia64 +$ then +$ open/write aopt a.opt +$ open/write bopt b.opt +$ write aopt " CASE_SENSITIVE=YES" +$ write bopt "SYMBOL_VECTOR= (-" +$ mod_sym_num = 1 +$ MOD_SYM_LOOP: +$ if f$type(module'mod_sym_num') .nes. "" +$ then +$ mod_in = 0 +$ MOD_SYM_IN: +$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') +$ if shared_proc .nes. "#" +$ then +$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- + f$edit(shared_proc,"upcase"),shared_proc) +$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) +$ mod_in = mod_in + 1 +$ goto mod_sym_in +$ endif +$ mod_sym_num = mod_sym_num + 1 +$ goto mod_sym_loop +$ endif +$MAP_LOOP: +$ read/end=map_end map line +$ if (f$locate("{",line).lt. f$length(line)) .or. - + (f$locate("global:", line) .lt. f$length(line)) +$ then +$ proc = true +$ goto map_loop +$ endif +$ if f$locate("}",line).lt. f$length(line) then proc = false +$ if f$locate("local:", line) .lt. f$length(line) then proc = false +$ if proc +$ then +$ shared_proc = f$edit(line,"collapse") +$ chop_semi = f$locate(";", shared_proc) +$ if chop_semi .lt. f$length(shared_proc) then - + shared_proc = f$extract(0, chop_semi, shared_proc) +$ write aopt f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)",- + f$edit(shared_proc,"upcase"),shared_proc) +$ write bopt f$fao("!AS=PROCEDURE,-",shared_proc) +$ endif +$ goto map_loop +$MAP_END: +$ close/nolog aopt +$ close/nolog bopt +$ open/append libopt 'p2' +$ open/read aopt a.opt +$ open/read bopt b.opt +$ALOOP: +$ read/end=aloop_end aopt line +$ write libopt line +$ goto aloop +$ALOOP_END: +$ close/nolog aopt +$ sv = "" +$BLOOP: +$ read/end=bloop_end bopt svn +$ if (svn.nes."") +$ then +$ if (sv.nes."") then write libopt sv +$ sv = svn +$ endif +$ goto bloop +$BLOOP_END: +$ write libopt f$extract(0,f$length(sv)-2,sv), "-" +$ write libopt ")" +$ close/nolog bopt +$ delete/nolog/noconf a.opt;*,b.opt;* +$ else +$ if vax +$ then +$ open/append libopt 'p2' +$ mod_sym_num = 1 +$ VMOD_SYM_LOOP: +$ if f$type(module'mod_sym_num') .nes. "" +$ then +$ mod_in = 0 +$ VMOD_SYM_IN: +$ shared_proc = f$element(mod_in, "#", module'mod_sym_num') +$ if shared_proc .nes. "#" +$ then +$ write libopt f$fao("UNIVERSAL=!AS",- + f$edit(shared_proc,"upcase")) +$ mod_in = mod_in + 1 +$ goto vmod_sym_in +$ endif +$ mod_sym_num = mod_sym_num + 1 +$ goto vmod_sym_loop +$ endif +$VMAP_LOOP: +$ read/end=vmap_end map line +$ if (f$locate("{",line).lt. f$length(line)) .or. - + (f$locate("global:", line) .lt. f$length(line)) +$ then +$ proc = true +$ goto vmap_loop +$ endif +$ if f$locate("}",line).lt. f$length(line) then proc = false +$ if f$locate("local:", line) .lt. f$length(line) then proc = false +$ if proc +$ then +$ shared_proc = f$edit(line,"collapse") +$ chop_semi = f$locate(";", shared_proc) +$ if chop_semi .lt. f$length(shared_proc) then - + shared_proc = f$extract(0, chop_semi, shared_proc) +$ write libopt f$fao("UNIVERSAL=!AS",- + f$edit(shared_proc,"upcase")) +$ endif +$ goto vmap_loop +$VMAP_END: +$ else +$ write sys$output "Unknown Architecture (Not VAX, AXP, or IA64)" +$ write sys$output "No options file created" +$ endif +$ endif +$ EXIT_M2S: +$ close/nolog map +$ close/nolog libopt +$ endsubroutine diff --git a/third_party/zlib/v1_2_11/msdos/Makefile.bor b/third_party/zlib/v1_2_11/msdos/Makefile.bor new file mode 100644 index 0000000..3d12a2c --- /dev/null +++ b/third_party/zlib/v1_2_11/msdos/Makefile.bor @@ -0,0 +1,115 @@ +# Makefile for zlib +# Borland C++ +# Last updated: 15-Mar-2003 + +# To use, do "make -fmakefile.bor" +# To compile in small model, set below: MODEL=s + +# WARNING: the small model is supported but only for small values of +# MAX_WBITS and MAX_MEM_LEVEL. For example: +# -DMAX_WBITS=11 -DDEF_WBITS=11 -DMAX_MEM_LEVEL=3 +# If you wish to reduce the memory requirements (default 256K for big +# objects plus a few K), you can add to the LOC macro below: +# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 +# See zconf.h for details about the memory requirements. + +# ------------ Turbo C++, Borland C++ ------------ + +# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) +# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added +# to the declaration of LOC here: +LOC = $(LOCAL_ZLIB) + +# type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. +CPU_TYP = 0 + +# memory model: one of s, m, c, l (small, medium, compact, large) +MODEL=l + +# replace bcc with tcc for Turbo C++ 1.0, with bcc32 for the 32 bit version +CC=bcc +LD=bcc +AR=tlib + +# compiler flags +# replace "-O2" by "-O -G -a -d" for Turbo C++ 1.0 +CFLAGS=-O2 -Z -m$(MODEL) $(LOC) + +LDFLAGS=-m$(MODEL) -f- + + +# variables +ZLIB_LIB = zlib_$(MODEL).lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj +OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj +OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(CFLAGS) $*.c + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + +minigzip.obj: test/minigzip.c zlib.h zconf.h + + +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) + -del $(ZLIB_LIB) + $(AR) $(ZLIB_LIB) $(OBJP1) + $(AR) $(ZLIB_LIB) $(OBJP2) + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) + +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +clean: + -del *.obj + -del *.lib + -del *.exe + -del zlib_*.bak + -del foo.gz diff --git a/third_party/zlib/v1_2_11/msdos/Makefile.dj2 b/third_party/zlib/v1_2_11/msdos/Makefile.dj2 new file mode 100644 index 0000000..59d2037 --- /dev/null +++ b/third_party/zlib/v1_2_11/msdos/Makefile.dj2 @@ -0,0 +1,104 @@ +# Makefile for zlib. Modified for djgpp v2.0 by F. J. Donahoe, 3/15/96. +# Copyright (C) 1995-1998 Jean-loup Gailly. +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile, or to compile and test, type: +# +# make -fmakefile.dj2; make test -fmakefile.dj2 +# +# To install libz.a, zconf.h and zlib.h in the djgpp directories, type: +# +# make install -fmakefile.dj2 +# +# after first defining LIBRARY_PATH and INCLUDE_PATH in djgpp.env as +# in the sample below if the pattern of the DJGPP distribution is to +# be followed. Remember that, while 'es around <=> are ignored in +# makefiles, they are *not* in batch files or in djgpp.env. +# - - - - - +# [make] +# INCLUDE_PATH=%\>;INCLUDE_PATH%%\DJDIR%\include +# LIBRARY_PATH=%\>;LIBRARY_PATH%%\DJDIR%\lib +# BUTT=-m486 +# - - - - - +# Alternately, these variables may be defined below, overriding the values +# in djgpp.env, as +# INCLUDE_PATH=c:\usr\include +# LIBRARY_PATH=c:\usr\lib + +CC=gcc + +#CFLAGS=-MMD -O +#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 +#CFLAGS=-MMD -g -DZLIB_DEBUG +CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ + -Wstrict-prototypes -Wmissing-prototypes + +# If cp.exe is available, replace "copy /Y" with "cp -fp" . +CP=copy /Y +# If gnu install.exe is available, replace $(CP) with ginstall. +INSTALL=$(CP) +# The default value of RM is "rm -f." If "rm.exe" is found, comment out: +RM=del +LDLIBS=-L. -lz +LD=$(CC) -s -o +LDSHARED=$(CC) + +INCL=zlib.h zconf.h +LIBS=libz.a + +AR=ar rcs + +prefix=/usr/local +exec_prefix = $(prefix) + +OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ + uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o + +OBJA = +# to use the asm code: make OBJA=match.o + +TEST_OBJS = example.o minigzip.o + +all: example.exe minigzip.exe + +check: test +test: all + ./example + echo hello world | .\minigzip | .\minigzip -d + +%.o : %.c + $(CC) $(CFLAGS) -c $< -o $@ + +libz.a: $(OBJS) $(OBJA) + $(AR) $@ $(OBJS) $(OBJA) + +%.exe : %.o $(LIBS) + $(LD) $@ $< $(LDLIBS) + +# INCLUDE_PATH and LIBRARY_PATH were set for [make] in djgpp.env . + +.PHONY : uninstall clean + +install: $(INCL) $(LIBS) + -@if not exist $(INCLUDE_PATH)\nul mkdir $(INCLUDE_PATH) + -@if not exist $(LIBRARY_PATH)\nul mkdir $(LIBRARY_PATH) + $(INSTALL) zlib.h $(INCLUDE_PATH) + $(INSTALL) zconf.h $(INCLUDE_PATH) + $(INSTALL) libz.a $(LIBRARY_PATH) + +uninstall: + $(RM) $(INCLUDE_PATH)\zlib.h + $(RM) $(INCLUDE_PATH)\zconf.h + $(RM) $(LIBRARY_PATH)\libz.a + +clean: + $(RM) *.d + $(RM) *.o + $(RM) *.exe + $(RM) libz.a + $(RM) foo.gz + +DEPS := $(wildcard *.d) +ifneq ($(DEPS),) +include $(DEPS) +endif diff --git a/third_party/zlib/v1_2_11/msdos/Makefile.emx b/third_party/zlib/v1_2_11/msdos/Makefile.emx new file mode 100644 index 0000000..e30f67b --- /dev/null +++ b/third_party/zlib/v1_2_11/msdos/Makefile.emx @@ -0,0 +1,69 @@ +# Makefile for zlib. Modified for emx 0.9c by Chr. Spieler, 6/17/98. +# Copyright (C) 1995-1998 Jean-loup Gailly. +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile, or to compile and test, type: +# +# make -fmakefile.emx; make test -fmakefile.emx +# + +CC=gcc + +#CFLAGS=-MMD -O +#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 +#CFLAGS=-MMD -g -DZLIB_DEBUG +CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ + -Wstrict-prototypes -Wmissing-prototypes + +# If cp.exe is available, replace "copy /Y" with "cp -fp" . +CP=copy /Y +# If gnu install.exe is available, replace $(CP) with ginstall. +INSTALL=$(CP) +# The default value of RM is "rm -f." If "rm.exe" is found, comment out: +RM=del +LDLIBS=-L. -lzlib +LD=$(CC) -s -o +LDSHARED=$(CC) + +INCL=zlib.h zconf.h +LIBS=zlib.a + +AR=ar rcs + +prefix=/usr/local +exec_prefix = $(prefix) + +OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \ + uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o + +TEST_OBJS = example.o minigzip.o + +all: example.exe minigzip.exe + +test: all + ./example + echo hello world | .\minigzip | .\minigzip -d + +%.o : %.c + $(CC) $(CFLAGS) -c $< -o $@ + +zlib.a: $(OBJS) + $(AR) $@ $(OBJS) + +%.exe : %.o $(LIBS) + $(LD) $@ $< $(LDLIBS) + + +.PHONY : clean + +clean: + $(RM) *.d + $(RM) *.o + $(RM) *.exe + $(RM) zlib.a + $(RM) foo.gz + +DEPS := $(wildcard *.d) +ifneq ($(DEPS),) +include $(DEPS) +endif diff --git a/third_party/zlib/v1_2_11/msdos/Makefile.msc b/third_party/zlib/v1_2_11/msdos/Makefile.msc new file mode 100644 index 0000000..ae83786 --- /dev/null +++ b/third_party/zlib/v1_2_11/msdos/Makefile.msc @@ -0,0 +1,112 @@ +# Makefile for zlib +# Microsoft C 5.1 or later +# Last updated: 19-Mar-2003 + +# To use, do "make makefile.msc" +# To compile in small model, set below: MODEL=S + +# If you wish to reduce the memory requirements (default 256K for big +# objects plus a few K), you can add to the LOC macro below: +# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 +# See zconf.h for details about the memory requirements. + +# ------------- Microsoft C 5.1 and later ------------- + +# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) +# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or added +# to the declaration of LOC here: +LOC = $(LOCAL_ZLIB) + +# Type for CPU required: 0: 8086, 1: 80186, 2: 80286, 3: 80386, etc. +CPU_TYP = 0 + +# Memory model: one of S, M, C, L (small, medium, compact, large) +MODEL=L + +CC=cl +CFLAGS=-nologo -A$(MODEL) -G$(CPU_TYP) -W3 -Oait -Gs $(LOC) +#-Ox generates bad code with MSC 5.1 +LIB_CFLAGS=-Zl $(CFLAGS) + +LD=link +LDFLAGS=/noi/e/st:0x1500/noe/farcall/packcode +# "/farcall/packcode" are only useful for `large code' memory models +# but should be a "no-op" for small code models. + + +# variables +ZLIB_LIB = zlib_$(MODEL).lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(LIB_CFLAGS) $*.c + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + $(CC) -c $(CFLAGS) $*.c + +minigzip.obj: test/minigzip.c zlib.h zconf.h + $(CC) -c $(CFLAGS) $*.c + + +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) + if exist $(ZLIB_LIB) del $(ZLIB_LIB) + lib $(ZLIB_LIB) $(OBJ1); + lib $(ZLIB_LIB) $(OBJ2); + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj,,,$(ZLIB_LIB); + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj,,,$(ZLIB_LIB); + +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +clean: + -del *.obj + -del *.lib + -del *.exe + -del *.map + -del zlib_*.bak + -del foo.gz diff --git a/third_party/zlib/v1_2_11/msdos/Makefile.tc b/third_party/zlib/v1_2_11/msdos/Makefile.tc new file mode 100644 index 0000000..5aec82a --- /dev/null +++ b/third_party/zlib/v1_2_11/msdos/Makefile.tc @@ -0,0 +1,100 @@ +# Makefile for zlib +# Turbo C 2.01, Turbo C++ 1.01 +# Last updated: 15-Mar-2003 + +# To use, do "make -fmakefile.tc" +# To compile in small model, set below: MODEL=s + +# WARNING: the small model is supported but only for small values of +# MAX_WBITS and MAX_MEM_LEVEL. For example: +# -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 +# If you wish to reduce the memory requirements (default 256K for big +# objects plus a few K), you can add to CFLAGS below: +# -DMAX_MEM_LEVEL=7 -DMAX_WBITS=14 +# See zconf.h for details about the memory requirements. + +# ------------ Turbo C 2.01, Turbo C++ 1.01 ------------ +MODEL=l +CC=tcc +LD=tcc +AR=tlib +# CFLAGS=-O2 -G -Z -m$(MODEL) -DMAX_WBITS=11 -DMAX_MEM_LEVEL=3 +CFLAGS=-O2 -G -Z -m$(MODEL) +LDFLAGS=-m$(MODEL) -f- + + +# variables +ZLIB_LIB = zlib_$(MODEL).lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj +OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj +OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(CFLAGS) $*.c + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + +minigzip.obj: test/minigzip.c zlib.h zconf.h + + +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) + -del $(ZLIB_LIB) + $(AR) $(ZLIB_LIB) $(OBJP1) + $(AR) $(ZLIB_LIB) $(OBJP2) + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) + +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +clean: + -del *.obj + -del *.lib + -del *.exe + -del zlib_*.bak + -del foo.gz diff --git a/third_party/zlib/v1_2_11/nintendods/Makefile b/third_party/zlib/v1_2_11/nintendods/Makefile new file mode 100644 index 0000000..21337d0 --- /dev/null +++ b/third_party/zlib/v1_2_11/nintendods/Makefile @@ -0,0 +1,126 @@ +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITARM)),) +$(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM") +endif + +include $(DEVKITARM)/ds_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output +# BUILD is the directory where object files & intermediate files will be placed +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#--------------------------------------------------------------------------------- +TARGET := $(shell basename $(CURDIR)) +BUILD := build +SOURCES := ../../ +DATA := data +INCLUDES := include + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +ARCH := -mthumb -mthumb-interwork + +CFLAGS := -Wall -O2\ + -march=armv5te -mtune=arm946e-s \ + -fomit-frame-pointer -ffast-math \ + $(ARCH) + +CFLAGS += $(INCLUDE) -DARM9 +CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions + +ASFLAGS := $(ARCH) -march=armv5te -mtune=arm946e-s +LDFLAGS = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(LIBNDS) + +#--------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#--------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#--------------------------------------------------------------------------------- + +export OUTPUT := $(CURDIR)/lib/libz.a + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +export DEPSDIR := $(CURDIR)/$(BUILD) + +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES := $(addsuffix .o,$(BINFILES)) \ + $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +.PHONY: $(BUILD) clean all + +#--------------------------------------------------------------------------------- +all: $(BUILD) + @[ -d $@ ] || mkdir -p include + @cp ../../*.h include + +lib: + @[ -d $@ ] || mkdir -p $@ + +$(BUILD): lib + @[ -d $@ ] || mkdir -p $@ + @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr $(BUILD) lib + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- +$(OUTPUT) : $(OFILES) + +#--------------------------------------------------------------------------------- +%.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------------- diff --git a/third_party/zlib/v1_2_11/nintendods/README b/third_party/zlib/v1_2_11/nintendods/README new file mode 100644 index 0000000..ba7a37d --- /dev/null +++ b/third_party/zlib/v1_2_11/nintendods/README @@ -0,0 +1,5 @@ +This Makefile requires devkitARM (http://www.devkitpro.org/category/devkitarm/) and works inside "contrib/nds". It is based on a devkitARM template. + +Eduardo Costa +January 3, 2009 + diff --git a/third_party/zlib/v1_2_11/old/Makefile.emx b/third_party/zlib/v1_2_11/old/Makefile.emx new file mode 100644 index 0000000..612b037 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/Makefile.emx @@ -0,0 +1,69 @@ +# Makefile for zlib. Modified for emx/rsxnt by Chr. Spieler, 6/16/98. +# Copyright (C) 1995-1998 Jean-loup Gailly. +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile, or to compile and test, type: +# +# make -fmakefile.emx; make test -fmakefile.emx +# + +CC=gcc -Zwin32 + +#CFLAGS=-MMD -O +#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 +#CFLAGS=-MMD -g -DZLIB_DEBUG +CFLAGS=-MMD -O3 $(BUTT) -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ + -Wstrict-prototypes -Wmissing-prototypes + +# If cp.exe is available, replace "copy /Y" with "cp -fp" . +CP=copy /Y +# If gnu install.exe is available, replace $(CP) with ginstall. +INSTALL=$(CP) +# The default value of RM is "rm -f." If "rm.exe" is found, comment out: +RM=del +LDLIBS=-L. -lzlib +LD=$(CC) -s -o +LDSHARED=$(CC) + +INCL=zlib.h zconf.h +LIBS=zlib.a + +AR=ar rcs + +prefix=/usr/local +exec_prefix = $(prefix) + +OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ + gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o + +TEST_OBJS = example.o minigzip.o + +all: example.exe minigzip.exe + +test: all + ./example + echo hello world | .\minigzip | .\minigzip -d + +%.o : %.c + $(CC) $(CFLAGS) -c $< -o $@ + +zlib.a: $(OBJS) + $(AR) $@ $(OBJS) + +%.exe : %.o $(LIBS) + $(LD) $@ $< $(LDLIBS) + + +.PHONY : clean + +clean: + $(RM) *.d + $(RM) *.o + $(RM) *.exe + $(RM) zlib.a + $(RM) foo.gz + +DEPS := $(wildcard *.d) +ifneq ($(DEPS),) +include $(DEPS) +endif diff --git a/third_party/zlib/v1_2_11/old/Makefile.riscos b/third_party/zlib/v1_2_11/old/Makefile.riscos new file mode 100644 index 0000000..57e29d3 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/Makefile.riscos @@ -0,0 +1,151 @@ +# Project: zlib_1_03 +# Patched for zlib 1.1.2 rw@shadow.org.uk 19980430 +# test works out-of-the-box, installs `somewhere' on demand + +# Toolflags: +CCflags = -c -depend !Depend -IC: -g -throwback -DRISCOS -fah +C++flags = -c -depend !Depend -IC: -throwback +Linkflags = -aif -c++ -o $@ +ObjAsmflags = -throwback -NoCache -depend !Depend +CMHGflags = +LibFileflags = -c -l -o $@ +Squeezeflags = -o $@ + +# change the line below to where _you_ want the library installed. +libdest = lib:zlib + +# Final targets: +@.lib: @.o.adler32 @.o.compress @.o.crc32 @.o.deflate @.o.gzio \ + @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil @.o.trees \ + @.o.uncompr @.o.zutil + LibFile $(LibFileflags) @.o.adler32 @.o.compress @.o.crc32 @.o.deflate \ + @.o.gzio @.o.infblock @.o.infcodes @.o.inffast @.o.inflate @.o.inftrees @.o.infutil \ + @.o.trees @.o.uncompr @.o.zutil +test: @.minigzip @.example @.lib + @copy @.lib @.libc A~C~DF~L~N~P~Q~RS~TV + @echo running tests: hang on. + @/@.minigzip -f -9 libc + @/@.minigzip -d libc-gz + @/@.minigzip -f -1 libc + @/@.minigzip -d libc-gz + @/@.minigzip -h -9 libc + @/@.minigzip -d libc-gz + @/@.minigzip -h -1 libc + @/@.minigzip -d libc-gz + @/@.minigzip -9 libc + @/@.minigzip -d libc-gz + @/@.minigzip -1 libc + @/@.minigzip -d libc-gz + @diff @.lib @.libc + @echo that should have reported '@.lib and @.libc identical' if you have diff. + @/@.example @.fred @.fred + @echo that will have given lots of hello!'s. + +@.minigzip: @.o.minigzip @.lib C:o.Stubs + Link $(Linkflags) @.o.minigzip @.lib C:o.Stubs +@.example: @.o.example @.lib C:o.Stubs + Link $(Linkflags) @.o.example @.lib C:o.Stubs + +install: @.lib + cdir $(libdest) + cdir $(libdest).h + @copy @.h.zlib $(libdest).h.zlib A~C~DF~L~N~P~Q~RS~TV + @copy @.h.zconf $(libdest).h.zconf A~C~DF~L~N~P~Q~RS~TV + @copy @.lib $(libdest).lib A~C~DF~L~N~P~Q~RS~TV + @echo okay, installed zlib in $(libdest) + +clean:; remove @.minigzip + remove @.example + remove @.libc + -wipe @.o.* F~r~cV + remove @.fred + +# User-editable dependencies: +.c.o: + cc $(ccflags) -o $@ $< + +# Static dependencies: + +# Dynamic dependencies: +o.example: c.example +o.example: h.zlib +o.example: h.zconf +o.minigzip: c.minigzip +o.minigzip: h.zlib +o.minigzip: h.zconf +o.adler32: c.adler32 +o.adler32: h.zlib +o.adler32: h.zconf +o.compress: c.compress +o.compress: h.zlib +o.compress: h.zconf +o.crc32: c.crc32 +o.crc32: h.zlib +o.crc32: h.zconf +o.deflate: c.deflate +o.deflate: h.deflate +o.deflate: h.zutil +o.deflate: h.zlib +o.deflate: h.zconf +o.gzio: c.gzio +o.gzio: h.zutil +o.gzio: h.zlib +o.gzio: h.zconf +o.infblock: c.infblock +o.infblock: h.zutil +o.infblock: h.zlib +o.infblock: h.zconf +o.infblock: h.infblock +o.infblock: h.inftrees +o.infblock: h.infcodes +o.infblock: h.infutil +o.infcodes: c.infcodes +o.infcodes: h.zutil +o.infcodes: h.zlib +o.infcodes: h.zconf +o.infcodes: h.inftrees +o.infcodes: h.infblock +o.infcodes: h.infcodes +o.infcodes: h.infutil +o.infcodes: h.inffast +o.inffast: c.inffast +o.inffast: h.zutil +o.inffast: h.zlib +o.inffast: h.zconf +o.inffast: h.inftrees +o.inffast: h.infblock +o.inffast: h.infcodes +o.inffast: h.infutil +o.inffast: h.inffast +o.inflate: c.inflate +o.inflate: h.zutil +o.inflate: h.zlib +o.inflate: h.zconf +o.inflate: h.infblock +o.inftrees: c.inftrees +o.inftrees: h.zutil +o.inftrees: h.zlib +o.inftrees: h.zconf +o.inftrees: h.inftrees +o.inftrees: h.inffixed +o.infutil: c.infutil +o.infutil: h.zutil +o.infutil: h.zlib +o.infutil: h.zconf +o.infutil: h.infblock +o.infutil: h.inftrees +o.infutil: h.infcodes +o.infutil: h.infutil +o.trees: c.trees +o.trees: h.deflate +o.trees: h.zutil +o.trees: h.zlib +o.trees: h.zconf +o.trees: h.trees +o.uncompr: c.uncompr +o.uncompr: h.zlib +o.uncompr: h.zconf +o.zutil: c.zutil +o.zutil: h.zutil +o.zutil: h.zlib +o.zutil: h.zconf diff --git a/third_party/zlib/v1_2_11/old/README b/third_party/zlib/v1_2_11/old/README new file mode 100644 index 0000000..800bf07 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/README @@ -0,0 +1,3 @@ +This directory contains files that have not been updated for zlib 1.2.x + +(Volunteers are encouraged to help clean this up. Thanks.) diff --git a/third_party/zlib/v1_2_11/old/descrip.mms b/third_party/zlib/v1_2_11/old/descrip.mms new file mode 100644 index 0000000..7066da5 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/descrip.mms @@ -0,0 +1,48 @@ +# descrip.mms: MMS description file for building zlib on VMS +# written by Martin P.J. Zinser + +cc_defs = +c_deb = + +.ifdef __DECC__ +pref = /prefix=all +.endif + +OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj,\ + deflate.obj, trees.obj, zutil.obj, inflate.obj, infblock.obj,\ + inftrees.obj, infcodes.obj, infutil.obj, inffast.obj + +CFLAGS= $(C_DEB) $(CC_DEFS) $(PREF) + +all : example.exe minigzip.exe + @ write sys$output " Example applications available" +libz.olb : libz.olb($(OBJS)) + @ write sys$output " libz available" + +example.exe : example.obj libz.olb + link example,libz.olb/lib + +minigzip.exe : minigzip.obj libz.olb + link minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib + +clean : + delete *.obj;*,libz.olb;* + + +# Other dependencies. +adler32.obj : zutil.h zlib.h zconf.h +compress.obj : zlib.h zconf.h +crc32.obj : zutil.h zlib.h zconf.h +deflate.obj : deflate.h zutil.h zlib.h zconf.h +example.obj : zlib.h zconf.h +gzio.obj : zutil.h zlib.h zconf.h +infblock.obj : zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h +infcodes.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h infcodes.h inffast.h +inffast.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h inffast.h +inflate.obj : zutil.h zlib.h zconf.h infblock.h +inftrees.obj : zutil.h zlib.h zconf.h inftrees.h +infutil.obj : zutil.h zlib.h zconf.h inftrees.h infutil.h +minigzip.obj : zlib.h zconf.h +trees.obj : deflate.h zutil.h zlib.h zconf.h +uncompr.obj : zlib.h zconf.h +zutil.obj : zutil.h zlib.h zconf.h diff --git a/third_party/zlib/v1_2_11/old/os2/Makefile.os2 b/third_party/zlib/v1_2_11/old/os2/Makefile.os2 new file mode 100644 index 0000000..bb426c0 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/os2/Makefile.os2 @@ -0,0 +1,136 @@ +# Makefile for zlib under OS/2 using GCC (PGCC) +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile and test, type: +# cp Makefile.os2 .. +# cd .. +# make -f Makefile.os2 test + +# This makefile will build a static library z.lib, a shared library +# z.dll and a import library zdll.lib. You can use either z.lib or +# zdll.lib by specifying either -lz or -lzdll on gcc's command line + +CC=gcc -Zomf -s + +CFLAGS=-O6 -Wall +#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 +#CFLAGS=-g -DZLIB_DEBUG +#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ +# -Wstrict-prototypes -Wmissing-prototypes + +#################### BUG WARNING: ##################### +## infcodes.c hits a bug in pgcc-1.0, so you have to use either +## -O# where # <= 4 or one of (-fno-ommit-frame-pointer or -fno-force-mem) +## This bug is reportedly fixed in pgcc >1.0, but this was not tested +CFLAGS+=-fno-force-mem + +LDFLAGS=-s -L. -lzdll -Zcrtdll +LDSHARED=$(CC) -s -Zomf -Zdll -Zcrtdll + +VER=1.1.0 +ZLIB=z.lib +SHAREDLIB=z.dll +SHAREDLIBIMP=zdll.lib +LIBS=$(ZLIB) $(SHAREDLIB) $(SHAREDLIBIMP) + +AR=emxomfar cr +IMPLIB=emximp +RANLIB=echo +TAR=tar +SHELL=bash + +prefix=/usr/local +exec_prefix = $(prefix) + +OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ + zutil.o inflate.o infblock.o inftrees.o infcodes.o infutil.o inffast.o + +TEST_OBJS = example.o minigzip.o + +DISTFILES = README INDEX ChangeLog configure Make*[a-z0-9] *.[ch] descrip.mms \ + algorithm.txt zlib.3 msdos/Make*[a-z0-9] msdos/zlib.def msdos/zlib.rc \ + nt/Makefile.nt nt/zlib.dnt contrib/README.contrib contrib/*.txt \ + contrib/asm386/*.asm contrib/asm386/*.c \ + contrib/asm386/*.bat contrib/asm386/zlibvc.d?? contrib/iostream/*.cpp \ + contrib/iostream/*.h contrib/iostream2/*.h contrib/iostream2/*.cpp \ + contrib/untgz/Makefile contrib/untgz/*.c contrib/untgz/*.w32 + +all: example.exe minigzip.exe + +test: all + @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ + echo hello world | ./minigzip | ./minigzip -d || \ + echo ' *** minigzip test FAILED ***' ; \ + if ./example; then \ + echo ' *** zlib test OK ***'; \ + else \ + echo ' *** zlib test FAILED ***'; \ + fi + +$(ZLIB): $(OBJS) + $(AR) $@ $(OBJS) + -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 + +$(SHAREDLIB): $(OBJS) os2/z.def + $(LDSHARED) -o $@ $^ + +$(SHAREDLIBIMP): os2/z.def + $(IMPLIB) -o $@ $^ + +example.exe: example.o $(LIBS) + $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) + +minigzip.exe: minigzip.o $(LIBS) + $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) + +clean: + rm -f *.o *~ example minigzip libz.a libz.so* foo.gz + +distclean: clean + +zip: + mv Makefile Makefile~; cp -p Makefile.in Makefile + rm -f test.c ztest*.c + v=`sed -n -e 's/\.//g' -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ + zip -ul9 zlib$$v $(DISTFILES) + mv Makefile~ Makefile + +dist: + mv Makefile Makefile~; cp -p Makefile.in Makefile + rm -f test.c ztest*.c + d=zlib-`sed -n '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`;\ + rm -f $$d.tar.gz; \ + if test ! -d ../$$d; then rm -f ../$$d; ln -s `pwd` ../$$d; fi; \ + files=""; \ + for f in $(DISTFILES); do files="$$files $$d/$$f"; done; \ + cd ..; \ + GZIP=-9 $(TAR) chofz $$d/$$d.tar.gz $$files; \ + if test ! -d $$d; then rm -f $$d; fi + mv Makefile~ Makefile + +tags: + etags *.[ch] + +depend: + makedepend -- $(CFLAGS) -- *.[ch] + +# DO NOT DELETE THIS LINE -- make depend depends on it. + +adler32.o: zlib.h zconf.h +compress.o: zlib.h zconf.h +crc32.o: zlib.h zconf.h +deflate.o: deflate.h zutil.h zlib.h zconf.h +example.o: zlib.h zconf.h +gzio.o: zutil.h zlib.h zconf.h +infblock.o: infblock.h inftrees.h infcodes.h infutil.h zutil.h zlib.h zconf.h +infcodes.o: zutil.h zlib.h zconf.h +infcodes.o: inftrees.h infblock.h infcodes.h infutil.h inffast.h +inffast.o: zutil.h zlib.h zconf.h inftrees.h +inffast.o: infblock.h infcodes.h infutil.h inffast.h +inflate.o: zutil.h zlib.h zconf.h infblock.h +inftrees.o: zutil.h zlib.h zconf.h inftrees.h +infutil.o: zutil.h zlib.h zconf.h infblock.h inftrees.h infcodes.h infutil.h +minigzip.o: zlib.h zconf.h +trees.o: deflate.h zutil.h zlib.h zconf.h trees.h +uncompr.o: zlib.h zconf.h +zutil.o: zutil.h zlib.h zconf.h diff --git a/third_party/zlib/v1_2_11/old/os2/zlib.def b/third_party/zlib/v1_2_11/old/os2/zlib.def new file mode 100644 index 0000000..4c753f1 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/os2/zlib.def @@ -0,0 +1,51 @@ +; +; Slightly modified version of ../nt/zlib.dnt :-) +; + +LIBRARY Z +DESCRIPTION "Zlib compression library for OS/2" +CODE PRELOAD MOVEABLE DISCARDABLE +DATA PRELOAD MOVEABLE MULTIPLE + +EXPORTS + adler32 + compress + crc32 + deflate + deflateCopy + deflateEnd + deflateInit2_ + deflateInit_ + deflateParams + deflateReset + deflateSetDictionary + gzclose + gzdopen + gzerror + gzflush + gzopen + gzread + gzwrite + inflate + inflateEnd + inflateInit2_ + inflateInit_ + inflateReset + inflateSetDictionary + inflateSync + uncompress + zlibVersion + gzprintf + gzputc + gzgetc + gzseek + gzrewind + gztell + gzeof + gzsetparams + zError + inflateSyncPoint + get_crc_table + compress2 + gzputs + gzgets diff --git a/third_party/zlib/v1_2_11/old/visual-basic.txt b/third_party/zlib/v1_2_11/old/visual-basic.txt new file mode 100644 index 0000000..57efe58 --- /dev/null +++ b/third_party/zlib/v1_2_11/old/visual-basic.txt @@ -0,0 +1,160 @@ +See below some functions declarations for Visual Basic. + +Frequently Asked Question: + +Q: Each time I use the compress function I get the -5 error (not enough + room in the output buffer). + +A: Make sure that the length of the compressed buffer is passed by + reference ("as any"), not by value ("as long"). Also check that + before the call of compress this length is equal to the total size of + the compressed buffer and not zero. + + +From: "Jon Caruana" +Subject: Re: How to port zlib declares to vb? +Date: Mon, 28 Oct 1996 18:33:03 -0600 + +Got the answer! (I haven't had time to check this but it's what I got, and +looks correct): + +He has the following routines working: + compress + uncompress + gzopen + gzwrite + gzread + gzclose + +Declares follow: (Quoted from Carlos Rios , in Vb4 form) + +#If Win16 Then 'Use Win16 calls. +Declare Function compress Lib "ZLIB.DLL" (ByVal compr As + String, comprLen As Any, ByVal buf As String, ByVal buflen + As Long) As Integer +Declare Function uncompress Lib "ZLIB.DLL" (ByVal uncompr + As String, uncomprLen As Any, ByVal compr As String, ByVal + lcompr As Long) As Integer +Declare Function gzopen Lib "ZLIB.DLL" (ByVal filePath As + String, ByVal mode As String) As Long +Declare Function gzread Lib "ZLIB.DLL" (ByVal file As + Long, ByVal uncompr As String, ByVal uncomprLen As Integer) + As Integer +Declare Function gzwrite Lib "ZLIB.DLL" (ByVal file As + Long, ByVal uncompr As String, ByVal uncomprLen As Integer) + As Integer +Declare Function gzclose Lib "ZLIB.DLL" (ByVal file As + Long) As Integer +#Else +Declare Function compress Lib "ZLIB32.DLL" + (ByVal compr As String, comprLen As Any, ByVal buf As + String, ByVal buflen As Long) As Integer +Declare Function uncompress Lib "ZLIB32.DLL" + (ByVal uncompr As String, uncomprLen As Any, ByVal compr As + String, ByVal lcompr As Long) As Long +Declare Function gzopen Lib "ZLIB32.DLL" + (ByVal file As String, ByVal mode As String) As Long +Declare Function gzread Lib "ZLIB32.DLL" + (ByVal file As Long, ByVal uncompr As String, ByVal + uncomprLen As Long) As Long +Declare Function gzwrite Lib "ZLIB32.DLL" + (ByVal file As Long, ByVal uncompr As String, ByVal + uncomprLen As Long) As Long +Declare Function gzclose Lib "ZLIB32.DLL" + (ByVal file As Long) As Long +#End If + +-Jon Caruana +jon-net@usa.net +Microsoft Sitebuilder Network Level 1 Member - HTML Writer's Guild Member + + +Here is another example from Michael that he +says conforms to the VB guidelines, and that solves the problem of not +knowing the uncompressed size by storing it at the end of the file: + +'Calling the functions: +'bracket meaning: [optional] {Range of possible values} +'Call subCompressFile( [, , [level of compression {1..9}]]) +'Call subUncompressFile() + +Option Explicit +Private lngpvtPcnSml As Long 'Stores value for 'lngPercentSmaller' +Private Const SUCCESS As Long = 0 +Private Const strFilExt As String = ".cpr" +Private Declare Function lngfncCpr Lib "zlib.dll" Alias "compress2" (ByRef +dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long, +ByVal level As Integer) As Long +Private Declare Function lngfncUcp Lib "zlib.dll" Alias "uncompress" (ByRef +dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long) +As Long + +Public Sub subCompressFile(ByVal strargOriFilPth As String, Optional ByVal +strargCprFilPth As String, Optional ByVal intLvl As Integer = 9) + Dim strCprPth As String + Dim lngOriSiz As Long + Dim lngCprSiz As Long + Dim bytaryOri() As Byte + Dim bytaryCpr() As Byte + lngOriSiz = FileLen(strargOriFilPth) + ReDim bytaryOri(lngOriSiz - 1) + Open strargOriFilPth For Binary Access Read As #1 + Get #1, , bytaryOri() + Close #1 + strCprPth = IIf(strargCprFilPth = "", strargOriFilPth, strargCprFilPth) +'Select file path and name + strCprPth = strCprPth & IIf(Right(strCprPth, Len(strFilExt)) = +strFilExt, "", strFilExt) 'Add file extension if not exists + lngCprSiz = (lngOriSiz * 1.01) + 12 'Compression needs temporary a bit +more space then original file size + ReDim bytaryCpr(lngCprSiz - 1) + If lngfncCpr(bytaryCpr(0), lngCprSiz, bytaryOri(0), lngOriSiz, intLvl) = +SUCCESS Then + lngpvtPcnSml = (1# - (lngCprSiz / lngOriSiz)) * 100 + ReDim Preserve bytaryCpr(lngCprSiz - 1) + Open strCprPth For Binary Access Write As #1 + Put #1, , bytaryCpr() + Put #1, , lngOriSiz 'Add the the original size value to the end +(last 4 bytes) + Close #1 + Else + MsgBox "Compression error" + End If + Erase bytaryCpr + Erase bytaryOri +End Sub + +Public Sub subUncompressFile(ByVal strargFilPth As String) + Dim bytaryCpr() As Byte + Dim bytaryOri() As Byte + Dim lngOriSiz As Long + Dim lngCprSiz As Long + Dim strOriPth As String + lngCprSiz = FileLen(strargFilPth) + ReDim bytaryCpr(lngCprSiz - 1) + Open strargFilPth For Binary Access Read As #1 + Get #1, , bytaryCpr() + Close #1 + 'Read the original file size value: + lngOriSiz = bytaryCpr(lngCprSiz - 1) * (2 ^ 24) _ + + bytaryCpr(lngCprSiz - 2) * (2 ^ 16) _ + + bytaryCpr(lngCprSiz - 3) * (2 ^ 8) _ + + bytaryCpr(lngCprSiz - 4) + ReDim Preserve bytaryCpr(lngCprSiz - 5) 'Cut of the original size value + ReDim bytaryOri(lngOriSiz - 1) + If lngfncUcp(bytaryOri(0), lngOriSiz, bytaryCpr(0), lngCprSiz) = SUCCESS +Then + strOriPth = Left(strargFilPth, Len(strargFilPth) - Len(strFilExt)) + Open strOriPth For Binary Access Write As #1 + Put #1, , bytaryOri() + Close #1 + Else + MsgBox "Uncompression error" + End If + Erase bytaryCpr + Erase bytaryOri +End Sub +Public Property Get lngPercentSmaller() As Long + lngPercentSmaller = lngpvtPcnSml +End Property diff --git a/third_party/zlib/v1_2_11/os400/README400 b/third_party/zlib/v1_2_11/os400/README400 new file mode 100644 index 0000000..4f98334 --- /dev/null +++ b/third_party/zlib/v1_2_11/os400/README400 @@ -0,0 +1,48 @@ + ZLIB version 1.2.11 for OS/400 installation instructions + +1) Download and unpack the zlib tarball to some IFS directory. + (i.e.: /path/to/the/zlib/ifs/source/directory) + + If the installed IFS command suppors gzip format, this is straightforward, +else you have to unpack first to some directory on a system supporting it, +then move the whole directory to the IFS via the network (via SMB or FTP). + +2) Edit the configuration parameters in the compilation script. + + EDTF STMF('/path/to/the/zlib/ifs/source/directory/os400/make.sh') + +Tune the parameters according to your needs if not matching the defaults. +Save the file and exit after edition. + +3) Enter qshell, then work in the zlib OS/400 specific directory. + + QSH + cd /path/to/the/zlib/ifs/source/directory/os400 + +4) Compile and install + + sh make.sh + +The script will: +- create the libraries, objects and IFS directories for the zlib environment, +- compile all modules, +- create a service program, +- create a static and a dynamic binding directory, +- install header files for C/C++ and for ILE/RPG, both for compilation in + DB2 and IFS environments. + +That's all. + + +Notes: For OS/400 ILE RPG programmers, a /copy member defining the ZLIB + API prototypes for ILE RPG can be found in ZLIB/H(ZLIB.INC). + In the ILE environment, the same definitions are available from + file zlib.inc located in the same IFS include directory as the + C/C++ header files. + Please read comments in this member for more information. + + Remember that most foreign textual data are ASCII coded: this + implementation does not handle conversion from/to ASCII, so + text data code conversions must be done explicitely. + + Mainly for the reason above, always open zipped files in binary mode. diff --git a/third_party/zlib/v1_2_11/os400/bndsrc b/third_party/zlib/v1_2_11/os400/bndsrc new file mode 100644 index 0000000..5e6e0a2 --- /dev/null +++ b/third_party/zlib/v1_2_11/os400/bndsrc @@ -0,0 +1,119 @@ +STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('ZLIB') + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.1.3 entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("adler32") + EXPORT SYMBOL("compress") + EXPORT SYMBOL("compress2") + EXPORT SYMBOL("crc32") + EXPORT SYMBOL("get_crc_table") + EXPORT SYMBOL("deflate") + EXPORT SYMBOL("deflateEnd") + EXPORT SYMBOL("deflateSetDictionary") + EXPORT SYMBOL("deflateCopy") + EXPORT SYMBOL("deflateReset") + EXPORT SYMBOL("deflateParams") + EXPORT SYMBOL("deflatePrime") + EXPORT SYMBOL("deflateInit_") + EXPORT SYMBOL("deflateInit2_") + EXPORT SYMBOL("gzopen") + EXPORT SYMBOL("gzdopen") + EXPORT SYMBOL("gzsetparams") + EXPORT SYMBOL("gzread") + EXPORT SYMBOL("gzwrite") + EXPORT SYMBOL("gzprintf") + EXPORT SYMBOL("gzputs") + EXPORT SYMBOL("gzgets") + EXPORT SYMBOL("gzputc") + EXPORT SYMBOL("gzgetc") + EXPORT SYMBOL("gzflush") + EXPORT SYMBOL("gzseek") + EXPORT SYMBOL("gzrewind") + EXPORT SYMBOL("gztell") + EXPORT SYMBOL("gzeof") + EXPORT SYMBOL("gzclose") + EXPORT SYMBOL("gzerror") + EXPORT SYMBOL("inflate") + EXPORT SYMBOL("inflateEnd") + EXPORT SYMBOL("inflateSetDictionary") + EXPORT SYMBOL("inflateSync") + EXPORT SYMBOL("inflateReset") + EXPORT SYMBOL("inflateInit_") + EXPORT SYMBOL("inflateInit2_") + EXPORT SYMBOL("inflateSyncPoint") + EXPORT SYMBOL("uncompress") + EXPORT SYMBOL("zlibVersion") + EXPORT SYMBOL("zError") + EXPORT SYMBOL("z_errmsg") + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.2.1 additional entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("compressBound") + EXPORT SYMBOL("deflateBound") + EXPORT SYMBOL("deflatePending") + EXPORT SYMBOL("gzungetc") + EXPORT SYMBOL("gzclearerr") + EXPORT SYMBOL("inflateBack") + EXPORT SYMBOL("inflateBackEnd") + EXPORT SYMBOL("inflateBackInit_") + EXPORT SYMBOL("inflateCopy") + EXPORT SYMBOL("zlibCompileFlags") + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.2.4 additional entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("adler32_combine") + EXPORT SYMBOL("adler32_combine64") + EXPORT SYMBOL("crc32_combine") + EXPORT SYMBOL("crc32_combine64") + EXPORT SYMBOL("deflateSetHeader") + EXPORT SYMBOL("deflateTune") + EXPORT SYMBOL("gzbuffer") + EXPORT SYMBOL("gzclose_r") + EXPORT SYMBOL("gzclose_w") + EXPORT SYMBOL("gzdirect") + EXPORT SYMBOL("gzoffset") + EXPORT SYMBOL("gzoffset64") + EXPORT SYMBOL("gzopen64") + EXPORT SYMBOL("gzseek64") + EXPORT SYMBOL("gztell64") + EXPORT SYMBOL("inflateGetHeader") + EXPORT SYMBOL("inflateMark") + EXPORT SYMBOL("inflatePrime") + EXPORT SYMBOL("inflateReset2") + EXPORT SYMBOL("inflateUndermine") + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.2.6 additional entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("deflateResetKeep") + EXPORT SYMBOL("gzgetc_") + EXPORT SYMBOL("inflateResetKeep") + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.2.8 additional entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("gzvprintf") + EXPORT SYMBOL("inflateGetDictionary") + +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ +/* Version 1.2.9 additional entry points. */ +/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ + + EXPORT SYMBOL("adler32_z") + EXPORT SYMBOL("crc32_z") + EXPORT SYMBOL("deflateGetDictionary") + EXPORT SYMBOL("gzfread") + EXPORT SYMBOL("gzfwrite") + EXPORT SYMBOL("inflateCodesUsed") + EXPORT SYMBOL("inflateValidate") + EXPORT SYMBOL("uncompress2") + +ENDPGMEXP diff --git a/third_party/zlib/v1_2_11/os400/make.sh b/third_party/zlib/v1_2_11/os400/make.sh new file mode 100644 index 0000000..19eec11 --- /dev/null +++ b/third_party/zlib/v1_2_11/os400/make.sh @@ -0,0 +1,366 @@ +#!/bin/sh +# +# ZLIB compilation script for the OS/400. +# +# +# This is a shell script since make is not a standard component of OS/400. + + +################################################################################ +# +# Tunable configuration parameters. +# +################################################################################ + +TARGETLIB='ZLIB' # Target OS/400 program library +STATBNDDIR='ZLIB_A' # Static binding directory. +DYNBNDDIR='ZLIB' # Dynamic binding directory. +SRVPGM="ZLIB" # Service program. +IFSDIR='/zlib' # IFS support base directory. +TGTCCSID='500' # Target CCSID of objects +DEBUG='*NONE' # Debug level +OPTIMIZE='40' # Optimisation level +OUTPUT='*NONE' # Compilation output option. +TGTRLS='V6R1M0' # Target OS release + +export TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR +export TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS + + +################################################################################ +# +# OS/400 specific definitions. +# +################################################################################ + +LIBIFSNAME="/QSYS.LIB/${TARGETLIB}.LIB" + + +################################################################################ +# +# Procedures. +# +################################################################################ + +# action_needed dest [src] +# +# dest is an object to build +# if specified, src is an object on which dest depends. +# +# exit 0 (succeeds) if some action has to be taken, else 1. + +action_needed() + +{ + [ ! -e "${1}" ] && return 0 + [ "${2}" ] || return 1 + [ "${1}" -ot "${2}" ] && return 0 + return 1 +} + + +# make_module module_name source_name [additional_definitions] +# +# Compile source name into module if needed. +# As side effect, append the module name to variable MODULES. +# Set LINK to "YES" if the module has been compiled. + +make_module() + +{ + MODULES="${MODULES} ${1}" + MODIFSNAME="${LIBIFSNAME}/${1}.MODULE" + CSRC="`basename \"${2}\"`" + + if action_needed "${MODIFSNAME}" "${2}" + then : + elif [ ! "`sed -e \"//,/<\\\\/source>/!d\" \ + -e '/ tmphdrfile + + # Need to translate to target CCSID. + + CMD="CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')" + CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" + system "${CMD}" + # touch -r "${HFILE}" "${DEST}" + rm -f tmphdrfile + fi + + IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" + + if action_needed "${IFSFILE}" "${DEST}" + then rm -f "${IFSFILE}" + ln -s "${DEST}" "${IFSFILE}" + fi +done + + +# Install the ILE/RPG header file. + + +HFILE="${SCRIPTDIR}/zlib.inc" +DEST="${SRCPF}/ZLIB.INC.MBR" + +if action_needed "${DEST}" "${HFILE}" +then CMD="CPY OBJ('${HFILE}') TOOBJ('${DEST}')" + CMD="${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)" + system "${CMD}" + # touch -r "${HFILE}" "${DEST}" +fi + +IFSFILE="${IFSDIR}/include/`basename \"${HFILE}\"`" + +if action_needed "${IFSFILE}" "${DEST}" +then rm -f "${IFSFILE}" + ln -s "${DEST}" "${IFSFILE}" +fi + + +# Create and compile the identification source file. + +echo '#pragma comment(user, "ZLIB version '"${VERSION}"'")' > os400.c +echo '#pragma comment(user, __DATE__)' >> os400.c +echo '#pragma comment(user, __TIME__)' >> os400.c +echo '#pragma comment(copyright, "Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.")' >> os400.c +make_module OS400 os400.c +LINK= # No need to rebuild service program yet. +MODULES= + + +# Get source list. + +CSOURCES=`sed -e '/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Library + + Medium + + 2.0 + + + + zlib + zlib + alain.bonnefoy@icbt.com + Public + public + www.gzip.org/zlib + + + Jean-Loup Gailly,Mark Adler + www.gzip.org/zlib + + zlib@gzip.org + + + A massively spiffy yet delicately unobtrusive compression library. + zlib is designed to be a free, general-purpose, legally unencumbered, lossless data compression library for use on virtually any computer hardware and operating system. + http://www.gzip.org/zlib + + + + + 1.2.11 + Medium + Stable + + + + + + + No License + + + + Software Development/Libraries and Extensions/C Libraries + zlib,compression + qnx6 + qnx6 + None + Developer + + + + + + + + + + + + + + Install + Post + No + Ignore + + No + Optional + + + + + + + + + + + + + InstallOver + zlib + + + + + + + + + + + + + InstallOver + zlib-dev + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/test/example.c b/third_party/zlib/v1_2_11/test/example.c new file mode 100644 index 0000000..eee17ce --- /dev/null +++ b/third_party/zlib/v1_2_11/test/example.c @@ -0,0 +1,602 @@ +/* example.c -- usage example of the zlib compression library + * Copyright (C) 1995-2006, 2011, 2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zlib.h" +#include + +#ifdef STDC +# include +# include +#endif + +#if defined(VMS) || defined(RISCOS) +# define TESTFILE "foo-gz" +#else +# define TESTFILE "foo.gz" +#endif + +#define CHECK_ERR(err, msg) { \ + if (err != Z_OK) { \ + fprintf(stderr, "%s error: %d\n", msg, err); \ + exit(1); \ + } \ +} + +static z_const char hello[] = "hello, hello!"; +/* "hello world" would be more standard, but the repeated "hello" + * stresses the compression code better, sorry... + */ + +static const char dictionary[] = "hello"; +static uLong dictId; /* Adler32 value of the dictionary */ + +void test_deflate OF((Byte *compr, uLong comprLen)); +void test_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_large_deflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_large_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_flush OF((Byte *compr, uLong *comprLen)); +void test_sync OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_dict_deflate OF((Byte *compr, uLong comprLen)); +void test_dict_inflate OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +int main OF((int argc, char *argv[])); + + +#ifdef Z_SOLO + +void *myalloc OF((void *, unsigned, unsigned)); +void myfree OF((void *, void *)); + +void *myalloc(q, n, m) + void *q; + unsigned n, m; +{ + (void)q; + return calloc(n, m); +} + +void myfree(void *q, void *p) +{ + (void)q; + free(p); +} + +static alloc_func zalloc = myalloc; +static free_func zfree = myfree; + +#else /* !Z_SOLO */ + +static alloc_func zalloc = (alloc_func)0; +static free_func zfree = (free_func)0; + +void test_compress OF((Byte *compr, uLong comprLen, + Byte *uncompr, uLong uncomprLen)); +void test_gzio OF((const char *fname, + Byte *uncompr, uLong uncomprLen)); + +/* =========================================================================== + * Test compress() and uncompress() + */ +void test_compress(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + uLong len = (uLong)strlen(hello)+1; + + err = compress(compr, &comprLen, (const Bytef*)hello, len); + CHECK_ERR(err, "compress"); + + strcpy((char*)uncompr, "garbage"); + + err = uncompress(uncompr, &uncomprLen, compr, comprLen); + CHECK_ERR(err, "uncompress"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad uncompress\n"); + exit(1); + } else { + printf("uncompress(): %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Test read/write of .gz files + */ +void test_gzio(fname, uncompr, uncomprLen) + const char *fname; /* compressed file name */ + Byte *uncompr; + uLong uncomprLen; +{ +#ifdef NO_GZCOMPRESS + fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); +#else + int err; + int len = (int)strlen(hello)+1; + gzFile file; + z_off_t pos; + + file = gzopen(fname, "wb"); + if (file == NULL) { + fprintf(stderr, "gzopen error\n"); + exit(1); + } + gzputc(file, 'h'); + if (gzputs(file, "ello") != 4) { + fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); + exit(1); + } + if (gzprintf(file, ", %s!", "hello") != 8) { + fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); + exit(1); + } + gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ + gzclose(file); + + file = gzopen(fname, "rb"); + if (file == NULL) { + fprintf(stderr, "gzopen error\n"); + exit(1); + } + strcpy((char*)uncompr, "garbage"); + + if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { + fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); + exit(1); + } + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); + exit(1); + } else { + printf("gzread(): %s\n", (char*)uncompr); + } + + pos = gzseek(file, -8L, SEEK_CUR); + if (pos != 6 || gztell(file) != pos) { + fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", + (long)pos, (long)gztell(file)); + exit(1); + } + + if (gzgetc(file) != ' ') { + fprintf(stderr, "gzgetc error\n"); + exit(1); + } + + if (gzungetc(' ', file) != ' ') { + fprintf(stderr, "gzungetc error\n"); + exit(1); + } + + gzgets(file, (char*)uncompr, (int)uncomprLen); + if (strlen((char*)uncompr) != 7) { /* " hello!" */ + fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); + exit(1); + } + if (strcmp((char*)uncompr, hello + 6)) { + fprintf(stderr, "bad gzgets after gzseek\n"); + exit(1); + } else { + printf("gzgets() after gzseek: %s\n", (char*)uncompr); + } + + gzclose(file); +#endif +} + +#endif /* Z_SOLO */ + +/* =========================================================================== + * Test deflate() with small buffers + */ +void test_deflate(compr, comprLen) + Byte *compr; + uLong comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + uLong len = (uLong)strlen(hello)+1; + + c_stream.zalloc = zalloc; + c_stream.zfree = zfree; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_in = (z_const unsigned char *)hello; + c_stream.next_out = compr; + + while (c_stream.total_in != len && c_stream.total_out < comprLen) { + c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + } + /* Finish the stream, still forcing small buffers: */ + for (;;) { + c_stream.avail_out = 1; + err = deflate(&c_stream, Z_FINISH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "deflate"); + } + + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with small buffers + */ +void test_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = zalloc; + d_stream.zfree = zfree; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = 0; + d_stream.next_out = uncompr; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { + d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "inflate"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad inflate\n"); + exit(1); + } else { + printf("inflate(): %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Test deflate() with large buffers and dynamic change of compression level + */ +void test_large_deflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + + c_stream.zalloc = zalloc; + c_stream.zfree = zfree; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_BEST_SPEED); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_out = compr; + c_stream.avail_out = (uInt)comprLen; + + /* At this point, uncompr is still mostly zeroes, so it should compress + * very well: + */ + c_stream.next_in = uncompr; + c_stream.avail_in = (uInt)uncomprLen; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + if (c_stream.avail_in != 0) { + fprintf(stderr, "deflate not greedy\n"); + exit(1); + } + + /* Feed in already compressed data and switch to no compression: */ + deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); + c_stream.next_in = compr; + c_stream.avail_in = (uInt)comprLen/2; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + + /* Switch back to compressing mode: */ + deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); + c_stream.next_in = uncompr; + c_stream.avail_in = (uInt)uncomprLen; + err = deflate(&c_stream, Z_NO_FLUSH); + CHECK_ERR(err, "deflate"); + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + fprintf(stderr, "deflate should report Z_STREAM_END\n"); + exit(1); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with large buffers + */ +void test_large_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = zalloc; + d_stream.zfree = zfree; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = (uInt)comprLen; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + for (;;) { + d_stream.next_out = uncompr; /* discard the output */ + d_stream.avail_out = (uInt)uncomprLen; + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + CHECK_ERR(err, "large inflate"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (d_stream.total_out != 2*uncomprLen + comprLen/2) { + fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); + exit(1); + } else { + printf("large_inflate(): OK\n"); + } +} + +/* =========================================================================== + * Test deflate() with full flush + */ +void test_flush(compr, comprLen) + Byte *compr; + uLong *comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + uInt len = (uInt)strlen(hello)+1; + + c_stream.zalloc = zalloc; + c_stream.zfree = zfree; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + c_stream.next_in = (z_const unsigned char *)hello; + c_stream.next_out = compr; + c_stream.avail_in = 3; + c_stream.avail_out = (uInt)*comprLen; + err = deflate(&c_stream, Z_FULL_FLUSH); + CHECK_ERR(err, "deflate"); + + compr[3]++; /* force an error in first compressed block */ + c_stream.avail_in = len - 3; + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + CHECK_ERR(err, "deflate"); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); + + *comprLen = c_stream.total_out; +} + +/* =========================================================================== + * Test inflateSync() + */ +void test_sync(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = zalloc; + d_stream.zfree = zfree; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = 2; /* just read the zlib header */ + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + d_stream.next_out = uncompr; + d_stream.avail_out = (uInt)uncomprLen; + + err = inflate(&d_stream, Z_NO_FLUSH); + CHECK_ERR(err, "inflate"); + + d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ + err = inflateSync(&d_stream); /* but skip the damaged part */ + CHECK_ERR(err, "inflateSync"); + + err = inflate(&d_stream, Z_FINISH); + if (err != Z_DATA_ERROR) { + fprintf(stderr, "inflate should report DATA_ERROR\n"); + /* Because of incorrect adler32 */ + exit(1); + } + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + printf("after inflateSync(): hel%s\n", (char *)uncompr); +} + +/* =========================================================================== + * Test deflate() with preset dictionary + */ +void test_dict_deflate(compr, comprLen) + Byte *compr; + uLong comprLen; +{ + z_stream c_stream; /* compression stream */ + int err; + + c_stream.zalloc = zalloc; + c_stream.zfree = zfree; + c_stream.opaque = (voidpf)0; + + err = deflateInit(&c_stream, Z_BEST_COMPRESSION); + CHECK_ERR(err, "deflateInit"); + + err = deflateSetDictionary(&c_stream, + (const Bytef*)dictionary, (int)sizeof(dictionary)); + CHECK_ERR(err, "deflateSetDictionary"); + + dictId = c_stream.adler; + c_stream.next_out = compr; + c_stream.avail_out = (uInt)comprLen; + + c_stream.next_in = (z_const unsigned char *)hello; + c_stream.avail_in = (uInt)strlen(hello)+1; + + err = deflate(&c_stream, Z_FINISH); + if (err != Z_STREAM_END) { + fprintf(stderr, "deflate should report Z_STREAM_END\n"); + exit(1); + } + err = deflateEnd(&c_stream); + CHECK_ERR(err, "deflateEnd"); +} + +/* =========================================================================== + * Test inflate() with a preset dictionary + */ +void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) + Byte *compr, *uncompr; + uLong comprLen, uncomprLen; +{ + int err; + z_stream d_stream; /* decompression stream */ + + strcpy((char*)uncompr, "garbage"); + + d_stream.zalloc = zalloc; + d_stream.zfree = zfree; + d_stream.opaque = (voidpf)0; + + d_stream.next_in = compr; + d_stream.avail_in = (uInt)comprLen; + + err = inflateInit(&d_stream); + CHECK_ERR(err, "inflateInit"); + + d_stream.next_out = uncompr; + d_stream.avail_out = (uInt)uncomprLen; + + for (;;) { + err = inflate(&d_stream, Z_NO_FLUSH); + if (err == Z_STREAM_END) break; + if (err == Z_NEED_DICT) { + if (d_stream.adler != dictId) { + fprintf(stderr, "unexpected dictionary"); + exit(1); + } + err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, + (int)sizeof(dictionary)); + } + CHECK_ERR(err, "inflate with dict"); + } + + err = inflateEnd(&d_stream); + CHECK_ERR(err, "inflateEnd"); + + if (strcmp((char*)uncompr, hello)) { + fprintf(stderr, "bad inflate with dict\n"); + exit(1); + } else { + printf("inflate with dictionary: %s\n", (char *)uncompr); + } +} + +/* =========================================================================== + * Usage: example [output.gz [input.gz]] + */ + +int main(argc, argv) + int argc; + char *argv[]; +{ + Byte *compr, *uncompr; + uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ + uLong uncomprLen = comprLen; + static const char* myVersion = ZLIB_VERSION; + + if (zlibVersion()[0] != myVersion[0]) { + fprintf(stderr, "incompatible zlib version\n"); + exit(1); + + } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { + fprintf(stderr, "warning: different zlib version\n"); + } + + printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", + ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); + + compr = (Byte*)calloc((uInt)comprLen, 1); + uncompr = (Byte*)calloc((uInt)uncomprLen, 1); + /* compr and uncompr are cleared to avoid reading uninitialized + * data and to ensure that uncompr compresses well. + */ + if (compr == Z_NULL || uncompr == Z_NULL) { + printf("out of memory\n"); + exit(1); + } + +#ifdef Z_SOLO + (void)argc; + (void)argv; +#else + test_compress(compr, comprLen, uncompr, uncomprLen); + + test_gzio((argc > 1 ? argv[1] : TESTFILE), + uncompr, uncomprLen); +#endif + + test_deflate(compr, comprLen); + test_inflate(compr, comprLen, uncompr, uncomprLen); + + test_large_deflate(compr, comprLen, uncompr, uncomprLen); + test_large_inflate(compr, comprLen, uncompr, uncomprLen); + + test_flush(compr, &comprLen); + test_sync(compr, comprLen, uncompr, uncomprLen); + comprLen = uncomprLen; + + test_dict_deflate(compr, comprLen); + test_dict_inflate(compr, comprLen, uncompr, uncomprLen); + + free(compr); + free(uncompr); + + return 0; +} diff --git a/third_party/zlib/v1_2_11/test/infcover.c b/third_party/zlib/v1_2_11/test/infcover.c new file mode 100644 index 0000000..2be0164 --- /dev/null +++ b/third_party/zlib/v1_2_11/test/infcover.c @@ -0,0 +1,671 @@ +/* infcover.c -- test zlib's inflate routines with full code coverage + * Copyright (C) 2011, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* to use, do: ./configure --cover && make cover */ + +#include +#include +#include +#include +#include "zlib.h" + +/* get definition of internal structure so we can mess with it (see pull()), + and so we can call inflate_trees() (see cover5()) */ +#define ZLIB_INTERNAL +#include "inftrees.h" +#include "inflate.h" + +#define local static + +/* -- memory tracking routines -- */ + +/* + These memory tracking routines are provided to zlib and track all of zlib's + allocations and deallocations, check for LIFO operations, keep a current + and high water mark of total bytes requested, optionally set a limit on the + total memory that can be allocated, and when done check for memory leaks. + + They are used as follows: + + z_stream strm; + mem_setup(&strm) initializes the memory tracking and sets the + zalloc, zfree, and opaque members of strm to use + memory tracking for all zlib operations on strm + mem_limit(&strm, limit) sets a limit on the total bytes requested -- a + request that exceeds this limit will result in an + allocation failure (returns NULL) -- setting the + limit to zero means no limit, which is the default + after mem_setup() + mem_used(&strm, "msg") prints to stderr "msg" and the total bytes used + mem_high(&strm, "msg") prints to stderr "msg" and the high water mark + mem_done(&strm, "msg") ends memory tracking, releases all allocations + for the tracking as well as leaked zlib blocks, if + any. If there was anything unusual, such as leaked + blocks, non-FIFO frees, or frees of addresses not + allocated, then "msg" and information about the + problem is printed to stderr. If everything is + normal, nothing is printed. mem_done resets the + strm members to Z_NULL to use the default memory + allocation routines on the next zlib initialization + using strm. + */ + +/* these items are strung together in a linked list, one for each allocation */ +struct mem_item { + void *ptr; /* pointer to allocated memory */ + size_t size; /* requested size of allocation */ + struct mem_item *next; /* pointer to next item in list, or NULL */ +}; + +/* this structure is at the root of the linked list, and tracks statistics */ +struct mem_zone { + struct mem_item *first; /* pointer to first item in list, or NULL */ + size_t total, highwater; /* total allocations, and largest total */ + size_t limit; /* memory allocation limit, or 0 if no limit */ + int notlifo, rogue; /* counts of non-LIFO frees and rogue frees */ +}; + +/* memory allocation routine to pass to zlib */ +local void *mem_alloc(void *mem, unsigned count, unsigned size) +{ + void *ptr; + struct mem_item *item; + struct mem_zone *zone = mem; + size_t len = count * (size_t)size; + + /* induced allocation failure */ + if (zone == NULL || (zone->limit && zone->total + len > zone->limit)) + return NULL; + + /* perform allocation using the standard library, fill memory with a + non-zero value to make sure that the code isn't depending on zeros */ + ptr = malloc(len); + if (ptr == NULL) + return NULL; + memset(ptr, 0xa5, len); + + /* create a new item for the list */ + item = malloc(sizeof(struct mem_item)); + if (item == NULL) { + free(ptr); + return NULL; + } + item->ptr = ptr; + item->size = len; + + /* insert item at the beginning of the list */ + item->next = zone->first; + zone->first = item; + + /* update the statistics */ + zone->total += item->size; + if (zone->total > zone->highwater) + zone->highwater = zone->total; + + /* return the allocated memory */ + return ptr; +} + +/* memory free routine to pass to zlib */ +local void mem_free(void *mem, void *ptr) +{ + struct mem_item *item, *next; + struct mem_zone *zone = mem; + + /* if no zone, just do a free */ + if (zone == NULL) { + free(ptr); + return; + } + + /* point next to the item that matches ptr, or NULL if not found -- remove + the item from the linked list if found */ + next = zone->first; + if (next) { + if (next->ptr == ptr) + zone->first = next->next; /* first one is it, remove from list */ + else { + do { /* search the linked list */ + item = next; + next = item->next; + } while (next != NULL && next->ptr != ptr); + if (next) { /* if found, remove from linked list */ + item->next = next->next; + zone->notlifo++; /* not a LIFO free */ + } + + } + } + + /* if found, update the statistics and free the item */ + if (next) { + zone->total -= next->size; + free(next); + } + + /* if not found, update the rogue count */ + else + zone->rogue++; + + /* in any case, do the requested free with the standard library function */ + free(ptr); +} + +/* set up a controlled memory allocation space for monitoring, set the stream + parameters to the controlled routines, with opaque pointing to the space */ +local void mem_setup(z_stream *strm) +{ + struct mem_zone *zone; + + zone = malloc(sizeof(struct mem_zone)); + assert(zone != NULL); + zone->first = NULL; + zone->total = 0; + zone->highwater = 0; + zone->limit = 0; + zone->notlifo = 0; + zone->rogue = 0; + strm->opaque = zone; + strm->zalloc = mem_alloc; + strm->zfree = mem_free; +} + +/* set a limit on the total memory allocation, or 0 to remove the limit */ +local void mem_limit(z_stream *strm, size_t limit) +{ + struct mem_zone *zone = strm->opaque; + + zone->limit = limit; +} + +/* show the current total requested allocations in bytes */ +local void mem_used(z_stream *strm, char *prefix) +{ + struct mem_zone *zone = strm->opaque; + + fprintf(stderr, "%s: %lu allocated\n", prefix, zone->total); +} + +/* show the high water allocation in bytes */ +local void mem_high(z_stream *strm, char *prefix) +{ + struct mem_zone *zone = strm->opaque; + + fprintf(stderr, "%s: %lu high water mark\n", prefix, zone->highwater); +} + +/* release the memory allocation zone -- if there are any surprises, notify */ +local void mem_done(z_stream *strm, char *prefix) +{ + int count = 0; + struct mem_item *item, *next; + struct mem_zone *zone = strm->opaque; + + /* show high water mark */ + mem_high(strm, prefix); + + /* free leftover allocations and item structures, if any */ + item = zone->first; + while (item != NULL) { + free(item->ptr); + next = item->next; + free(item); + item = next; + count++; + } + + /* issue alerts about anything unexpected */ + if (count || zone->total) + fprintf(stderr, "** %s: %lu bytes in %d blocks not freed\n", + prefix, zone->total, count); + if (zone->notlifo) + fprintf(stderr, "** %s: %d frees not LIFO\n", prefix, zone->notlifo); + if (zone->rogue) + fprintf(stderr, "** %s: %d frees not recognized\n", + prefix, zone->rogue); + + /* free the zone and delete from the stream */ + free(zone); + strm->opaque = Z_NULL; + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; +} + +/* -- inflate test routines -- */ + +/* Decode a hexadecimal string, set *len to length, in[] to the bytes. This + decodes liberally, in that hex digits can be adjacent, in which case two in + a row writes a byte. Or they can be delimited by any non-hex character, + where the delimiters are ignored except when a single hex digit is followed + by a delimiter, where that single digit writes a byte. The returned data is + allocated and must eventually be freed. NULL is returned if out of memory. + If the length is not needed, then len can be NULL. */ +local unsigned char *h2b(const char *hex, unsigned *len) +{ + unsigned char *in, *re; + unsigned next, val; + + in = malloc((strlen(hex) + 1) >> 1); + if (in == NULL) + return NULL; + next = 0; + val = 1; + do { + if (*hex >= '0' && *hex <= '9') + val = (val << 4) + *hex - '0'; + else if (*hex >= 'A' && *hex <= 'F') + val = (val << 4) + *hex - 'A' + 10; + else if (*hex >= 'a' && *hex <= 'f') + val = (val << 4) + *hex - 'a' + 10; + else if (val != 1 && val < 32) /* one digit followed by delimiter */ + val += 240; /* make it look like two digits */ + if (val > 255) { /* have two digits */ + in[next++] = val & 0xff; /* save the decoded byte */ + val = 1; /* start over */ + } + } while (*hex++); /* go through the loop with the terminating null */ + if (len != NULL) + *len = next; + re = realloc(in, next); + return re == NULL ? in : re; +} + +/* generic inflate() run, where hex is the hexadecimal input data, what is the + text to include in an error message, step is how much input data to feed + inflate() on each call, or zero to feed it all, win is the window bits + parameter to inflateInit2(), len is the size of the output buffer, and err + is the error code expected from the first inflate() call (the second + inflate() call is expected to return Z_STREAM_END). If win is 47, then + header information is collected with inflateGetHeader(). If a zlib stream + is looking for a dictionary, then an empty dictionary is provided. + inflate() is run until all of the input data is consumed. */ +local void inf(char *hex, char *what, unsigned step, int win, unsigned len, + int err) +{ + int ret; + unsigned have; + unsigned char *in, *out; + z_stream strm, copy; + gz_header head; + + mem_setup(&strm); + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, win); + if (ret != Z_OK) { + mem_done(&strm, what); + return; + } + out = malloc(len); assert(out != NULL); + if (win == 47) { + head.extra = out; + head.extra_max = len; + head.name = out; + head.name_max = len; + head.comment = out; + head.comm_max = len; + ret = inflateGetHeader(&strm, &head); assert(ret == Z_OK); + } + in = h2b(hex, &have); assert(in != NULL); + if (step == 0 || step > have) + step = have; + strm.avail_in = step; + have -= step; + strm.next_in = in; + do { + strm.avail_out = len; + strm.next_out = out; + ret = inflate(&strm, Z_NO_FLUSH); assert(err == 9 || ret == err); + if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_NEED_DICT) + break; + if (ret == Z_NEED_DICT) { + ret = inflateSetDictionary(&strm, in, 1); + assert(ret == Z_DATA_ERROR); + mem_limit(&strm, 1); + ret = inflateSetDictionary(&strm, out, 0); + assert(ret == Z_MEM_ERROR); + mem_limit(&strm, 0); + ((struct inflate_state *)strm.state)->mode = DICT; + ret = inflateSetDictionary(&strm, out, 0); + assert(ret == Z_OK); + ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_BUF_ERROR); + } + ret = inflateCopy(©, &strm); assert(ret == Z_OK); + ret = inflateEnd(©); assert(ret == Z_OK); + err = 9; /* don't care next time around */ + have += strm.avail_in; + strm.avail_in = step > have ? have : step; + have -= strm.avail_in; + } while (strm.avail_in); + free(in); + free(out); + ret = inflateReset2(&strm, -8); assert(ret == Z_OK); + ret = inflateEnd(&strm); assert(ret == Z_OK); + mem_done(&strm, what); +} + +/* cover all of the lines in inflate.c up to inflate() */ +local void cover_support(void) +{ + int ret; + z_stream strm; + + mem_setup(&strm); + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit(&strm); assert(ret == Z_OK); + mem_used(&strm, "inflate init"); + ret = inflatePrime(&strm, 5, 31); assert(ret == Z_OK); + ret = inflatePrime(&strm, -1, 0); assert(ret == Z_OK); + ret = inflateSetDictionary(&strm, Z_NULL, 0); + assert(ret == Z_STREAM_ERROR); + ret = inflateEnd(&strm); assert(ret == Z_OK); + mem_done(&strm, "prime"); + + inf("63 0", "force window allocation", 0, -15, 1, Z_OK); + inf("63 18 5", "force window replacement", 0, -8, 259, Z_OK); + inf("63 18 68 30 d0 0 0", "force split window update", 4, -8, 259, Z_OK); + inf("3 0", "use fixed blocks", 0, -15, 1, Z_STREAM_END); + inf("", "bad window size", 0, 1, 0, Z_STREAM_ERROR); + + mem_setup(&strm); + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit_(&strm, ZLIB_VERSION - 1, (int)sizeof(z_stream)); + assert(ret == Z_VERSION_ERROR); + mem_done(&strm, "wrong version"); + + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit(&strm); assert(ret == Z_OK); + ret = inflateEnd(&strm); assert(ret == Z_OK); + fputs("inflate built-in memory routines\n", stderr); +} + +/* cover all inflate() header and trailer cases and code after inflate() */ +local void cover_wrap(void) +{ + int ret; + z_stream strm, copy; + unsigned char dict[257]; + + ret = inflate(Z_NULL, 0); assert(ret == Z_STREAM_ERROR); + ret = inflateEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); + ret = inflateCopy(Z_NULL, Z_NULL); assert(ret == Z_STREAM_ERROR); + fputs("inflate bad parameters\n", stderr); + + inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR); + inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR); + inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR); + inf("8 99", "set window size from header", 0, 0, 0, Z_OK); + inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR); + inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END); + inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1, + Z_DATA_ERROR); + inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length", + 0, 47, 0, Z_STREAM_END); + inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR); + inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT); + inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK); + + mem_setup(&strm); + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, -8); + strm.avail_in = 2; + strm.next_in = (void *)"\x63"; + strm.avail_out = 1; + strm.next_out = (void *)&ret; + mem_limit(&strm, 1); + ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); + ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_MEM_ERROR); + mem_limit(&strm, 0); + memset(dict, 0, 257); + ret = inflateSetDictionary(&strm, dict, 257); + assert(ret == Z_OK); + mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256); + ret = inflatePrime(&strm, 16, 0); assert(ret == Z_OK); + strm.avail_in = 2; + strm.next_in = (void *)"\x80"; + ret = inflateSync(&strm); assert(ret == Z_DATA_ERROR); + ret = inflate(&strm, Z_NO_FLUSH); assert(ret == Z_STREAM_ERROR); + strm.avail_in = 4; + strm.next_in = (void *)"\0\0\xff\xff"; + ret = inflateSync(&strm); assert(ret == Z_OK); + (void)inflateSyncPoint(&strm); + ret = inflateCopy(©, &strm); assert(ret == Z_MEM_ERROR); + mem_limit(&strm, 0); + ret = inflateUndermine(&strm, 1); assert(ret == Z_DATA_ERROR); + (void)inflateMark(&strm); + ret = inflateEnd(&strm); assert(ret == Z_OK); + mem_done(&strm, "miscellaneous, force memory errors"); +} + +/* input and output functions for inflateBack() */ +local unsigned pull(void *desc, unsigned char **buf) +{ + static unsigned int next = 0; + static unsigned char dat[] = {0x63, 0, 2, 0}; + struct inflate_state *state; + + if (desc == Z_NULL) { + next = 0; + return 0; /* no input (already provided at next_in) */ + } + state = (void *)((z_stream *)desc)->state; + if (state != Z_NULL) + state->mode = SYNC; /* force an otherwise impossible situation */ + return next < sizeof(dat) ? (*buf = dat + next++, 1) : 0; +} + +local int push(void *desc, unsigned char *buf, unsigned len) +{ + buf += len; + return desc != Z_NULL; /* force error if desc not null */ +} + +/* cover inflateBack() up to common deflate data cases and after those */ +local void cover_back(void) +{ + int ret; + z_stream strm; + unsigned char win[32768]; + + ret = inflateBackInit_(Z_NULL, 0, win, 0, 0); + assert(ret == Z_VERSION_ERROR); + ret = inflateBackInit(Z_NULL, 0, win); assert(ret == Z_STREAM_ERROR); + ret = inflateBack(Z_NULL, Z_NULL, Z_NULL, Z_NULL, Z_NULL); + assert(ret == Z_STREAM_ERROR); + ret = inflateBackEnd(Z_NULL); assert(ret == Z_STREAM_ERROR); + fputs("inflateBack bad parameters\n", stderr); + + mem_setup(&strm); + ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); + strm.avail_in = 2; + strm.next_in = (void *)"\x03"; + ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); + assert(ret == Z_STREAM_END); + /* force output error */ + strm.avail_in = 3; + strm.next_in = (void *)"\x63\x00"; + ret = inflateBack(&strm, pull, Z_NULL, push, &strm); + assert(ret == Z_BUF_ERROR); + /* force mode error by mucking with state */ + ret = inflateBack(&strm, pull, &strm, push, Z_NULL); + assert(ret == Z_STREAM_ERROR); + ret = inflateBackEnd(&strm); assert(ret == Z_OK); + mem_done(&strm, "inflateBack bad state"); + + ret = inflateBackInit(&strm, 15, win); assert(ret == Z_OK); + ret = inflateBackEnd(&strm); assert(ret == Z_OK); + fputs("inflateBack built-in memory routines\n", stderr); +} + +/* do a raw inflate of data in hexadecimal with both inflate and inflateBack */ +local int try(char *hex, char *id, int err) +{ + int ret; + unsigned len, size; + unsigned char *in, *out, *win; + char *prefix; + z_stream strm; + + /* convert to hex */ + in = h2b(hex, &len); + assert(in != NULL); + + /* allocate work areas */ + size = len << 3; + out = malloc(size); + assert(out != NULL); + win = malloc(32768); + assert(win != NULL); + prefix = malloc(strlen(id) + 6); + assert(prefix != NULL); + + /* first with inflate */ + strcpy(prefix, id); + strcat(prefix, "-late"); + mem_setup(&strm); + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit2(&strm, err < 0 ? 47 : -15); + assert(ret == Z_OK); + strm.avail_in = len; + strm.next_in = in; + do { + strm.avail_out = size; + strm.next_out = out; + ret = inflate(&strm, Z_TREES); + assert(ret != Z_STREAM_ERROR && ret != Z_MEM_ERROR); + if (ret == Z_DATA_ERROR || ret == Z_NEED_DICT) + break; + } while (strm.avail_in || strm.avail_out == 0); + if (err) { + assert(ret == Z_DATA_ERROR); + assert(strcmp(id, strm.msg) == 0); + } + inflateEnd(&strm); + mem_done(&strm, prefix); + + /* then with inflateBack */ + if (err >= 0) { + strcpy(prefix, id); + strcat(prefix, "-back"); + mem_setup(&strm); + ret = inflateBackInit(&strm, 15, win); + assert(ret == Z_OK); + strm.avail_in = len; + strm.next_in = in; + ret = inflateBack(&strm, pull, Z_NULL, push, Z_NULL); + assert(ret != Z_STREAM_ERROR); + if (err) { + assert(ret == Z_DATA_ERROR); + assert(strcmp(id, strm.msg) == 0); + } + inflateBackEnd(&strm); + mem_done(&strm, prefix); + } + + /* clean up */ + free(prefix); + free(win); + free(out); + free(in); + return ret; +} + +/* cover deflate data cases in both inflate() and inflateBack() */ +local void cover_inflate(void) +{ + try("0 0 0 0 0", "invalid stored block lengths", 1); + try("3 0", "fixed", 0); + try("6", "invalid block type", 1); + try("1 1 0 fe ff 0", "stored", 0); + try("fc 0 0", "too many length or distance symbols", 1); + try("4 0 fe ff", "invalid code lengths set", 1); + try("4 0 24 49 0", "invalid bit length repeat", 1); + try("4 0 24 e9 ff ff", "invalid bit length repeat", 1); + try("4 0 24 e9 ff 6d", "invalid code -- missing end-of-block", 1); + try("4 80 49 92 24 49 92 24 71 ff ff 93 11 0", + "invalid literal/lengths set", 1); + try("4 80 49 92 24 49 92 24 f b4 ff ff c3 84", "invalid distances set", 1); + try("4 c0 81 8 0 0 0 0 20 7f eb b 0 0", "invalid literal/length code", 1); + try("2 7e ff ff", "invalid distance code", 1); + try("c c0 81 0 0 0 0 0 90 ff 6b 4 0", "invalid distance too far back", 1); + + /* also trailer mismatch just in inflate() */ + try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 1", "incorrect data check", -1); + try("1f 8b 8 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 1", + "incorrect length check", -1); + try("5 c0 21 d 0 0 0 80 b0 fe 6d 2f 91 6c", "pull 17", 0); + try("5 e0 81 91 24 cb b2 2c 49 e2 f 2e 8b 9a 47 56 9f fb fe ec d2 ff 1f", + "long code", 0); + try("ed c0 1 1 0 0 0 40 20 ff 57 1b 42 2c 4f", "length extra", 0); + try("ed cf c1 b1 2c 47 10 c4 30 fa 6f 35 1d 1 82 59 3d fb be 2e 2a fc f c", + "long distance and extra", 0); + try("ed c0 81 0 0 0 0 80 a0 fd a9 17 a9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 " + "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6", "window end", 0); + inf("2 8 20 80 0 3 0", "inflate_fast TYPE return", 0, -15, 258, + Z_STREAM_END); + inf("63 18 5 40 c 0", "window wrap", 3, -8, 300, Z_OK); +} + +/* cover remaining lines in inftrees.c */ +local void cover_trees(void) +{ + int ret; + unsigned bits; + unsigned short lens[16], work[16]; + code *next, table[ENOUGH_DISTS]; + + /* we need to call inflate_table() directly in order to manifest not- + enough errors, since zlib insures that enough is always enough */ + for (bits = 0; bits < 15; bits++) + lens[bits] = (unsigned short)(bits + 1); + lens[15] = 15; + next = table; + bits = 15; + ret = inflate_table(DISTS, lens, 16, &next, &bits, work); + assert(ret == 1); + next = table; + bits = 1; + ret = inflate_table(DISTS, lens, 16, &next, &bits, work); + assert(ret == 1); + fputs("inflate_table not enough errors\n", stderr); +} + +/* cover remaining inffast.c decoding and window copying */ +local void cover_fast(void) +{ + inf("e5 e0 81 ad 6d cb b2 2c c9 01 1e 59 63 ae 7d ee fb 4d fd b5 35 41 68" + " ff 7f 0f 0 0 0", "fast length extra bits", 0, -8, 258, Z_DATA_ERROR); + inf("25 fd 81 b5 6d 59 b6 6a 49 ea af 35 6 34 eb 8c b9 f6 b9 1e ef 67 49" + " 50 fe ff ff 3f 0 0", "fast distance extra bits", 0, -8, 258, + Z_DATA_ERROR); + inf("3 7e 0 0 0 0 0", "fast invalid distance code", 0, -8, 258, + Z_DATA_ERROR); + inf("1b 7 0 0 0 0 0", "fast invalid literal/length code", 0, -8, 258, + Z_DATA_ERROR); + inf("d c7 1 ae eb 38 c 4 41 a0 87 72 de df fb 1f b8 36 b1 38 5d ff ff 0", + "fast 2nd level codes and too far back", 0, -8, 258, Z_DATA_ERROR); + inf("63 18 5 8c 10 8 0 0 0 0", "very common case", 0, -8, 259, Z_OK); + inf("63 60 60 18 c9 0 8 18 18 18 26 c0 28 0 29 0 0 0", + "contiguous and wrap around window", 6, -8, 259, Z_OK); + inf("63 0 3 0 0 0 0 0", "copy direct from output", 0, -8, 259, + Z_STREAM_END); +} + +int main(void) +{ + fprintf(stderr, "%s\n", zlibVersion()); + cover_support(); + cover_wrap(); + cover_back(); + cover_inflate(); + cover_trees(); + cover_fast(); + return 0; +} diff --git a/third_party/zlib/v1_2_11/test/minigzip.c b/third_party/zlib/v1_2_11/test/minigzip.c new file mode 100644 index 0000000..e22fb08 --- /dev/null +++ b/third_party/zlib/v1_2_11/test/minigzip.c @@ -0,0 +1,651 @@ +/* minigzip.c -- simulate gzip using the zlib compression library + * Copyright (C) 1995-2006, 2010, 2011, 2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * minigzip is a minimal implementation of the gzip utility. This is + * only an example of using zlib and isn't meant to replace the + * full-featured gzip. No attempt is made to deal with file systems + * limiting names to 14 or 8+3 characters, etc... Error checking is + * very limited. So use minigzip only for testing; use gzip for the + * real thing. On MSDOS, use only on file names without extension + * or in pipe mode. + */ + +/* @(#) $Id$ */ + +#include "zlib.h" +#include + +#ifdef STDC +# include +# include +#endif + +#ifdef USE_MMAP +# include +# include +# include +#endif + +#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) +# include +# include +# ifdef UNDER_CE +# include +# endif +# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1900 +# define snprintf _snprintf +#endif + +#ifdef VMS +# define unlink delete +# define GZ_SUFFIX "-gz" +#endif +#ifdef RISCOS +# define unlink remove +# define GZ_SUFFIX "-gz" +# define fileno(file) file->__file +#endif +#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fileno */ +#endif + +#if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE) +#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ + extern int unlink OF((const char *)); +#endif +#endif + +#if defined(UNDER_CE) +# include +# define perror(s) pwinerror(s) + +/* Map the Windows error number in ERROR to a locale-dependent error + message string and return a pointer to it. Typically, the values + for ERROR come from GetLastError. + + The string pointed to shall not be modified by the application, + but may be overwritten by a subsequent call to strwinerror + + The strwinerror function does not change the current setting + of GetLastError. */ + +static char *strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +static void pwinerror (s) + const char *s; +{ + if (s && *s) + fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ())); + else + fprintf(stderr, "%s\n", strwinerror(GetLastError ())); +} + +#endif /* UNDER_CE */ + +#ifndef GZ_SUFFIX +# define GZ_SUFFIX ".gz" +#endif +#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) + +#define BUFLEN 16384 +#define MAX_NAME_LEN 1024 + +#ifdef MAXSEG_64K +# define local static + /* Needed for systems with limitation on stack size. */ +#else +# define local +#endif + +#ifdef Z_SOLO +/* for Z_SOLO, create simplified gz* functions using deflate and inflate */ + +#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE) +# include /* for unlink() */ +#endif + +void *myalloc OF((void *, unsigned, unsigned)); +void myfree OF((void *, void *)); + +void *myalloc(q, n, m) + void *q; + unsigned n, m; +{ + (void)q; + return calloc(n, m); +} + +void myfree(q, p) + void *q, *p; +{ + (void)q; + free(p); +} + +typedef struct gzFile_s { + FILE *file; + int write; + int err; + char *msg; + z_stream strm; +} *gzFile; + +gzFile gzopen OF((const char *, const char *)); +gzFile gzdopen OF((int, const char *)); +gzFile gz_open OF((const char *, int, const char *)); + +gzFile gzopen(path, mode) +const char *path; +const char *mode; +{ + return gz_open(path, -1, mode); +} + +gzFile gzdopen(fd, mode) +int fd; +const char *mode; +{ + return gz_open(NULL, fd, mode); +} + +gzFile gz_open(path, fd, mode) + const char *path; + int fd; + const char *mode; +{ + gzFile gz; + int ret; + + gz = malloc(sizeof(struct gzFile_s)); + if (gz == NULL) + return NULL; + gz->write = strchr(mode, 'w') != NULL; + gz->strm.zalloc = myalloc; + gz->strm.zfree = myfree; + gz->strm.opaque = Z_NULL; + if (gz->write) + ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0); + else { + gz->strm.next_in = 0; + gz->strm.avail_in = Z_NULL; + ret = inflateInit2(&(gz->strm), 15 + 16); + } + if (ret != Z_OK) { + free(gz); + return NULL; + } + gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") : + fopen(path, gz->write ? "wb" : "rb"); + if (gz->file == NULL) { + gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm)); + free(gz); + return NULL; + } + gz->err = 0; + gz->msg = ""; + return gz; +} + +int gzwrite OF((gzFile, const void *, unsigned)); + +int gzwrite(gz, buf, len) + gzFile gz; + const void *buf; + unsigned len; +{ + z_stream *strm; + unsigned char out[BUFLEN]; + + if (gz == NULL || !gz->write) + return 0; + strm = &(gz->strm); + strm->next_in = (void *)buf; + strm->avail_in = len; + do { + strm->next_out = out; + strm->avail_out = BUFLEN; + (void)deflate(strm, Z_NO_FLUSH); + fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); + } while (strm->avail_out == 0); + return len; +} + +int gzread OF((gzFile, void *, unsigned)); + +int gzread(gz, buf, len) + gzFile gz; + void *buf; + unsigned len; +{ + int ret; + unsigned got; + unsigned char in[1]; + z_stream *strm; + + if (gz == NULL || gz->write) + return 0; + if (gz->err) + return 0; + strm = &(gz->strm); + strm->next_out = (void *)buf; + strm->avail_out = len; + do { + got = fread(in, 1, 1, gz->file); + if (got == 0) + break; + strm->next_in = in; + strm->avail_in = 1; + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_DATA_ERROR) { + gz->err = Z_DATA_ERROR; + gz->msg = strm->msg; + return 0; + } + if (ret == Z_STREAM_END) + inflateReset(strm); + } while (strm->avail_out); + return len - strm->avail_out; +} + +int gzclose OF((gzFile)); + +int gzclose(gz) + gzFile gz; +{ + z_stream *strm; + unsigned char out[BUFLEN]; + + if (gz == NULL) + return Z_STREAM_ERROR; + strm = &(gz->strm); + if (gz->write) { + strm->next_in = Z_NULL; + strm->avail_in = 0; + do { + strm->next_out = out; + strm->avail_out = BUFLEN; + (void)deflate(strm, Z_FINISH); + fwrite(out, 1, BUFLEN - strm->avail_out, gz->file); + } while (strm->avail_out == 0); + deflateEnd(strm); + } + else + inflateEnd(strm); + fclose(gz->file); + free(gz); + return Z_OK; +} + +const char *gzerror OF((gzFile, int *)); + +const char *gzerror(gz, err) + gzFile gz; + int *err; +{ + *err = gz->err; + return gz->msg; +} + +#endif + +static char *prog; + +void error OF((const char *msg)); +void gz_compress OF((FILE *in, gzFile out)); +#ifdef USE_MMAP +int gz_compress_mmap OF((FILE *in, gzFile out)); +#endif +void gz_uncompress OF((gzFile in, FILE *out)); +void file_compress OF((char *file, char *mode)); +void file_uncompress OF((char *file)); +int main OF((int argc, char *argv[])); + +/* =========================================================================== + * Display error message and exit + */ +void error(msg) + const char *msg; +{ + fprintf(stderr, "%s: %s\n", prog, msg); + exit(1); +} + +/* =========================================================================== + * Compress input to output then close both files. + */ + +void gz_compress(in, out) + FILE *in; + gzFile out; +{ + local char buf[BUFLEN]; + int len; + int err; + +#ifdef USE_MMAP + /* Try first compressing with mmap. If mmap fails (minigzip used in a + * pipe), use the normal fread loop. + */ + if (gz_compress_mmap(in, out) == Z_OK) return; +#endif + for (;;) { + len = (int)fread(buf, 1, sizeof(buf), in); + if (ferror(in)) { + perror("fread"); + exit(1); + } + if (len == 0) break; + + if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); + } + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); +} + +#ifdef USE_MMAP /* MMAP version, Miguel Albrecht */ + +/* Try compressing the input file at once using mmap. Return Z_OK if + * if success, Z_ERRNO otherwise. + */ +int gz_compress_mmap(in, out) + FILE *in; + gzFile out; +{ + int len; + int err; + int ifd = fileno(in); + caddr_t buf; /* mmap'ed buffer for the entire input file */ + off_t buf_len; /* length of the input file */ + struct stat sb; + + /* Determine the size of the file, needed for mmap: */ + if (fstat(ifd, &sb) < 0) return Z_ERRNO; + buf_len = sb.st_size; + if (buf_len <= 0) return Z_ERRNO; + + /* Now do the actual mmap: */ + buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); + if (buf == (caddr_t)(-1)) return Z_ERRNO; + + /* Compress the whole file at once: */ + len = gzwrite(out, (char *)buf, (unsigned)buf_len); + + if (len != (int)buf_len) error(gzerror(out, &err)); + + munmap(buf, buf_len); + fclose(in); + if (gzclose(out) != Z_OK) error("failed gzclose"); + return Z_OK; +} +#endif /* USE_MMAP */ + +/* =========================================================================== + * Uncompress input to output then close both files. + */ +void gz_uncompress(in, out) + gzFile in; + FILE *out; +{ + local char buf[BUFLEN]; + int len; + int err; + + for (;;) { + len = gzread(in, buf, sizeof(buf)); + if (len < 0) error (gzerror(in, &err)); + if (len == 0) break; + + if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { + error("failed fwrite"); + } + } + if (fclose(out)) error("failed fclose"); + + if (gzclose(in) != Z_OK) error("failed gzclose"); +} + + +/* =========================================================================== + * Compress the given file: create a corresponding .gz file and remove the + * original. + */ +void file_compress(file, mode) + char *file; + char *mode; +{ + local char outfile[MAX_NAME_LEN]; + FILE *in; + gzFile out; + + if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) { + fprintf(stderr, "%s: filename too long\n", prog); + exit(1); + } + +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(outfile, sizeof(outfile), "%s%s", file, GZ_SUFFIX); +#else + strcpy(outfile, file); + strcat(outfile, GZ_SUFFIX); +#endif + + in = fopen(file, "rb"); + if (in == NULL) { + perror(file); + exit(1); + } + out = gzopen(outfile, mode); + if (out == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); + exit(1); + } + gz_compress(in, out); + + unlink(file); +} + + +/* =========================================================================== + * Uncompress the given file and remove the original. + */ +void file_uncompress(file) + char *file; +{ + local char buf[MAX_NAME_LEN]; + char *infile, *outfile; + FILE *out; + gzFile in; + unsigned len = strlen(file); + + if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) { + fprintf(stderr, "%s: filename too long\n", prog); + exit(1); + } + +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(buf, sizeof(buf), "%s", file); +#else + strcpy(buf, file); +#endif + + if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { + infile = file; + outfile = buf; + outfile[len-3] = '\0'; + } else { + outfile = file; + infile = buf; +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(buf + len, sizeof(buf) - len, "%s", GZ_SUFFIX); +#else + strcat(infile, GZ_SUFFIX); +#endif + } + in = gzopen(infile, "rb"); + if (in == NULL) { + fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); + exit(1); + } + out = fopen(outfile, "wb"); + if (out == NULL) { + perror(file); + exit(1); + } + + gz_uncompress(in, out); + + unlink(infile); +} + + +/* =========================================================================== + * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...] + * -c : write to standard output + * -d : decompress + * -f : compress with Z_FILTERED + * -h : compress with Z_HUFFMAN_ONLY + * -r : compress with Z_RLE + * -1 to -9 : compression level + */ + +int main(argc, argv) + int argc; + char *argv[]; +{ + int copyout = 0; + int uncompr = 0; + gzFile file; + char *bname, outmode[20]; + +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(outmode, sizeof(outmode), "%s", "wb6 "); +#else + strcpy(outmode, "wb6 "); +#endif + + prog = argv[0]; + bname = strrchr(argv[0], '/'); + if (bname) + bname++; + else + bname = argv[0]; + argc--, argv++; + + if (!strcmp(bname, "gunzip")) + uncompr = 1; + else if (!strcmp(bname, "zcat")) + copyout = uncompr = 1; + + while (argc > 0) { + if (strcmp(*argv, "-c") == 0) + copyout = 1; + else if (strcmp(*argv, "-d") == 0) + uncompr = 1; + else if (strcmp(*argv, "-f") == 0) + outmode[3] = 'f'; + else if (strcmp(*argv, "-h") == 0) + outmode[3] = 'h'; + else if (strcmp(*argv, "-r") == 0) + outmode[3] = 'R'; + else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && + (*argv)[2] == 0) + outmode[2] = (*argv)[1]; + else + break; + argc--, argv++; + } + if (outmode[3] == ' ') + outmode[3] = 0; + if (argc == 0) { + SET_BINARY_MODE(stdin); + SET_BINARY_MODE(stdout); + if (uncompr) { + file = gzdopen(fileno(stdin), "rb"); + if (file == NULL) error("can't gzdopen stdin"); + gz_uncompress(file, stdout); + } else { + file = gzdopen(fileno(stdout), outmode); + if (file == NULL) error("can't gzdopen stdout"); + gz_compress(stdin, file); + } + } else { + if (copyout) { + SET_BINARY_MODE(stdout); + } + do { + if (uncompr) { + if (copyout) { + file = gzopen(*argv, "rb"); + if (file == NULL) + fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv); + else + gz_uncompress(file, stdout); + } else { + file_uncompress(*argv); + } + } else { + if (copyout) { + FILE * in = fopen(*argv, "rb"); + + if (in == NULL) { + perror(*argv); + } else { + file = gzdopen(fileno(stdout), outmode); + if (file == NULL) error("can't gzdopen stdout"); + + gz_compress(in, file); + } + + } else { + file_compress(*argv, outmode); + } + } + } while (argv++, --argc); + } + return 0; +} diff --git a/third_party/zlib/v1_2_11/treebuild.xml b/third_party/zlib/v1_2_11/treebuild.xml new file mode 100644 index 0000000..fd75525 --- /dev/null +++ b/third_party/zlib/v1_2_11/treebuild.xml @@ -0,0 +1,116 @@ + + + + zip compression library + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/zlib/v1_2_11/trees.c b/third_party/zlib/v1_2_11/trees.c new file mode 100644 index 0000000..50cf4b4 --- /dev/null +++ b/third_party/zlib/v1_2_11/trees.c @@ -0,0 +1,1203 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2017 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef ZLIB_DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {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,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {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}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local const static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local const static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local const static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef ZLIB_DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* !ZLIB_DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef ZLIB_DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !ZLIB_DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = (int)value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* ZLIB_DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef ZLIB_DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); + } + if (overflow == 0) return; + + Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + unsigned code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits-1]) << 1; + next_code[bits] = (ush)code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); + zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); + s->pending += stored_len; +#ifdef ZLIB_DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; + s->bits_sent += stored_len<<3; +#endif +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef ZLIB_DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef ZLIB_DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= (unsigned)base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} diff --git a/third_party/zlib/v1_2_11/trees.h b/third_party/zlib/v1_2_11/trees.h new file mode 100644 index 0000000..d35639d --- /dev/null +++ b/third_party/zlib/v1_2_11/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +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, 0 +}; + +local const int base_dist[D_CODES] = { + 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 +}; + diff --git a/third_party/zlib/v1_2_11/uncompr.c b/third_party/zlib/v1_2_11/uncompr.c new file mode 100644 index 0000000..f03a1a8 --- /dev/null +++ b/third_party/zlib/v1_2_11/uncompr.c @@ -0,0 +1,93 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. *sourceLen is + the byte length of the source buffer. Upon entry, *destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, + *destLen is the size of the decompressed data and *sourceLen is the number + of source bytes consumed. Upon return, source + *sourceLen points to the + first unused input byte. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, or + Z_DATA_ERROR if the input data was corrupted, including if the input data is + an incomplete zlib stream. +*/ +int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong *sourceLen; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong len, left; + Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */ + + len = *sourceLen; + if (*destLen) { + left = *destLen; + *destLen = 0; + } + else { + left = 1; + dest = buf; + } + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = len > (uLong)max ? max : (uInt)len; + len -= stream.avail_in; + } + err = inflate(&stream, Z_NO_FLUSH); + } while (err == Z_OK); + + *sourceLen -= len + stream.avail_in; + if (dest != buf) + *destLen = stream.total_out; + else if (stream.total_out && err == Z_BUF_ERROR) + left = 1; + + inflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : + err == Z_NEED_DICT ? Z_DATA_ERROR : + err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR : + err; +} + +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return uncompress2(dest, destLen, source, &sourceLen); +} diff --git a/third_party/zlib/v1_2_11/watcom/watcom_f.mak b/third_party/zlib/v1_2_11/watcom/watcom_f.mak new file mode 100644 index 0000000..37f4d74 --- /dev/null +++ b/third_party/zlib/v1_2_11/watcom/watcom_f.mak @@ -0,0 +1,43 @@ +# Makefile for zlib +# OpenWatcom flat model +# Last updated: 28-Dec-2005 + +# To use, do "wmake -f watcom_f.mak" + +C_SOURCE = adler32.c compress.c crc32.c deflate.c & + gzclose.c gzlib.c gzread.c gzwrite.c & + infback.c inffast.c inflate.c inftrees.c & + trees.c uncompr.c zutil.c + +OBJS = adler32.obj compress.obj crc32.obj deflate.obj & + gzclose.obj gzlib.obj gzread.obj gzwrite.obj & + infback.obj inffast.obj inflate.obj inftrees.obj & + trees.obj uncompr.obj zutil.obj + +CC = wcc386 +LINKER = wcl386 +CFLAGS = -zq -mf -3r -fp3 -s -bt=dos -oilrtfm -fr=nul -wx +ZLIB_LIB = zlib_f.lib + +.C.OBJ: + $(CC) $(CFLAGS) $[@ + +all: $(ZLIB_LIB) example.exe minigzip.exe + +$(ZLIB_LIB): $(OBJS) + wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj + wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj + wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj + wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj + wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj + +example.exe: $(ZLIB_LIB) example.obj + $(LINKER) -ldos32a -fe=example.exe example.obj $(ZLIB_LIB) + +minigzip.exe: $(ZLIB_LIB) minigzip.obj + $(LINKER) -ldos32a -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) + +clean: .SYMBOLIC + del *.obj + del $(ZLIB_LIB) + @echo Cleaning done diff --git a/third_party/zlib/v1_2_11/watcom/watcom_l.mak b/third_party/zlib/v1_2_11/watcom/watcom_l.mak new file mode 100644 index 0000000..193eed7 --- /dev/null +++ b/third_party/zlib/v1_2_11/watcom/watcom_l.mak @@ -0,0 +1,43 @@ +# Makefile for zlib +# OpenWatcom large model +# Last updated: 28-Dec-2005 + +# To use, do "wmake -f watcom_l.mak" + +C_SOURCE = adler32.c compress.c crc32.c deflate.c & + gzclose.c gzlib.c gzread.c gzwrite.c & + infback.c inffast.c inflate.c inftrees.c & + trees.c uncompr.c zutil.c + +OBJS = adler32.obj compress.obj crc32.obj deflate.obj & + gzclose.obj gzlib.obj gzread.obj gzwrite.obj & + infback.obj inffast.obj inflate.obj inftrees.obj & + trees.obj uncompr.obj zutil.obj + +CC = wcc +LINKER = wcl +CFLAGS = -zq -ml -s -bt=dos -oilrtfm -fr=nul -wx +ZLIB_LIB = zlib_l.lib + +.C.OBJ: + $(CC) $(CFLAGS) $[@ + +all: $(ZLIB_LIB) example.exe minigzip.exe + +$(ZLIB_LIB): $(OBJS) + wlib -b -c $(ZLIB_LIB) -+adler32.obj -+compress.obj -+crc32.obj + wlib -b -c $(ZLIB_LIB) -+gzclose.obj -+gzlib.obj -+gzread.obj -+gzwrite.obj + wlib -b -c $(ZLIB_LIB) -+deflate.obj -+infback.obj + wlib -b -c $(ZLIB_LIB) -+inffast.obj -+inflate.obj -+inftrees.obj + wlib -b -c $(ZLIB_LIB) -+trees.obj -+uncompr.obj -+zutil.obj + +example.exe: $(ZLIB_LIB) example.obj + $(LINKER) -fe=example.exe example.obj $(ZLIB_LIB) + +minigzip.exe: $(ZLIB_LIB) minigzip.obj + $(LINKER) -fe=minigzip.exe minigzip.obj $(ZLIB_LIB) + +clean: .SYMBOLIC + del *.obj + del $(ZLIB_LIB) + @echo Cleaning done diff --git a/third_party/zlib/v1_2_11/win32/DLL_FAQ.txt b/third_party/zlib/v1_2_11/win32/DLL_FAQ.txt new file mode 100644 index 0000000..12c0090 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/DLL_FAQ.txt @@ -0,0 +1,397 @@ + + Frequently Asked Questions about ZLIB1.DLL + + +This document describes the design, the rationale, and the usage +of the official DLL build of zlib, named ZLIB1.DLL. If you have +general questions about zlib, you should see the file "FAQ" found +in the zlib distribution, or at the following location: + http://www.gzip.org/zlib/zlib_faq.html + + + 1. What is ZLIB1.DLL, and how can I get it? + + - ZLIB1.DLL is the official build of zlib as a DLL. + (Please remark the character '1' in the name.) + + Pointers to a precompiled ZLIB1.DLL can be found in the zlib + web site at: + http://www.zlib.net/ + + Applications that link to ZLIB1.DLL can rely on the following + specification: + + * The exported symbols are exclusively defined in the source + files "zlib.h" and "zlib.def", found in an official zlib + source distribution. + * The symbols are exported by name, not by ordinal. + * The exported names are undecorated. + * The calling convention of functions is "C" (CDECL). + * The ZLIB1.DLL binary is linked to MSVCRT.DLL. + + The archive in which ZLIB1.DLL is bundled contains compiled + test programs that must run with a valid build of ZLIB1.DLL. + It is recommended to download the prebuilt DLL from the zlib + web site, instead of building it yourself, to avoid potential + incompatibilities that could be introduced by your compiler + and build settings. If you do build the DLL yourself, please + make sure that it complies with all the above requirements, + and it runs with the precompiled test programs, bundled with + the original ZLIB1.DLL distribution. + + If, for any reason, you need to build an incompatible DLL, + please use a different file name. + + + 2. Why did you change the name of the DLL to ZLIB1.DLL? + What happened to the old ZLIB.DLL? + + - The old ZLIB.DLL, built from zlib-1.1.4 or earlier, required + compilation settings that were incompatible to those used by + a static build. The DLL settings were supposed to be enabled + by defining the macro ZLIB_DLL, before including "zlib.h". + Incorrect handling of this macro was silently accepted at + build time, resulting in two major problems: + + * ZLIB_DLL was missing from the old makefile. When building + the DLL, not all people added it to the build options. In + consequence, incompatible incarnations of ZLIB.DLL started + to circulate around the net. + + * When switching from using the static library to using the + DLL, applications had to define the ZLIB_DLL macro and + to recompile all the sources that contained calls to zlib + functions. Failure to do so resulted in creating binaries + that were unable to run with the official ZLIB.DLL build. + + The only possible solution that we could foresee was to make + a binary-incompatible change in the DLL interface, in order to + remove the dependency on the ZLIB_DLL macro, and to release + the new DLL under a different name. + + We chose the name ZLIB1.DLL, where '1' indicates the major + zlib version number. We hope that we will not have to break + the binary compatibility again, at least not as long as the + zlib-1.x series will last. + + There is still a ZLIB_DLL macro, that can trigger a more + efficient build and use of the DLL, but compatibility no + longer dependents on it. + + + 3. Can I build ZLIB.DLL from the new zlib sources, and replace + an old ZLIB.DLL, that was built from zlib-1.1.4 or earlier? + + - In principle, you can do it by assigning calling convention + keywords to the macros ZEXPORT and ZEXPORTVA. In practice, + it depends on what you mean by "an old ZLIB.DLL", because the + old DLL exists in several mutually-incompatible versions. + You have to find out first what kind of calling convention is + being used in your particular ZLIB.DLL build, and to use the + same one in the new build. If you don't know what this is all + about, you might be better off if you would just leave the old + DLL intact. + + + 4. Can I compile my application using the new zlib interface, and + link it to an old ZLIB.DLL, that was built from zlib-1.1.4 or + earlier? + + - The official answer is "no"; the real answer depends again on + what kind of ZLIB.DLL you have. Even if you are lucky, this + course of action is unreliable. + + If you rebuild your application and you intend to use a newer + version of zlib (post- 1.1.4), it is strongly recommended to + link it to the new ZLIB1.DLL. + + + 5. Why are the zlib symbols exported by name, and not by ordinal? + + - Although exporting symbols by ordinal is a little faster, it + is risky. Any single glitch in the maintenance or use of the + DEF file that contains the ordinals can result in incompatible + builds and frustrating crashes. Simply put, the benefits of + exporting symbols by ordinal do not justify the risks. + + Technically, it should be possible to maintain ordinals in + the DEF file, and still export the symbols by name. Ordinals + exist in every DLL, and even if the dynamic linking performed + at the DLL startup is searching for names, ordinals serve as + hints, for a faster name lookup. However, if the DEF file + contains ordinals, the Microsoft linker automatically builds + an implib that will cause the executables linked to it to use + those ordinals, and not the names. It is interesting to + notice that the GNU linker for Win32 does not suffer from this + problem. + + It is possible to avoid the DEF file if the exported symbols + are accompanied by a "__declspec(dllexport)" attribute in the + source files. You can do this in zlib by predefining the + ZLIB_DLL macro. + + + 6. I see that the ZLIB1.DLL functions use the "C" (CDECL) calling + convention. Why not use the STDCALL convention? + STDCALL is the standard convention in Win32, and I need it in + my Visual Basic project! + + (For readability, we use CDECL to refer to the convention + triggered by the "__cdecl" keyword, STDCALL to refer to + the convention triggered by "__stdcall", and FASTCALL to + refer to the convention triggered by "__fastcall".) + + - Most of the native Windows API functions (without varargs) use + indeed the WINAPI convention (which translates to STDCALL in + Win32), but the standard C functions use CDECL. If a user + application is intrinsically tied to the Windows API (e.g. + it calls native Windows API functions such as CreateFile()), + sometimes it makes sense to decorate its own functions with + WINAPI. But if ANSI C or POSIX portability is a goal (e.g. + it calls standard C functions such as fopen()), it is not a + sound decision to request the inclusion of , or to + use non-ANSI constructs, for the sole purpose to make the user + functions STDCALL-able. + + The functionality offered by zlib is not in the category of + "Windows functionality", but is more like "C functionality". + + Technically, STDCALL is not bad; in fact, it is slightly + faster than CDECL, and it works with variable-argument + functions, just like CDECL. It is unfortunate that, in spite + of using STDCALL in the Windows API, it is not the default + convention used by the C compilers that run under Windows. + The roots of the problem reside deep inside the unsafety of + the K&R-style function prototypes, where the argument types + are not specified; but that is another story for another day. + + The remaining fact is that CDECL is the default convention. + Even if an explicit convention is hard-coded into the function + prototypes inside C headers, problems may appear. The + necessity to expose the convention in users' callbacks is one + of these problems. + + The calling convention issues are also important when using + zlib in other programming languages. Some of them, like Ada + (GNAT) and Fortran (GNU G77), have C bindings implemented + initially on Unix, and relying on the C calling convention. + On the other hand, the pre- .NET versions of Microsoft Visual + Basic require STDCALL, while Borland Delphi prefers, although + it does not require, FASTCALL. + + In fairness to all possible uses of zlib outside the C + programming language, we choose the default "C" convention. + Anyone interested in different bindings or conventions is + encouraged to maintain specialized projects. The "contrib/" + directory from the zlib distribution already holds a couple + of foreign bindings, such as Ada, C++, and Delphi. + + + 7. I need a DLL for my Visual Basic project. What can I do? + + - Define the ZLIB_WINAPI macro before including "zlib.h", when + building both the DLL and the user application (except that + you don't need to define anything when using the DLL in Visual + Basic). The ZLIB_WINAPI macro will switch on the WINAPI + (STDCALL) convention. The name of this DLL must be different + than the official ZLIB1.DLL. + + Gilles Vollant has contributed a build named ZLIBWAPI.DLL, + with the ZLIB_WINAPI macro turned on, and with the minizip + functionality built in. For more information, please read + the notes inside "contrib/vstudio/readme.txt", found in the + zlib distribution. + + + 8. I need to use zlib in my Microsoft .NET project. What can I + do? + + - Henrik Ravn has contributed a .NET wrapper around zlib. Look + into contrib/dotzlib/, inside the zlib distribution. + + + 9. If my application uses ZLIB1.DLL, should I link it to + MSVCRT.DLL? Why? + + - It is not required, but it is recommended to link your + application to MSVCRT.DLL, if it uses ZLIB1.DLL. + + The executables (.EXE, .DLL, etc.) that are involved in the + same process and are using the C run-time library (i.e. they + are calling standard C functions), must link to the same + library. There are several libraries in the Win32 system: + CRTDLL.DLL, MSVCRT.DLL, the static C libraries, etc. + Since ZLIB1.DLL is linked to MSVCRT.DLL, the executables that + depend on it should also be linked to MSVCRT.DLL. + + +10. Why are you saying that ZLIB1.DLL and my application should + be linked to the same C run-time (CRT) library? I linked my + application and my DLLs to different C libraries (e.g. my + application to a static library, and my DLLs to MSVCRT.DLL), + and everything works fine. + + - If a user library invokes only pure Win32 API (accessible via + and the related headers), its DLL build will work + in any context. But if this library invokes standard C API, + things get more complicated. + + There is a single Win32 library in a Win32 system. Every + function in this library resides in a single DLL module, that + is safe to call from anywhere. On the other hand, there are + multiple versions of the C library, and each of them has its + own separate internal state. Standalone executables and user + DLLs that call standard C functions must link to a C run-time + (CRT) library, be it static or shared (DLL). Intermixing + occurs when an executable (not necessarily standalone) and a + DLL are linked to different CRTs, and both are running in the + same process. + + Intermixing multiple CRTs is possible, as long as their + internal states are kept intact. The Microsoft Knowledge Base + articles KB94248 "HOWTO: Use the C Run-Time" and KB140584 + "HOWTO: Link with the Correct C Run-Time (CRT) Library" + mention the potential problems raised by intermixing. + + If intermixing works for you, it's because your application + and DLLs are avoiding the corruption of each of the CRTs' + internal states, maybe by careful design, or maybe by fortune. + + Also note that linking ZLIB1.DLL to non-Microsoft CRTs, such + as those provided by Borland, raises similar problems. + + +11. Why are you linking ZLIB1.DLL to MSVCRT.DLL? + + - MSVCRT.DLL exists on every Windows 95 with a new service pack + installed, or with Microsoft Internet Explorer 4 or later, and + on all other Windows 4.x or later (Windows 98, Windows NT 4, + or later). It is freely distributable; if not present in the + system, it can be downloaded from Microsoft or from other + software provider for free. + + The fact that MSVCRT.DLL does not exist on a virgin Windows 95 + is not so problematic. Windows 95 is scarcely found nowadays, + Microsoft ended its support a long time ago, and many recent + applications from various vendors, including Microsoft, do not + even run on it. Furthermore, no serious user should run + Windows 95 without a proper update installed. + + +12. Why are you not linking ZLIB1.DLL to + <> ? + + - We considered and abandoned the following alternatives: + + * Linking ZLIB1.DLL to a static C library (LIBC.LIB, or + LIBCMT.LIB) is not a good option. People are using the DLL + mainly to save disk space. If you are linking your program + to a static C library, you may as well consider linking zlib + in statically, too. + + * Linking ZLIB1.DLL to CRTDLL.DLL looks appealing, because + CRTDLL.DLL is present on every Win32 installation. + Unfortunately, it has a series of problems: it does not + work properly with Microsoft's C++ libraries, it does not + provide support for 64-bit file offsets, (and so on...), + and Microsoft discontinued its support a long time ago. + + * Linking ZLIB1.DLL to MSVCR70.DLL or MSVCR71.DLL, supplied + with the Microsoft .NET platform, and Visual C++ 7.0/7.1, + raises problems related to the status of ZLIB1.DLL as a + system component. According to the Microsoft Knowledge Base + article KB326922 "INFO: Redistribution of the Shared C + Runtime Component in Visual C++ .NET", MSVCR70.DLL and + MSVCR71.DLL are not supposed to function as system DLLs, + because they may clash with MSVCRT.DLL. Instead, the + application's installer is supposed to put these DLLs + (if needed) in the application's private directory. + If ZLIB1.DLL depends on a non-system runtime, it cannot + function as a redistributable system component. + + * Linking ZLIB1.DLL to non-Microsoft runtimes, such as + Borland's, or Cygwin's, raises problems related to the + reliable presence of these runtimes on Win32 systems. + It's easier to let the DLL build of zlib up to the people + who distribute these runtimes, and who may proceed as + explained in the answer to Question 14. + + +13. If ZLIB1.DLL cannot be linked to MSVCR70.DLL or MSVCR71.DLL, + how can I build/use ZLIB1.DLL in Microsoft Visual C++ 7.0 + (Visual Studio .NET) or newer? + + - Due to the problems explained in the Microsoft Knowledge Base + article KB326922 (see the previous answer), the C runtime that + comes with the VC7 environment is no longer considered a + system component. That is, it should not be assumed that this + runtime exists, or may be installed in a system directory. + Since ZLIB1.DLL is supposed to be a system component, it may + not depend on a non-system component. + + In order to link ZLIB1.DLL and your application to MSVCRT.DLL + in VC7, you need the library of Visual C++ 6.0 or older. If + you don't have this library at hand, it's probably best not to + use ZLIB1.DLL. + + We are hoping that, in the future, Microsoft will provide a + way to build applications linked to a proper system runtime, + from the Visual C++ environment. Until then, you have a + couple of alternatives, such as linking zlib in statically. + If your application requires dynamic linking, you may proceed + as explained in the answer to Question 14. + + +14. I need to link my own DLL build to a CRT different than + MSVCRT.DLL. What can I do? + + - Feel free to rebuild the DLL from the zlib sources, and link + it the way you want. You should, however, clearly state that + your build is unofficial. You should give it a different file + name, and/or install it in a private directory that can be + accessed by your application only, and is not visible to the + others (i.e. it's neither in the PATH, nor in the SYSTEM or + SYSTEM32 directories). Otherwise, your build may clash with + applications that link to the official build. + + For example, in Cygwin, zlib is linked to the Cygwin runtime + CYGWIN1.DLL, and it is distributed under the name CYGZ.DLL. + + +15. May I include additional pieces of code that I find useful, + link them in ZLIB1.DLL, and export them? + + - No. A legitimate build of ZLIB1.DLL must not include code + that does not originate from the official zlib source code. + But you can make your own private DLL build, under a different + file name, as suggested in the previous answer. + + For example, zlib is a part of the VCL library, distributed + with Borland Delphi and C++ Builder. The DLL build of VCL + is a redistributable file, named VCLxx.DLL. + + +16. May I remove some functionality out of ZLIB1.DLL, by enabling + macros like NO_GZCOMPRESS or NO_GZIP at compile time? + + - No. A legitimate build of ZLIB1.DLL must provide the complete + zlib functionality, as implemented in the official zlib source + code. But you can make your own private DLL build, under a + different file name, as suggested in the previous answer. + + +17. I made my own ZLIB1.DLL build. Can I test it for compliance? + + - We prefer that you download the official DLL from the zlib + web site. If you need something peculiar from this DLL, you + can send your suggestion to the zlib mailing list. + + However, in case you do rebuild the DLL yourself, you can run + it with the test programs found in the DLL distribution. + Running these test programs is not a guarantee of compliance, + but a failure can imply a detected problem. + +** + +This document is written and maintained by +Cosmin Truta diff --git a/third_party/zlib/v1_2_11/win32/Makefile.bor b/third_party/zlib/v1_2_11/win32/Makefile.bor new file mode 100644 index 0000000..d152bbb --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/Makefile.bor @@ -0,0 +1,110 @@ +# Makefile for zlib +# Borland C++ for Win32 +# +# Usage: +# make -f win32/Makefile.bor +# make -f win32/Makefile.bor LOCAL_ZLIB=-DASMV OBJA=match.obj OBJPA=+match.obj + +# ------------ Borland C++ ------------ + +# Optional nonstandard preprocessor flags (e.g. -DMAX_MEM_LEVEL=7) +# should be added to the environment via "set LOCAL_ZLIB=-DFOO" or +# added to the declaration of LOC here: +LOC = $(LOCAL_ZLIB) + +CC = bcc32 +AS = bcc32 +LD = bcc32 +AR = tlib +CFLAGS = -a -d -k- -O2 $(LOC) +ASFLAGS = $(LOC) +LDFLAGS = $(LOC) + + +# variables +ZLIB_LIB = zlib.lib + +OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj +OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj +#OBJA = +OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj +OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj +#OBJPA= + + +# targets +all: $(ZLIB_LIB) example.exe minigzip.exe + +.c.obj: + $(CC) -c $(CFLAGS) $< + +.asm.obj: + $(AS) -c $(ASFLAGS) $< + +adler32.obj: adler32.c zlib.h zconf.h + +compress.obj: compress.c zlib.h zconf.h + +crc32.obj: crc32.c zlib.h zconf.h crc32.h + +deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h + +gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h + +gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h + +gzread.obj: gzread.c zlib.h zconf.h gzguts.h + +gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h + +infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h + +inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ + inffast.h inffixed.h + +inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h + +trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h + +uncompr.obj: uncompr.c zlib.h zconf.h + +zutil.obj: zutil.c zutil.h zlib.h zconf.h + +example.obj: test/example.c zlib.h zconf.h + +minigzip.obj: test/minigzip.c zlib.h zconf.h + + +# For the sake of the old Borland make, +# the command line is cut to fit in the MS-DOS 128 byte limit: +$(ZLIB_LIB): $(OBJ1) $(OBJ2) $(OBJA) + -del $(ZLIB_LIB) + $(AR) $(ZLIB_LIB) $(OBJP1) + $(AR) $(ZLIB_LIB) $(OBJP2) + $(AR) $(ZLIB_LIB) $(OBJPA) + + +# testing +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +example.exe: example.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB) + +minigzip.exe: minigzip.obj $(ZLIB_LIB) + $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB) + + +# cleanup +clean: + -del $(ZLIB_LIB) + -del *.obj + -del *.exe + -del *.tds + -del zlib.bak + -del foo.gz diff --git a/third_party/zlib/v1_2_11/win32/Makefile.gcc b/third_party/zlib/v1_2_11/win32/Makefile.gcc new file mode 100644 index 0000000..305be50 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/Makefile.gcc @@ -0,0 +1,182 @@ +# Makefile for zlib, derived from Makefile.dj2. +# Modified for mingw32 by C. Spieler, 6/16/98. +# Updated for zlib 1.2.x by Christian Spieler and Cosmin Truta, Mar-2003. +# Last updated: Mar 2012. +# Tested under Cygwin and MinGW. + +# Copyright (C) 1995-2003 Jean-loup Gailly. +# For conditions of distribution and use, see copyright notice in zlib.h + +# To compile, or to compile and test, type from the top level zlib directory: +# +# make -fwin32/Makefile.gcc; make test testdll -fwin32/Makefile.gcc +# +# To use the asm code, type: +# cp contrib/asm?86/match.S ./match.S +# make LOC=-DASMV OBJA=match.o -fwin32/Makefile.gcc +# +# To install libz.a, zconf.h and zlib.h in the system directories, type: +# +# make install -fwin32/Makefile.gcc +# +# BINARY_PATH, INCLUDE_PATH and LIBRARY_PATH must be set. +# +# To install the shared lib, append SHARED_MODE=1 to the make command : +# +# make install -fwin32/Makefile.gcc SHARED_MODE=1 + +# Note: +# If the platform is *not* MinGW (e.g. it is Cygwin or UWIN), +# the DLL name should be changed from "zlib1.dll". + +STATICLIB = libz.a +SHAREDLIB = zlib1.dll +IMPLIB = libz.dll.a + +# +# Set to 1 if shared object needs to be installed +# +SHARED_MODE=0 + +#LOC = -DASMV +#LOC = -DZLIB_DEBUG -g + +PREFIX = +CC = $(PREFIX)gcc +CFLAGS = $(LOC) -O3 -Wall + +AS = $(CC) +ASFLAGS = $(LOC) -Wall + +LD = $(CC) +LDFLAGS = $(LOC) + +AR = $(PREFIX)ar +ARFLAGS = rcs + +RC = $(PREFIX)windres +RCFLAGS = --define GCC_WINDRES + +STRIP = $(PREFIX)strip + +CP = cp -fp +# If GNU install is available, replace $(CP) with install. +INSTALL = $(CP) +RM = rm -f + +prefix ?= /usr/local +exec_prefix = $(prefix) + +OBJS = adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o \ + gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o +OBJA = + +all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) example.exe minigzip.exe example_d.exe minigzip_d.exe + +test: example.exe minigzip.exe + ./example + echo hello world | ./minigzip | ./minigzip -d + +testdll: example_d.exe minigzip_d.exe + ./example_d + echo hello world | ./minigzip_d | ./minigzip_d -d + +.c.o: + $(CC) $(CFLAGS) -c -o $@ $< + +.S.o: + $(AS) $(ASFLAGS) -c -o $@ $< + +$(STATICLIB): $(OBJS) $(OBJA) + $(AR) $(ARFLAGS) $@ $(OBJS) $(OBJA) + +$(IMPLIB): $(SHAREDLIB) + +$(SHAREDLIB): win32/zlib.def $(OBJS) $(OBJA) zlibrc.o + $(CC) -shared -Wl,--out-implib,$(IMPLIB) $(LDFLAGS) \ + -o $@ win32/zlib.def $(OBJS) $(OBJA) zlibrc.o + $(STRIP) $@ + +example.exe: example.o $(STATICLIB) + $(LD) $(LDFLAGS) -o $@ example.o $(STATICLIB) + $(STRIP) $@ + +minigzip.exe: minigzip.o $(STATICLIB) + $(LD) $(LDFLAGS) -o $@ minigzip.o $(STATICLIB) + $(STRIP) $@ + +example_d.exe: example.o $(IMPLIB) + $(LD) $(LDFLAGS) -o $@ example.o $(IMPLIB) + $(STRIP) $@ + +minigzip_d.exe: minigzip.o $(IMPLIB) + $(LD) $(LDFLAGS) -o $@ minigzip.o $(IMPLIB) + $(STRIP) $@ + +example.o: test/example.c zlib.h zconf.h + $(CC) $(CFLAGS) -I. -c -o $@ test/example.c + +minigzip.o: test/minigzip.c zlib.h zconf.h + $(CC) $(CFLAGS) -I. -c -o $@ test/minigzip.c + +zlibrc.o: win32/zlib1.rc + $(RC) $(RCFLAGS) -o $@ win32/zlib1.rc + +.PHONY: install uninstall clean + +install: zlib.h zconf.h $(STATICLIB) $(IMPLIB) + @if test -z "$(DESTDIR)$(INCLUDE_PATH)" -o -z "$(DESTDIR)$(LIBRARY_PATH)" -o -z "$(DESTDIR)$(BINARY_PATH)"; then \ + echo INCLUDE_PATH, LIBRARY_PATH, and BINARY_PATH must be specified; \ + exit 1; \ + fi + -@mkdir -p '$(DESTDIR)$(INCLUDE_PATH)' + -@mkdir -p '$(DESTDIR)$(LIBRARY_PATH)' '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig + -if [ "$(SHARED_MODE)" = "1" ]; then \ + mkdir -p '$(DESTDIR)$(BINARY_PATH)'; \ + $(INSTALL) $(SHAREDLIB) '$(DESTDIR)$(BINARY_PATH)'; \ + $(INSTALL) $(IMPLIB) '$(DESTDIR)$(LIBRARY_PATH)'; \ + fi + -$(INSTALL) zlib.h '$(DESTDIR)$(INCLUDE_PATH)' + -$(INSTALL) zconf.h '$(DESTDIR)$(INCLUDE_PATH)' + -$(INSTALL) $(STATICLIB) '$(DESTDIR)$(LIBRARY_PATH)' + sed \ + -e 's|@prefix@|${prefix}|g' \ + -e 's|@exec_prefix@|${exec_prefix}|g' \ + -e 's|@libdir@|$(LIBRARY_PATH)|g' \ + -e 's|@sharedlibdir@|$(LIBRARY_PATH)|g' \ + -e 's|@includedir@|$(INCLUDE_PATH)|g' \ + -e 's|@VERSION@|'`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' zlib.h`'|g' \ + zlib.pc.in > '$(DESTDIR)$(LIBRARY_PATH)'/pkgconfig/zlib.pc + +uninstall: + -if [ "$(SHARED_MODE)" = "1" ]; then \ + $(RM) '$(DESTDIR)$(BINARY_PATH)'/$(SHAREDLIB); \ + $(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(IMPLIB); \ + fi + -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zlib.h + -$(RM) '$(DESTDIR)$(INCLUDE_PATH)'/zconf.h + -$(RM) '$(DESTDIR)$(LIBRARY_PATH)'/$(STATICLIB) + +clean: + -$(RM) $(STATICLIB) + -$(RM) $(SHAREDLIB) + -$(RM) $(IMPLIB) + -$(RM) *.o + -$(RM) *.exe + -$(RM) foo.gz + +adler32.o: zlib.h zconf.h +compress.o: zlib.h zconf.h +crc32.o: crc32.h zlib.h zconf.h +deflate.o: deflate.h zutil.h zlib.h zconf.h +gzclose.o: zlib.h zconf.h gzguts.h +gzlib.o: zlib.h zconf.h gzguts.h +gzread.o: zlib.h zconf.h gzguts.h +gzwrite.o: zlib.h zconf.h gzguts.h +inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h +inftrees.o: zutil.h zlib.h zconf.h inftrees.h +trees.o: deflate.h zutil.h zlib.h zconf.h trees.h +uncompr.o: zlib.h zconf.h +zutil.o: zutil.h zlib.h zconf.h diff --git a/third_party/zlib/v1_2_11/win32/Makefile.msc b/third_party/zlib/v1_2_11/win32/Makefile.msc new file mode 100644 index 0000000..6831882 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/Makefile.msc @@ -0,0 +1,163 @@ +# Makefile for zlib using Microsoft (Visual) C +# zlib is copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler +# +# Usage: +# nmake -f win32/Makefile.msc (standard build) +# nmake -f win32/Makefile.msc LOC=-DFOO (nonstandard build) +# nmake -f win32/Makefile.msc LOC="-DASMV -DASMINF" \ +# OBJA="inffas32.obj match686.obj" (use ASM code, x86) +# nmake -f win32/Makefile.msc AS=ml64 LOC="-DASMV -DASMINF -I." \ +# OBJA="inffasx64.obj gvmat64.obj inffas8664.obj" (use ASM code, x64) + +# The toplevel directory of the source tree. +# +TOP = . + +# optional build flags +LOC = + +# variables +STATICLIB = zlib.lib +SHAREDLIB = zlib1.dll +IMPLIB = zdll.lib + +CC = cl +AS = ml +LD = link +AR = lib +RC = rc +CFLAGS = -nologo -MD -W3 -O2 -Oy- -Zi -Fd"zlib" $(LOC) +WFLAGS = -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE +ASFLAGS = -coff -Zi $(LOC) +LDFLAGS = -nologo -debug -incremental:no -opt:ref +ARFLAGS = -nologo +RCFLAGS = /dWIN32 /r + +OBJS = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj \ + gzwrite.obj infback.obj inflate.obj inftrees.obj inffast.obj trees.obj uncompr.obj zutil.obj +OBJA = + + +# targets +all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \ + example.exe minigzip.exe example_d.exe minigzip_d.exe + +$(STATICLIB): $(OBJS) $(OBJA) + $(AR) $(ARFLAGS) -out:$@ $(OBJS) $(OBJA) + +$(IMPLIB): $(SHAREDLIB) + +$(SHAREDLIB): $(TOP)/win32/zlib.def $(OBJS) $(OBJA) zlib1.res + $(LD) $(LDFLAGS) -def:$(TOP)/win32/zlib.def -dll -implib:$(IMPLIB) \ + -out:$@ -base:0x5A4C0000 $(OBJS) $(OBJA) zlib1.res + if exist $@.manifest \ + mt -nologo -manifest $@.manifest -outputresource:$@;2 + +example.exe: example.obj $(STATICLIB) + $(LD) $(LDFLAGS) example.obj $(STATICLIB) + if exist $@.manifest \ + mt -nologo -manifest $@.manifest -outputresource:$@;1 + +minigzip.exe: minigzip.obj $(STATICLIB) + $(LD) $(LDFLAGS) minigzip.obj $(STATICLIB) + if exist $@.manifest \ + mt -nologo -manifest $@.manifest -outputresource:$@;1 + +example_d.exe: example.obj $(IMPLIB) + $(LD) $(LDFLAGS) -out:$@ example.obj $(IMPLIB) + if exist $@.manifest \ + mt -nologo -manifest $@.manifest -outputresource:$@;1 + +minigzip_d.exe: minigzip.obj $(IMPLIB) + $(LD) $(LDFLAGS) -out:$@ minigzip.obj $(IMPLIB) + if exist $@.manifest \ + mt -nologo -manifest $@.manifest -outputresource:$@;1 + +{$(TOP)}.c.obj: + $(CC) -c $(WFLAGS) $(CFLAGS) $< + +{$(TOP)/test}.c.obj: + $(CC) -c -I$(TOP) $(WFLAGS) $(CFLAGS) $< + +{$(TOP)/contrib/masmx64}.c.obj: + $(CC) -c $(WFLAGS) $(CFLAGS) $< + +{$(TOP)/contrib/masmx64}.asm.obj: + $(AS) -c $(ASFLAGS) $< + +{$(TOP)/contrib/masmx86}.asm.obj: + $(AS) -c $(ASFLAGS) $< + +adler32.obj: $(TOP)/adler32.c $(TOP)/zlib.h $(TOP)/zconf.h + +compress.obj: $(TOP)/compress.c $(TOP)/zlib.h $(TOP)/zconf.h + +crc32.obj: $(TOP)/crc32.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/crc32.h + +deflate.obj: $(TOP)/deflate.c $(TOP)/deflate.h $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h + +gzclose.obj: $(TOP)/gzclose.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h + +gzlib.obj: $(TOP)/gzlib.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h + +gzread.obj: $(TOP)/gzread.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h + +gzwrite.obj: $(TOP)/gzwrite.c $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/gzguts.h + +infback.obj: $(TOP)/infback.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ + $(TOP)/inffast.h $(TOP)/inffixed.h + +inffast.obj: $(TOP)/inffast.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ + $(TOP)/inffast.h + +inflate.obj: $(TOP)/inflate.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h $(TOP)/inflate.h \ + $(TOP)/inffast.h $(TOP)/inffixed.h + +inftrees.obj: $(TOP)/inftrees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/inftrees.h + +trees.obj: $(TOP)/trees.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h $(TOP)/deflate.h $(TOP)/trees.h + +uncompr.obj: $(TOP)/uncompr.c $(TOP)/zlib.h $(TOP)/zconf.h + +zutil.obj: $(TOP)/zutil.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h + +gvmat64.obj: $(TOP)/contrib\masmx64\gvmat64.asm + +inffasx64.obj: $(TOP)/contrib\masmx64\inffasx64.asm + +inffas8664.obj: $(TOP)/contrib\masmx64\inffas8664.c $(TOP)/zutil.h $(TOP)/zlib.h $(TOP)/zconf.h \ + $(TOP)/inftrees.h $(TOP)/inflate.h $(TOP)/inffast.h + +inffas32.obj: $(TOP)/contrib\masmx86\inffas32.asm + +match686.obj: $(TOP)/contrib\masmx86\match686.asm + +example.obj: $(TOP)/test/example.c $(TOP)/zlib.h $(TOP)/zconf.h + +minigzip.obj: $(TOP)/test/minigzip.c $(TOP)/zlib.h $(TOP)/zconf.h + +zlib1.res: $(TOP)/win32/zlib1.rc + $(RC) $(RCFLAGS) /fo$@ $(TOP)/win32/zlib1.rc + +# testing +test: example.exe minigzip.exe + example + echo hello world | minigzip | minigzip -d + +testdll: example_d.exe minigzip_d.exe + example_d + echo hello world | minigzip_d | minigzip_d -d + + +# cleanup +clean: + -del $(STATICLIB) + -del $(SHAREDLIB) + -del $(IMPLIB) + -del *.obj + -del *.res + -del *.exp + -del *.exe + -del *.pdb + -del *.manifest + -del foo.gz diff --git a/third_party/zlib/v1_2_11/win32/README-WIN32.txt b/third_party/zlib/v1_2_11/win32/README-WIN32.txt new file mode 100644 index 0000000..df7ab7f --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/README-WIN32.txt @@ -0,0 +1,103 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.11 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) +and rfc1952.txt (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). Two compiled +examples are distributed in this package, example and minigzip. The example_d +and minigzip_d flavors validate that the zlib1.dll file is working correctly. + +Questions about zlib should be sent to . The zlib home page +is http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read DLL_FAQ.txt, and the the zlib FAQ http://zlib.net/zlib_faq.html +before asking for help. + + +Manifest: + +The package zlib-1.2.11-win32-x86.zip will contain the following files: + + README-WIN32.txt This document + ChangeLog Changes since previous zlib packages + DLL_FAQ.txt Frequently asked questions about zlib1.dll + zlib.3.pdf Documentation of this library in Adobe Acrobat format + + example.exe A statically-bound example (using zlib.lib, not the dll) + example.pdb Symbolic information for debugging example.exe + + example_d.exe A zlib1.dll bound example (using zdll.lib) + example_d.pdb Symbolic information for debugging example_d.exe + + minigzip.exe A statically-bound test program (using zlib.lib, not the dll) + minigzip.pdb Symbolic information for debugging minigzip.exe + + minigzip_d.exe A zlib1.dll bound test program (using zdll.lib) + minigzip_d.pdb Symbolic information for debugging minigzip_d.exe + + zlib.h Install these files into the compilers' INCLUDE path to + zconf.h compile programs which use zlib.lib or zdll.lib + + zdll.lib Install these files into the compilers' LIB path if linking + zdll.exp a compiled program to the zlib1.dll binary + + zlib.lib Install these files into the compilers' LIB path to link zlib + zlib.pdb into compiled programs, without zlib1.dll runtime dependency + (zlib.pdb provides debugging info to the compile time linker) + + zlib1.dll Install this binary shared library into the system PATH, or + the program's runtime directory (where the .exe resides) + zlib1.pdb Install in the same directory as zlib1.dll, in order to debug + an application crash using WinDbg or similar tools. + +All .pdb files above are entirely optional, but are very useful to a developer +attempting to diagnose program misbehavior or a crash. Many additional +important files for developers can be found in the zlib127.zip source package +available from http://zlib.net/ - review that package's README file for details. + + +Acknowledgments: + +The deflate format used by zlib was defined by Phil Katz. The deflate and +zlib specifications were written by L. Peter Deutsch. Thanks to all the +people who reported problems and suggested various improvements in zlib; they +are too numerous to cite here. + + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/third_party/zlib/v1_2_11/win32/VisualC.txt b/third_party/zlib/v1_2_11/win32/VisualC.txt new file mode 100644 index 0000000..1005b21 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/VisualC.txt @@ -0,0 +1,3 @@ + +To build zlib using the Microsoft Visual C++ environment, +use the appropriate project from the contrib/vstudio/ directory. diff --git a/third_party/zlib/v1_2_11/win32/zlib.def b/third_party/zlib/v1_2_11/win32/zlib.def new file mode 100644 index 0000000..784b138 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/zlib.def @@ -0,0 +1,94 @@ +; zlib data compression library +EXPORTS +; basic functions + zlibVersion + deflate + deflateEnd + inflate + inflateEnd +; advanced functions + deflateSetDictionary + deflateGetDictionary + deflateCopy + deflateReset + deflateParams + deflateTune + deflateBound + deflatePending + deflatePrime + deflateSetHeader + inflateSetDictionary + inflateGetDictionary + inflateSync + inflateCopy + inflateReset + inflateReset2 + inflatePrime + inflateMark + inflateGetHeader + inflateBack + inflateBackEnd + zlibCompileFlags +; utility functions + compress + compress2 + compressBound + uncompress + uncompress2 + gzopen + gzdopen + gzbuffer + gzsetparams + gzread + gzfread + gzwrite + gzfwrite + gzprintf + gzvprintf + gzputs + gzgets + gzputc + gzgetc + gzungetc + gzflush + gzseek + gzrewind + gztell + gzoffset + gzeof + gzdirect + gzclose + gzclose_r + gzclose_w + gzerror + gzclearerr +; large file functions + gzopen64 + gzseek64 + gztell64 + gzoffset64 + adler32_combine64 + crc32_combine64 +; checksum functions + adler32 + adler32_z + crc32 + crc32_z + adler32_combine + crc32_combine +; various hacks, don't look :) + deflateInit_ + deflateInit2_ + inflateInit_ + inflateInit2_ + inflateBackInit_ + gzgetc_ + zError + inflateSyncPoint + get_crc_table + inflateUndermine + inflateValidate + inflateCodesUsed + inflateResetKeep + deflateResetKeep + gzopen_w diff --git a/third_party/zlib/v1_2_11/win32/zlib1.rc b/third_party/zlib/v1_2_11/win32/zlib1.rc new file mode 100644 index 0000000..234e641 --- /dev/null +++ b/third_party/zlib/v1_2_11/win32/zlib1.rc @@ -0,0 +1,40 @@ +#include +#include "../zlib.h" + +#ifdef GCC_WINDRES +VS_VERSION_INFO VERSIONINFO +#else +VS_VERSION_INFO VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE +#endif + FILEVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 + PRODUCTVERSION ZLIB_VER_MAJOR,ZLIB_VER_MINOR,ZLIB_VER_REVISION,0 + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS 1 +#else + FILEFLAGS 0 +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL + FILESUBTYPE 0 // not used +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904E4" + //language ID = U.S. English, char set = Windows, Multilingual + BEGIN + VALUE "FileDescription", "zlib data compression library\0" + VALUE "FileVersion", ZLIB_VERSION "\0" + VALUE "InternalName", "zlib1.dll\0" + VALUE "LegalCopyright", "(C) 1995-2017 Jean-loup Gailly & Mark Adler\0" + VALUE "OriginalFilename", "zlib1.dll\0" + VALUE "ProductName", "zlib\0" + VALUE "ProductVersion", ZLIB_VERSION "\0" + VALUE "Comments", "For more information visit http://www.zlib.net/\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 1252 + END +END diff --git a/third_party/zlib/v1_2_11/zconf.h b/third_party/zlib/v1_2_11/zconf.h new file mode 100644 index 0000000..5e1d68a --- /dev/null +++ b/third_party/zlib/v1_2_11/zconf.h @@ -0,0 +1,534 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/third_party/zlib/v1_2_11/zconf.h.cmakein b/third_party/zlib/v1_2_11/zconf.h.cmakein new file mode 100644 index 0000000..a7f24cc --- /dev/null +++ b/third_party/zlib/v1_2_11/zconf.h.cmakein @@ -0,0 +1,536 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H +#cmakedefine Z_PREFIX +#cmakedefine Z_HAVE_UNISTD_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/third_party/zlib/v1_2_11/zconf.h.in b/third_party/zlib/v1_2_11/zconf.h.in new file mode 100644 index 0000000..5e1d68a --- /dev/null +++ b/third_party/zlib/v1_2_11/zconf.h.in @@ -0,0 +1,534 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/third_party/zlib/v1_2_11/zlib.3 b/third_party/zlib/v1_2_11/zlib.3 new file mode 100644 index 0000000..bda4eb0 --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib.3 @@ -0,0 +1,149 @@ +.TH ZLIB 3 "15 Jan 2017" +.SH NAME +zlib \- compression/decompression library +.SH SYNOPSIS +[see +.I zlib.h +for full description] +.SH DESCRIPTION +The +.I zlib +library is a general purpose data compression library. +The code is thread safe, assuming that the standard library functions +used are thread safe, such as memory allocation routines. +It provides in-memory compression and decompression functions, +including integrity checks of the uncompressed data. +This version of the library supports only one compression method (deflation) +but other algorithms may be added later +with the same stream interface. +.LP +Compression can be done in a single step if the buffers are large enough +or can be done by repeated calls of the compression function. +In the latter case, +the application must provide more input and/or consume the output +(providing more output space) before each call. +.LP +The library also supports reading and writing files in +.IR gzip (1) +(.gz) format +with an interface similar to that of stdio. +.LP +The library does not install any signal handler. +The decoder checks the consistency of the compressed data, +so the library should never crash even in the case of corrupted input. +.LP +All functions of the compression library are documented in the file +.IR zlib.h . +The distribution source includes examples of use of the library +in the files +.I test/example.c +and +.IR test/minigzip.c, +as well as other examples in the +.IR examples/ +directory. +.LP +Changes to this version are documented in the file +.I ChangeLog +that accompanies the source. +.LP +.I zlib +is built in to many languages and operating systems, including but not limited to +Java, Python, .NET, PHP, Perl, Ruby, Swift, and Go. +.LP +An experimental package to read and write files in the .zip format, +written on top of +.I zlib +by Gilles Vollant (info@winimage.com), +is available at: +.IP +http://www.winimage.com/zLibDll/minizip.html +and also in the +.I contrib/minizip +directory of the main +.I zlib +source distribution. +.SH "SEE ALSO" +The +.I zlib +web site can be found at: +.IP +http://zlib.net/ +.LP +The data format used by the +.I zlib +library is described by RFC +(Request for Comments) 1950 to 1952 in the files: +.IP +http://tools.ietf.org/html/rfc1950 (for the zlib header and trailer format) +.br +http://tools.ietf.org/html/rfc1951 (for the deflate compressed data format) +.br +http://tools.ietf.org/html/rfc1952 (for the gzip header and trailer format) +.LP +Mark Nelson wrote an article about +.I zlib +for the Jan. 1997 issue of Dr. Dobb's Journal; +a copy of the article is available at: +.IP +http://marknelson.us/1997/01/01/zlib-engine/ +.SH "REPORTING PROBLEMS" +Before reporting a problem, +please check the +.I zlib +web site to verify that you have the latest version of +.IR zlib ; +otherwise, +obtain the latest version and see if the problem still exists. +Please read the +.I zlib +FAQ at: +.IP +http://zlib.net/zlib_faq.html +.LP +before asking for help. +Send questions and/or comments to zlib@gzip.org, +or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). +.SH AUTHORS AND LICENSE +Version 1.2.11 +.LP +Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler +.LP +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. +.LP +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: +.LP +.nr step 1 1 +.IP \n[step]. 3 +The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +.IP \n+[step]. +Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +.IP \n+[step]. +This notice may not be removed or altered from any source distribution. +.LP +Jean-loup Gailly Mark Adler +.br +jloup@gzip.org madler@alumni.caltech.edu +.LP +The deflate format used by +.I zlib +was defined by Phil Katz. +The deflate and +.I zlib +specifications were written by L. Peter Deutsch. +Thanks to all the people who reported problems and suggested various +improvements in +.IR zlib ; +who are too numerous to cite here. +.LP +UNIX manual page by R. P. C. Rodgers, +U.S. National Library of Medicine (rodgers@nlm.nih.gov). +.\" end of man page diff --git a/third_party/zlib/v1_2_11/zlib.3.pdf b/third_party/zlib/v1_2_11/zlib.3.pdf new file mode 100644 index 0000000..6fa519c Binary files /dev/null and b/third_party/zlib/v1_2_11/zlib.3.pdf differ diff --git a/third_party/zlib/v1_2_11/zlib.h b/third_party/zlib/v1_2_11/zlib.h new file mode 100644 index 0000000..f09cdaf --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib.h @@ -0,0 +1,1912 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.11" +#define ZLIB_VERNUM 0x12b0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 11 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more ouput + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if any input has been consumed in a previous + deflate() call, then the input available so far is compressed with the old + level and strategy using deflate(strm, Z_BLOCK). There are three approaches + for the compression levels 0, 1..3, and 4..9 respectively. The new level + and strategy will take effect at the next call of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will not automatically decode concatenated gzip streams. + inflate() will return Z_STREAM_END at the end of the gzip stream. The state + would need to be reset to continue decoding a subsequent gzip stream. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Three times that size in buffer space is allocated. A larger buffer + size of, for example, 64K or 128K bytes will noticeably increase the speed + of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. Previously provided + data is flushed before the parameter change. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read up to nitems items of size size from file to buf, otherwise operating + as gzread() does. This duplicates the interface of stdio's fread(), with + size_t request and return types. If the library defines size_t, then + z_size_t is identical to size_t. If not, then z_size_t is an unsigned + integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevetheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, reseting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + gzfwrite() writes nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/third_party/zlib/v1_2_11/zlib.map b/third_party/zlib/v1_2_11/zlib.map new file mode 100644 index 0000000..40fa9db --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib.map @@ -0,0 +1,94 @@ +ZLIB_1.2.0 { + global: + compressBound; + deflateBound; + inflateBack; + inflateBackEnd; + inflateBackInit_; + inflateCopy; + local: + deflate_copyright; + inflate_copyright; + inflate_fast; + inflate_table; + zcalloc; + zcfree; + z_errmsg; + gz_error; + gz_intmax; + _*; +}; + +ZLIB_1.2.0.2 { + gzclearerr; + gzungetc; + zlibCompileFlags; +} ZLIB_1.2.0; + +ZLIB_1.2.0.8 { + deflatePrime; +} ZLIB_1.2.0.2; + +ZLIB_1.2.2 { + adler32_combine; + crc32_combine; + deflateSetHeader; + inflateGetHeader; +} ZLIB_1.2.0.8; + +ZLIB_1.2.2.3 { + deflateTune; + gzdirect; +} ZLIB_1.2.2; + +ZLIB_1.2.2.4 { + inflatePrime; +} ZLIB_1.2.2.3; + +ZLIB_1.2.3.3 { + adler32_combine64; + crc32_combine64; + gzopen64; + gzseek64; + gztell64; + inflateUndermine; +} ZLIB_1.2.2.4; + +ZLIB_1.2.3.4 { + inflateReset2; + inflateMark; +} ZLIB_1.2.3.3; + +ZLIB_1.2.3.5 { + gzbuffer; + gzoffset; + gzoffset64; + gzclose_r; + gzclose_w; +} ZLIB_1.2.3.4; + +ZLIB_1.2.5.1 { + deflatePending; +} ZLIB_1.2.3.5; + +ZLIB_1.2.5.2 { + deflateResetKeep; + gzgetc_; + inflateResetKeep; +} ZLIB_1.2.5.1; + +ZLIB_1.2.7.1 { + inflateGetDictionary; + gzvprintf; +} ZLIB_1.2.5.2; + +ZLIB_1.2.9 { + inflateCodesUsed; + inflateValidate; + uncompress2; + gzfread; + gzfwrite; + deflateGetDictionary; + adler32_z; + crc32_z; +} ZLIB_1.2.7.1; diff --git a/third_party/zlib/v1_2_11/zlib.pc.cmakein b/third_party/zlib/v1_2_11/zlib.pc.cmakein new file mode 100644 index 0000000..a5e6429 --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib.pc.cmakein @@ -0,0 +1,13 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=@CMAKE_INSTALL_PREFIX@ +libdir=@INSTALL_LIB_DIR@ +sharedlibdir=@INSTALL_LIB_DIR@ +includedir=@INSTALL_INC_DIR@ + +Name: zlib +Description: zlib compression library +Version: @VERSION@ + +Requires: +Libs: -L${libdir} -L${sharedlibdir} -lz +Cflags: -I${includedir} diff --git a/third_party/zlib/v1_2_11/zlib.pc.in b/third_party/zlib/v1_2_11/zlib.pc.in new file mode 100644 index 0000000..7e5acf9 --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib.pc.in @@ -0,0 +1,13 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +sharedlibdir=@sharedlibdir@ +includedir=@includedir@ + +Name: zlib +Description: zlib compression library +Version: @VERSION@ + +Requires: +Libs: -L${libdir} -L${sharedlibdir} -lz +Cflags: -I${includedir} diff --git a/third_party/zlib/v1_2_11/zlib2ansi b/third_party/zlib/v1_2_11/zlib2ansi new file mode 100644 index 0000000..15e3e16 --- /dev/null +++ b/third_party/zlib/v1_2_11/zlib2ansi @@ -0,0 +1,152 @@ +#!/usr/bin/perl + +# Transform K&R C function definitions into ANSI equivalent. +# +# Author: Paul Marquess +# Version: 1.0 +# Date: 3 October 2006 + +# TODO +# +# Asumes no function pointer parameters. unless they are typedefed. +# Assumes no literal strings that look like function definitions +# Assumes functions start at the beginning of a line + +use strict; +use warnings; + +local $/; +$_ = <>; + +my $sp = qr{ \s* (?: /\* .*? \*/ )? \s* }x; # assume no nested comments + +my $d1 = qr{ $sp (?: [\w\*\s]+ $sp)* $sp \w+ $sp [\[\]\s]* $sp }x ; +my $decl = qr{ $sp (?: \w+ $sp )+ $d1 }xo ; +my $dList = qr{ $sp $decl (?: $sp , $d1 )* $sp ; $sp }xo ; + + +while (s/^ + ( # Start $1 + ( # Start $2 + .*? # Minimal eat content + ( ^ \w [\w\s\*]+ ) # $3 -- function name + \s* # optional whitespace + ) # $2 - Matched up to before parameter list + + \( \s* # Literal "(" + optional whitespace + ( [^\)]+ ) # $4 - one or more anythings except ")" + \s* \) # optional whitespace surrounding a Literal ")" + + ( (?: $dList )+ ) # $5 + + $sp ^ { # literal "{" at start of line + ) # Remember to $1 + //xsom + ) +{ + my $all = $1 ; + my $prefix = $2; + my $param_list = $4 ; + my $params = $5; + + StripComments($params); + StripComments($param_list); + $param_list =~ s/^\s+//; + $param_list =~ s/\s+$//; + + my $i = 0 ; + my %pList = map { $_ => $i++ } + split /\s*,\s*/, $param_list; + my $pMatch = '(\b' . join('|', keys %pList) . '\b)\W*$' ; + + my @params = split /\s*;\s*/, $params; + my @outParams = (); + foreach my $p (@params) + { + if ($p =~ /,/) + { + my @bits = split /\s*,\s*/, $p; + my $first = shift @bits; + $first =~ s/^\s*//; + push @outParams, $first; + $first =~ /^(\w+\s*)/; + my $type = $1 ; + push @outParams, map { $type . $_ } @bits; + } + else + { + $p =~ s/^\s+//; + push @outParams, $p; + } + } + + + my %tmp = map { /$pMatch/; $_ => $pList{$1} } + @outParams ; + + @outParams = map { " $_" } + sort { $tmp{$a} <=> $tmp{$b} } + @outParams ; + + print $prefix ; + print "(\n" . join(",\n", @outParams) . ")\n"; + print "{" ; + +} + +# Output any trailing code. +print ; +exit 0; + + +sub StripComments +{ + + no warnings; + + # Strip C & C++ coments + # From the perlfaq + $_[0] =~ + + s{ + /\* ## Start of /* ... */ comment + [^*]*\*+ ## Non-* followed by 1-or-more *'s + ( + [^/*][^*]*\*+ + )* ## 0-or-more things which don't start with / + ## but do end with '*' + / ## End of /* ... */ comment + + | ## OR C++ Comment + // ## Start of C++ comment // + [^\n]* ## followed by 0-or-more non end of line characters + + | ## OR various things which aren't comments: + + ( + " ## Start of " ... " string + ( + \\. ## Escaped char + | ## OR + [^"\\] ## Non "\ + )* + " ## End of " ... " string + + | ## OR + + ' ## Start of ' ... ' string + ( + \\. ## Escaped char + | ## OR + [^'\\] ## Non '\ + )* + ' ## End of ' ... ' string + + | ## OR + + . ## Anything other char + [^/"'\\]* ## Chars which doesn't start a comment, string or escape + ) + }{$2}gxs; + +} diff --git a/third_party/zlib/v1_2_11/zutil.c b/third_party/zlib/v1_2_11/zutil.c new file mode 100644 index 0000000..a76c6b0 --- /dev/null +++ b/third_party/zlib/v1_2_11/zutil.c @@ -0,0 +1,325 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2017 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +z_const char * const z_errmsg[10] = { + (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ + (z_const char *)"stream end", /* Z_STREAM_END 1 */ + (z_const char *)"", /* Z_OK 0 */ + (z_const char *)"file error", /* Z_ERRNO (-1) */ + (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ + (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ + (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ + (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ + (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ + (z_const char *)"" +}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef ZLIB_DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef ZLIB_DEBUG +#include +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf; + ulg bsize = (ulg)items*size; + + (void)opaque; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + + (void)opaque; + + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + (void)opaque; + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + (void)opaque; + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + (void)opaque; + free(ptr); +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/third_party/zlib/v1_2_11/zutil.h b/third_party/zlib/v1_2_11/zutil.h new file mode 100644 index 0000000..b079ea6 --- /dev/null +++ b/third_party/zlib/v1_2_11/zutil.h @@ -0,0 +1,271 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 1 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 2 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef __370__ +# if __TARGET_LIB__ < 0x20000000 +# define OS_CODE 4 +# elif __TARGET_LIB__ < 0x40000000 +# define OS_CODE 11 +# else +# define OS_CODE 8 +# endif +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 5 +#endif + +#ifdef OS2 +# define OS_CODE 6 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 7 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef __acorn +# define OS_CODE 13 +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) +# define OS_CODE 10 +#endif + +#ifdef _BEOS_ +# define OS_CODE 16 +#endif + +#ifdef __TOS_OS400__ +# define OS_CODE 18 +#endif + +#ifdef __APPLE__ +# define OS_CODE 19 +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 3 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef ZLIB_DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */