# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


import ntpath
import os
import posixpath
import re
import subprocess
import sys

from collections import OrderedDict

import gyp.common
import gyp.easy_xml as easy_xml
import gyp.generator.ninja as ninja_generator
import gyp.MSVSNew as MSVSNew
import gyp.MSVSProject as MSVSProject
import gyp.MSVSSettings as MSVSSettings
import gyp.MSVSToolFile as MSVSToolFile
import gyp.MSVSUserFile as MSVSUserFile
import gyp.MSVSUtil as MSVSUtil
import gyp.MSVSVersion as MSVSVersion
from gyp.common import GypError
from gyp.common import OrderedSet


# Regular expression for validating Visual Studio GUIDs.  If the GUID
# contains lowercase hex letters, MSVS will be fine. However,
# IncrediBuild BuildConsole will parse the solution file, but then
# silently skip building the target causing hard to track down errors.
# Note that this only happens with the BuildConsole, and does not occur
# if IncrediBuild is executed from inside Visual Studio.  This regex
# validates that the string looks like a GUID with all uppercase hex
# letters.
VALID_MSVS_GUID_CHARS = re.compile(r"^[A-F0-9\-]+$")

generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()

generator_default_variables = {
    "DRIVER_PREFIX": "",
    "DRIVER_SUFFIX": ".sys",
    "EXECUTABLE_PREFIX": "",
    "EXECUTABLE_SUFFIX": ".exe",
    "STATIC_LIB_PREFIX": "",
    "SHARED_LIB_PREFIX": "",
    "STATIC_LIB_SUFFIX": ".lib",
    "SHARED_LIB_SUFFIX": ".dll",
    "INTERMEDIATE_DIR": "$(IntDir)",
    "SHARED_INTERMEDIATE_DIR": "$(OutDir)/obj/global_intermediate",
    "OS": "win",
    "PRODUCT_DIR": "$(OutDir)",
    "LIB_DIR": "$(OutDir)lib",
    "RULE_INPUT_ROOT": "$(InputName)",
    "RULE_INPUT_DIRNAME": "$(InputDir)",
    "RULE_INPUT_EXT": "$(InputExt)",
    "RULE_INPUT_NAME": "$(InputFileName)",
    "RULE_INPUT_PATH": "$(InputPath)",
    "CONFIGURATION_NAME": "$(ConfigurationName)",
}


# The msvs specific sections that hold paths
generator_additional_path_sections = [
    "msvs_cygwin_dirs",
    "msvs_props",
]


generator_additional_non_configuration_keys = [
    "msvs_cygwin_dirs",
    "msvs_cygwin_shell",
    "msvs_large_pdb",
    "msvs_shard",
    "msvs_external_builder",
    "msvs_external_builder_out_dir",
    "msvs_external_builder_build_cmd",
    "msvs_external_builder_clean_cmd",
    "msvs_external_builder_clcompile_cmd",
    "msvs_enable_winrt",
    "msvs_requires_importlibrary",
    "msvs_enable_winphone",
    "msvs_application_type_revision",
    "msvs_target_platform_version",
    "msvs_target_platform_minversion",
]

generator_filelist_paths = None

# List of precompiled header related keys.
precomp_keys = [
    "msvs_precompiled_header",
    "msvs_precompiled_source",
]


cached_username = None


cached_domain = None


# TODO(gspencer): Switch the os.environ calls to be
# win32api.GetDomainName() and win32api.GetUserName() once the
# python version in depot_tools has been updated to work on Vista
# 64-bit.
def _GetDomainAndUserName():
    if sys.platform not in ("win32", "cygwin"):
        return ("DOMAIN", "USERNAME")
    global cached_username
    global cached_domain
    if not cached_domain or not cached_username:
        domain = os.environ.get("USERDOMAIN")
        username = os.environ.get("USERNAME")
        if not domain or not username:
            call = subprocess.Popen(
                ["net", "config", "Workstation"], stdout=subprocess.PIPE
            )
            config = call.communicate()[0].decode("utf-8")
            username_re = re.compile(r"^User name\s+(\S+)", re.MULTILINE)
            username_match = username_re.search(config)
            if username_match:
                username = username_match.group(1)
            domain_re = re.compile(r"^Logon domain\s+(\S+)", re.MULTILINE)
            domain_match = domain_re.search(config)
            if domain_match:
                domain = domain_match.group(1)
        cached_domain = domain
        cached_username = username
    return (cached_domain, cached_username)


fixpath_prefix = None


def _NormalizedSource(source):
    """Normalize the path.

  But not if that gets rid of a variable, as this may expand to something
  larger than one directory.

  Arguments:
      source: The path to be normalize.d

  Returns:
      The normalized path.
  """
    normalized = os.path.normpath(source)
    if source.count("$") == normalized.count("$"):
        source = normalized
    return source


def _FixPath(path, separator="\\"):
    """Convert paths to a form that will make sense in a vcproj file.

  Arguments:
    path: The path to convert, may contain / etc.
  Returns:
    The path with all slashes made into backslashes.
  """
    if (
        fixpath_prefix
        and path
        and not os.path.isabs(path)
        and path[0] != "$"
        and not _IsWindowsAbsPath(path)
    ):
        path = os.path.join(fixpath_prefix, path)
    if separator == "\\":
        path = path.replace("/", "\\")
    path = _NormalizedSource(path)
    if separator == "/":
        path = path.replace("\\", "/")
    if path and path[-1] == separator:
        path = path[:-1]
    return path


def _IsWindowsAbsPath(path):
    """
  On Cygwin systems Python needs a little help determining if a path
  is an absolute Windows path or not, so that
  it does not treat those as relative, which results in bad paths like:
  '..\\C:\\<some path>\\some_source_code_file.cc'
  """
    return path.startswith("c:") or path.startswith("C:")


def _FixPaths(paths, separator="\\"):
    """Fix each of the paths of the list."""
    return [_FixPath(i, separator) for i in paths]


def _ConvertSourcesToFilterHierarchy(
    sources, prefix=None, excluded=None, list_excluded=True, msvs_version=None
):
    """Converts a list split source file paths into a vcproj folder hierarchy.

  Arguments:
    sources: A list of source file paths split.
    prefix: A list of source file path layers meant to apply to each of sources.
    excluded: A set of excluded files.
    msvs_version: A MSVSVersion object.

  Returns:
    A hierarchy of filenames and MSVSProject.Filter objects that matches the
    layout of the source tree.
    For example:
    _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
                                     prefix=['joe'])
    -->
    [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
     MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])]
  """
    if not prefix:
        prefix = []
    result = []
    excluded_result = []
    folders = OrderedDict()
    # Gather files into the final result, excluded, or folders.
    for s in sources:
        if len(s) == 1:
            filename = _NormalizedSource("\\".join(prefix + s))
            if filename in excluded:
                excluded_result.append(filename)
            else:
                result.append(filename)
        elif msvs_version and not msvs_version.UsesVcxproj():
            # For MSVS 2008 and earlier, we need to process all files before walking
            # the sub folders.
            if not folders.get(s[0]):
                folders[s[0]] = []
            folders[s[0]].append(s[1:])
        else:
            contents = _ConvertSourcesToFilterHierarchy(
                [s[1:]],
                prefix + [s[0]],
                excluded=excluded,
                list_excluded=list_excluded,
                msvs_version=msvs_version,
            )
            contents = MSVSProject.Filter(s[0], contents=contents)
            result.append(contents)
    # Add a folder for excluded files.
    if excluded_result and list_excluded:
        excluded_folder = MSVSProject.Filter(
            "_excluded_files", contents=excluded_result
        )
        result.append(excluded_folder)

    if msvs_version and msvs_version.UsesVcxproj():
        return result

    # Populate all the folders.
    for f in folders:
        contents = _ConvertSourcesToFilterHierarchy(
            folders[f],
            prefix=prefix + [f],
            excluded=excluded,
            list_excluded=list_excluded,
            msvs_version=msvs_version,
        )
        contents = MSVSProject.Filter(f, contents=contents)
        result.append(contents)
    return result


def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False):
    if not value:
        return
    _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset)


def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False):
    # TODO(bradnelson): ugly hack, fix this more generally!!!
    if "Directories" in setting or "Dependencies" in setting:
        if type(value) == str:
            value = value.replace("/", "\\")
        else:
            value = [i.replace("/", "\\") for i in value]
    if not tools.get(tool_name):
        tools[tool_name] = {}
    tool = tools[tool_name]
    if setting == "CompileAsWinRT":
        return
    if tool.get(setting):
        if only_if_unset:
            return
        if type(tool[setting]) == list and type(value) == list:
            tool[setting] += value
        else:
            raise TypeError(
                'Appending "%s" to a non-list setting "%s" for tool "%s" is '
                "not allowed, previous value: %s"
                % (value, setting, tool_name, str(tool[setting]))
            )
    else:
        tool[setting] = value


def _ConfigTargetVersion(config_data):
    return config_data.get("msvs_target_version", "Windows7")


def _ConfigPlatform(config_data):
    return config_data.get("msvs_configuration_platform", "Win32")


def _ConfigBaseName(config_name, platform_name):
    if config_name.endswith("_" + platform_name):
        return config_name[0 : -len(platform_name) - 1]
    else:
        return config_name


def _ConfigFullName(config_name, config_data):
    platform_name = _ConfigPlatform(config_data)
    return f"{_ConfigBaseName(config_name, platform_name)}|{platform_name}"


def _ConfigWindowsTargetPlatformVersion(config_data, version):
    target_ver = config_data.get("msvs_windows_target_platform_version")
    if target_ver and re.match(r"^\d+", target_ver):
        return target_ver
    config_ver = config_data.get("msvs_windows_sdk_version")
    vers = [config_ver] if config_ver else version.compatible_sdks
    for ver in vers:
        for key in [
            r"HKLM\Software\Microsoft\Microsoft SDKs\Windows\%s",
            r"HKLM\Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows\%s",
        ]:
            sdk_dir = MSVSVersion._RegistryGetValue(key % ver, "InstallationFolder")
            if not sdk_dir:
                continue
            version = MSVSVersion._RegistryGetValue(key % ver, "ProductVersion") or ""
            # Find a matching entry in sdk_dir\include.
            expected_sdk_dir = r"%s\include" % sdk_dir
            names = sorted(
                (
                    x
                    for x in (
                        os.listdir(expected_sdk_dir)
                        if os.path.isdir(expected_sdk_dir)
                        else []
                    )
                    if x.startswith(version)
                ),
                reverse=True,
            )
            if names:
                return names[0]
            else:
                print(
                    "Warning: No include files found for detected "
                    "Windows SDK version %s" % (version),
                    file=sys.stdout,
                )


def _BuildCommandLineForRuleRaw(
    spec, cmd, cygwin_shell, has_input_path, quote_cmd, do_setup_env
):

    if [x for x in cmd if "$(InputDir)" in x]:
        input_dir_preamble = (
            "set INPUTDIR=$(InputDir)\n"
            "if NOT DEFINED INPUTDIR set INPUTDIR=.\\\n"
            "set INPUTDIR=%INPUTDIR:~0,-1%\n"
        )
    else:
        input_dir_preamble = ""

    if cygwin_shell:
        # Find path to cygwin.
        cygwin_dir = _FixPath(spec.get("msvs_cygwin_dirs", ["."])[0])
        # Prepare command.
        direct_cmd = cmd
        direct_cmd = [
            i.replace("$(IntDir)", '`cygpath -m "${INTDIR}"`') for i in direct_cmd
        ]
        direct_cmd = [
            i.replace("$(OutDir)", '`cygpath -m "${OUTDIR}"`') for i in direct_cmd
        ]
        direct_cmd = [
            i.replace("$(InputDir)", '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd
        ]
        if has_input_path:
            direct_cmd = [
                i.replace("$(InputPath)", '`cygpath -m "${INPUTPATH}"`')
                for i in direct_cmd
            ]
        direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd]
        # direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd)
        direct_cmd = " ".join(direct_cmd)
        # TODO(quote):  regularize quoting path names throughout the module
        cmd = ""
        if do_setup_env:
            cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && '
        cmd += "set CYGWIN=nontsec&& "
        if direct_cmd.find("NUMBER_OF_PROCESSORS") >= 0:
            cmd += "set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& "
        if direct_cmd.find("INTDIR") >= 0:
            cmd += "set INTDIR=$(IntDir)&& "
        if direct_cmd.find("OUTDIR") >= 0:
            cmd += "set OUTDIR=$(OutDir)&& "
        if has_input_path and direct_cmd.find("INPUTPATH") >= 0:
            cmd += "set INPUTPATH=$(InputPath) && "
        cmd += 'bash -c "%(cmd)s"'
        cmd = cmd % {"cygwin_dir": cygwin_dir, "cmd": direct_cmd}
        return input_dir_preamble + cmd
    else:
        # Convert cat --> type to mimic unix.
        command = ["type"] if cmd[0] == "cat" else [cmd[0].replace("/", "\\")]
        # Add call before command to ensure that commands can be tied together one
        # after the other without aborting in Incredibuild, since IB makes a bat
        # file out of the raw command string, and some commands (like python) are
        # actually batch files themselves.
        command.insert(0, "call")
        # Fix the paths
        # TODO(quote): This is a really ugly heuristic, and will miss path fixing
        #              for arguments like "--arg=path", arg=path, or "/opt:path".
        # If the argument starts with a slash or dash, or contains an equal sign,
        # it's probably a command line switch.
        # Return the path with forward slashes because the command using it might
        # not support backslashes.
        arguments = [
            i if (i[:1] in "/-" or "=" in i) else _FixPath(i, "/")
            for i in cmd[1:]
        ]
        arguments = [i.replace("$(InputDir)", "%INPUTDIR%") for i in arguments]
        arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments]
        if quote_cmd:
            # Support a mode for using cmd directly.
            # Convert any paths to native form (first element is used directly).
            # TODO(quote):  regularize quoting path names throughout the module
            command[1] = '"%s"' % command[1]
            arguments = ['"%s"' % i for i in arguments]
        # Collapse into a single command.
        return input_dir_preamble + " ".join(command + arguments)


def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env):
    # Currently this weird argument munging is used to duplicate the way a
    # python script would need to be run as part of the chrome tree.
    # Eventually we should add some sort of rule_default option to set this
    # per project. For now the behavior chrome needs is the default.
    mcs = rule.get("msvs_cygwin_shell")
    if mcs is None:
        mcs = int(spec.get("msvs_cygwin_shell", 1))
    elif isinstance(mcs, str):
        mcs = int(mcs)
    quote_cmd = int(rule.get("msvs_quote_cmd", 1))
    return _BuildCommandLineForRuleRaw(
        spec, rule["action"], mcs, has_input_path, quote_cmd, do_setup_env=do_setup_env
    )


def _AddActionStep(actions_dict, inputs, outputs, description, command):
    """Merge action into an existing list of actions.

  Care must be taken so that actions which have overlapping inputs either don't
  get assigned to the same input, or get collapsed into one.

  Arguments:
    actions_dict: dictionary keyed on input name, which maps to a list of
      dicts describing the actions attached to that input file.
    inputs: list of inputs
    outputs: list of outputs
    description: description of the action
    command: command line to execute
  """
    # Require there to be at least one input (call sites will ensure this).
    assert inputs

    action = {
        "inputs": inputs,
        "outputs": outputs,
        "description": description,
        "command": command,
    }

    # Pick where to stick this action.
    # While less than optimal in terms of build time, attach them to the first
    # input for now.
    chosen_input = inputs[0]

    # Add it there.
    if chosen_input not in actions_dict:
        actions_dict[chosen_input] = []
    actions_dict[chosen_input].append(action)


def _AddCustomBuildToolForMSVS(
    p, spec, primary_input, inputs, outputs, description, cmd
):
    """Add a custom build tool to execute something.

  Arguments:
    p: the target project
    spec: the target project dict
    primary_input: input file to attach the build tool to
    inputs: list of inputs
    outputs: list of outputs
    description: description of the action
    cmd: command line to execute
  """
    inputs = _FixPaths(inputs)
    outputs = _FixPaths(outputs)
    tool = MSVSProject.Tool(
        "VCCustomBuildTool",
        {
            "Description": description,
            "AdditionalDependencies": ";".join(inputs),
            "Outputs": ";".join(outputs),
            "CommandLine": cmd,
        },
    )
    # Add to the properties of primary input for each config.
    for config_name, c_data in spec["configurations"].items():
        p.AddFileConfig(
            _FixPath(primary_input), _ConfigFullName(config_name, c_data), tools=[tool]
        )


def _AddAccumulatedActionsToMSVS(p, spec, actions_dict):
    """Add actions accumulated into an actions_dict, merging as needed.

  Arguments:
    p: the target project
    spec: the target project dict
    actions_dict: dictionary keyed on input name, which maps to a list of
        dicts describing the actions attached to that input file.
  """
    for primary_input in actions_dict:
        inputs = OrderedSet()
        outputs = OrderedSet()
        descriptions = []
        commands = []
        for action in actions_dict[primary_input]:
            inputs.update(OrderedSet(action["inputs"]))
            outputs.update(OrderedSet(action["outputs"]))
            descriptions.append(action["description"])
            commands.append(action["command"])
        # Add the custom build step for one input file.
        description = ", and also ".join(descriptions)
        command = "\r\n".join(commands)
        _AddCustomBuildToolForMSVS(
            p,
            spec,
            primary_input=primary_input,
            inputs=inputs,
            outputs=outputs,
            description=description,
            cmd=command,
        )


def _RuleExpandPath(path, input_file):
    """Given the input file to which a rule applied, string substitute a path.

  Arguments:
    path: a path to string expand
    input_file: the file to which the rule applied.
  Returns:
    The string substituted path.
  """
    path = path.replace(
        "$(InputName)", os.path.splitext(os.path.split(input_file)[1])[0]
    )
    path = path.replace("$(InputDir)", os.path.dirname(input_file))
    path = path.replace(
        "$(InputExt)", os.path.splitext(os.path.split(input_file)[1])[1]
    )
    path = path.replace("$(InputFileName)", os.path.split(input_file)[1])
    path = path.replace("$(InputPath)", input_file)
    return path


def _FindRuleTriggerFiles(rule, sources):
    """Find the list of files which a particular rule applies to.

  Arguments:
    rule: the rule in question
    sources: the set of all known source files for this project
  Returns:
    The list of sources that trigger a particular rule.
  """
    return rule.get("rule_sources", [])


def _RuleInputsAndOutputs(rule, trigger_file):
    """Find the inputs and outputs generated by a rule.

  Arguments:
    rule: the rule in question.
    trigger_file: the main trigger for this rule.
  Returns:
    The pair of (inputs, outputs) involved in this rule.
  """
    raw_inputs = _FixPaths(rule.get("inputs", []))
    raw_outputs = _FixPaths(rule.get("outputs", []))
    inputs = OrderedSet()
    outputs = OrderedSet()
    inputs.add(trigger_file)
    for i in raw_inputs:
        inputs.add(_RuleExpandPath(i, trigger_file))
    for o in raw_outputs:
        outputs.add(_RuleExpandPath(o, trigger_file))
    return (inputs, outputs)


def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
    """Generate a native rules file.

  Arguments:
    p: the target project
    rules: the set of rules to include
    output_dir: the directory in which the project/gyp resides
    spec: the project dict
    options: global generator options
  """
    rules_filename = "{}{}.rules".format(spec["target_name"], options.suffix)
    rules_file = MSVSToolFile.Writer(
        os.path.join(output_dir, rules_filename), spec["target_name"]
    )
    # Add each rule.
    for r in rules:
        rule_name = r["rule_name"]
        rule_ext = r["extension"]
        inputs = _FixPaths(r.get("inputs", []))
        outputs = _FixPaths(r.get("outputs", []))
        # Skip a rule with no action and no inputs.
        if "action" not in r and not r.get("rule_sources", []):
            continue
        cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, do_setup_env=True)
        rules_file.AddCustomBuildRule(
            name=rule_name,
            description=r.get("message", rule_name),
            extensions=[rule_ext],
            additional_dependencies=inputs,
            outputs=outputs,
            cmd=cmd,
        )
    # Write out rules file.
    rules_file.WriteIfChanged()

    # Add rules file to project.
    p.AddToolFile(rules_filename)


def _Cygwinify(path):
    path = path.replace("$(OutDir)", "$(OutDirCygwin)")
    path = path.replace("$(IntDir)", "$(IntDirCygwin)")
    return path


def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to_add):
    """Generate an external makefile to do a set of rules.

  Arguments:
    rules: the list of rules to include
    output_dir: path containing project and gyp files
    spec: project specification data
    sources: set of sources known
    options: global generator options
    actions_to_add: The list of actions we will add to.
  """
    filename = "{}_rules{}.mk".format(spec["target_name"], options.suffix)
    mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename))
    # Find cygwin style versions of some paths.
    mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n')
    mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n')
    # Gather stuff needed to emit all: target.
    all_inputs = OrderedSet()
    all_outputs = OrderedSet()
    all_output_dirs = OrderedSet()
    first_outputs = []
    for rule in rules:
        trigger_files = _FindRuleTriggerFiles(rule, sources)
        for tf in trigger_files:
            inputs, outputs = _RuleInputsAndOutputs(rule, tf)
            all_inputs.update(OrderedSet(inputs))
            all_outputs.update(OrderedSet(outputs))
            # Only use one target from each rule as the dependency for
            # 'all' so we don't try to build each rule multiple times.
            first_outputs.append(next(iter(outputs)))
            # Get the unique output directories for this rule.
            output_dirs = [os.path.split(i)[0] for i in outputs]
            for od in output_dirs:
                all_output_dirs.add(od)
    first_outputs_cyg = [_Cygwinify(i) for i in first_outputs]
    # Write out all: target, including mkdir for each output directory.
    mk_file.write("all: %s\n" % " ".join(first_outputs_cyg))
    for od in all_output_dirs:
        if od:
            mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od)
    mk_file.write("\n")
    # Define how each output is generated.
    for rule in rules:
        trigger_files = _FindRuleTriggerFiles(rule, sources)
        for tf in trigger_files:
            # Get all the inputs and outputs for this rule for this trigger file.
            inputs, outputs = _RuleInputsAndOutputs(rule, tf)
            inputs = [_Cygwinify(i) for i in inputs]
            outputs = [_Cygwinify(i) for i in outputs]
            # Prepare the command line for this rule.
            cmd = [_RuleExpandPath(c, tf) for c in rule["action"]]
            cmd = ['"%s"' % i for i in cmd]
            cmd = " ".join(cmd)
            # Add it to the makefile.
            mk_file.write("{}: {}\n".format(" ".join(outputs), " ".join(inputs)))
            mk_file.write("\t%s\n\n" % cmd)
    # Close up the file.
    mk_file.close()

    # Add makefile to list of sources.
    sources.add(filename)
    # Add a build action to call makefile.
    cmd = [
        "make",
        "OutDir=$(OutDir)",
        "IntDir=$(IntDir)",
        "-j",
        "${NUMBER_OF_PROCESSORS_PLUS_1}",
        "-f",
        filename,
    ]
    cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True)
    # Insert makefile as 0'th input, so it gets the action attached there,
    # as this is easier to understand from in the IDE.
    all_inputs = list(all_inputs)
    all_inputs.insert(0, filename)
    _AddActionStep(
        actions_to_add,
        inputs=_FixPaths(all_inputs),
        outputs=_FixPaths(all_outputs),
        description="Running external rules for %s" % spec["target_name"],
        command=cmd,
    )


def _EscapeEnvironmentVariableExpansion(s):
    """Escapes % characters.

  Escapes any % characters so that Windows-style environment variable
  expansions will leave them alone.
  See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
  to understand why we have to do this.

  Args:
      s: The string to be escaped.

  Returns:
      The escaped string.
  """
    s = s.replace("%", "%%")
    return s


quote_replacer_regex = re.compile(r'(\\*)"')


def _EscapeCommandLineArgumentForMSVS(s):
    """Escapes a Windows command-line argument.

  So that the Win32 CommandLineToArgv function will turn the escaped result back
  into the original string.
  See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  ("Parsing C++ Command-Line Arguments") to understand why we have to do
  this.

  Args:
      s: the string to be escaped.
  Returns:
      the escaped string.
  """

    def _Replace(match):
        # For a literal quote, CommandLineToArgv requires an odd number of
        # backslashes preceding it, and it produces half as many literal backslashes
        # (rounded down). So we need to produce 2n+1 backslashes.
        return 2 * match.group(1) + '\\"'

    # Escape all quotes so that they are interpreted literally.
    s = quote_replacer_regex.sub(_Replace, s)
    # Now add unescaped quotes so that any whitespace is interpreted literally.
    s = '"' + s + '"'
    return s


delimiters_replacer_regex = re.compile(r"(\\*)([,;]+)")


def _EscapeVCProjCommandLineArgListItem(s):
    """Escapes command line arguments for MSVS.

  The VCProj format stores string lists in a single string using commas and
  semi-colons as separators, which must be quoted if they are to be
  interpreted literally. However, command-line arguments may already have
  quotes, and the VCProj parser is ignorant of the backslash escaping
  convention used by CommandLineToArgv, so the command-line quotes and the
  VCProj quotes may not be the same quotes. So to store a general
  command-line argument in a VCProj list, we need to parse the existing
  quoting according to VCProj's convention and quote any delimiters that are
  not already quoted by that convention. The quotes that we add will also be
  seen by CommandLineToArgv, so if backslashes precede them then we also have
  to escape those backslashes according to the CommandLineToArgv
  convention.

  Args:
      s: the string to be escaped.
  Returns:
      the escaped string.
  """

    def _Replace(match):
        # For a non-literal quote, CommandLineToArgv requires an even number of
        # backslashes preceding it, and it produces half as many literal
        # backslashes. So we need to produce 2n backslashes.
        return 2 * match.group(1) + '"' + match.group(2) + '"'

    segments = s.split('"')
    # The unquoted segments are at the even-numbered indices.
    for i in range(0, len(segments), 2):
        segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i])
    # Concatenate back into a single string
    s = '"'.join(segments)
    if len(segments) % 2 == 0:
        # String ends while still quoted according to VCProj's convention. This
        # means the delimiter and the next list item that follow this one in the
        # .vcproj file will be misinterpreted as part of this item. There is nothing
        # we can do about this. Adding an extra quote would correct the problem in
        # the VCProj but cause the same problem on the final command-line. Moving
        # the item to the end of the list does works, but that's only possible if
        # there's only one such item. Let's just warn the user.
        print(
            "Warning: MSVS may misinterpret the odd number of " + "quotes in " + s,
            file=sys.stderr,
        )
    return s


def _EscapeCppDefineForMSVS(s):
    """Escapes a CPP define so that it will reach the compiler unaltered."""
    s = _EscapeEnvironmentVariableExpansion(s)
    s = _EscapeCommandLineArgumentForMSVS(s)
    s = _EscapeVCProjCommandLineArgListItem(s)
    # cl.exe replaces literal # characters with = in preprocessor definitions for
    # some reason. Octal-encode to work around that.
    s = s.replace("#", "\\%03o" % ord("#"))
    return s


quote_replacer_regex2 = re.compile(r'(\\+)"')


def _EscapeCommandLineArgumentForMSBuild(s):
    """Escapes a Windows command-line argument for use by MSBuild."""

    def _Replace(match):
        return (len(match.group(1)) / 2 * 4) * "\\" + '\\"'

    # Escape all quotes so that they are interpreted literally.
    s = quote_replacer_regex2.sub(_Replace, s)
    return s


def _EscapeMSBuildSpecialCharacters(s):
    escape_dictionary = {
        "%": "%25",
        "$": "%24",
        "@": "%40",
        "'": "%27",
        ";": "%3B",
        "?": "%3F",
        "*": "%2A",
    }
    result = "".join([escape_dictionary.get(c, c) for c in s])
    return result


def _EscapeCppDefineForMSBuild(s):
    """Escapes a CPP define so that it will reach the compiler unaltered."""
    s = _EscapeEnvironmentVariableExpansion(s)
    s = _EscapeCommandLineArgumentForMSBuild(s)
    s = _EscapeMSBuildSpecialCharacters(s)
    # cl.exe replaces literal # characters with = in preprocessor definitions for
    # some reason. Octal-encode to work around that.
    s = s.replace("#", "\\%03o" % ord("#"))
    return s


def _GenerateRulesForMSVS(
    p, output_dir, options, spec, sources, excluded_sources, actions_to_add
):
    """Generate all the rules for a particular project.

  Arguments:
    p: the project
    output_dir: directory to emit rules to
    options: global options passed to the generator
    spec: the specification for this project
    sources: the set of all known source files in this project
    excluded_sources: the set of sources excluded from normal processing
    actions_to_add: deferred list of actions to add in
  """
    rules = spec.get("rules", [])
    rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))]
    rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))]

    # Handle rules that use a native rules file.
    if rules_native:
        _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options)

    # Handle external rules (non-native rules).
    if rules_external:
        _GenerateExternalRules(
            rules_external, output_dir, spec, sources, options, actions_to_add
        )
    _AdjustSourcesForRules(rules, sources, excluded_sources, False)


def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild):
    # Add outputs generated by each rule (if applicable).
    for rule in rules:
        # Add in the outputs from this rule.
        trigger_files = _FindRuleTriggerFiles(rule, sources)
        for trigger_file in trigger_files:
            # Remove trigger_file from excluded_sources to let the rule be triggered
            # (e.g. rule trigger ax_enums.idl is added to excluded_sources
            # because it's also in an action's inputs in the same project)
            excluded_sources.discard(_FixPath(trigger_file))
            # Done if not processing outputs as sources.
            if int(rule.get("process_outputs_as_sources", False)):
                inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file)
                inputs = OrderedSet(_FixPaths(inputs))
                outputs = OrderedSet(_FixPaths(outputs))
                inputs.remove(_FixPath(trigger_file))
                sources.update(inputs)
                if not is_msbuild:
                    excluded_sources.update(inputs)
                sources.update(outputs)


def _FilterActionsFromExcluded(excluded_sources, actions_to_add):
    """Take inputs with actions attached out of the list of exclusions.

  Arguments:
    excluded_sources: list of source files not to be built.
    actions_to_add: dict of actions keyed on source file they're attached to.
  Returns:
    excluded_sources with files that have actions attached removed.
  """
    must_keep = OrderedSet(_FixPaths(actions_to_add.keys()))
    return [s for s in excluded_sources if s not in must_keep]


def _GetDefaultConfiguration(spec):
    return spec["configurations"][spec["default_configuration"]]


def _GetGuidOfProject(proj_path, spec):
    """Get the guid for the project.

  Arguments:
    proj_path: Path of the vcproj or vcxproj file to generate.
    spec: The target dictionary containing the properties of the target.
  Returns:
    the guid.
  Raises:
    ValueError: if the specified GUID is invalid.
  """
    # Pluck out the default configuration.
    default_config = _GetDefaultConfiguration(spec)
    # Decide the guid of the project.
    guid = default_config.get("msvs_guid")
    if guid:
        if VALID_MSVS_GUID_CHARS.match(guid) is None:
            raise ValueError(
                'Invalid MSVS guid: "%s".  Must match regex: "%s".'
                % (guid, VALID_MSVS_GUID_CHARS.pattern)
            )
        guid = "{%s}" % guid
    guid = guid or MSVSNew.MakeGuid(proj_path)
    return guid


def _GetMsbuildToolsetOfProject(proj_path, spec, version):
    """Get the platform toolset for the project.

  Arguments:
    proj_path: Path of the vcproj or vcxproj file to generate.
    spec: The target dictionary containing the properties of the target.
    version: The MSVSVersion object.
  Returns:
    the platform toolset string or None.
  """
    # Pluck out the default configuration.
    default_config = _GetDefaultConfiguration(spec)
    toolset = default_config.get("msbuild_toolset")
    if not toolset and version.DefaultToolset():
        toolset = version.DefaultToolset()
    if spec["type"] == "windows_driver":
        toolset = "WindowsKernelModeDriver10.0"
    return toolset


def _GenerateProject(project, options, version, generator_flags, spec):
    """Generates a vcproj file.

  Arguments:
    project: the MSVSProject object.
    options: global generator options.
    version: the MSVSVersion object.
    generator_flags: dict of generator-specific flags.
  Returns:
    A list of source files that cannot be found on disk.
  """
    default_config = _GetDefaultConfiguration(project.spec)

    # Skip emitting anything if told to with msvs_existing_vcproj option.
    if default_config.get("msvs_existing_vcproj"):
        return []

    if version.UsesVcxproj():
        return _GenerateMSBuildProject(project, options, version, generator_flags, spec)
    else:
        return _GenerateMSVSProject(project, options, version, generator_flags)


def _GenerateMSVSProject(project, options, version, generator_flags):
    """Generates a .vcproj file.  It may create .rules and .user files too.

  Arguments:
    project: The project object we will generate the file for.
    options: Global options passed to the generator.
    version: The VisualStudioVersion object.
    generator_flags: dict of generator-specific flags.
  """
    spec = project.spec
    gyp.common.EnsureDirExists(project.path)

    platforms = _GetUniquePlatforms(spec)
    p = MSVSProject.Writer(
        project.path, version, spec["target_name"], project.guid, platforms
    )

    # Get directory project file is in.
    project_dir = os.path.split(project.path)[0]
    gyp_path = _NormalizedSource(project.build_file)
    relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)

    config_type = _GetMSVSConfigurationType(spec, project.build_file)
    for config_name, config in spec["configurations"].items():
        _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)

    # Prepare list of sources and excluded sources.
    gyp_file = os.path.split(project.build_file)[1]
    sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file)

    # Add rules.
    actions_to_add = {}
    _GenerateRulesForMSVS(
        p, project_dir, options, spec, sources, excluded_sources, actions_to_add
    )
    list_excluded = generator_flags.get("msvs_list_excluded_files", True)
    sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy(
        spec, options, project_dir, sources, excluded_sources, list_excluded, version
    )

    # Add in files.
    missing_sources = _VerifySourcesExist(sources, project_dir)
    p.AddFiles(sources)

    _AddToolFilesToMSVS(p, spec)
    _HandlePreCompiledHeaders(p, sources, spec)
    _AddActions(actions_to_add, spec, relative_path_of_gyp_file)
    _AddCopies(actions_to_add, spec)
    _WriteMSVSUserFile(project.path, version, spec)

    # NOTE: this stanza must appear after all actions have been decided.
    # Don't excluded sources with actions attached, or they won't run.
    excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add)
    _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded)
    _AddAccumulatedActionsToMSVS(p, spec, actions_to_add)

    # Write it out.
    p.WriteIfChanged()

    return missing_sources


def _GetUniquePlatforms(spec):
    """Returns the list of unique platforms for this spec, e.g ['win32', ...].

  Arguments:
    spec: The target dictionary containing the properties of the target.
  Returns:
    The MSVSUserFile object created.
  """
    # Gather list of unique platforms.
    platforms = OrderedSet()
    for configuration in spec["configurations"]:
        platforms.add(_ConfigPlatform(spec["configurations"][configuration]))
    platforms = list(platforms)
    return platforms


def _CreateMSVSUserFile(proj_path, version, spec):
    """Generates a .user file for the user running this Gyp program.

  Arguments:
    proj_path: The path of the project file being created.  The .user file
               shares the same path (with an appropriate suffix).
    version: The VisualStudioVersion object.
    spec: The target dictionary containing the properties of the target.
  Returns:
    The MSVSUserFile object created.
  """
    (domain, username) = _GetDomainAndUserName()
    vcuser_filename = ".".join([proj_path, domain, username, "user"])
    user_file = MSVSUserFile.Writer(vcuser_filename, version, spec["target_name"])
    return user_file


def _GetMSVSConfigurationType(spec, build_file):
    """Returns the configuration type for this project.

  It's a number defined by Microsoft.  May raise an exception.

  Args:
      spec: The target dictionary containing the properties of the target.
      build_file: The path of the gyp file.
  Returns:
      An integer, the configuration type.
  """
    try:
        config_type = {
            "executable": "1",  # .exe
            "shared_library": "2",  # .dll
            "loadable_module": "2",  # .dll
            "static_library": "4",  # .lib
            "windows_driver": "5",  # .sys
            "none": "10",  # Utility type
        }[spec["type"]]
    except KeyError:
        if spec.get("type"):
            raise GypError(
                "Target type %s is not a valid target type for "
                "target %s in %s." % (spec["type"], spec["target_name"], build_file)
            )
        else:
            raise GypError(
                "Missing type field for target %s in %s."
                % (spec["target_name"], build_file)
            )
    return config_type


def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config):
    """Adds a configuration to the MSVS project.

  Many settings in a vcproj file are specific to a configuration.  This
  function the main part of the vcproj file that's configuration specific.

  Arguments:
    p: The target project being generated.
    spec: The target dictionary containing the properties of the target.
    config_type: The configuration type, a number as defined by Microsoft.
    config_name: The name of the configuration.
    config: The dictionary that defines the special processing to be done
            for this configuration.
  """
    # Get the information for this configuration
    include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(config)
    libraries = _GetLibraries(spec)
    library_dirs = _GetLibraryDirs(config)
    out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False)
    defines = _GetDefines(config)
    defines = [_EscapeCppDefineForMSVS(d) for d in defines]
    disabled_warnings = _GetDisabledWarnings(config)
    prebuild = config.get("msvs_prebuild")
    postbuild = config.get("msvs_postbuild")
    def_file = _GetModuleDefinition(spec)
    precompiled_header = config.get("msvs_precompiled_header")

    # Prepare the list of tools as a dictionary.
    tools = {}
    # Add in user specified msvs_settings.
    msvs_settings = config.get("msvs_settings", {})
    MSVSSettings.ValidateMSVSSettings(msvs_settings)

    # Prevent default library inheritance from the environment.
    _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", ["$(NOINHERIT)"])

    for tool in msvs_settings:
        settings = config["msvs_settings"][tool]
        for setting in settings:
            _ToolAppend(tools, tool, setting, settings[setting])
    # Add the information to the appropriate tool
    _ToolAppend(tools, "VCCLCompilerTool", "AdditionalIncludeDirectories", include_dirs)
    _ToolAppend(tools, "VCMIDLTool", "AdditionalIncludeDirectories", midl_include_dirs)
    _ToolAppend(
        tools,
        "VCResourceCompilerTool",
        "AdditionalIncludeDirectories",
        resource_include_dirs,
    )
    # Add in libraries.
    _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", libraries)
    _ToolAppend(tools, "VCLinkerTool", "AdditionalLibraryDirectories", library_dirs)
    if out_file:
        _ToolAppend(tools, vc_tool, "OutputFile", out_file, only_if_unset=True)
    # Add defines.
    _ToolAppend(tools, "VCCLCompilerTool", "PreprocessorDefinitions", defines)
    _ToolAppend(tools, "VCResourceCompilerTool", "PreprocessorDefinitions", defines)
    # Change program database directory to prevent collisions.
    _ToolAppend(
        tools,
        "VCCLCompilerTool",
        "ProgramDataBaseFileName",
        "$(IntDir)$(ProjectName)\\vc80.pdb",
        only_if_unset=True,
    )
    # Add disabled warnings.
    _ToolAppend(tools, "VCCLCompilerTool", "DisableSpecificWarnings", disabled_warnings)
    # Add Pre-build.
    _ToolAppend(tools, "VCPreBuildEventTool", "CommandLine", prebuild)
    # Add Post-build.
    _ToolAppend(tools, "VCPostBuildEventTool", "CommandLine", postbuild)
    # Turn on precompiled headers if appropriate.
    if precompiled_header:
        precompiled_header = os.path.split(precompiled_header)[1]
        _ToolAppend(tools, "VCCLCompilerTool", "UsePrecompiledHeader", "2")
        _ToolAppend(
            tools, "VCCLCompilerTool", "PrecompiledHeaderThrough", precompiled_header
        )
        _ToolAppend(tools, "VCCLCompilerTool", "ForcedIncludeFiles", precompiled_header)
    # Loadable modules don't generate import libraries;
    # tell dependent projects to not expect one.
    if spec["type"] == "loadable_module":
        _ToolAppend(tools, "VCLinkerTool", "IgnoreImportLibrary", "true")
    # Set the module definition file if any.
    if def_file:
        _ToolAppend(tools, "VCLinkerTool", "ModuleDefinitionFile", def_file)

    _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name)


def _GetIncludeDirs(config):
    """Returns the list of directories to be used for #include directives.

  Arguments:
    config: The dictionary that defines the special processing to be done
            for this configuration.
  Returns:
    The list of directory paths.
  """
    # TODO(bradnelson): include_dirs should really be flexible enough not to
    #                   require this sort of thing.
    include_dirs = config.get("include_dirs", []) + config.get(
        "msvs_system_include_dirs", []
    )
    midl_include_dirs = config.get("midl_include_dirs", []) + config.get(
        "msvs_system_include_dirs", []
    )
    resource_include_dirs = config.get("resource_include_dirs", include_dirs)
    include_dirs = _FixPaths(include_dirs)
    midl_include_dirs = _FixPaths(midl_include_dirs)
    resource_include_dirs = _FixPaths(resource_include_dirs)
    return include_dirs, midl_include_dirs, resource_include_dirs


def _GetLibraryDirs(config):
    """Returns the list of directories to be used for library search paths.

  Arguments:
    config: The dictionary that defines the special processing to be done
            for this configuration.
  Returns:
    The list of directory paths.
  """

    library_dirs = config.get("library_dirs", [])
    library_dirs = _FixPaths(library_dirs)
    return library_dirs


def _GetLibraries(spec):
    """Returns the list of libraries for this configuration.

  Arguments:
    spec: The target dictionary containing the properties of the target.
  Returns:
    The list of directory paths.
  """
    libraries = spec.get("libraries", [])
    # Strip out -l, as it is not used on windows (but is needed so we can pass
    # in libraries that are assumed to be in the default library path).
    # Also remove duplicate entries, leaving only the last duplicate, while
    # preserving order.
    found = OrderedSet()
    unique_libraries_list = []
    for entry in reversed(libraries):
        library = re.sub(r"^\-l", "", entry)
        if not os.path.splitext(library)[1]:
            library += ".lib"
        if library not in found:
            found.add(library)
            unique_libraries_list.append(library)
    unique_libraries_list.reverse()
    return unique_libraries_list


def _GetOutputFilePathAndTool(spec, msbuild):
    """Returns the path and tool to use for this target.

  Figures out the path of the file this spec will create and the name of
  the VC tool that will create it.

  Arguments:
    spec: The target dictionary containing the properties of the target.
  Returns:
    A triple of (file path, name of the vc tool, name of the msbuild tool)
  """
    # Select a name for the output file.
    out_file = ""
    vc_tool = ""
    msbuild_tool = ""
    output_file_map = {
        "executable": ("VCLinkerTool", "Link", "$(OutDir)", ".exe"),
        "shared_library": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"),
        "loadable_module": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"),
        "windows_driver": ("VCLinkerTool", "Link", "$(OutDir)", ".sys"),
        "static_library": ("VCLibrarianTool", "Lib", "$(OutDir)lib\\", ".lib"),
    }
    output_file_props = output_file_map.get(spec["type"])
    if output_file_props and int(spec.get("msvs_auto_output_file", 1)):
        vc_tool, msbuild_tool, out_dir, suffix = output_file_props
        if spec.get("standalone_static_library", 0):
            out_dir = "$(OutDir)"
        out_dir = spec.get("product_dir", out_dir)
        product_extension = spec.get("product_extension")
        if product_extension:
            suffix = "." + product_extension
        elif msbuild:
            suffix = "$(TargetExt)"
        prefix = spec.get("product_prefix", "")
        product_name = spec.get("product_name", "$(ProjectName)")
        out_file = ntpath.join(out_dir, prefix + product_name + suffix)
    return out_file, vc_tool, msbuild_tool


def _GetOutputTargetExt(spec):
    """Returns the extension for this target, including the dot

  If product_extension is specified, set target_extension to this to avoid
  MSB8012, returns None otherwise. Ignores any target_extension settings in
  the input files.

  Arguments:
    spec: The target dictionary containing the properties of the target.
  Returns:
    A string with the extension, or None
  """
    target_extension = spec.get("product_extension")
    if target_extension:
        return "." + target_extension
    return None


def _GetDefines(config):
    """Returns the list of preprocessor definitions for this configuration.

  Arguments:
    config: The dictionary that defines the special processing to be done
            for this configuration.
  Returns:
    The list of preprocessor definitions.
  """
    defines = []
    for d in config.get("defines", []):
        fd = "=".join([str(dpart) for dpart in d]) if isinstance(d, list) else str(d)
        defines.append(fd)
    return defines


def _GetDisabledWarnings(config):
    return [str(i) for i in config.get("msvs_disabled_warnings", [])]


def _GetModuleDefinition(spec):
    def_file = ""
    if spec["type"] in [
        "shared_library",
        "loadable_module",
        "executable",
        "windows_driver",
    ]:
        def_files = [s for s in spec.get("sources", []) if s.endswith(".def")]
        if len(def_files) == 1:
            def_file = _FixPath(def_files[0])
        elif def_files:
            raise ValueError(
                "Multiple module definition files in one target, target %s lists "
                "multiple .def files: %s" % (spec["target_name"], " ".join(def_files))
            )
    return def_file


def _ConvertToolsToExpectedForm(tools):
    """Convert tools to a form expected by Visual Studio.

  Arguments:
    tools: A dictionary of settings; the tool name is the key.
  Returns:
    A list of Tool objects.
  """
    tool_list = []
    for tool, settings in tools.items():
        # Collapse settings with lists.
        settings_fixed = {}
        for setting, value in settings.items():
            if type(value) == list:
                if (
                    tool == "VCLinkerTool" and setting == "AdditionalDependencies"
                ) or setting == "AdditionalOptions":
                    settings_fixed[setting] = " ".join(value)
                else:
                    settings_fixed[setting] = ";".join(value)
            else:
                settings_fixed[setting] = value
        # Add in this tool.
        tool_list.append(MSVSProject.Tool(tool, settings_fixed))
    return tool_list


def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name):
    """Add to the project file the configuration specified by config.

  Arguments:
    p: The target project being generated.
    spec: the target project dict.
    tools: A dictionary of settings; the tool name is the key.
    config: The dictionary that defines the special processing to be done
            for this configuration.
    config_type: The configuration type, a number as defined by Microsoft.
    config_name: The name of the configuration.
  """
    attributes = _GetMSVSAttributes(spec, config, config_type)
    # Add in this configuration.
    tool_list = _ConvertToolsToExpectedForm(tools)
    p.AddConfig(_ConfigFullName(config_name, config), attrs=attributes, tools=tool_list)


def _GetMSVSAttributes(spec, config, config_type):
    # Prepare configuration attributes.
    prepared_attrs = {}
    source_attrs = config.get("msvs_configuration_attributes", {})
    for a in source_attrs:
        prepared_attrs[a] = source_attrs[a]
    # Add props files.
    vsprops_dirs = config.get("msvs_props", [])
    vsprops_dirs = _FixPaths(vsprops_dirs)
    if vsprops_dirs:
        prepared_attrs["InheritedPropertySheets"] = ";".join(vsprops_dirs)
    # Set configuration type.
    prepared_attrs["ConfigurationType"] = config_type
    output_dir = prepared_attrs.get(
        "OutputDirectory", "$(SolutionDir)$(ConfigurationName)"
    )
    prepared_attrs["OutputDirectory"] = _FixPath(output_dir) + "\\"
    if "IntermediateDirectory" not in prepared_attrs:
        intermediate = "$(ConfigurationName)\\obj\\$(ProjectName)"
        prepared_attrs["IntermediateDirectory"] = _FixPath(intermediate) + "\\"
    else:
        intermediate = _FixPath(prepared_attrs["IntermediateDirectory"]) + "\\"
        intermediate = MSVSSettings.FixVCMacroSlashes(intermediate)
        prepared_attrs["IntermediateDirectory"] = intermediate
    return prepared_attrs


def _AddNormalizedSources(sources_set, sources_array):
    sources_set.update(_NormalizedSource(s) for s in sources_array)


def _PrepareListOfSources(spec, generator_flags, gyp_file):
    """Prepare list of sources and excluded sources.

  Besides the sources specified directly in the spec, adds the gyp file so
  that a change to it will cause a re-compile. Also adds appropriate sources
  for actions and copies. Assumes later stage will un-exclude files which
  have custom build steps attached.

  Arguments:
    spec: The target dictionary containing the properties of the target.
    gyp_file: The name of the gyp file.
  Returns:
    A pair of (list of sources, list of excluded sources).
    The sources will be relative to the gyp file.
  """
    sources = OrderedSet()
    _AddNormalizedSources(sources, spec.get("sources", []))
    excluded_sources = OrderedSet()
    # Add in the gyp file.
    if not generator_flags.get("standalone"):
        sources.add(gyp_file)

    # Add in 'action' inputs and outputs.
    for a in spec.get("actions", []):
        inputs = a["inputs"]
        inputs = [_NormalizedSource(i) for i in inputs]
        # Add all inputs to sources and excluded sources.
        inputs = OrderedSet(inputs)
        sources.update(inputs)
        if not spec.get("msvs_external_builder"):
            excluded_sources.update(inputs)
        if int(a.get("process_outputs_as_sources", False)):
            _AddNormalizedSources(sources, a.get("outputs", []))
    # Add in 'copies' inputs and outputs.
    for cpy in spec.get("copies", []):
        _AddNormalizedSources(sources, cpy.get("files", []))
    return (sources, excluded_sources)


def _AdjustSourcesAndConvertToFilterHierarchy(
    spec, options, gyp_dir, sources, excluded_sources, list_excluded, version
):
    """Adjusts the list of sources and excluded sources.

  Also converts the sets to lists.

  Arguments:
    spec: The target dictionary containing the properties of the target.
    options: Global generator options.
    gyp_dir: The path to the gyp file being processed.
    sources: A set of sources to be included for this project.
    excluded_sources: A set of sources to be excluded for this project.
    version: A MSVSVersion object.
  Returns:
    A trio of (list of sources, list of excluded sources,
               path of excluded IDL file)
  """
    # Exclude excluded sources coming into the generator.
    excluded_sources.update(OrderedSet(spec.get("sources_excluded", [])))
    # Add excluded sources into sources for good measure.
    sources.update(excluded_sources)
    # Convert to proper windows form.
    # NOTE: sources goes from being a set to a list here.
    # NOTE: excluded_sources goes from being a set to a list here.
    sources = _FixPaths(sources)
    # Convert to proper windows form.
    excluded_sources = _FixPaths(excluded_sources)

    excluded_idl = _IdlFilesHandledNonNatively(spec, sources)

    precompiled_related = _GetPrecompileRelatedFiles(spec)
    # Find the excluded ones, minus the precompiled header related ones.
    fully_excluded = [i for i in excluded_sources if i not in precompiled_related]

    # Convert to folders and the right slashes.
    sources = [i.split("\\") for i in sources]
    sources = _ConvertSourcesToFilterHierarchy(
        sources,
        excluded=fully_excluded,
        list_excluded=list_excluded,
        msvs_version=version,
    )

    # Prune filters with a single child to flatten ugly directory structures
    # such as ../../src/modules/module1 etc.
    if version.UsesVcxproj():
        while (
            all(isinstance(s, MSVSProject.Filter) for s in sources)
            and len({s.name for s in sources}) == 1
        ):
            assert all(len(s.contents) == 1 for s in sources)
            sources = [s.contents[0] for s in sources]
    else:
        while len(sources) == 1 and isinstance(sources[0], MSVSProject.Filter):
            sources = sources[0].contents

    return sources, excluded_sources, excluded_idl


def _IdlFilesHandledNonNatively(spec, sources):
    # If any non-native rules use 'idl' as an extension exclude idl files.
    # Gather a list here to use later.
    using_idl = False
    for rule in spec.get("rules", []):
        if rule["extension"] == "idl" and int(rule.get("msvs_external_rule", 0)):
            using_idl = True
            break
    excluded_idl = [i for i in sources if i.endswith(".idl")] if using_idl else []
    return excluded_idl


def _GetPrecompileRelatedFiles(spec):
    # Gather a list of precompiled header related sources.
    precompiled_related = []
    for _, config in spec["configurations"].items():
        for k in precomp_keys:
            f = config.get(k)
            if f:
                precompiled_related.append(_FixPath(f))
    return precompiled_related


def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded):
    exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
    for file_name, excluded_configs in exclusions.items():
        if not list_excluded and len(excluded_configs) == len(spec["configurations"]):
            # If we're not listing excluded files, then they won't appear in the
            # project, so don't try to configure them to be excluded.
            pass
        else:
            for config_name, config in excluded_configs:
                p.AddFileConfig(
                    file_name,
                    _ConfigFullName(config_name, config),
                    {"ExcludedFromBuild": "true"},
                )


def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
    exclusions = {}
    # Exclude excluded sources from being built.
    for f in excluded_sources:
        excluded_configs = []
        for config_name, config in spec["configurations"].items():
            precomped = [_FixPath(config.get(i, "")) for i in precomp_keys]
            # Don't do this for ones that are precompiled header related.
            if f not in precomped:
                excluded_configs.append((config_name, config))
        exclusions[f] = excluded_configs
    # If any non-native rules use 'idl' as an extension exclude idl files.
    # Exclude them now.
    for f in excluded_idl:
        excluded_configs = []
        for config_name, config in spec["configurations"].items():
            excluded_configs.append((config_name, config))
        exclusions[f] = excluded_configs
    return exclusions


def _AddToolFilesToMSVS(p, spec):
    # Add in tool files (rules).
    tool_files = OrderedSet()
    for _, config in spec["configurations"].items():
        for f in config.get("msvs_tool_files", []):
            tool_files.add(f)
    for f in tool_files:
        p.AddToolFile(f)


def _HandlePreCompiledHeaders(p, sources, spec):
    # Pre-compiled header source stubs need a different compiler flag
    # (generate precompiled header) and any source file not of the same
    # kind (i.e. C vs. C++) as the precompiled header source stub needs
    # to have use of precompiled headers disabled.
    extensions_excluded_from_precompile = []
    for config_name, config in spec["configurations"].items():
        source = config.get("msvs_precompiled_source")
        if source:
            source = _FixPath(source)
            # UsePrecompiledHeader=1 for if using precompiled headers.
            tool = MSVSProject.Tool("VCCLCompilerTool", {"UsePrecompiledHeader": "1"})
            p.AddFileConfig(
                source, _ConfigFullName(config_name, config), {}, tools=[tool]
            )
            basename, extension = os.path.splitext(source)
            if extension == ".c":
                extensions_excluded_from_precompile = [".cc", ".cpp", ".cxx"]
            else:
                extensions_excluded_from_precompile = [".c"]

    def DisableForSourceTree(source_tree):
        for source in source_tree:
            if isinstance(source, MSVSProject.Filter):
                DisableForSourceTree(source.contents)
            else:
                basename, extension = os.path.splitext(source)
                if extension in extensions_excluded_from_precompile:
                    for config_name, config in spec["configurations"].items():
                        tool = MSVSProject.Tool(
                            "VCCLCompilerTool",
                            {
                                "UsePrecompiledHeader": "0",
                                "ForcedIncludeFiles": "$(NOINHERIT)",
                            },
                        )
                        p.AddFileConfig(
                            _FixPath(source),
                            _ConfigFullName(config_name, config),
                            {},
                            tools=[tool],
                        )

    # Do nothing if there was no precompiled source.
    if extensions_excluded_from_precompile:
        DisableForSourceTree(sources)


def _AddActions(actions_to_add, spec, relative_path_of_gyp_file):
    # Add actions.
    actions = spec.get("actions", [])
    # Don't setup_env every time. When all the actions are run together in one
    # batch file in VS, the PATH will grow too long.
    # Membership in this set means that the cygwin environment has been set up,
    # and does not need to be set up again.
    have_setup_env = set()
    for a in actions:
        # Attach actions to the gyp file if nothing else is there.
        inputs = a.get("inputs") or [relative_path_of_gyp_file]
        attached_to = inputs[0]
        need_setup_env = attached_to not in have_setup_env
        cmd = _BuildCommandLineForRule(
            spec, a, has_input_path=False, do_setup_env=need_setup_env
        )
        have_setup_env.add(attached_to)
        # Add the action.
        _AddActionStep(
            actions_to_add,
            inputs=inputs,
            outputs=a.get("outputs", []),
            description=a.get("message", a["action_name"]),
            command=cmd,
        )


def _WriteMSVSUserFile(project_path, version, spec):
    # Add run_as and test targets.
    if "run_as" in spec:
        run_as = spec["run_as"]
        action = run_as.get("action", [])
        environment = run_as.get("environment", [])
        working_directory = run_as.get("working_directory", ".")
    elif int(spec.get("test", 0)):
        action = ["$(TargetPath)", "--gtest_print_time"]
        environment = []
        working_directory = "."
    else:
        return  # Nothing to add
    # Write out the user file.
    user_file = _CreateMSVSUserFile(project_path, version, spec)
    for config_name, c_data in spec["configurations"].items():
        user_file.AddDebugSettings(
            _ConfigFullName(config_name, c_data), action, environment, working_directory
        )
    user_file.WriteIfChanged()


def _AddCopies(actions_to_add, spec):
    copies = _GetCopies(spec)
    for inputs, outputs, cmd, description in copies:
        _AddActionStep(
            actions_to_add,
            inputs=inputs,
            outputs=outputs,
            description=description,
            command=cmd,
        )


def _GetCopies(spec):
    copies = []
    # Add copies.
    for cpy in spec.get("copies", []):
        for src in cpy.get("files", []):
            dst = os.path.join(cpy["destination"], os.path.basename(src))
            # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and
            # outputs, so do the same for our generated command line.
            if src.endswith("/"):
                src_bare = src[:-1]
                base_dir = posixpath.split(src_bare)[0]
                outer_dir = posixpath.split(src_bare)[1]
                fixed_dst = _FixPath(dst)
                full_dst = f'"{fixed_dst}\\{outer_dir}\\"'
                cmd = (
                    f'mkdir {full_dst} 2>nul & cd "{_FixPath(base_dir)}" '
                    f'&& xcopy /e /f /y "{outer_dir}" {full_dst}'
                )
                copies.append(
                    (
                        [src],
                        ["dummy_copies", dst],
                        cmd,
                        f"Copying {src} to {fixed_dst}",
                    )
                )
            else:
                fix_dst = _FixPath(cpy["destination"])
                cmd = (
                    f'mkdir "{fix_dst}" 2>nul & set ERRORLEVEL=0 & '
                    f'copy /Y "{_FixPath(src)}" "{_FixPath(dst)}"'
                )
                copies.append(([src], [dst], cmd, f"Copying {src} to {fix_dst}"))
    return copies


def _GetPathDict(root, path):
    # |path| will eventually be empty (in the recursive calls) if it was initially
    # relative; otherwise it will eventually end up as '\', 'D:\', etc.
    if not path or path.endswith(os.sep):
        return root
    parent, folder = os.path.split(path)
    parent_dict = _GetPathDict(root, parent)
    if folder not in parent_dict:
        parent_dict[folder] = {}
    return parent_dict[folder]


def _DictsToFolders(base_path, bucket, flat):
    # Convert to folders recursively.
    children = []
    for folder, contents in bucket.items():
        if type(contents) == dict:
            folder_children = _DictsToFolders(
                os.path.join(base_path, folder), contents, flat
            )
            if flat:
                children += folder_children
            else:
                folder_children = MSVSNew.MSVSFolder(
                    os.path.join(base_path, folder),
                    name="(" + folder + ")",
                    entries=folder_children,
                )
                children.append(folder_children)
        else:
            children.append(contents)
    return children


def _CollapseSingles(parent, node):
    # Recursively explorer the tree of dicts looking for projects which are
    # the sole item in a folder which has the same name as the project. Bring
    # such projects up one level.
    if type(node) == dict and len(node) == 1 and next(iter(node)) == parent + ".vcproj":
        return node[next(iter(node))]
    if type(node) != dict:
        return node
    for child in node:
        node[child] = _CollapseSingles(child, node[child])
    return node


def _GatherSolutionFolders(sln_projects, project_objects, flat):
    root = {}
    # Convert into a tree of dicts on path.
    for p in sln_projects:
        gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2]
        if p.endswith("#host"):
            target += "_host"
        gyp_dir = os.path.dirname(gyp_file)
        path_dict = _GetPathDict(root, gyp_dir)
        path_dict[target + ".vcproj"] = project_objects[p]
    # Walk down from the top until we hit a folder that has more than one entry.
    # In practice, this strips the top-level "src/" dir from the hierarchy in
    # the solution.
    while len(root) == 1 and type(root[next(iter(root))]) == dict:
        root = root[next(iter(root))]
    # Collapse singles.
    root = _CollapseSingles("", root)
    # Merge buckets until everything is a root entry.
    return _DictsToFolders("", root, flat)


def _GetPathOfProject(qualified_target, spec, options, msvs_version):
    default_config = _GetDefaultConfiguration(spec)
    proj_filename = default_config.get("msvs_existing_vcproj")
    if not proj_filename:
        proj_filename = spec["target_name"]
        if spec["toolset"] == "host":
            proj_filename += "_host"
        proj_filename = proj_filename + options.suffix + msvs_version.ProjectExtension()

    build_file = gyp.common.BuildFile(qualified_target)
    proj_path = os.path.join(os.path.dirname(build_file), proj_filename)
    fix_prefix = None
    if options.generator_output:
        project_dir_path = os.path.dirname(os.path.abspath(proj_path))
        proj_path = os.path.join(options.generator_output, proj_path)
        fix_prefix = gyp.common.RelativePath(
            project_dir_path, os.path.dirname(proj_path)
        )
    return proj_path, fix_prefix


def _GetPlatformOverridesOfProject(spec):
    # Prepare a dict indicating which project configurations are used for which
    # solution configurations for this target.
    config_platform_overrides = {}
    for config_name, c in spec["configurations"].items():
        config_fullname = _ConfigFullName(config_name, c)
        platform = c.get("msvs_target_platform", _ConfigPlatform(c))
        base_name = _ConfigBaseName(config_name, _ConfigPlatform(c))
        fixed_config_fullname = f"{base_name}|{platform}"
        if spec["toolset"] == "host" and generator_supports_multiple_toolsets:
            fixed_config_fullname = f"{config_name}|x64"
        config_platform_overrides[config_fullname] = fixed_config_fullname
    return config_platform_overrides


def _CreateProjectObjects(target_list, target_dicts, options, msvs_version):
    """Create a MSVSProject object for the targets found in target list.

  Arguments:
    target_list: the list of targets to generate project objects for.
    target_dicts: the dictionary of specifications.
    options: global generator options.
    msvs_version: the MSVSVersion object.
  Returns:
    A set of created projects, keyed by target.
  """
    global fixpath_prefix
    # Generate each project.
    projects = {}
    for qualified_target in target_list:
        spec = target_dicts[qualified_target]
        proj_path, fixpath_prefix = _GetPathOfProject(
            qualified_target, spec, options, msvs_version
        )
        guid = _GetGuidOfProject(proj_path, spec)
        overrides = _GetPlatformOverridesOfProject(spec)
        build_file = gyp.common.BuildFile(qualified_target)
        # Create object for this project.
        target_name = spec["target_name"]
        if spec["toolset"] == "host":
            target_name += "_host"
        obj = MSVSNew.MSVSProject(
            proj_path,
            name=target_name,
            guid=guid,
            spec=spec,
            build_file=build_file,
            config_platform_overrides=overrides,
            fixpath_prefix=fixpath_prefix,
        )
        # Set project toolset if any (MS build only)
        if msvs_version.UsesVcxproj():
            obj.set_msbuild_toolset(
                _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)
            )
        projects[qualified_target] = obj
    # Set all the dependencies, but not if we are using an external builder like
    # ninja
    for project in projects.values():
        if not project.spec.get("msvs_external_builder"):
            deps = project.spec.get("dependencies", [])
            deps = [projects[d] for d in deps]
            project.set_dependencies(deps)
    return projects


def _InitNinjaFlavor(params, target_list, target_dicts):
    """Initialize targets for the ninja flavor.

  This sets up the necessary variables in the targets to generate msvs projects
  that use ninja as an external builder. The variables in the spec are only set
  if they have not been set. This allows individual specs to override the
  default values initialized here.
  Arguments:
    params: Params provided to the generator.
    target_list: List of target pairs: 'base/base.gyp:base'.
    target_dicts: Dict of target properties keyed on target pair.
  """
    for qualified_target in target_list:
        spec = target_dicts[qualified_target]
        if spec.get("msvs_external_builder"):
            # The spec explicitly defined an external builder, so don't change it.
            continue

        path_to_ninja = spec.get("msvs_path_to_ninja", "ninja.exe")

        spec["msvs_external_builder"] = "ninja"
        if not spec.get("msvs_external_builder_out_dir"):
            gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
            gyp_dir = os.path.dirname(gyp_file)
            configuration = "$(Configuration)"
            if params.get("target_arch") == "x64":
                configuration += "_x64"
            if params.get("target_arch") == "arm64":
                configuration += "_arm64"
            spec["msvs_external_builder_out_dir"] = os.path.join(
                gyp.common.RelativePath(params["options"].toplevel_dir, gyp_dir),
                ninja_generator.ComputeOutputDir(params),
                configuration,
            )
        if not spec.get("msvs_external_builder_build_cmd"):
            spec["msvs_external_builder_build_cmd"] = [
                path_to_ninja,
                "-C",
                "$(OutDir)",
                "$(ProjectName)",
            ]
        if not spec.get("msvs_external_builder_clean_cmd"):
            spec["msvs_external_builder_clean_cmd"] = [
                path_to_ninja,
                "-C",
                "$(OutDir)",
                "-tclean",
                "$(ProjectName)",
            ]


def CalculateVariables(default_variables, params):
    """Generated variables that require params to be known."""

    generator_flags = params.get("generator_flags", {})

    # Select project file format version (if unset, default to auto detecting).
    msvs_version = MSVSVersion.SelectVisualStudioVersion(
        generator_flags.get("msvs_version", "auto")
    )
    # Stash msvs_version for later (so we don't have to probe the system twice).
    params["msvs_version"] = msvs_version

    # Set a variable so conditions can be based on msvs_version.
    default_variables["MSVS_VERSION"] = msvs_version.ShortName()

    # To determine processor word size on Windows, in addition to checking
    # PROCESSOR_ARCHITECTURE (which reflects the word size of the current
    # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which
    # contains the actual word size of the system when running thru WOW64).
    if (
        os.environ.get("PROCESSOR_ARCHITECTURE", "").find("64") >= 0
        or os.environ.get("PROCESSOR_ARCHITEW6432", "").find("64") >= 0
    ):
        default_variables["MSVS_OS_BITS"] = 64
    else:
        default_variables["MSVS_OS_BITS"] = 32

    if gyp.common.GetFlavor(params) == "ninja":
        default_variables["SHARED_INTERMEDIATE_DIR"] = "$(OutDir)gen"


def PerformBuild(data, configurations, params):
    options = params["options"]
    msvs_version = params["msvs_version"]
    devenv = os.path.join(msvs_version.path, "Common7", "IDE", "devenv.com")

    for build_file, build_file_dict in data.items():
        (build_file_root, build_file_ext) = os.path.splitext(build_file)
        if build_file_ext != ".gyp":
            continue
        sln_path = build_file_root + options.suffix + ".sln"
        if options.generator_output:
            sln_path = os.path.join(options.generator_output, sln_path)

    for config in configurations:
        arguments = [devenv, sln_path, "/Build", config]
        print(f"Building [{config}]: {arguments}")
        subprocess.check_call(arguments)


def CalculateGeneratorInputInfo(params):
    if params.get("flavor") == "ninja":
        toplevel = params["options"].toplevel_dir
        qualified_out_dir = os.path.normpath(
            os.path.join(
                toplevel,
                ninja_generator.ComputeOutputDir(params),
                "gypfiles-msvs-ninja",
            )
        )

        global generator_filelist_paths
        generator_filelist_paths = {
            "toplevel": toplevel,
            "qualified_out_dir": qualified_out_dir,
        }


def GenerateOutput(target_list, target_dicts, data, params):
    """Generate .sln and .vcproj files.

  This is the entry point for this generator.
  Arguments:
    target_list: List of target pairs: 'base/base.gyp:base'.
    target_dicts: Dict of target properties keyed on target pair.
    data: Dictionary containing per .gyp data.
  """
    global fixpath_prefix

    options = params["options"]

    # Get the project file format version back out of where we stashed it in
    # GeneratorCalculatedVariables.
    msvs_version = params["msvs_version"]

    generator_flags = params.get("generator_flags", {})

    # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT.
    (target_list, target_dicts) = MSVSUtil.ShardTargets(target_list, target_dicts)

    # Optionally use the large PDB workaround for targets marked with
    # 'msvs_large_pdb': 1.
    (target_list, target_dicts) = MSVSUtil.InsertLargePdbShims(
        target_list, target_dicts, generator_default_variables
    )

    # Optionally configure each spec to use ninja as the external builder.
    if params.get("flavor") == "ninja":
        _InitNinjaFlavor(params, target_list, target_dicts)

    # Prepare the set of configurations.
    configs = set()
    for qualified_target in target_list:
        spec = target_dicts[qualified_target]
        for config_name, config in spec["configurations"].items():
            config_name = _ConfigFullName(config_name, config)
            configs.add(config_name)
            if config_name == "Release|arm64":
                configs.add("Release|x64")
    configs = list(configs)

    # Figure out all the projects that will be generated and their guids
    project_objects = _CreateProjectObjects(
        target_list, target_dicts, options, msvs_version
    )

    # Generate each project.
    missing_sources = []
    for project in project_objects.values():
        fixpath_prefix = project.fixpath_prefix
        missing_sources.extend(
            _GenerateProject(project, options, msvs_version, generator_flags, spec)
        )
    fixpath_prefix = None

    for build_file in data:
        # Validate build_file extension
        target_only_configs = configs
        if generator_supports_multiple_toolsets:
            target_only_configs = [i for i in configs if i.endswith("arm64")]
        if not build_file.endswith(".gyp"):
            continue
        sln_path = os.path.splitext(build_file)[0] + options.suffix + ".sln"
        if options.generator_output:
            sln_path = os.path.join(options.generator_output, sln_path)
        # Get projects in the solution, and their dependents.
        sln_projects = gyp.common.BuildFileTargets(target_list, build_file)
        sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects)
        # Create folder hierarchy.
        root_entries = _GatherSolutionFolders(
            sln_projects, project_objects, flat=msvs_version.FlatSolution()
        )
        # Create solution.
        sln = MSVSNew.MSVSSolution(
            sln_path,
            entries=root_entries,
            variants=target_only_configs,
            websiteProperties=False,
            version=msvs_version,
        )
        sln.Write()

    if missing_sources:
        error_message = "Missing input files:\n" + "\n".join(set(missing_sources))
        if generator_flags.get("msvs_error_on_missing_sources", False):
            raise GypError(error_message)
        else:
            print("Warning: " + error_message, file=sys.stdout)


def _GenerateMSBuildFiltersFile(
    filters_path,
    source_files,
    rule_dependencies,
    extension_to_rule_name,
    platforms,
    toolset,
):
    """Generate the filters file.

  This file is used by Visual Studio to organize the presentation of source
  files into folders.

  Arguments:
      filters_path: The path of the file to be created.
      source_files: The hierarchical structure of all the sources.
      extension_to_rule_name: A dictionary mapping file extensions to rules.
  """
    filter_group = []
    source_group = []
    _AppendFiltersForMSBuild(
        "",
        source_files,
        rule_dependencies,
        extension_to_rule_name,
        platforms,
        toolset,
        filter_group,
        source_group,
    )
    if filter_group:
        content = [
            "Project",
            {
                "ToolsVersion": "4.0",
                "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003",
            },
            ["ItemGroup"] + filter_group,
            ["ItemGroup"] + source_group,
        ]
        easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True)
    elif os.path.exists(filters_path):
        # We don't need this filter anymore.  Delete the old filter file.
        os.unlink(filters_path)


def _AppendFiltersForMSBuild(
    parent_filter_name,
    sources,
    rule_dependencies,
    extension_to_rule_name,
    platforms,
    toolset,
    filter_group,
    source_group,
):
    """Creates the list of filters and sources to be added in the filter file.

  Args:
      parent_filter_name: The name of the filter under which the sources are
          found.
      sources: The hierarchy of filters and sources to process.
      extension_to_rule_name: A dictionary mapping file extensions to rules.
      filter_group: The list to which filter entries will be appended.
      source_group: The list to which source entries will be appended.
  """
    for source in sources:
        if isinstance(source, MSVSProject.Filter):
            # We have a sub-filter.  Create the name of that sub-filter.
            if not parent_filter_name:
                filter_name = source.name
            else:
                filter_name = f"{parent_filter_name}\\{source.name}"
            # Add the filter to the group.
            filter_group.append(
                [
                    "Filter",
                    {"Include": filter_name},
                    ["UniqueIdentifier", MSVSNew.MakeGuid(source.name)],
                ]
            )
            # Recurse and add its dependents.
            _AppendFiltersForMSBuild(
                filter_name,
                source.contents,
                rule_dependencies,
                extension_to_rule_name,
                platforms,
                toolset,
                filter_group,
                source_group,
            )
        else:
            # It's a source.  Create a source entry.
            _, element = _MapFileToMsBuildSourceType(
                source, rule_dependencies, extension_to_rule_name, platforms, toolset
            )
            source_entry = [element, {"Include": source}]
            # Specify the filter it is part of, if any.
            if parent_filter_name:
                source_entry.append(["Filter", parent_filter_name])
            source_group.append(source_entry)


def _MapFileToMsBuildSourceType(
    source, rule_dependencies, extension_to_rule_name, platforms, toolset
):
    """Returns the group and element type of the source file.

  Arguments:
      source: The source file name.
      extension_to_rule_name: A dictionary mapping file extensions to rules.

  Returns:
      A pair of (group this file should be part of, the label of element)
  """
    _, ext = os.path.splitext(source)
    ext = ext.lower()
    if ext in extension_to_rule_name:
        group = "rule"
        element = extension_to_rule_name[ext]
    elif ext in [".cc", ".cpp", ".c", ".cxx", ".mm"]:
        group = "compile"
        element = "ClCompile"
    elif ext in [".h", ".hxx"]:
        group = "include"
        element = "ClInclude"
    elif ext == ".rc":
        group = "resource"
        element = "ResourceCompile"
    elif ext in [".s", ".asm"]:
        group = "masm"
        element = "MASM"
        if "arm64" in platforms and toolset == "target":
            element = "MARMASM"
    elif ext == ".idl":
        group = "midl"
        element = "Midl"
    elif source in rule_dependencies:
        group = "rule_dependency"
        element = "CustomBuild"
    else:
        group = "none"
        element = "None"
    return (group, element)


def _GenerateRulesForMSBuild(
    output_dir,
    options,
    spec,
    sources,
    excluded_sources,
    props_files_of_rules,
    targets_files_of_rules,
    actions_to_add,
    rule_dependencies,
    extension_to_rule_name,
):
    # MSBuild rules are implemented using three files: an XML file, a .targets
    # file and a .props file.
    # For more details see:
    # https://devblogs.microsoft.com/cppblog/quick-help-on-vs2010-custom-build-rule/
    rules = spec.get("rules", [])
    rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))]
    rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))]

    msbuild_rules = []
    for rule in rules_native:
        # Skip a rule with no action and no inputs.
        if "action" not in rule and not rule.get("rule_sources", []):
            continue
        msbuild_rule = MSBuildRule(rule, spec)
        msbuild_rules.append(msbuild_rule)
        rule_dependencies.update(msbuild_rule.additional_dependencies.split(";"))
        extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name
    if msbuild_rules:
        base = spec["target_name"] + options.suffix
        props_name = base + ".props"
        targets_name = base + ".targets"
        xml_name = base + ".xml"

        props_files_of_rules.add(props_name)
        targets_files_of_rules.add(targets_name)

        props_path = os.path.join(output_dir, props_name)
        targets_path = os.path.join(output_dir, targets_name)
        xml_path = os.path.join(output_dir, xml_name)

        _GenerateMSBuildRulePropsFile(props_path, msbuild_rules)
        _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules)
        _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules)

    if rules_external:
        _GenerateExternalRules(
            rules_external, output_dir, spec, sources, options, actions_to_add
        )
    _AdjustSourcesForRules(rules, sources, excluded_sources, True)


class MSBuildRule:
    """Used to store information used to generate an MSBuild rule.

  Attributes:
    rule_name: The rule name, sanitized to use in XML.
    target_name: The name of the target.
    after_targets: The name of the AfterTargets element.
    before_targets: The name of the BeforeTargets element.
    depends_on: The name of the DependsOn element.
    compute_output: The name of the ComputeOutput element.
    dirs_to_make: The name of the DirsToMake element.
    inputs: The name of the _inputs element.
    tlog: The name of the _tlog element.
    extension: The extension this rule applies to.
    description: The message displayed when this rule is invoked.
    additional_dependencies: A string listing additional dependencies.
    outputs: The outputs of this rule.
    command: The command used to run the rule.
  """

    def __init__(self, rule, spec):
        self.display_name = rule["rule_name"]
        # Assure that the rule name is only characters and numbers
        self.rule_name = re.sub(r"\W", "_", self.display_name)
        # Create the various element names, following the example set by the
        # Visual Studio 2008 to 2010 conversion.  I don't know if VS2010
        # is sensitive to the exact names.
        self.target_name = "_" + self.rule_name
        self.after_targets = self.rule_name + "AfterTargets"
        self.before_targets = self.rule_name + "BeforeTargets"
        self.depends_on = self.rule_name + "DependsOn"
        self.compute_output = "Compute%sOutput" % self.rule_name
        self.dirs_to_make = self.rule_name + "DirsToMake"
        self.inputs = self.rule_name + "_inputs"
        self.tlog = self.rule_name + "_tlog"
        self.extension = rule["extension"]
        if not self.extension.startswith("."):
            self.extension = "." + self.extension

        self.description = MSVSSettings.ConvertVCMacrosToMSBuild(
            rule.get("message", self.rule_name)
        )
        old_additional_dependencies = _FixPaths(rule.get("inputs", []))
        self.additional_dependencies = ";".join(
            [
                MSVSSettings.ConvertVCMacrosToMSBuild(i)
                for i in old_additional_dependencies
            ]
        )
        old_outputs = _FixPaths(rule.get("outputs", []))
        self.outputs = ";".join(
            [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_outputs]
        )
        old_command = _BuildCommandLineForRule(
            spec, rule, has_input_path=True, do_setup_env=True
        )
        self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command)


def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
    """Generate the .props file."""
    content = [
        "Project",
        {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"},
    ]
    for rule in msbuild_rules:
        content.extend(
            [
                [
                    "PropertyGroup",
                    {
                        "Condition": "'$(%s)' == '' and '$(%s)' == '' and "
                        "'$(ConfigurationType)' != 'Makefile'"
                        % (rule.before_targets, rule.after_targets)
                    },
                    [rule.before_targets, "Midl"],
                    [rule.after_targets, "CustomBuild"],
                ],
                [
                    "PropertyGroup",
                    [
                        rule.depends_on,
                        {"Condition": "'$(ConfigurationType)' != 'Makefile'"},
                        "_SelectedFiles;$(%s)" % rule.depends_on,
                    ],
                ],
                [
                    "ItemDefinitionGroup",
                    [
                        rule.rule_name,
                        ["CommandLineTemplate", rule.command],
                        ["Outputs", rule.outputs],
                        ["ExecutionDescription", rule.description],
                        ["AdditionalDependencies", rule.additional_dependencies],
                    ],
                ],
            ]
        )
    easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True)


def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules):
    """Generate the .targets file."""
    content = [
        "Project",
        {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"},
    ]
    item_group = [
        "ItemGroup",
        [
            "PropertyPageSchema",
            {"Include": "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"},
        ],
    ]
    for rule in msbuild_rules:
        item_group.append(
            [
                "AvailableItemName",
                {"Include": rule.rule_name},
                ["Targets", rule.target_name],
            ]
        )
    content.append(item_group)

    for rule in msbuild_rules:
        content.append(
            [
                "UsingTask",
                {
                    "TaskName": rule.rule_name,
                    "TaskFactory": "XamlTaskFactory",
                    "AssemblyName": "Microsoft.Build.Tasks.v4.0",
                },
                ["Task", "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"],
            ]
        )
    for rule in msbuild_rules:
        rule_name = rule.rule_name
        target_outputs = "%%(%s.Outputs)" % rule_name
        target_inputs = (
            "%%(%s.Identity);%%(%s.AdditionalDependencies);" "$(MSBuildProjectFile)"
        ) % (rule_name, rule_name)
        rule_inputs = "%%(%s.Identity)" % rule_name
        extension_condition = (
            "'%(Extension)'=='.obj' or "
            "'%(Extension)'=='.res' or "
            "'%(Extension)'=='.rsc' or "
            "'%(Extension)'=='.lib'"
        )
        remove_section = [
            "ItemGroup",
            {"Condition": "'@(SelectedFiles)' != ''"},
            [
                rule_name,
                {
                    "Remove": "@(%s)" % rule_name,
                    "Condition": "'%(Identity)' != '@(SelectedFiles)'",
                },
            ],
        ]
        inputs_section = [
            "ItemGroup",
            [rule.inputs, {"Include": "%%(%s.AdditionalDependencies)" % rule_name}],
        ]
        logging_section = [
            "ItemGroup",
            [
                rule.tlog,
                {
                    "Include": "%%(%s.Outputs)" % rule_name,
                    "Condition": (
                        "'%%(%s.Outputs)' != '' and "
                        "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name)
                    ),
                },
                ["Source", "@(%s, '|')" % rule_name],
                ["Inputs", "@(%s -> '%%(Fullpath)', ';')" % rule.inputs],
            ],
        ]
        message_section = [
            "Message",
            {"Importance": "High", "Text": "%%(%s.ExecutionDescription)" % rule_name},
        ]
        write_tlog_section = [
            "WriteLinesToFile",
            {
                "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
                "'true'" % (rule.tlog, rule.tlog),
                "File": "$(IntDir)$(ProjectName).write.1.tlog",
                "Lines": "^%%(%s.Source);@(%s->'%%(Fullpath)')"
                % (rule.tlog, rule.tlog),
            },
        ]
        read_tlog_section = [
            "WriteLinesToFile",
            {
                "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
                "'true'" % (rule.tlog, rule.tlog),
                "File": "$(IntDir)$(ProjectName).read.1.tlog",
                "Lines": f"^%({rule.tlog}.Source);%({rule.tlog}.Inputs)",
            },
        ]
        command_and_input_section = [
            rule_name,
            {
                "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
                "'true'" % (rule_name, rule_name),
                "EchoOff": "true",
                "StandardOutputImportance": "High",
                "StandardErrorImportance": "High",
                "CommandLineTemplate": "%%(%s.CommandLineTemplate)" % rule_name,
                "AdditionalOptions": "%%(%s.AdditionalOptions)" % rule_name,
                "Inputs": rule_inputs,
            },
        ]
        content.extend(
            [
                [
                    "Target",
                    {
                        "Name": rule.target_name,
                        "BeforeTargets": "$(%s)" % rule.before_targets,
                        "AfterTargets": "$(%s)" % rule.after_targets,
                        "Condition": "'@(%s)' != ''" % rule_name,
                        "DependsOnTargets": "$(%s);%s"
                        % (rule.depends_on, rule.compute_output),
                        "Outputs": target_outputs,
                        "Inputs": target_inputs,
                    },
                    remove_section,
                    inputs_section,
                    logging_section,
                    message_section,
                    write_tlog_section,
                    read_tlog_section,
                    command_and_input_section,
                ],
                [
                    "PropertyGroup",
                    [
                        "ComputeLinkInputsTargets",
                        "$(ComputeLinkInputsTargets);",
                        "%s;" % rule.compute_output,
                    ],
                    [
                        "ComputeLibInputsTargets",
                        "$(ComputeLibInputsTargets);",
                        "%s;" % rule.compute_output,
                    ],
                ],
                [
                    "Target",
                    {
                        "Name": rule.compute_output,
                        "Condition": "'@(%s)' != ''" % rule_name,
                    },
                    [
                        "ItemGroup",
                        [
                            rule.dirs_to_make,
                            {
                                "Condition": "'@(%s)' != '' and "
                                "'%%(%s.ExcludedFromBuild)' != 'true'"
                                % (rule_name, rule_name),
                                "Include": "%%(%s.Outputs)" % rule_name,
                            },
                        ],
                        [
                            "Link",
                            {
                                "Include": "%%(%s.Identity)" % rule.dirs_to_make,
                                "Condition": extension_condition,
                            },
                        ],
                        [
                            "Lib",
                            {
                                "Include": "%%(%s.Identity)" % rule.dirs_to_make,
                                "Condition": extension_condition,
                            },
                        ],
                        [
                            "ImpLib",
                            {
                                "Include": "%%(%s.Identity)" % rule.dirs_to_make,
                                "Condition": extension_condition,
                            },
                        ],
                    ],
                    [
                        "MakeDir",
                        {
                            "Directories": (
                                "@(%s->'%%(RootDir)%%(Directory)')" % rule.dirs_to_make
                            )
                        },
                    ],
                ],
            ]
        )
    easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True)


def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules):
    # Generate the .xml file
    content = [
        "ProjectSchemaDefinitions",
        {
            "xmlns": (
                "clr-namespace:Microsoft.Build.Framework.XamlTypes;"
                "assembly=Microsoft.Build.Framework"
            ),
            "xmlns:x": "http://schemas.microsoft.com/winfx/2006/xaml",
            "xmlns:sys": "clr-namespace:System;assembly=mscorlib",
            "xmlns:transformCallback": "Microsoft.Cpp.Dev10.ConvertPropertyCallback",
        },
    ]
    for rule in msbuild_rules:
        content.extend(
            [
                [
                    "Rule",
                    {
                        "Name": rule.rule_name,
                        "PageTemplate": "tool",
                        "DisplayName": rule.display_name,
                        "Order": "200",
                    },
                    [
                        "Rule.DataSource",
                        [
                            "DataSource",
                            {"Persistence": "ProjectFile", "ItemType": rule.rule_name},
                        ],
                    ],
                    [
                        "Rule.Categories",
                        [
                            "Category",
                            {"Name": "General"},
                            ["Category.DisplayName", ["sys:String", "General"]],
                        ],
                        [
                            "Category",
                            {"Name": "Command Line", "Subtype": "CommandLine"},
                            ["Category.DisplayName", ["sys:String", "Command Line"]],
                        ],
                    ],
                    [
                        "StringListProperty",
                        {
                            "Name": "Inputs",
                            "Category": "Command Line",
                            "IsRequired": "true",
                            "Switch": " ",
                        },
                        [
                            "StringListProperty.DataSource",
                            [
                                "DataSource",
                                {
                                    "Persistence": "ProjectFile",
                                    "ItemType": rule.rule_name,
                                    "SourceType": "Item",
                                },
                            ],
                        ],
                    ],
                    [
                        "StringProperty",
                        {
                            "Name": "CommandLineTemplate",
                            "DisplayName": "Command Line",
                            "Visible": "False",
                            "IncludeInCommandLine": "False",
                        },
                    ],
                    [
                        "DynamicEnumProperty",
                        {
                            "Name": rule.before_targets,
                            "Category": "General",
                            "EnumProvider": "Targets",
                            "IncludeInCommandLine": "False",
                        },
                        [
                            "DynamicEnumProperty.DisplayName",
                            ["sys:String", "Execute Before"],
                        ],
                        [
                            "DynamicEnumProperty.Description",
                            [
                                "sys:String",
                                "Specifies the targets for the build customization"
                                " to run before.",
                            ],
                        ],
                        [
                            "DynamicEnumProperty.ProviderSettings",
                            [
                                "NameValuePair",
                                {
                                    "Name": "Exclude",
                                    "Value": "^%s|^Compute" % rule.before_targets,
                                },
                            ],
                        ],
                        [
                            "DynamicEnumProperty.DataSource",
                            [
                                "DataSource",
                                {
                                    "Persistence": "ProjectFile",
                                    "HasConfigurationCondition": "true",
                                },
                            ],
                        ],
                    ],
                    [
                        "DynamicEnumProperty",
                        {
                            "Name": rule.after_targets,
                            "Category": "General",
                            "EnumProvider": "Targets",
                            "IncludeInCommandLine": "False",
                        },
                        [
                            "DynamicEnumProperty.DisplayName",
                            ["sys:String", "Execute After"],
                        ],
                        [
                            "DynamicEnumProperty.Description",
                            [
                                "sys:String",
                                (
                                    "Specifies the targets for the build customization"
                                    " to run after."
                                ),
                            ],
                        ],
                        [
                            "DynamicEnumProperty.ProviderSettings",
                            [
                                "NameValuePair",
                                {
                                    "Name": "Exclude",
                                    "Value": "^%s|^Compute" % rule.after_targets,
                                },
                            ],
                        ],
                        [
                            "DynamicEnumProperty.DataSource",
                            [
                                "DataSource",
                                {
                                    "Persistence": "ProjectFile",
                                    "ItemType": "",
                                    "HasConfigurationCondition": "true",
                                },
                            ],
                        ],
                    ],
                    [
                        "StringListProperty",
                        {
                            "Name": "Outputs",
                            "DisplayName": "Outputs",
                            "Visible": "False",
                            "IncludeInCommandLine": "False",
                        },
                    ],
                    [
                        "StringProperty",
                        {
                            "Name": "ExecutionDescription",
                            "DisplayName": "Execution Description",
                            "Visible": "False",
                            "IncludeInCommandLine": "False",
                        },
                    ],
                    [
                        "StringListProperty",
                        {
                            "Name": "AdditionalDependencies",
                            "DisplayName": "Additional Dependencies",
                            "IncludeInCommandLine": "False",
                            "Visible": "false",
                        },
                    ],
                    [
                        "StringProperty",
                        {
                            "Subtype": "AdditionalOptions",
                            "Name": "AdditionalOptions",
                            "Category": "Command Line",
                        },
                        [
                            "StringProperty.DisplayName",
                            ["sys:String", "Additional Options"],
                        ],
                        [
                            "StringProperty.Description",
                            ["sys:String", "Additional Options"],
                        ],
                    ],
                ],
                [
                    "ItemType",
                    {"Name": rule.rule_name, "DisplayName": rule.display_name},
                ],
                [
                    "FileExtension",
                    {"Name": "*" + rule.extension, "ContentType": rule.rule_name},
                ],
                [
                    "ContentType",
                    {
                        "Name": rule.rule_name,
                        "DisplayName": "",
                        "ItemType": rule.rule_name,
                    },
                ],
            ]
        )
    easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True)


def _GetConfigurationAndPlatform(name, settings, spec):
    configuration = name.rsplit("_", 1)[0]
    platform = settings.get("msvs_configuration_platform", "Win32")
    if spec["toolset"] == "host" and platform == "arm64":
        platform = "x64"  # Host-only tools are always built for x64
    return (configuration, platform)


def _GetConfigurationCondition(name, settings, spec):
    return r"'$(Configuration)|$(Platform)'=='%s|%s'" % _GetConfigurationAndPlatform(
        name, settings, spec
    )


def _GetMSBuildProjectConfigurations(configurations, spec):
    group = ["ItemGroup", {"Label": "ProjectConfigurations"}]
    for (name, settings) in sorted(configurations.items()):
        configuration, platform = _GetConfigurationAndPlatform(name, settings, spec)
        designation = f"{configuration}|{platform}"
        group.append(
            [
                "ProjectConfiguration",
                {"Include": designation},
                ["Configuration", configuration],
                ["Platform", platform],
            ]
        )
    return [group]


def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name):
    namespace = os.path.splitext(gyp_file_name)[0]
    properties = [
        [
            "PropertyGroup",
            {"Label": "Globals"},
            ["ProjectGuid", guid],
            ["Keyword", "Win32Proj"],
            ["RootNamespace", namespace],
            ["IgnoreWarnCompileDuplicatedFilename", "true"],
        ]
    ]

    if (
        os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64"
        or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64"
    ):
        properties[0].append(["PreferredToolArchitecture", "x64"])

    if spec.get("msvs_target_platform_version"):
        target_platform_version = spec.get("msvs_target_platform_version")
        properties[0].append(["WindowsTargetPlatformVersion", target_platform_version])
        if spec.get("msvs_target_platform_minversion"):
            target_platform_minversion = spec.get("msvs_target_platform_minversion")
            properties[0].append(
                ["WindowsTargetPlatformMinVersion", target_platform_minversion]
            )
        else:
            properties[0].append(
                ["WindowsTargetPlatformMinVersion", target_platform_version]
            )

    if spec.get("msvs_enable_winrt"):
        properties[0].append(["DefaultLanguage", "en-US"])
        properties[0].append(["AppContainerApplication", "true"])
        if spec.get("msvs_application_type_revision"):
            app_type_revision = spec.get("msvs_application_type_revision")
            properties[0].append(["ApplicationTypeRevision", app_type_revision])
        else:
            properties[0].append(["ApplicationTypeRevision", "8.1"])
        if spec.get("msvs_enable_winphone"):
            properties[0].append(["ApplicationType", "Windows Phone"])
        else:
            properties[0].append(["ApplicationType", "Windows Store"])

    platform_name = None
    msvs_windows_sdk_version = None
    for configuration in spec["configurations"].values():
        platform_name = platform_name or _ConfigPlatform(configuration)
        msvs_windows_sdk_version = (
            msvs_windows_sdk_version
            or _ConfigWindowsTargetPlatformVersion(configuration, version)
        )
        if platform_name and msvs_windows_sdk_version:
            break
    if msvs_windows_sdk_version:
        properties[0].append(
            ["WindowsTargetPlatformVersion", str(msvs_windows_sdk_version)]
        )
    elif version.compatible_sdks:
        raise GypError(
            "%s requires any SDK of %s version, but none were found"
            % (version.description, version.compatible_sdks)
        )

    if platform_name == "ARM":
        properties[0].append(["WindowsSDKDesktopARMSupport", "true"])

    return properties


def _GetMSBuildConfigurationDetails(spec, build_file):
    properties = {}
    for name, settings in spec["configurations"].items():
        msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file)
        condition = _GetConfigurationCondition(name, settings, spec)
        character_set = msbuild_attributes.get("CharacterSet")
        vctools_version = msbuild_attributes.get("VCToolsVersion")
        config_type = msbuild_attributes.get("ConfigurationType")
        _AddConditionalProperty(properties, condition, "ConfigurationType", config_type)
        spectre_mitigation = msbuild_attributes.get('SpectreMitigation')
        if spectre_mitigation:
            _AddConditionalProperty(properties, condition, "SpectreMitigation",
                                    spectre_mitigation)
        if config_type == "Driver":
            _AddConditionalProperty(properties, condition, "DriverType", "WDM")
            _AddConditionalProperty(
                properties, condition, "TargetVersion", _ConfigTargetVersion(settings)
            )
        if character_set and "msvs_enable_winrt" not in spec:
            _AddConditionalProperty(
                properties, condition, "CharacterSet", character_set
            )
        if vctools_version and "msvs_enable_winrt" not in spec:
            _AddConditionalProperty(
                properties, condition, "VCToolsVersion", vctools_version
            )
    return _GetMSBuildPropertyGroup(spec, "Configuration", properties)


def _GetMSBuildLocalProperties(msbuild_toolset):
    # Currently the only local property we support is PlatformToolset
    properties = {}
    if msbuild_toolset:
        properties = [
            [
                "PropertyGroup",
                {"Label": "Locals"},
                ["PlatformToolset", msbuild_toolset],
            ]
        ]
    return properties


def _GetMSBuildPropertySheets(configurations, spec):
    user_props = r"$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"
    additional_props = {}
    props_specified = False
    for name, settings in sorted(configurations.items()):
        configuration = _GetConfigurationCondition(name, settings, spec)
        if "msbuild_props" in settings:
            additional_props[configuration] = _FixPaths(settings["msbuild_props"])
            props_specified = True
        else:
            additional_props[configuration] = ""

    if not props_specified:
        return [
            [
                "ImportGroup",
                {"Label": "PropertySheets"},
                [
                    "Import",
                    {
                        "Project": user_props,
                        "Condition": "exists('%s')" % user_props,
                        "Label": "LocalAppDataPlatform",
                    },
                ],
            ]
        ]
    else:
        sheets = []
        for condition, props in additional_props.items():
            import_group = [
                "ImportGroup",
                {"Label": "PropertySheets", "Condition": condition},
                [
                    "Import",
                    {
                        "Project": user_props,
                        "Condition": "exists('%s')" % user_props,
                        "Label": "LocalAppDataPlatform",
                    },
                ],
            ]
            for props_file in props:
                import_group.append(["Import", {"Project": props_file}])
            sheets.append(import_group)
        return sheets


def _ConvertMSVSBuildAttributes(spec, config, build_file):
    config_type = _GetMSVSConfigurationType(spec, build_file)
    msvs_attributes = _GetMSVSAttributes(spec, config, config_type)
    msbuild_attributes = {}
    for a in msvs_attributes:
        if a in ["IntermediateDirectory", "OutputDirectory"]:
            directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a])
            if not directory.endswith("\\"):
                directory += "\\"
            msbuild_attributes[a] = directory
        elif a == "CharacterSet":
            msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a])
        elif a == "ConfigurationType":
            msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a])
        elif a == "SpectreMitigation":
            msbuild_attributes[a] = msvs_attributes[a]
        elif a == "VCToolsVersion":
            msbuild_attributes[a] = msvs_attributes[a]
        else:
            print("Warning: Do not know how to convert MSVS attribute " + a)
    return msbuild_attributes


def _ConvertMSVSCharacterSet(char_set):
    if char_set.isdigit():
        char_set = {"0": "MultiByte", "1": "Unicode", "2": "MultiByte"}[char_set]
    return char_set


def _ConvertMSVSConfigurationType(config_type):
    if config_type.isdigit():
        config_type = {
            "1": "Application",
            "2": "DynamicLibrary",
            "4": "StaticLibrary",
            "5": "Driver",
            "10": "Utility",
        }[config_type]
    return config_type


def _GetMSBuildAttributes(spec, config, build_file):
    if "msbuild_configuration_attributes" not in config:
        msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file)

    else:
        config_type = _GetMSVSConfigurationType(spec, build_file)
        config_type = _ConvertMSVSConfigurationType(config_type)
        msbuild_attributes = config.get("msbuild_configuration_attributes", {})
        msbuild_attributes.setdefault("ConfigurationType", config_type)
        output_dir = msbuild_attributes.get(
            "OutputDirectory", "$(SolutionDir)$(Configuration)"
        )
        msbuild_attributes["OutputDirectory"] = _FixPath(output_dir) + "\\"
        if "IntermediateDirectory" not in msbuild_attributes:
            intermediate = _FixPath("$(Configuration)") + "\\"
            msbuild_attributes["IntermediateDirectory"] = intermediate
        if "CharacterSet" in msbuild_attributes:
            msbuild_attributes["CharacterSet"] = _ConvertMSVSCharacterSet(
                msbuild_attributes["CharacterSet"]
            )
    if "TargetName" not in msbuild_attributes:
        prefix = spec.get("product_prefix", "")
        product_name = spec.get("product_name", "$(ProjectName)")
        target_name = prefix + product_name
        msbuild_attributes["TargetName"] = target_name
    if "TargetExt" not in msbuild_attributes and "product_extension" in spec:
        ext = spec.get("product_extension")
        msbuild_attributes["TargetExt"] = "." + ext

    if spec.get("msvs_external_builder"):
        external_out_dir = spec.get("msvs_external_builder_out_dir", ".")
        msbuild_attributes["OutputDirectory"] = _FixPath(external_out_dir) + "\\"

    # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile'
    # (depending on the tool used) to avoid MSB8012 warning.
    msbuild_tool_map = {
        "executable": "Link",
        "shared_library": "Link",
        "loadable_module": "Link",
        "windows_driver": "Link",
        "static_library": "Lib",
    }
    msbuild_tool = msbuild_tool_map.get(spec["type"])
    if msbuild_tool:
        msbuild_settings = config["finalized_msbuild_settings"]
        out_file = msbuild_settings[msbuild_tool].get("OutputFile")
        if out_file:
            msbuild_attributes["TargetPath"] = _FixPath(out_file)
        target_ext = msbuild_settings[msbuild_tool].get("TargetExt")
        if target_ext:
            msbuild_attributes["TargetExt"] = target_ext

    return msbuild_attributes


def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file):
    # TODO(jeanluc) We could optimize out the following and do it only if
    # there are actions.
    # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'.
    new_paths = []
    cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])[0]
    if cygwin_dirs:
        cyg_path = "$(MSBuildProjectDirectory)\\%s\\bin\\" % _FixPath(cygwin_dirs)
        new_paths.append(cyg_path)
        # TODO(jeanluc) Change the convention to have both a cygwin_dir and a
        # python_dir.
        python_path = cyg_path.replace("cygwin\\bin", "python_26")
        new_paths.append(python_path)
        if new_paths:
            new_paths = "$(ExecutablePath);" + ";".join(new_paths)

    properties = {}
    for (name, configuration) in sorted(configurations.items()):
        condition = _GetConfigurationCondition(name, configuration, spec)
        attributes = _GetMSBuildAttributes(spec, configuration, build_file)
        msbuild_settings = configuration["finalized_msbuild_settings"]
        _AddConditionalProperty(
            properties, condition, "IntDir", attributes["IntermediateDirectory"]
        )
        _AddConditionalProperty(
            properties, condition, "OutDir", attributes["OutputDirectory"]
        )
        _AddConditionalProperty(
            properties, condition, "TargetName", attributes["TargetName"]
        )
        if "TargetExt" in attributes:
            _AddConditionalProperty(
                properties, condition, "TargetExt", attributes["TargetExt"]
            )

        if attributes.get("TargetPath"):
            _AddConditionalProperty(
                properties, condition, "TargetPath", attributes["TargetPath"]
            )
        if attributes.get("TargetExt"):
            _AddConditionalProperty(
                properties, condition, "TargetExt", attributes["TargetExt"]
            )

        if new_paths:
            _AddConditionalProperty(properties, condition, "ExecutablePath", new_paths)
        tool_settings = msbuild_settings.get("", {})
        for name, value in sorted(tool_settings.items()):
            formatted_value = _GetValueFormattedForMSBuild("", name, value)
            _AddConditionalProperty(properties, condition, name, formatted_value)
    return _GetMSBuildPropertyGroup(spec, None, properties)


def _AddConditionalProperty(properties, condition, name, value):
    """Adds a property / conditional value pair to a dictionary.

  Arguments:
    properties: The dictionary to be modified.  The key is the name of the
        property.  The value is itself a dictionary; its key is the value and
        the value a list of condition for which this value is true.
    condition: The condition under which the named property has the value.
    name: The name of the property.
    value: The value of the property.
  """
    if name not in properties:
        properties[name] = {}
    values = properties[name]
    if value not in values:
        values[value] = []
    conditions = values[value]
    conditions.append(condition)


# Regex for msvs variable references ( i.e. $(FOO) ).
MSVS_VARIABLE_REFERENCE = re.compile(r"\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)")


def _GetMSBuildPropertyGroup(spec, label, properties):
    """Returns a PropertyGroup definition for the specified properties.

  Arguments:
    spec: The target project dict.
    label: An optional label for the PropertyGroup.
    properties: The dictionary to be converted.  The key is the name of the
        property.  The value is itself a dictionary; its key is the value and
        the value a list of condition for which this value is true.
  """
    group = ["PropertyGroup"]
    if label:
        group.append({"Label": label})
    num_configurations = len(spec["configurations"])

    def GetEdges(node):
        # Use a definition of edges such that user_of_variable -> used_varible.
        # This happens to be easier in this case, since a variable's
        # definition contains all variables it references in a single string.
        edges = set()
        for value in sorted(properties[node].keys()):
            # Add to edges all $(...) references to variables.
            #
            # Variable references that refer to names not in properties are excluded
            # These can exist for instance to refer built in definitions like
            # $(SolutionDir).
            #
            # Self references are ignored. Self reference is used in a few places to
            # append to the default value. I.e. PATH=$(PATH);other_path
            edges.update(
                {
                    v
                    for v in MSVS_VARIABLE_REFERENCE.findall(value)
                    if v in properties and v != node
                }
            )
        return edges

    properties_ordered = gyp.common.TopologicallySorted(properties.keys(), GetEdges)
    # Walk properties in the reverse of a topological sort on
    # user_of_variable -> used_variable as this ensures variables are
    # defined before they are used.
    # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
    for name in reversed(properties_ordered):
        values = properties[name]
        for value, conditions in sorted(values.items()):
            if len(conditions) == num_configurations:
                # If the value is the same all configurations,
                # just add one unconditional entry.
                group.append([name, value])
            else:
                for condition in conditions:
                    group.append([name, {"Condition": condition}, value])
    return [group]


def _GetMSBuildToolSettingsSections(spec, configurations):
    groups = []
    for (name, configuration) in sorted(configurations.items()):
        msbuild_settings = configuration["finalized_msbuild_settings"]
        group = [
            "ItemDefinitionGroup",
            {"Condition": _GetConfigurationCondition(name, configuration, spec)},
        ]
        for tool_name, tool_settings in sorted(msbuild_settings.items()):
            # Skip the tool named '' which is a holder of global settings handled
            # by _GetMSBuildConfigurationGlobalProperties.
            if tool_name and tool_settings:
                tool = [tool_name]
                for name, value in sorted(tool_settings.items()):
                    formatted_value = _GetValueFormattedForMSBuild(
                        tool_name, name, value
                    )
                    tool.append([name, formatted_value])
                group.append(tool)
        groups.append(group)
    return groups


def _FinalizeMSBuildSettings(spec, configuration):
    if "msbuild_settings" in configuration:
        converted = False
        msbuild_settings = configuration["msbuild_settings"]
        MSVSSettings.ValidateMSBuildSettings(msbuild_settings)
    else:
        converted = True
        msvs_settings = configuration.get("msvs_settings", {})
        msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings)
    include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(
        configuration
    )
    libraries = _GetLibraries(spec)
    library_dirs = _GetLibraryDirs(configuration)
    out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True)
    target_ext = _GetOutputTargetExt(spec)
    defines = _GetDefines(configuration)
    if converted:
        # Visual Studio 2010 has TR1
        defines = [d for d in defines if d != "_HAS_TR1=0"]
        # Warn of ignored settings
        ignored_settings = ["msvs_tool_files"]
        for ignored_setting in ignored_settings:
            value = configuration.get(ignored_setting)
            if value:
                print(
                    "Warning: The automatic conversion to MSBuild does not handle "
                    "%s.  Ignoring setting of %s" % (ignored_setting, str(value))
                )

    defines = [_EscapeCppDefineForMSBuild(d) for d in defines]
    disabled_warnings = _GetDisabledWarnings(configuration)
    prebuild = configuration.get("msvs_prebuild")
    postbuild = configuration.get("msvs_postbuild")
    def_file = _GetModuleDefinition(spec)
    precompiled_header = configuration.get("msvs_precompiled_header")

    # Add the information to the appropriate tool
    # TODO(jeanluc) We could optimize and generate these settings only if
    # the corresponding files are found, e.g. don't generate ResourceCompile
    # if you don't have any resources.
    _ToolAppend(
        msbuild_settings, "ClCompile", "AdditionalIncludeDirectories", include_dirs
    )
    _ToolAppend(
        msbuild_settings, "Midl", "AdditionalIncludeDirectories", midl_include_dirs
    )
    _ToolAppend(
        msbuild_settings,
        "ResourceCompile",
        "AdditionalIncludeDirectories",
        resource_include_dirs,
    )
    # Add in libraries, note that even for empty libraries, we want this
    # set, to prevent inheriting default libraries from the environment.
    _ToolSetOrAppend(msbuild_settings, "Link", "AdditionalDependencies", libraries)
    _ToolAppend(msbuild_settings, "Link", "AdditionalLibraryDirectories", library_dirs)
    if out_file:
        _ToolAppend(
            msbuild_settings, msbuild_tool, "OutputFile", out_file, only_if_unset=True
        )
    if target_ext:
        _ToolAppend(
            msbuild_settings, msbuild_tool, "TargetExt", target_ext, only_if_unset=True
        )
    # Add defines.
    _ToolAppend(msbuild_settings, "ClCompile", "PreprocessorDefinitions", defines)
    _ToolAppend(msbuild_settings, "ResourceCompile", "PreprocessorDefinitions", defines)
    # Add disabled warnings.
    _ToolAppend(
        msbuild_settings, "ClCompile", "DisableSpecificWarnings", disabled_warnings
    )
    # Turn on precompiled headers if appropriate.
    if precompiled_header:
        precompiled_header = os.path.split(precompiled_header)[1]
        _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "Use")
        _ToolAppend(
            msbuild_settings, "ClCompile", "PrecompiledHeaderFile", precompiled_header
        )
        _ToolAppend(
            msbuild_settings, "ClCompile", "ForcedIncludeFiles", [precompiled_header]
        )
    else:
        _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "NotUsing")
    # Turn off WinRT compilation
    _ToolAppend(msbuild_settings, "ClCompile", "CompileAsWinRT", "false")
    # Turn on import libraries if appropriate
    if spec.get("msvs_requires_importlibrary"):
        _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "false")
    # Loadable modules don't generate import libraries;
    # tell dependent projects to not expect one.
    if spec["type"] == "loadable_module":
        _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "true")
    # Set the module definition file if any.
    if def_file:
        _ToolAppend(msbuild_settings, "Link", "ModuleDefinitionFile", def_file)
    configuration["finalized_msbuild_settings"] = msbuild_settings
    if prebuild:
        _ToolAppend(msbuild_settings, "PreBuildEvent", "Command", prebuild)
    if postbuild:
        _ToolAppend(msbuild_settings, "PostBuildEvent", "Command", postbuild)


def _GetValueFormattedForMSBuild(tool_name, name, value):
    if type(value) == list:
        # For some settings, VS2010 does not automatically extends the settings
        # TODO(jeanluc) Is this what we want?
        if name in [
            "AdditionalIncludeDirectories",
            "AdditionalLibraryDirectories",
            "AdditionalOptions",
            "DelayLoadDLLs",
            "DisableSpecificWarnings",
            "PreprocessorDefinitions",
        ]:
            value.append("%%(%s)" % name)
        # For most tools, entries in a list should be separated with ';' but some
        # settings use a space.  Check for those first.
        exceptions = {
            "ClCompile": ["AdditionalOptions"],
            "Link": ["AdditionalOptions"],
            "Lib": ["AdditionalOptions"],
        }
        char = " " if name in exceptions.get(tool_name, []) else ";"
        formatted_value = char.join(
            [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value]
        )
    else:
        formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value)
    return formatted_value


def _VerifySourcesExist(sources, root_dir):
    """Verifies that all source files exist on disk.

  Checks that all regular source files, i.e. not created at run time,
  exist on disk.  Missing files cause needless recompilation but no otherwise
  visible errors.

  Arguments:
    sources: A recursive list of Filter/file names.
    root_dir: The root directory for the relative path names.
  Returns:
    A list of source files that cannot be found on disk.
  """
    missing_sources = []
    for source in sources:
        if isinstance(source, MSVSProject.Filter):
            missing_sources.extend(_VerifySourcesExist(source.contents, root_dir))
        else:
            if "$" not in source:
                full_path = os.path.join(root_dir, source)
                if not os.path.exists(full_path):
                    missing_sources.append(full_path)
    return missing_sources


def _GetMSBuildSources(
    spec,
    sources,
    exclusions,
    rule_dependencies,
    extension_to_rule_name,
    actions_spec,
    sources_handled_by_action,
    list_excluded,
):
    groups = [
        "none",
        "masm",
        "midl",
        "include",
        "compile",
        "resource",
        "rule",
        "rule_dependency",
    ]
    grouped_sources = {}
    for g in groups:
        grouped_sources[g] = []

    _AddSources2(
        spec,
        sources,
        exclusions,
        grouped_sources,
        rule_dependencies,
        extension_to_rule_name,
        sources_handled_by_action,
        list_excluded,
    )
    sources = []
    for g in groups:
        if grouped_sources[g]:
            sources.append(["ItemGroup"] + grouped_sources[g])
    if actions_spec:
        sources.append(["ItemGroup"] + actions_spec)
    return sources


def _AddSources2(
    spec,
    sources,
    exclusions,
    grouped_sources,
    rule_dependencies,
    extension_to_rule_name,
    sources_handled_by_action,
    list_excluded,
):
    extensions_excluded_from_precompile = []
    for source in sources:
        if isinstance(source, MSVSProject.Filter):
            _AddSources2(
                spec,
                source.contents,
                exclusions,
                grouped_sources,
                rule_dependencies,
                extension_to_rule_name,
                sources_handled_by_action,
                list_excluded,
            )
        else:
            if source not in sources_handled_by_action:
                detail = []
                excluded_configurations = exclusions.get(source, [])
                if len(excluded_configurations) == len(spec["configurations"]):
                    detail.append(["ExcludedFromBuild", "true"])
                else:
                    for config_name, configuration in sorted(excluded_configurations):
                        condition = _GetConfigurationCondition(
                            config_name, configuration
                        )
                        detail.append(
                            ["ExcludedFromBuild", {"Condition": condition}, "true"]
                        )
                # Add precompile if needed
                for config_name, configuration in spec["configurations"].items():
                    precompiled_source = configuration.get(
                        "msvs_precompiled_source", ""
                    )
                    if precompiled_source != "":
                        precompiled_source = _FixPath(precompiled_source)
                        if not extensions_excluded_from_precompile:
                            # If the precompiled header is generated by a C source,
                            # we must not try to use it for C++ sources,
                            # and vice versa.
                            basename, extension = os.path.splitext(precompiled_source)
                            if extension == ".c":
                                extensions_excluded_from_precompile = [
                                    ".cc",
                                    ".cpp",
                                    ".cxx",
                                ]
                            else:
                                extensions_excluded_from_precompile = [".c"]

                    if precompiled_source == source:
                        condition = _GetConfigurationCondition(
                            config_name, configuration, spec
                        )
                        detail.append(
                            ["PrecompiledHeader", {"Condition": condition}, "Create"]
                        )
                    else:
                        # Turn off precompiled header usage for source files of a
                        # different type than the file that generated the
                        # precompiled header.
                        for extension in extensions_excluded_from_precompile:
                            if source.endswith(extension):
                                detail.append(["PrecompiledHeader", ""])
                                detail.append(["ForcedIncludeFiles", ""])

                group, element = _MapFileToMsBuildSourceType(
                    source,
                    rule_dependencies,
                    extension_to_rule_name,
                    _GetUniquePlatforms(spec),
                    spec["toolset"],
                )
                if group == "compile" and not os.path.isabs(source):
                    # Add an <ObjectFileName> value to support duplicate source
                    # file basenames, except for absolute paths to avoid paths
                    # with more than 260 characters.
                    file_name = os.path.splitext(source)[0] + ".obj"
                    if file_name.startswith("..\\"):
                        file_name = re.sub(r"^(\.\.\\)+", "", file_name)
                    elif file_name.startswith("$("):
                        file_name = re.sub(r"^\$\([^)]+\)\\", "", file_name)
                    detail.append(["ObjectFileName", "$(IntDir)\\" + file_name])
                grouped_sources[group].append([element, {"Include": source}] + detail)


def _GetMSBuildProjectReferences(project):
    references = []
    if project.dependencies:
        group = ["ItemGroup"]
        added_dependency_set = set()
        for dependency in project.dependencies:
            dependency_spec = dependency.spec
            should_skip_dep = False
            if project.spec["toolset"] == "target":
                if dependency_spec["toolset"] == "host":
                    if dependency_spec["type"] == "static_library":
                        should_skip_dep = True
            if dependency.name.startswith("run_"):
                should_skip_dep = False
            if should_skip_dep:
                continue

            canonical_name = dependency.name.replace("_host", "")
            added_dependency_set.add(canonical_name)
            guid = dependency.guid
            project_dir = os.path.split(project.path)[0]
            relative_path = gyp.common.RelativePath(dependency.path, project_dir)
            project_ref = [
                "ProjectReference",
                {"Include": relative_path},
                ["Project", guid],
                ["ReferenceOutputAssembly", "false"],
            ]
            for config in dependency.spec.get("configurations", {}).values():
                if config.get("msvs_use_library_dependency_inputs", 0):
                    project_ref.append(["UseLibraryDependencyInputs", "true"])
                    break
                # If it's disabled in any config, turn it off in the reference.
                if config.get("msvs_2010_disable_uldi_when_referenced", 0):
                    project_ref.append(["UseLibraryDependencyInputs", "false"])
                    break
            group.append(project_ref)
        references.append(group)
    return references


def _GenerateMSBuildProject(project, options, version, generator_flags, spec):
    spec = project.spec
    configurations = spec["configurations"]
    toolset = spec["toolset"]
    project_dir, project_file_name = os.path.split(project.path)
    gyp.common.EnsureDirExists(project.path)
    # Prepare list of sources and excluded sources.

    gyp_file = os.path.split(project.build_file)[1]
    sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file)
    # Add rules.
    actions_to_add = {}
    props_files_of_rules = set()
    targets_files_of_rules = set()
    rule_dependencies = set()
    extension_to_rule_name = {}
    list_excluded = generator_flags.get("msvs_list_excluded_files", True)
    platforms = _GetUniquePlatforms(spec)

    # Don't generate rules if we are using an external builder like ninja.
    if not spec.get("msvs_external_builder"):
        _GenerateRulesForMSBuild(
            project_dir,
            options,
            spec,
            sources,
            excluded_sources,
            props_files_of_rules,
            targets_files_of_rules,
            actions_to_add,
            rule_dependencies,
            extension_to_rule_name,
        )
    else:
        rules = spec.get("rules", [])
        _AdjustSourcesForRules(rules, sources, excluded_sources, True)

    sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy(
        spec, options, project_dir, sources, excluded_sources, list_excluded, version
    )

    # Don't add actions if we are using an external builder like ninja.
    if not spec.get("msvs_external_builder"):
        _AddActions(actions_to_add, spec, project.build_file)
        _AddCopies(actions_to_add, spec)

        # NOTE: this stanza must appear after all actions have been decided.
        # Don't excluded sources with actions attached, or they won't run.
        excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add)

    exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
    actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild(
        spec, actions_to_add
    )

    _GenerateMSBuildFiltersFile(
        project.path + ".filters",
        sources,
        rule_dependencies,
        extension_to_rule_name,
        platforms,
        toolset,
    )
    missing_sources = _VerifySourcesExist(sources, project_dir)

    for configuration in configurations.values():
        _FinalizeMSBuildSettings(spec, configuration)

    # Add attributes to root element

    import_default_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.Default.props"}]
    ]
    import_cpp_props_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.props"}]
    ]
    import_cpp_targets_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.targets"}]
    ]
    import_masm_props_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.props"}]
    ]
    import_masm_targets_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.targets"}]
    ]
    import_marmasm_props_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.props"}]
    ]
    import_marmasm_targets_section = [
        ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.targets"}]
    ]
    macro_section = [["PropertyGroup", {"Label": "UserMacros"}]]

    content = [
        "Project",
        {
            "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003",
            "ToolsVersion": version.ProjectVersion(),
            "DefaultTargets": "Build",
        },
    ]

    content += _GetMSBuildProjectConfigurations(configurations, spec)
    content += _GetMSBuildGlobalProperties(
        spec, version, project.guid, project_file_name
    )
    content += import_default_section
    content += _GetMSBuildConfigurationDetails(spec, project.build_file)
    if spec.get("msvs_enable_winphone"):
        content += _GetMSBuildLocalProperties("v120_wp81")
    else:
        content += _GetMSBuildLocalProperties(project.msbuild_toolset)
    content += import_cpp_props_section
    content += import_masm_props_section
    if "arm64" in platforms and toolset == "target":
        content += import_marmasm_props_section
    content += _GetMSBuildExtensions(props_files_of_rules)
    content += _GetMSBuildPropertySheets(configurations, spec)
    content += macro_section
    content += _GetMSBuildConfigurationGlobalProperties(
        spec, configurations, project.build_file
    )
    content += _GetMSBuildToolSettingsSections(spec, configurations)
    content += _GetMSBuildSources(
        spec,
        sources,
        exclusions,
        rule_dependencies,
        extension_to_rule_name,
        actions_spec,
        sources_handled_by_action,
        list_excluded,
    )
    content += _GetMSBuildProjectReferences(project)
    content += import_cpp_targets_section
    content += import_masm_targets_section
    if "arm64" in platforms and toolset == "target":
        content += import_marmasm_targets_section
    content += _GetMSBuildExtensionTargets(targets_files_of_rules)

    if spec.get("msvs_external_builder"):
        content += _GetMSBuildExternalBuilderTargets(spec)

    # TODO(jeanluc) File a bug to get rid of runas.  We had in MSVS:
    # has_run_as = _WriteMSVSUserFile(project.path, version, spec)

    easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True)

    return missing_sources


def _GetMSBuildExternalBuilderTargets(spec):
    """Return a list of MSBuild targets for external builders.

  The "Build" and "Clean" targets are always generated.  If the spec contains
  'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also
  be generated, to support building selected C/C++ files.

  Arguments:
    spec: The gyp target spec.
  Returns:
    List of MSBuild 'Target' specs.
  """
    build_cmd = _BuildCommandLineForRuleRaw(
        spec, spec["msvs_external_builder_build_cmd"], False, False, False, False
    )
    build_target = ["Target", {"Name": "Build"}]
    build_target.append(["Exec", {"Command": build_cmd}])

    clean_cmd = _BuildCommandLineForRuleRaw(
        spec, spec["msvs_external_builder_clean_cmd"], False, False, False, False
    )
    clean_target = ["Target", {"Name": "Clean"}]
    clean_target.append(["Exec", {"Command": clean_cmd}])

    targets = [build_target, clean_target]

    if spec.get("msvs_external_builder_clcompile_cmd"):
        clcompile_cmd = _BuildCommandLineForRuleRaw(
            spec,
            spec["msvs_external_builder_clcompile_cmd"],
            False,
            False,
            False,
            False,
        )
        clcompile_target = ["Target", {"Name": "ClCompile"}]
        clcompile_target.append(["Exec", {"Command": clcompile_cmd}])
        targets.append(clcompile_target)

    return targets


def _GetMSBuildExtensions(props_files_of_rules):
    extensions = ["ImportGroup", {"Label": "ExtensionSettings"}]
    for props_file in props_files_of_rules:
        extensions.append(["Import", {"Project": props_file}])
    return [extensions]


def _GetMSBuildExtensionTargets(targets_files_of_rules):
    targets_node = ["ImportGroup", {"Label": "ExtensionTargets"}]
    for targets_file in sorted(targets_files_of_rules):
        targets_node.append(["Import", {"Project": targets_file}])
    return [targets_node]


def _GenerateActionsForMSBuild(spec, actions_to_add):
    """Add actions accumulated into an actions_to_add, merging as needed.

  Arguments:
    spec: the target project dict
    actions_to_add: dictionary keyed on input name, which maps to a list of
        dicts describing the actions attached to that input file.

  Returns:
    A pair of (action specification, the sources handled by this action).
  """
    sources_handled_by_action = OrderedSet()
    actions_spec = []
    for primary_input, actions in actions_to_add.items():
        if generator_supports_multiple_toolsets:
            primary_input = primary_input.replace(".exe", "_host.exe")
        inputs = OrderedSet()
        outputs = OrderedSet()
        descriptions = []
        commands = []
        for action in actions:

            def fixup_host_exe(i):
                if "$(OutDir)" in i:
                    i = i.replace(".exe", "_host.exe")
                return i

            if generator_supports_multiple_toolsets:
                action["inputs"] = [fixup_host_exe(i) for i in action["inputs"]]
            inputs.update(OrderedSet(action["inputs"]))
            outputs.update(OrderedSet(action["outputs"]))
            descriptions.append(action["description"])
            cmd = action["command"]
            if generator_supports_multiple_toolsets:
                cmd = cmd.replace(".exe", "_host.exe")
            # For most actions, add 'call' so that actions that invoke batch files
            # return and continue executing.  msbuild_use_call provides a way to
            # disable this but I have not seen any adverse effect from doing that
            # for everything.
            if action.get("msbuild_use_call", True):
                cmd = "call " + cmd
            commands.append(cmd)
        # Add the custom build action for one input file.
        description = ", and also ".join(descriptions)

        # We can't join the commands simply with && because the command line will
        # get too long. See also _AddActions: cygwin's setup_env mustn't be called
        # for every invocation or the command that sets the PATH will grow too
        # long.
        command = "\r\n".join(
            [c + "\r\nif %errorlevel% neq 0 exit /b %errorlevel%" for c in commands]
        )
        _AddMSBuildAction(
            spec,
            primary_input,
            inputs,
            outputs,
            command,
            description,
            sources_handled_by_action,
            actions_spec,
        )
    return actions_spec, sources_handled_by_action


def _AddMSBuildAction(
    spec,
    primary_input,
    inputs,
    outputs,
    cmd,
    description,
    sources_handled_by_action,
    actions_spec,
):
    command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd)
    primary_input = _FixPath(primary_input)
    inputs_array = _FixPaths(inputs)
    outputs_array = _FixPaths(outputs)
    additional_inputs = ";".join([i for i in inputs_array if i != primary_input])
    outputs = ";".join(outputs_array)
    sources_handled_by_action.add(primary_input)
    action_spec = ["CustomBuild", {"Include": primary_input}]
    action_spec.extend(
        # TODO(jeanluc) 'Document' for all or just if as_sources?
        [
            ["FileType", "Document"],
            ["Command", command],
            ["Message", description],
            ["Outputs", outputs],
        ]
    )
    if additional_inputs:
        action_spec.append(["AdditionalInputs", additional_inputs])
    actions_spec.append(action_spec)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Xcode project file generator.

This module is both an Xcode project file generator and a documentation of the
Xcode project file format.  Knowledge of the project file format was gained
based on extensive experience with Xcode, and by making changes to projects in
Xcode.app and observing the resultant changes in the associated project files.

XCODE PROJECT FILES

The generator targets the file format as written by Xcode 3.2 (specifically,
3.2.6), but past experience has taught that the format has not changed
significantly in the past several years, and future versions of Xcode are able
to read older project files.

Xcode project files are "bundled": the project "file" from an end-user's
perspective is actually a directory with an ".xcodeproj" extension.  The
project file from this module's perspective is actually a file inside this
directory, always named "project.pbxproj".  This file contains a complete
description of the project and is all that is needed to use the xcodeproj.
Other files contained in the xcodeproj directory are simply used to store
per-user settings, such as the state of various UI elements in the Xcode
application.

The project.pbxproj file is a property list, stored in a format almost
identical to the NeXTstep property list format.  The file is able to carry
Unicode data, and is encoded in UTF-8.  The root element in the property list
is a dictionary that contains several properties of minimal interest, and two
properties of immense interest.  The most important property is a dictionary
named "objects".  The entire structure of the project is represented by the
children of this property.  The objects dictionary is keyed by unique 96-bit
values represented by 24 uppercase hexadecimal characters.  Each value in the
objects dictionary is itself a dictionary, describing an individual object.

Each object in the dictionary is a member of a class, which is identified by
the "isa" property of each object.  A variety of classes are represented in a
project file.  Objects can refer to other objects by ID, using the 24-character
hexadecimal object key.  A project's objects form a tree, with a root object
of class PBXProject at the root.  As an example, the PBXProject object serves
as parent to an XCConfigurationList object defining the build configurations
used in the project, a PBXGroup object serving as a container for all files
referenced in the project, and a list of target objects, each of which defines
a target in the project.  There are several different types of target object,
such as PBXNativeTarget and PBXAggregateTarget.  In this module, this
relationship is expressed by having each target type derive from an abstract
base named XCTarget.

The project.pbxproj file's root dictionary also contains a property, sibling to
the "objects" dictionary, named "rootObject".  The value of rootObject is a
24-character object key referring to the root PBXProject object in the
objects dictionary.

In Xcode, every file used as input to a target or produced as a final product
of a target must appear somewhere in the hierarchy rooted at the PBXGroup
object referenced by the PBXProject's mainGroup property.  A PBXGroup is
generally represented as a folder in the Xcode application.  PBXGroups can
contain other PBXGroups as well as PBXFileReferences, which are pointers to
actual files.

Each XCTarget contains a list of build phases, represented in this module by
the abstract base XCBuildPhase.  Examples of concrete XCBuildPhase derivations
are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the
"Compile Sources" and "Link Binary With Libraries" phases displayed in the
Xcode application.  Files used as input to these phases (for example, source
files in the former case and libraries and frameworks in the latter) are
represented by PBXBuildFile objects, referenced by elements of "files" lists
in XCTarget objects.  Each PBXBuildFile object refers to a PBXBuildFile
object as a "weak" reference: it does not "own" the PBXBuildFile, which is
owned by the root object's mainGroup or a descendant group.  In most cases, the
layer of indirection between an XCBuildPhase and a PBXFileReference via a
PBXBuildFile appears extraneous, but there's actually one reason for this:
file-specific compiler flags are added to the PBXBuildFile object so as to
allow a single file to be a member of multiple targets while having distinct
compiler flags for each.  These flags can be modified in the Xcode applciation
in the "Build" tab of a File Info window.

When a project is open in the Xcode application, Xcode will rewrite it.  As
such, this module is careful to adhere to the formatting used by Xcode, to
avoid insignificant changes appearing in the file when it is used in the
Xcode application.  This will keep version control repositories happy, and
makes it possible to compare a project file used in Xcode to one generated by
this module to determine if any significant changes were made in the
application.

Xcode has its own way of assigning 24-character identifiers to each object,
which is not duplicated here.  Because the identifier only is only generated
once, when an object is created, and is then left unchanged, there is no need
to attempt to duplicate Xcode's behavior in this area.  The generator is free
to select any identifier, even at random, to refer to the objects it creates,
and Xcode will retain those identifiers and use them when subsequently
rewriting the project file.  However, the generator would choose new random
identifiers each time the project files are generated, leading to difficulties
comparing "used" project files to "pristine" ones produced by this module,
and causing the appearance of changes as every object identifier is changed
when updated projects are checked in to a version control repository.  To
mitigate this problem, this module chooses identifiers in a more deterministic
way, by hashing a description of each object as well as its parent and ancestor
objects.  This strategy should result in minimal "shift" in IDs as successive
generations of project files are produced.

THIS MODULE

This module introduces several classes, all derived from the XCObject class.
Nearly all of the "brains" are built into the XCObject class, which understands
how to create and modify objects, maintain the proper tree structure, compute
identifiers, and print objects.  For the most part, classes derived from
XCObject need only provide a _schema class object, a dictionary that
expresses what properties objects of the class may contain.

Given this structure, it's possible to build a minimal project file by creating
objects of the appropriate types and making the proper connections:

  config_list = XCConfigurationList()
  group = PBXGroup()
  project = PBXProject({'buildConfigurationList': config_list,
                        'mainGroup': group})

With the project object set up, it can be added to an XCProjectFile object.
XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject
subclass that does not actually correspond to a class type found in a project
file.  Rather, it is used to represent the project file's root dictionary.
Printing an XCProjectFile will print the entire project file, including the
full "objects" dictionary.

  project_file = XCProjectFile({'rootObject': project})
  project_file.ComputeIDs()
  project_file.Print()

Xcode project files are always encoded in UTF-8.  This module will accept
strings of either the str class or the unicode class.  Strings of class str
are assumed to already be encoded in UTF-8.  Obviously, if you're just using
ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset.
Strings of class unicode are handled properly and encoded in UTF-8 when
a project file is output.
"""

import gyp.common
from functools import cmp_to_key
import hashlib
from operator import attrgetter
import posixpath
import re
import struct
import sys


def cmp(x, y):
    return (x > y) - (x < y)


# See XCObject._EncodeString.  This pattern is used to determine when a string
# can be printed unquoted.  Strings that match this pattern may be printed
# unquoted.  Strings that do not match must be quoted and may be further
# transformed to be properly encoded.  Note that this expression matches the
# characters listed with "+", for 1 or more occurrences: if a string is empty,
# it must not match this pattern, because it needs to be encoded as "".
_unquoted = re.compile("^[A-Za-z0-9$./_]+$")

# Strings that match this pattern are quoted regardless of what _unquoted says.
# Oddly, Xcode will quote any string with a run of three or more underscores.
_quoted = re.compile("___")

# This pattern should match any character that needs to be escaped by
# XCObject._EncodeString.  See that function.
_escaped = re.compile('[\\\\"]|[\x00-\x1f]')


# Used by SourceTreeAndPathFromPath
_path_leading_variable = re.compile(r"^\$\((.*?)\)(/(.*))?$")


def SourceTreeAndPathFromPath(input_path):
    """Given input_path, returns a tuple with sourceTree and path values.

  Examples:
    input_path     (source_tree, output_path)
    '$(VAR)/path'  ('VAR', 'path')
    '$(VAR)'       ('VAR', None)
    'path'         (None, 'path')
  """

    source_group_match = _path_leading_variable.match(input_path)
    if source_group_match:
        source_tree = source_group_match.group(1)
        output_path = source_group_match.group(3)  # This may be None.
    else:
        source_tree = None
        output_path = input_path

    return (source_tree, output_path)


def ConvertVariablesToShellSyntax(input_string):
    return re.sub(r"\$\((.*?)\)", "${\\1}", input_string)


class XCObject:
    """The abstract base of all class types used in Xcode project files.

  Class variables:
    _schema: A dictionary defining the properties of this class.  The keys to
             _schema are string property keys as used in project files.  Values
             are a list of four or five elements:
             [ is_list, property_type, is_strong, is_required, default ]
             is_list: True if the property described is a list, as opposed
                      to a single element.
             property_type: The type to use as the value of the property,
                            or if is_list is True, the type to use for each
                            element of the value's list.  property_type must
                            be an XCObject subclass, or one of the built-in
                            types str, int, or dict.
             is_strong: If property_type is an XCObject subclass, is_strong
                        is True to assert that this class "owns," or serves
                        as parent, to the property value (or, if is_list is
                        True, values).  is_strong must be False if
                        property_type is not an XCObject subclass.
             is_required: True if the property is required for the class.
                          Note that is_required being True does not preclude
                          an empty string ("", in the case of property_type
                          str) or list ([], in the case of is_list True) from
                          being set for the property.
             default: Optional.  If is_required is True, default may be set
                      to provide a default value for objects that do not supply
                      their own value.  If is_required is True and default
                      is not provided, users of the class must supply their own
                      value for the property.
             Note that although the values of the array are expressed in
             boolean terms, subclasses provide values as integers to conserve
             horizontal space.
    _should_print_single_line: False in XCObject.  Subclasses whose objects
                               should be written to the project file in the
                               alternate single-line format, such as
                               PBXFileReference and PBXBuildFile, should
                               set this to True.
    _encode_transforms: Used by _EncodeString to encode unprintable characters.
                        The index into this list is the ordinal of the
                        character to transform; each value is a string
                        used to represent the character in the output.  XCObject
                        provides an _encode_transforms list suitable for most
                        XCObject subclasses.
    _alternate_encode_transforms: Provided for subclasses that wish to use
                                  the alternate encoding rules.  Xcode seems
                                  to use these rules when printing objects in
                                  single-line format.  Subclasses that desire
                                  this behavior should set _encode_transforms
                                  to _alternate_encode_transforms.
    _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs
                to construct this object's ID.  Most classes that need custom
                hashing behavior should do it by overriding Hashables,
                but in some cases an object's parent may wish to push a
                hashable value into its child, and it can do so by appending
                to _hashables.
  Attributes:
    id: The object's identifier, a 24-character uppercase hexadecimal string.
        Usually, objects being created should not set id until the entire
        project file structure is built.  At that point, UpdateIDs() should
        be called on the root object to assign deterministic values for id to
        each object in the tree.
    parent: The object's parent.  This is set by a parent XCObject when a child
            object is added to it.
    _properties: The object's property dictionary.  An object's properties are
                 described by its class' _schema variable.
  """

    _schema = {}
    _should_print_single_line = False

    # See _EncodeString.
    _encode_transforms = []
    i = 0
    while i < ord(" "):
        _encode_transforms.append("\\U%04x" % i)
        i = i + 1
    _encode_transforms[7] = "\\a"
    _encode_transforms[8] = "\\b"
    _encode_transforms[9] = "\\t"
    _encode_transforms[10] = "\\n"
    _encode_transforms[11] = "\\v"
    _encode_transforms[12] = "\\f"
    _encode_transforms[13] = "\\n"

    _alternate_encode_transforms = list(_encode_transforms)
    _alternate_encode_transforms[9] = chr(9)
    _alternate_encode_transforms[10] = chr(10)
    _alternate_encode_transforms[11] = chr(11)

    def __init__(self, properties=None, id=None, parent=None):
        self.id = id
        self.parent = parent
        self._properties = {}
        self._hashables = []
        self._SetDefaultsFromSchema()
        self.UpdateProperties(properties)

    def __repr__(self):
        try:
            name = self.Name()
        except NotImplementedError:
            return f"<{self.__class__.__name__} at 0x{id(self):x}>"
        return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"

    def Copy(self):
        """Make a copy of this object.

    The new object will have its own copy of lists and dicts.  Any XCObject
    objects owned by this object (marked "strong") will be copied in the
    new object, even those found in lists.  If this object has any weak
    references to other XCObjects, the same references are added to the new
    object without making a copy.
    """

        that = self.__class__(id=self.id, parent=self.parent)
        for key, value in self._properties.items():
            is_strong = self._schema[key][2]

            if isinstance(value, XCObject):
                if is_strong:
                    new_value = value.Copy()
                    new_value.parent = that
                    that._properties[key] = new_value
                else:
                    that._properties[key] = value
            elif isinstance(value, (str, int)):
                that._properties[key] = value
            elif isinstance(value, list):
                if is_strong:
                    # If is_strong is True, each element is an XCObject, so it's safe to
                    # call Copy.
                    that._properties[key] = []
                    for item in value:
                        new_item = item.Copy()
                        new_item.parent = that
                        that._properties[key].append(new_item)
                else:
                    that._properties[key] = value[:]
            elif isinstance(value, dict):
                # dicts are never strong.
                if is_strong:
                    raise TypeError(
                        "Strong dict for key " + key + " in " + self.__class__.__name__
                    )
                else:
                    that._properties[key] = value.copy()
            else:
                raise TypeError(
                    "Unexpected type "
                    + value.__class__.__name__
                    + " for key "
                    + key
                    + " in "
                    + self.__class__.__name__
                )

        return that

    def Name(self):
        """Return the name corresponding to an object.

    Not all objects necessarily need to be nameable, and not all that do have
    a "name" property.  Override as needed.
    """

        # If the schema indicates that "name" is required, try to access the
        # property even if it doesn't exist.  This will result in a KeyError
        # being raised for the property that should be present, which seems more
        # appropriate than NotImplementedError in this case.
        if "name" in self._properties or (
            "name" in self._schema and self._schema["name"][3]
        ):
            return self._properties["name"]

        raise NotImplementedError(self.__class__.__name__ + " must implement Name")

    def Comment(self):
        """Return a comment string for the object.

    Most objects just use their name as the comment, but PBXProject uses
    different values.

    The returned comment is not escaped and does not have any comment marker
    strings applied to it.
    """

        return self.Name()

    def Hashables(self):
        hashables = [self.__class__.__name__]

        name = self.Name()
        if name is not None:
            hashables.append(name)

        hashables.extend(self._hashables)

        return hashables

    def HashablesForChild(self):
        return None

    def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None):
        """Set "id" properties deterministically.

    An object's "id" property is set based on a hash of its class type and
    name, as well as the class type and name of all ancestor objects.  As
    such, it is only advisable to call ComputeIDs once an entire project file
    tree is built.

    If recursive is True, recurse into all descendant objects and update their
    hashes.

    If overwrite is True, any existing value set in the "id" property will be
    replaced.
    """

        def _HashUpdate(hash, data):
            """Update hash with data's length and contents.

      If the hash were updated only with the value of data, it would be
      possible for clowns to induce collisions by manipulating the names of
      their objects.  By adding the length, it's exceedingly less likely that
      ID collisions will be encountered, intentionally or not.
      """

            hash.update(struct.pack(">i", len(data)))
            if isinstance(data, str):
                data = data.encode("utf-8")
            hash.update(data)

        if seed_hash is None:
            seed_hash = hashlib.sha1()

        hash = seed_hash.copy()

        hashables = self.Hashables()
        assert len(hashables) > 0
        for hashable in hashables:
            _HashUpdate(hash, hashable)

        if recursive:
            hashables_for_child = self.HashablesForChild()
            if hashables_for_child is None:
                child_hash = hash
            else:
                assert len(hashables_for_child) > 0
                child_hash = seed_hash.copy()
                for hashable in hashables_for_child:
                    _HashUpdate(child_hash, hashable)

            for child in self.Children():
                child.ComputeIDs(recursive, overwrite, child_hash)

        if overwrite or self.id is None:
            # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is
            # is 160 bits.  Instead of throwing out 64 bits of the digest, xor them
            # into the portion that gets used.
            assert hash.digest_size % 4 == 0
            digest_int_count = hash.digest_size // 4
            digest_ints = struct.unpack(">" + "I" * digest_int_count, hash.digest())
            id_ints = [0, 0, 0]
            for index in range(0, digest_int_count):
                id_ints[index % 3] ^= digest_ints[index]
            self.id = "%08X%08X%08X" % tuple(id_ints)

    def EnsureNoIDCollisions(self):
        """Verifies that no two objects have the same ID.  Checks all descendants.
    """

        ids = {}
        descendants = self.Descendants()
        for descendant in descendants:
            if descendant.id in ids:
                other = ids[descendant.id]
                raise KeyError(
                    'Duplicate ID %s, objects "%s" and "%s" in "%s"'
                    % (
                        descendant.id,
                        str(descendant._properties),
                        str(other._properties),
                        self._properties["rootObject"].Name(),
                    )
                )
            ids[descendant.id] = descendant

    def Children(self):
        """Returns a list of all of this object's owned (strong) children."""

        children = []
        for property, attributes in self._schema.items():
            (is_list, property_type, is_strong) = attributes[0:3]
            if is_strong and property in self._properties:
                if not is_list:
                    children.append(self._properties[property])
                else:
                    children.extend(self._properties[property])
        return children

    def Descendants(self):
        """Returns a list of all of this object's descendants, including this
    object.
    """

        children = self.Children()
        descendants = [self]
        for child in children:
            descendants.extend(child.Descendants())
        return descendants

    def PBXProjectAncestor(self):
        # The base case for recursion is defined at PBXProject.PBXProjectAncestor.
        if self.parent:
            return self.parent.PBXProjectAncestor()
        return None

    def _EncodeComment(self, comment):
        """Encodes a comment to be placed in the project file output, mimicking
    Xcode behavior.
    """

        # This mimics Xcode behavior by wrapping the comment in "/*" and "*/".  If
        # the string already contains a "*/", it is turned into "(*)/".  This keeps
        # the file writer from outputting something that would be treated as the
        # end of a comment in the middle of something intended to be entirely a
        # comment.

        return "/* " + comment.replace("*/", "(*)/") + " */"

    def _EncodeTransform(self, match):
        # This function works closely with _EncodeString.  It will only be called
        # by re.sub with match.group(0) containing a character matched by the
        # the _escaped expression.
        char = match.group(0)

        # Backslashes (\) and quotation marks (") are always replaced with a
        # backslash-escaped version of the same.  Everything else gets its
        # replacement from the class' _encode_transforms array.
        if char == "\\":
            return "\\\\"
        if char == '"':
            return '\\"'
        return self._encode_transforms[ord(char)]

    def _EncodeString(self, value):
        """Encodes a string to be placed in the project file output, mimicking
    Xcode behavior.
    """

        # Use quotation marks when any character outside of the range A-Z, a-z, 0-9,
        # $ (dollar sign), . (period), and _ (underscore) is present.  Also use
        # quotation marks to represent empty strings.
        #
        # Escape " (double-quote) and \ (backslash) by preceding them with a
        # backslash.
        #
        # Some characters below the printable ASCII range are encoded specially:
        #     7 ^G BEL is encoded as "\a"
        #     8 ^H BS  is encoded as "\b"
        #    11 ^K VT  is encoded as "\v"
        #    12 ^L NP  is encoded as "\f"
        #   127 ^? DEL is passed through as-is without escaping
        #  - In PBXFileReference and PBXBuildFile objects:
        #     9 ^I HT  is passed through as-is without escaping
        #    10 ^J NL  is passed through as-is without escaping
        #    13 ^M CR  is passed through as-is without escaping
        #  - In other objects:
        #     9 ^I HT  is encoded as "\t"
        #    10 ^J NL  is encoded as "\n"
        #    13 ^M CR  is encoded as "\n" rendering it indistinguishable from
        #              10 ^J NL
        # All other characters within the ASCII control character range (0 through
        # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point
        # in hexadecimal.  For example, character 14 (^N SO) is encoded as "\U000e".
        # Characters above the ASCII range are passed through to the output encoded
        # as UTF-8 without any escaping.  These mappings are contained in the
        # class' _encode_transforms list.

        if _unquoted.search(value) and not _quoted.search(value):
            return value

        return '"' + _escaped.sub(self._EncodeTransform, value) + '"'

    def _XCPrint(self, file, tabs, line):
        file.write("\t" * tabs + line)

    def _XCPrintableValue(self, tabs, value, flatten_list=False):
        """Returns a representation of value that may be printed in a project file,
    mimicking Xcode's behavior.

    _XCPrintableValue can handle str and int values, XCObjects (which are
    made printable by returning their id property), and list and dict objects
    composed of any of the above types.  When printing a list or dict, and
    _should_print_single_line is False, the tabs parameter is used to determine
    how much to indent the lines corresponding to the items in the list or
    dict.

    If flatten_list is True, single-element lists will be transformed into
    strings.
    """

        printable = ""
        comment = None

        if self._should_print_single_line:
            sep = " "
            element_tabs = ""
            end_tabs = ""
        else:
            sep = "\n"
            element_tabs = "\t" * (tabs + 1)
            end_tabs = "\t" * tabs

        if isinstance(value, XCObject):
            printable += value.id
            comment = value.Comment()
        elif isinstance(value, str):
            printable += self._EncodeString(value)
        elif isinstance(value, str):
            printable += self._EncodeString(value.encode("utf-8"))
        elif isinstance(value, int):
            printable += str(value)
        elif isinstance(value, list):
            if flatten_list and len(value) <= 1:
                if len(value) == 0:
                    printable += self._EncodeString("")
                else:
                    printable += self._EncodeString(value[0])
            else:
                printable = "(" + sep
                for item in value:
                    printable += (
                        element_tabs
                        + self._XCPrintableValue(tabs + 1, item, flatten_list)
                        + ","
                        + sep
                    )
                printable += end_tabs + ")"
        elif isinstance(value, dict):
            printable = "{" + sep
            for item_key, item_value in sorted(value.items()):
                printable += (
                    element_tabs
                    + self._XCPrintableValue(tabs + 1, item_key, flatten_list)
                    + " = "
                    + self._XCPrintableValue(tabs + 1, item_value, flatten_list)
                    + ";"
                    + sep
                )
            printable += end_tabs + "}"
        else:
            raise TypeError("Can't make " + value.__class__.__name__ + " printable")

        if comment:
            printable += " " + self._EncodeComment(comment)

        return printable

    def _XCKVPrint(self, file, tabs, key, value):
        """Prints a key and value, members of an XCObject's _properties dictionary,
    to file.

    tabs is an int identifying the indentation level.  If the class'
    _should_print_single_line variable is True, tabs is ignored and the
    key-value pair will be followed by a space insead of a newline.
    """

        if self._should_print_single_line:
            printable = ""
            after_kv = " "
        else:
            printable = "\t" * tabs
            after_kv = "\n"

        # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy
        # objects without comments.  Sometimes it prints them with comments, but
        # the majority of the time, it doesn't.  To avoid unnecessary changes to
        # the project file after Xcode opens it, don't write comments for
        # remoteGlobalIDString.  This is a sucky hack and it would certainly be
        # cleaner to extend the schema to indicate whether or not a comment should
        # be printed, but since this is the only case where the problem occurs and
        # Xcode itself can't seem to make up its mind, the hack will suffice.
        #
        # Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].
        if key == "remoteGlobalIDString" and isinstance(self, PBXContainerItemProxy):
            value_to_print = value.id
        else:
            value_to_print = value

        # PBXBuildFile's settings property is represented in the output as a dict,
        # but a hack here has it represented as a string. Arrange to strip off the
        # quotes so that it shows up in the output as expected.
        if key == "settings" and isinstance(self, PBXBuildFile):
            strip_value_quotes = True
        else:
            strip_value_quotes = False

        # In another one-off, let's set flatten_list on buildSettings properties
        # of XCBuildConfiguration objects, because that's how Xcode treats them.
        if key == "buildSettings" and isinstance(self, XCBuildConfiguration):
            flatten_list = True
        else:
            flatten_list = False

        try:
            printable_key = self._XCPrintableValue(tabs, key, flatten_list)
            printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list)
            if (
                strip_value_quotes
                and len(printable_value) > 1
                and printable_value[0] == '"'
                and printable_value[-1] == '"'
            ):
                printable_value = printable_value[1:-1]
            printable += printable_key + " = " + printable_value + ";" + after_kv
        except TypeError as e:
            gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key)
            raise

        self._XCPrint(file, 0, printable)

    def Print(self, file=sys.stdout):
        """Prints a reprentation of this object to file, adhering to Xcode output
    formatting.
    """

        self.VerifyHasRequiredProperties()

        if self._should_print_single_line:
            # When printing an object in a single line, Xcode doesn't put any space
            # between the beginning of a dictionary (or presumably a list) and the
            # first contained item, so you wind up with snippets like
            #   ...CDEF = {isa = PBXFileReference; fileRef = 0123...
            # If it were me, I would have put a space in there after the opening
            # curly, but I guess this is just another one of those inconsistencies
            # between how Xcode prints PBXFileReference and PBXBuildFile objects as
            # compared to other objects.  Mimic Xcode's behavior here by using an
            # empty string for sep.
            sep = ""
            end_tabs = 0
        else:
            sep = "\n"
            end_tabs = 2

        # Start the object.  For example, '\t\tPBXProject = {\n'.
        self._XCPrint(file, 2, self._XCPrintableValue(2, self) + " = {" + sep)

        # "isa" isn't in the _properties dictionary, it's an intrinsic property
        # of the class which the object belongs to.  Xcode always outputs "isa"
        # as the first element of an object dictionary.
        self._XCKVPrint(file, 3, "isa", self.__class__.__name__)

        # The remaining elements of an object dictionary are sorted alphabetically.
        for property, value in sorted(self._properties.items()):
            self._XCKVPrint(file, 3, property, value)

        # End the object.
        self._XCPrint(file, end_tabs, "};\n")

    def UpdateProperties(self, properties, do_copy=False):
        """Merge the supplied properties into the _properties dictionary.

    The input properties must adhere to the class schema or a KeyError or
    TypeError exception will be raised.  If adding an object of an XCObject
    subclass and the schema indicates a strong relationship, the object's
    parent will be set to this object.

    If do_copy is True, then lists, dicts, strong-owned XCObjects, and
    strong-owned XCObjects in lists will be copied instead of having their
    references added.
    """

        if properties is None:
            return

        for property, value in properties.items():
            # Make sure the property is in the schema.
            if property not in self._schema:
                raise KeyError(property + " not in " + self.__class__.__name__)

            # Make sure the property conforms to the schema.
            (is_list, property_type, is_strong) = self._schema[property][0:3]
            if is_list:
                if value.__class__ != list:
                    raise TypeError(
                        property
                        + " of "
                        + self.__class__.__name__
                        + " must be list, not "
                        + value.__class__.__name__
                    )
                for item in value:
                    if not isinstance(item, property_type) and not (
                        isinstance(item, str) and property_type == str
                    ):
                        # Accept unicode where str is specified.  str is treated as
                        # UTF-8-encoded.
                        raise TypeError(
                            "item of "
                            + property
                            + " of "
                            + self.__class__.__name__
                            + " must be "
                            + property_type.__name__
                            + ", not "
                            + item.__class__.__name__
                        )
            elif not isinstance(value, property_type) and not (
                isinstance(value, str) and property_type == str
            ):
                # Accept unicode where str is specified.  str is treated as
                # UTF-8-encoded.
                raise TypeError(
                    property
                    + " of "
                    + self.__class__.__name__
                    + " must be "
                    + property_type.__name__
                    + ", not "
                    + value.__class__.__name__
                )

            # Checks passed, perform the assignment.
            if do_copy:
                if isinstance(value, XCObject):
                    if is_strong:
                        self._properties[property] = value.Copy()
                    else:
                        self._properties[property] = value
                elif isinstance(value, (str, int)):
                    self._properties[property] = value
                elif isinstance(value, list):
                    if is_strong:
                        # If is_strong is True, each element is an XCObject,
                        # so it's safe to call Copy.
                        self._properties[property] = []
                        for item in value:
                            self._properties[property].append(item.Copy())
                    else:
                        self._properties[property] = value[:]
                elif isinstance(value, dict):
                    self._properties[property] = value.copy()
                else:
                    raise TypeError(
                        "Don't know how to copy a "
                        + value.__class__.__name__
                        + " object for "
                        + property
                        + " in "
                        + self.__class__.__name__
                    )
            else:
                self._properties[property] = value

            # Set up the child's back-reference to this object.  Don't use |value|
            # any more because it may not be right if do_copy is true.
            if is_strong:
                if not is_list:
                    self._properties[property].parent = self
                else:
                    for item in self._properties[property]:
                        item.parent = self

    def HasProperty(self, key):
        return key in self._properties

    def GetProperty(self, key):
        return self._properties[key]

    def SetProperty(self, key, value):
        self.UpdateProperties({key: value})

    def DelProperty(self, key):
        if key in self._properties:
            del self._properties[key]

    def AppendProperty(self, key, value):
        # TODO(mark): Support ExtendProperty too (and make this call that)?

        # Schema validation.
        if key not in self._schema:
            raise KeyError(key + " not in " + self.__class__.__name__)

        (is_list, property_type, is_strong) = self._schema[key][0:3]
        if not is_list:
            raise TypeError(key + " of " + self.__class__.__name__ + " must be list")
        if not isinstance(value, property_type):
            raise TypeError(
                "item of "
                + key
                + " of "
                + self.__class__.__name__
                + " must be "
                + property_type.__name__
                + ", not "
                + value.__class__.__name__
            )

        # If the property doesn't exist yet, create a new empty list to receive the
        # item.
        self._properties[key] = self._properties.get(key, [])

        # Set up the ownership link.
        if is_strong:
            value.parent = self

        # Store the item.
        self._properties[key].append(value)

    def VerifyHasRequiredProperties(self):
        """Ensure that all properties identified as required by the schema are
    set.
    """

        # TODO(mark): A stronger verification mechanism is needed.  Some
        # subclasses need to perform validation beyond what the schema can enforce.
        for property, attributes in self._schema.items():
            (is_list, property_type, is_strong, is_required) = attributes[0:4]
            if is_required and property not in self._properties:
                raise KeyError(self.__class__.__name__ + " requires " + property)

    def _SetDefaultsFromSchema(self):
        """Assign object default values according to the schema.  This will not
    overwrite properties that have already been set."""

        defaults = {}
        for property, attributes in self._schema.items():
            (is_list, property_type, is_strong, is_required) = attributes[0:4]
            if (
                is_required
                and len(attributes) >= 5
                and property not in self._properties
            ):
                default = attributes[4]

                defaults[property] = default

        if len(defaults) > 0:
            # Use do_copy=True so that each new object gets its own copy of strong
            # objects, lists, and dicts.
            self.UpdateProperties(defaults, do_copy=True)


class XCHierarchicalElement(XCObject):
    """Abstract base for PBXGroup and PBXFileReference.  Not represented in a
  project file."""

    # TODO(mark): Do name and path belong here?  Probably so.
    # If path is set and name is not, name may have a default value.  Name will
    # be set to the basename of path, if the basename of path is different from
    # the full value of path.  If path is already just a leaf name, name will
    # not be set.
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "comments": [0, str, 0, 0],
            "fileEncoding": [0, str, 0, 0],
            "includeInIndex": [0, int, 0, 0],
            "indentWidth": [0, int, 0, 0],
            "lineEnding": [0, int, 0, 0],
            "sourceTree": [0, str, 0, 1, "<group>"],
            "tabWidth": [0, int, 0, 0],
            "usesTabs": [0, int, 0, 0],
            "wrapsLines": [0, int, 0, 0],
        }
    )

    def __init__(self, properties=None, id=None, parent=None):
        # super
        XCObject.__init__(self, properties, id, parent)
        if "path" in self._properties and "name" not in self._properties:
            path = self._properties["path"]
            name = posixpath.basename(path)
            if name not in ("", path):
                self.SetProperty("name", name)

        if "path" in self._properties and (
            "sourceTree" not in self._properties
            or self._properties["sourceTree"] == "<group>"
        ):
            # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take
            # the variable out and make the path be relative to that variable by
            # assigning the variable name as the sourceTree.
            (source_tree, path) = SourceTreeAndPathFromPath(self._properties["path"])
            if source_tree is not None:
                self._properties["sourceTree"] = source_tree
            if path is not None:
                self._properties["path"] = path
            if (
                source_tree is not None
                and path is None
                and "name" not in self._properties
            ):
                # The path was of the form "$(SDKROOT)" with no path following it.
                # This object is now relative to that variable, so it has no path
                # attribute of its own.  It does, however, keep a name.
                del self._properties["path"]
                self._properties["name"] = source_tree

    def Name(self):
        if "name" in self._properties:
            return self._properties["name"]
        elif "path" in self._properties:
            return self._properties["path"]
        else:
            # This happens in the case of the root PBXGroup.
            return None

    def Hashables(self):
        """Custom hashables for XCHierarchicalElements.

    XCHierarchicalElements are special.  Generally, their hashes shouldn't
    change if the paths don't change.  The normal XCObject implementation of
    Hashables adds a hashable for each object, which means that if
    the hierarchical structure changes (possibly due to changes caused when
    TakeOverOnlyChild runs and encounters slight changes in the hierarchy),
    the hashes will change.  For example, if a project file initially contains
    a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent
    a/b.  If someone later adds a/f2 to the project file, a/b can no longer be
    collapsed, and f1 winds up with parent b and grandparent a.  That would
    be sufficient to change f1's hash.

    To counteract this problem, hashables for all XCHierarchicalElements except
    for the main group (which has neither a name nor a path) are taken to be
    just the set of path components.  Because hashables are inherited from
    parents, this provides assurance that a/b/f1 has the same set of hashables
    whether its parent is b or a/b.

    The main group is a special case.  As it is permitted to have no name or
    path, it is permitted to use the standard XCObject hash mechanism.  This
    is not considered a problem because there can be only one main group.
    """

        if self == self.PBXProjectAncestor()._properties["mainGroup"]:
            # super
            return XCObject.Hashables(self)

        hashables = []

        # Put the name in first, ensuring that if TakeOverOnlyChild collapses
        # children into a top-level group like "Source", the name always goes
        # into the list of hashables without interfering with path components.
        if "name" in self._properties:
            # Make it less likely for people to manipulate hashes by following the
            # pattern of always pushing an object type value onto the list first.
            hashables.append(self.__class__.__name__ + ".name")
            hashables.append(self._properties["name"])

        # NOTE: This still has the problem that if an absolute path is encountered,
        # including paths with a sourceTree, they'll still inherit their parents'
        # hashables, even though the paths aren't relative to their parents.  This
        # is not expected to be much of a problem in practice.
        path = self.PathFromSourceTreeAndPath()
        if path is not None:
            components = path.split(posixpath.sep)
            for component in components:
                hashables.append(self.__class__.__name__ + ".path")
                hashables.append(component)

        hashables.extend(self._hashables)

        return hashables

    def Compare(self, other):
        # Allow comparison of these types.  PBXGroup has the highest sort rank;
        # PBXVariantGroup is treated as equal to PBXFileReference.
        valid_class_types = {
            PBXFileReference: "file",
            PBXGroup: "group",
            PBXVariantGroup: "file",
        }
        self_type = valid_class_types[self.__class__]
        other_type = valid_class_types[other.__class__]

        if self_type == other_type:
            # If the two objects are of the same sort rank, compare their names.
            return cmp(self.Name(), other.Name())

        # Otherwise, sort groups before everything else.
        if self_type == "group":
            return -1
        return 1

    def CompareRootGroup(self, other):
        # This function should be used only to compare direct children of the
        # containing PBXProject's mainGroup.  These groups should appear in the
        # listed order.
        # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the
        # generator should have a way of influencing this list rather than having
        # to hardcode for the generator here.
        order = [
            "Source",
            "Intermediates",
            "Projects",
            "Frameworks",
            "Products",
            "Build",
        ]

        # If the groups aren't in the listed order, do a name comparison.
        # Otherwise, groups in the listed order should come before those that
        # aren't.
        self_name = self.Name()
        other_name = other.Name()
        self_in = isinstance(self, PBXGroup) and self_name in order
        other_in = isinstance(self, PBXGroup) and other_name in order
        if not self_in and not other_in:
            return self.Compare(other)
        if self_name in order and other_name not in order:
            return -1
        if other_name in order and self_name not in order:
            return 1

        # If both groups are in the listed order, go by the defined order.
        self_index = order.index(self_name)
        other_index = order.index(other_name)
        if self_index < other_index:
            return -1
        if self_index > other_index:
            return 1
        return 0

    def PathFromSourceTreeAndPath(self):
        # Turn the object's sourceTree and path properties into a single flat
        # string of a form comparable to the path parameter.  If there's a
        # sourceTree property other than "<group>", wrap it in $(...) for the
        # comparison.
        components = []
        if self._properties["sourceTree"] != "<group>":
            components.append("$(" + self._properties["sourceTree"] + ")")
        if "path" in self._properties:
            components.append(self._properties["path"])

        if len(components) > 0:
            return posixpath.join(*components)

        return None

    def FullPath(self):
        # Returns a full path to self relative to the project file, or relative
        # to some other source tree.  Start with self, and walk up the chain of
        # parents prepending their paths, if any, until no more parents are
        # available (project-relative path) or until a path relative to some
        # source tree is found.
        xche = self
        path = None
        while isinstance(xche, XCHierarchicalElement) and (
            path is None or (not path.startswith("/") and not path.startswith("$"))
        ):
            this_path = xche.PathFromSourceTreeAndPath()
            if this_path is not None and path is not None:
                path = posixpath.join(this_path, path)
            elif this_path is not None:
                path = this_path
            xche = xche.parent

        return path


class PBXGroup(XCHierarchicalElement):
    """
  Attributes:
    _children_by_path: Maps pathnames of children of this PBXGroup to the
      actual child XCHierarchicalElement objects.
    _variant_children_by_name_and_path: Maps (name, path) tuples of
      PBXVariantGroup children to the actual child PBXVariantGroup objects.
  """

    _schema = XCHierarchicalElement._schema.copy()
    _schema.update(
        {
            "children": [1, XCHierarchicalElement, 1, 1, []],
            "name": [0, str, 0, 0],
            "path": [0, str, 0, 0],
        }
    )

    def __init__(self, properties=None, id=None, parent=None):
        # super
        XCHierarchicalElement.__init__(self, properties, id, parent)
        self._children_by_path = {}
        self._variant_children_by_name_and_path = {}
        for child in self._properties.get("children", []):
            self._AddChildToDicts(child)

    def Hashables(self):
        # super
        hashables = XCHierarchicalElement.Hashables(self)

        # It is not sufficient to just rely on name and parent to build a unique
        # hashable : a node could have two child PBXGroup sharing a common name.
        # To add entropy the hashable is enhanced with the names of all its
        # children.
        for child in self._properties.get("children", []):
            child_name = child.Name()
            if child_name is not None:
                hashables.append(child_name)

        return hashables

    def HashablesForChild(self):
        # To avoid a circular reference the hashables used to compute a child id do
        # not include the child names.
        return XCHierarchicalElement.Hashables(self)

    def _AddChildToDicts(self, child):
        # Sets up this PBXGroup object's dicts to reference the child properly.
        child_path = child.PathFromSourceTreeAndPath()
        if child_path:
            if child_path in self._children_by_path:
                raise ValueError("Found multiple children with path " + child_path)
            self._children_by_path[child_path] = child

        if isinstance(child, PBXVariantGroup):
            child_name = child._properties.get("name", None)
            key = (child_name, child_path)
            if key in self._variant_children_by_name_and_path:
                raise ValueError(
                    "Found multiple PBXVariantGroup children with "
                    + "name "
                    + str(child_name)
                    + " and path "
                    + str(child_path)
                )
            self._variant_children_by_name_and_path[key] = child

    def AppendChild(self, child):
        # Callers should use this instead of calling
        # AppendProperty('children', child) directly because this function
        # maintains the group's dicts.
        self.AppendProperty("children", child)
        self._AddChildToDicts(child)

    def GetChildByName(self, name):
        # This is not currently optimized with a dict as GetChildByPath is because
        # it has few callers.  Most callers probably want GetChildByPath.  This
        # function is only useful to get children that have names but no paths,
        # which is rare.  The children of the main group ("Source", "Products",
        # etc.) is pretty much the only case where this likely to come up.
        #
        # TODO(mark): Maybe this should raise an error if more than one child is
        # present with the same name.
        if "children" not in self._properties:
            return None

        for child in self._properties["children"]:
            if child.Name() == name:
                return child

        return None

    def GetChildByPath(self, path):
        if not path:
            return None

        if path in self._children_by_path:
            return self._children_by_path[path]

        return None

    def GetChildByRemoteObject(self, remote_object):
        # This method is a little bit esoteric.  Given a remote_object, which
        # should be a PBXFileReference in another project file, this method will
        # return this group's PBXReferenceProxy object serving as a local proxy
        # for the remote PBXFileReference.
        #
        # This function might benefit from a dict optimization as GetChildByPath
        # for some workloads, but profiling shows that it's not currently a
        # problem.
        if "children" not in self._properties:
            return None

        for child in self._properties["children"]:
            if not isinstance(child, PBXReferenceProxy):
                continue

            container_proxy = child._properties["remoteRef"]
            if container_proxy._properties["remoteGlobalIDString"] == remote_object:
                return child

        return None

    def AddOrGetFileByPath(self, path, hierarchical):
        """Returns an existing or new file reference corresponding to path.

    If hierarchical is True, this method will create or use the necessary
    hierarchical group structure corresponding to path.  Otherwise, it will
    look in and create an item in the current group only.

    If an existing matching reference is found, it is returned, otherwise, a
    new one will be created, added to the correct group, and returned.

    If path identifies a directory by virtue of carrying a trailing slash,
    this method returns a PBXFileReference of "folder" type.  If path
    identifies a variant, by virtue of it identifying a file inside a directory
    with an ".lproj" extension, this method returns a PBXVariantGroup
    containing the variant named by path, and possibly other variants.  For
    all other paths, a "normal" PBXFileReference will be returned.
    """

        # Adding or getting a directory?  Directories end with a trailing slash.
        is_dir = False
        if path.endswith("/"):
            is_dir = True
        path = posixpath.normpath(path)
        if is_dir:
            path = path + "/"

        # Adding or getting a variant?  Variants are files inside directories
        # with an ".lproj" extension.  Xcode uses variants for localization.  For
        # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named
        # MainMenu.nib inside path/to, and give it a variant named Language.  In
        # this example, grandparent would be set to path/to and parent_root would
        # be set to Language.
        variant_name = None
        parent = posixpath.dirname(path)
        grandparent = posixpath.dirname(parent)
        parent_basename = posixpath.basename(parent)
        (parent_root, parent_ext) = posixpath.splitext(parent_basename)
        if parent_ext == ".lproj":
            variant_name = parent_root
        if grandparent == "":
            grandparent = None

        # Putting a directory inside a variant group is not currently supported.
        assert not is_dir or variant_name is None

        path_split = path.split(posixpath.sep)
        if (
            len(path_split) == 1
            or ((is_dir or variant_name is not None) and len(path_split) == 2)
            or not hierarchical
        ):
            # The PBXFileReference or PBXVariantGroup will be added to or gotten from
            # this PBXGroup, no recursion necessary.
            if variant_name is None:
                # Add or get a PBXFileReference.
                file_ref = self.GetChildByPath(path)
                if file_ref is not None:
                    assert file_ref.__class__ == PBXFileReference
                else:
                    file_ref = PBXFileReference({"path": path})
                    self.AppendChild(file_ref)
            else:
                # Add or get a PBXVariantGroup.  The variant group name is the same
                # as the basename (MainMenu.nib in the example above).  grandparent
                # specifies the path to the variant group itself, and path_split[-2:]
                # is the path of the specific variant relative to its group.
                variant_group_name = posixpath.basename(path)
                variant_group_ref = self.AddOrGetVariantGroupByNameAndPath(
                    variant_group_name, grandparent
                )
                variant_path = posixpath.sep.join(path_split[-2:])
                variant_ref = variant_group_ref.GetChildByPath(variant_path)
                if variant_ref is not None:
                    assert variant_ref.__class__ == PBXFileReference
                else:
                    variant_ref = PBXFileReference(
                        {"name": variant_name, "path": variant_path}
                    )
                    variant_group_ref.AppendChild(variant_ref)
                # The caller is interested in the variant group, not the specific
                # variant file.
                file_ref = variant_group_ref
            return file_ref
        else:
            # Hierarchical recursion.  Add or get a PBXGroup corresponding to the
            # outermost path component, and then recurse into it, chopping off that
            # path component.
            next_dir = path_split[0]
            group_ref = self.GetChildByPath(next_dir)
            if group_ref is not None:
                assert group_ref.__class__ == PBXGroup
            else:
                group_ref = PBXGroup({"path": next_dir})
                self.AppendChild(group_ref)
            return group_ref.AddOrGetFileByPath(
                posixpath.sep.join(path_split[1:]), hierarchical
            )

    def AddOrGetVariantGroupByNameAndPath(self, name, path):
        """Returns an existing or new PBXVariantGroup for name and path.

    If a PBXVariantGroup identified by the name and path arguments is already
    present as a child of this object, it is returned.  Otherwise, a new
    PBXVariantGroup with the correct properties is created, added as a child,
    and returned.

    This method will generally be called by AddOrGetFileByPath, which knows
    when to create a variant group based on the structure of the pathnames
    passed to it.
    """

        key = (name, path)
        if key in self._variant_children_by_name_and_path:
            variant_group_ref = self._variant_children_by_name_and_path[key]
            assert variant_group_ref.__class__ == PBXVariantGroup
            return variant_group_ref

        variant_group_properties = {"name": name}
        if path is not None:
            variant_group_properties["path"] = path
        variant_group_ref = PBXVariantGroup(variant_group_properties)
        self.AppendChild(variant_group_ref)

        return variant_group_ref

    def TakeOverOnlyChild(self, recurse=False):
        """If this PBXGroup has only one child and it's also a PBXGroup, take
    it over by making all of its children this object's children.

    This function will continue to take over only children when those children
    are groups.  If there are three PBXGroups representing a, b, and c, with
    c inside b and b inside a, and a and b have no other children, this will
    result in a taking over both b and c, forming a PBXGroup for a/b/c.

    If recurse is True, this function will recurse into children and ask them
    to collapse themselves by taking over only children as well.  Assuming
    an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
    (d1, d2, and f are files, the rest are groups), recursion will result in
    a group for a/b/c containing a group for d3/e.
    """

        # At this stage, check that child class types are PBXGroup exactly,
        # instead of using isinstance.  The only subclass of PBXGroup,
        # PBXVariantGroup, should not participate in reparenting in the same way:
        # reparenting by merging different object types would be wrong.
        while (
            len(self._properties["children"]) == 1
            and self._properties["children"][0].__class__ == PBXGroup
        ):
            # Loop to take over the innermost only-child group possible.

            child = self._properties["children"][0]

            # Assume the child's properties, including its children.  Save a copy
            # of this object's old properties, because they'll still be needed.
            # This object retains its existing id and parent attributes.
            old_properties = self._properties
            self._properties = child._properties
            self._children_by_path = child._children_by_path

            if (
                "sourceTree" not in self._properties
                or self._properties["sourceTree"] == "<group>"
            ):
                # The child was relative to its parent.  Fix up the path.  Note that
                # children with a sourceTree other than "<group>" are not relative to
                # their parents, so no path fix-up is needed in that case.
                if "path" in old_properties:
                    if "path" in self._properties:
                        # Both the original parent and child have paths set.
                        self._properties["path"] = posixpath.join(
                            old_properties["path"], self._properties["path"]
                        )
                    else:
                        # Only the original parent has a path, use it.
                        self._properties["path"] = old_properties["path"]
                if "sourceTree" in old_properties:
                    # The original parent had a sourceTree set, use it.
                    self._properties["sourceTree"] = old_properties["sourceTree"]

            # If the original parent had a name set, keep using it.  If the original
            # parent didn't have a name but the child did, let the child's name
            # live on.  If the name attribute seems unnecessary now, get rid of it.
            if "name" in old_properties and old_properties["name"] not in (
                None,
                self.Name(),
            ):
                self._properties["name"] = old_properties["name"]
            if (
                "name" in self._properties
                and "path" in self._properties
                and self._properties["name"] == self._properties["path"]
            ):
                del self._properties["name"]

            # Notify all children of their new parent.
            for child in self._properties["children"]:
                child.parent = self

        # If asked to recurse, recurse.
        if recurse:
            for child in self._properties["children"]:
                if child.__class__ == PBXGroup:
                    child.TakeOverOnlyChild(recurse)

    def SortGroup(self):
        self._properties["children"] = sorted(
            self._properties["children"], key=cmp_to_key(lambda x, y: x.Compare(y))
        )

        # Recurse.
        for child in self._properties["children"]:
            if isinstance(child, PBXGroup):
                child.SortGroup()


class XCFileLikeElement(XCHierarchicalElement):
    # Abstract base for objects that can be used as the fileRef property of
    # PBXBuildFile.

    def PathHashables(self):
        # A PBXBuildFile that refers to this object will call this method to
        # obtain additional hashables specific to this XCFileLikeElement.  Don't
        # just use this object's hashables, they're not specific and unique enough
        # on their own (without access to the parent hashables.)  Instead, provide
        # hashables that identify this object by path by getting its hashables as
        # well as the hashables of ancestor XCHierarchicalElement objects.

        hashables = []
        xche = self
        while isinstance(xche, XCHierarchicalElement):
            xche_hashables = xche.Hashables()
            for index, xche_hashable in enumerate(xche_hashables):
                hashables.insert(index, xche_hashable)
            xche = xche.parent
        return hashables


class XCContainerPortal(XCObject):
    # Abstract base for objects that can be used as the containerPortal property
    # of PBXContainerItemProxy.
    pass


class XCRemoteObject(XCObject):
    # Abstract base for objects that can be used as the remoteGlobalIDString
    # property of PBXContainerItemProxy.
    pass


class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject):
    _schema = XCFileLikeElement._schema.copy()
    _schema.update(
        {
            "explicitFileType": [0, str, 0, 0],
            "lastKnownFileType": [0, str, 0, 0],
            "name": [0, str, 0, 0],
            "path": [0, str, 0, 1],
        }
    )

    # Weird output rules for PBXFileReference.
    _should_print_single_line = True
    # super
    _encode_transforms = XCFileLikeElement._alternate_encode_transforms

    def __init__(self, properties=None, id=None, parent=None):
        # super
        XCFileLikeElement.__init__(self, properties, id, parent)
        if "path" in self._properties and self._properties["path"].endswith("/"):
            self._properties["path"] = self._properties["path"][:-1]
            is_dir = True
        else:
            is_dir = False

        if (
            "path" in self._properties
            and "lastKnownFileType" not in self._properties
            and "explicitFileType" not in self._properties
        ):
            # TODO(mark): This is the replacement for a replacement for a quick hack.
            # It is no longer incredibly sucky, but this list needs to be extended.
            extension_map = {
                "a": "archive.ar",
                "app": "wrapper.application",
                "bdic": "file",
                "bundle": "wrapper.cfbundle",
                "c": "sourcecode.c.c",
                "cc": "sourcecode.cpp.cpp",
                "cpp": "sourcecode.cpp.cpp",
                "css": "text.css",
                "cxx": "sourcecode.cpp.cpp",
                "dart": "sourcecode",
                "dylib": "compiled.mach-o.dylib",
                "framework": "wrapper.framework",
                "gyp": "sourcecode",
                "gypi": "sourcecode",
                "h": "sourcecode.c.h",
                "hxx": "sourcecode.cpp.h",
                "icns": "image.icns",
                "java": "sourcecode.java",
                "js": "sourcecode.javascript",
                "kext": "wrapper.kext",
                "m": "sourcecode.c.objc",
                "mm": "sourcecode.cpp.objcpp",
                "nib": "wrapper.nib",
                "o": "compiled.mach-o.objfile",
                "pdf": "image.pdf",
                "pl": "text.script.perl",
                "plist": "text.plist.xml",
                "pm": "text.script.perl",
                "png": "image.png",
                "py": "text.script.python",
                "r": "sourcecode.rez",
                "rez": "sourcecode.rez",
                "s": "sourcecode.asm",
                "storyboard": "file.storyboard",
                "strings": "text.plist.strings",
                "swift": "sourcecode.swift",
                "ttf": "file",
                "xcassets": "folder.assetcatalog",
                "xcconfig": "text.xcconfig",
                "xcdatamodel": "wrapper.xcdatamodel",
                "xcdatamodeld": "wrapper.xcdatamodeld",
                "xib": "file.xib",
                "y": "sourcecode.yacc",
            }

            prop_map = {
                "dart": "explicitFileType",
                "gyp": "explicitFileType",
                "gypi": "explicitFileType",
            }

            if is_dir:
                file_type = "folder"
                prop_name = "lastKnownFileType"
            else:
                basename = posixpath.basename(self._properties["path"])
                (root, ext) = posixpath.splitext(basename)
                # Check the map using a lowercase extension.
                # TODO(mark): Maybe it should try with the original case first and fall
                # back to lowercase, in case there are any instances where case
                # matters.  There currently aren't.
                if ext != "":
                    ext = ext[1:].lower()

                # TODO(mark): "text" is the default value, but "file" is appropriate
                # for unrecognized files not containing text.  Xcode seems to choose
                # based on content.
                file_type = extension_map.get(ext, "text")
                prop_name = prop_map.get(ext, "lastKnownFileType")

            self._properties[prop_name] = file_type


class PBXVariantGroup(PBXGroup, XCFileLikeElement):
    """PBXVariantGroup is used by Xcode to represent localizations."""

    # No additions to the schema relative to PBXGroup.
    pass


# PBXReferenceProxy is also an XCFileLikeElement subclass.  It is defined below
# because it uses PBXContainerItemProxy, defined below.


class XCBuildConfiguration(XCObject):
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "baseConfigurationReference": [0, PBXFileReference, 0, 0],
            "buildSettings": [0, dict, 0, 1, {}],
            "name": [0, str, 0, 1],
        }
    )

    def HasBuildSetting(self, key):
        return key in self._properties["buildSettings"]

    def GetBuildSetting(self, key):
        return self._properties["buildSettings"][key]

    def SetBuildSetting(self, key, value):
        # TODO(mark): If a list, copy?
        self._properties["buildSettings"][key] = value

    def AppendBuildSetting(self, key, value):
        if key not in self._properties["buildSettings"]:
            self._properties["buildSettings"][key] = []
        self._properties["buildSettings"][key].append(value)

    def DelBuildSetting(self, key):
        if key in self._properties["buildSettings"]:
            del self._properties["buildSettings"][key]

    def SetBaseConfiguration(self, value):
        self._properties["baseConfigurationReference"] = value


class XCConfigurationList(XCObject):
    # _configs is the default list of configurations.
    _configs = [
        XCBuildConfiguration({"name": "Debug"}),
        XCBuildConfiguration({"name": "Release"}),
    ]

    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "buildConfigurations": [1, XCBuildConfiguration, 1, 1, _configs],
            "defaultConfigurationIsVisible": [0, int, 0, 1, 1],
            "defaultConfigurationName": [0, str, 0, 1, "Release"],
        }
    )

    def Name(self):
        return (
            "Build configuration list for "
            + self.parent.__class__.__name__
            + ' "'
            + self.parent.Name()
            + '"'
        )

    def ConfigurationNamed(self, name):
        """Convenience accessor to obtain an XCBuildConfiguration by name."""
        for configuration in self._properties["buildConfigurations"]:
            if configuration._properties["name"] == name:
                return configuration

        raise KeyError(name)

    def DefaultConfiguration(self):
        """Convenience accessor to obtain the default XCBuildConfiguration."""
        return self.ConfigurationNamed(self._properties["defaultConfigurationName"])

    def HasBuildSetting(self, key):
        """Determines the state of a build setting in all XCBuildConfiguration
    child objects.

    If all child objects have key in their build settings, and the value is the
    same in all child objects, returns 1.

    If no child objects have the key in their build settings, returns 0.

    If some, but not all, child objects have the key in their build settings,
    or if any children have different values for the key, returns -1.
    """

        has = None
        value = None
        for configuration in self._properties["buildConfigurations"]:
            configuration_has = configuration.HasBuildSetting(key)
            if has is None:
                has = configuration_has
            elif has != configuration_has:
                return -1

            if configuration_has:
                configuration_value = configuration.GetBuildSetting(key)
                if value is None:
                    value = configuration_value
                elif value != configuration_value:
                    return -1

        if not has:
            return 0

        return 1

    def GetBuildSetting(self, key):
        """Gets the build setting for key.

    All child XCConfiguration objects must have the same value set for the
    setting, or a ValueError will be raised.
    """

        # TODO(mark): This is wrong for build settings that are lists.  The list
        # contents should be compared (and a list copy returned?)

        value = None
        for configuration in self._properties["buildConfigurations"]:
            configuration_value = configuration.GetBuildSetting(key)
            if value is None:
                value = configuration_value
            else:
                if value != configuration_value:
                    raise ValueError("Variant values for " + key)

        return value

    def SetBuildSetting(self, key, value):
        """Sets the build setting for key to value in all child
    XCBuildConfiguration objects.
    """

        for configuration in self._properties["buildConfigurations"]:
            configuration.SetBuildSetting(key, value)

    def AppendBuildSetting(self, key, value):
        """Appends value to the build setting for key, which is treated as a list,
    in all child XCBuildConfiguration objects.
    """

        for configuration in self._properties["buildConfigurations"]:
            configuration.AppendBuildSetting(key, value)

    def DelBuildSetting(self, key):
        """Deletes the build setting key from all child XCBuildConfiguration
    objects.
    """

        for configuration in self._properties["buildConfigurations"]:
            configuration.DelBuildSetting(key)

    def SetBaseConfiguration(self, value):
        """Sets the build configuration in all child XCBuildConfiguration objects.
    """

        for configuration in self._properties["buildConfigurations"]:
            configuration.SetBaseConfiguration(value)


class PBXBuildFile(XCObject):
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "fileRef": [0, XCFileLikeElement, 0, 1],
            "settings": [0, str, 0, 0],  # hack, it's a dict
        }
    )

    # Weird output rules for PBXBuildFile.
    _should_print_single_line = True
    _encode_transforms = XCObject._alternate_encode_transforms

    def Name(self):
        # Example: "main.cc in Sources"
        return self._properties["fileRef"].Name() + " in " + self.parent.Name()

    def Hashables(self):
        # super
        hashables = XCObject.Hashables(self)

        # It is not sufficient to just rely on Name() to get the
        # XCFileLikeElement's name, because that is not a complete pathname.
        # PathHashables returns hashables unique enough that no two
        # PBXBuildFiles should wind up with the same set of hashables, unless
        # someone adds the same file multiple times to the same target.  That
        # would be considered invalid anyway.
        hashables.extend(self._properties["fileRef"].PathHashables())

        return hashables


class XCBuildPhase(XCObject):
    """Abstract base for build phase classes.  Not represented in a project
  file.

  Attributes:
    _files_by_path: A dict mapping each path of a child in the files list by
      path (keys) to the corresponding PBXBuildFile children (values).
    _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys)
      to the corresponding PBXBuildFile children (values).
  """

    # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't
    # actually have a "files" list.  XCBuildPhase should not have "files" but
    # another abstract subclass of it should provide this, and concrete build
    # phase types that do have "files" lists should be derived from that new
    # abstract subclass.  XCBuildPhase should only provide buildActionMask and
    # runOnlyForDeploymentPostprocessing, and not files or the various
    # file-related methods and attributes.

    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "buildActionMask": [0, int, 0, 1, 0x7FFFFFFF],
            "files": [1, PBXBuildFile, 1, 1, []],
            "runOnlyForDeploymentPostprocessing": [0, int, 0, 1, 0],
        }
    )

    def __init__(self, properties=None, id=None, parent=None):
        # super
        XCObject.__init__(self, properties, id, parent)

        self._files_by_path = {}
        self._files_by_xcfilelikeelement = {}
        for pbxbuildfile in self._properties.get("files", []):
            self._AddBuildFileToDicts(pbxbuildfile)

    def FileGroup(self, path):
        # Subclasses must override this by returning a two-element tuple.  The
        # first item in the tuple should be the PBXGroup to which "path" should be
        # added, either as a child or deeper descendant.  The second item should
        # be a boolean indicating whether files should be added into hierarchical
        # groups or one single flat group.
        raise NotImplementedError(self.__class__.__name__ + " must implement FileGroup")

    def _AddPathToDict(self, pbxbuildfile, path):
        """Adds path to the dict tracking paths belonging to this build phase.

    If the path is already a member of this build phase, raises an exception.
    """

        if path in self._files_by_path:
            raise ValueError("Found multiple build files with path " + path)
        self._files_by_path[path] = pbxbuildfile

    def _AddBuildFileToDicts(self, pbxbuildfile, path=None):
        """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.

    If path is specified, then it is the path that is being added to the
    phase, and pbxbuildfile must contain either a PBXFileReference directly
    referencing that path, or it must contain a PBXVariantGroup that itself
    contains a PBXFileReference referencing the path.

    If path is not specified, either the PBXFileReference's path or the paths
    of all children of the PBXVariantGroup are taken as being added to the
    phase.

    If the path is already present in the phase, raises an exception.

    If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile
    are already present in the phase, referenced by a different PBXBuildFile
    object, raises an exception.  This does not raise an exception when
    a PBXFileReference or PBXVariantGroup reappear and are referenced by the
    same PBXBuildFile that has already introduced them, because in the case
    of PBXVariantGroup objects, they may correspond to multiple paths that are
    not all added simultaneously.  When this situation occurs, the path needs
    to be added to _files_by_path, but nothing needs to change in
    _files_by_xcfilelikeelement, and the caller should have avoided adding
    the PBXBuildFile if it is already present in the list of children.
    """

        xcfilelikeelement = pbxbuildfile._properties["fileRef"]

        paths = []
        if path is not None:
            # It's best when the caller provides the path.
            if isinstance(xcfilelikeelement, PBXVariantGroup):
                paths.append(path)
        else:
            # If the caller didn't provide a path, there can be either multiple
            # paths (PBXVariantGroup) or one.
            if isinstance(xcfilelikeelement, PBXVariantGroup):
                for variant in xcfilelikeelement._properties["children"]:
                    paths.append(variant.FullPath())
            else:
                paths.append(xcfilelikeelement.FullPath())

        # Add the paths first, because if something's going to raise, the
        # messages provided by _AddPathToDict are more useful owing to its
        # having access to a real pathname and not just an object's Name().
        for a_path in paths:
            self._AddPathToDict(pbxbuildfile, a_path)

        # If another PBXBuildFile references this XCFileLikeElement, there's a
        # problem.
        if (
            xcfilelikeelement in self._files_by_xcfilelikeelement
            and self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile
        ):
            raise ValueError(
                "Found multiple build files for " + xcfilelikeelement.Name()
            )
        self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile

    def AppendBuildFile(self, pbxbuildfile, path=None):
        # Callers should use this instead of calling
        # AppendProperty('files', pbxbuildfile) directly because this function
        # maintains the object's dicts.  Better yet, callers can just call AddFile
        # with a pathname and not worry about building their own PBXBuildFile
        # objects.
        self.AppendProperty("files", pbxbuildfile)
        self._AddBuildFileToDicts(pbxbuildfile, path)

    def AddFile(self, path, settings=None):
        (file_group, hierarchical) = self.FileGroup(path)
        file_ref = file_group.AddOrGetFileByPath(path, hierarchical)

        if file_ref in self._files_by_xcfilelikeelement and isinstance(
            file_ref, PBXVariantGroup
        ):
            # There's already a PBXBuildFile in this phase corresponding to the
            # PBXVariantGroup.  path just provides a new variant that belongs to
            # the group.  Add the path to the dict.
            pbxbuildfile = self._files_by_xcfilelikeelement[file_ref]
            self._AddBuildFileToDicts(pbxbuildfile, path)
        else:
            # Add a new PBXBuildFile to get file_ref into the phase.
            if settings is None:
                pbxbuildfile = PBXBuildFile({"fileRef": file_ref})
            else:
                pbxbuildfile = PBXBuildFile({"fileRef": file_ref, "settings": settings})
            self.AppendBuildFile(pbxbuildfile, path)


class PBXHeadersBuildPhase(XCBuildPhase):
    # No additions to the schema relative to XCBuildPhase.

    def Name(self):
        return "Headers"

    def FileGroup(self, path):
        return self.PBXProjectAncestor().RootGroupForPath(path)


class PBXResourcesBuildPhase(XCBuildPhase):
    # No additions to the schema relative to XCBuildPhase.

    def Name(self):
        return "Resources"

    def FileGroup(self, path):
        return self.PBXProjectAncestor().RootGroupForPath(path)


class PBXSourcesBuildPhase(XCBuildPhase):
    # No additions to the schema relative to XCBuildPhase.

    def Name(self):
        return "Sources"

    def FileGroup(self, path):
        return self.PBXProjectAncestor().RootGroupForPath(path)


class PBXFrameworksBuildPhase(XCBuildPhase):
    # No additions to the schema relative to XCBuildPhase.

    def Name(self):
        return "Frameworks"

    def FileGroup(self, path):
        (root, ext) = posixpath.splitext(path)
        if ext != "":
            ext = ext[1:].lower()
        if ext == "o":
            # .o files are added to Xcode Frameworks phases, but conceptually aren't
            # frameworks, they're more like sources or intermediates. Redirect them
            # to show up in one of those other groups.
            return self.PBXProjectAncestor().RootGroupForPath(path)
        else:
            return (self.PBXProjectAncestor().FrameworksGroup(), False)


class PBXShellScriptBuildPhase(XCBuildPhase):
    _schema = XCBuildPhase._schema.copy()
    _schema.update(
        {
            "inputPaths": [1, str, 0, 1, []],
            "name": [0, str, 0, 0],
            "outputPaths": [1, str, 0, 1, []],
            "shellPath": [0, str, 0, 1, "/bin/sh"],
            "shellScript": [0, str, 0, 1],
            "showEnvVarsInLog": [0, int, 0, 0],
        }
    )

    def Name(self):
        if "name" in self._properties:
            return self._properties["name"]

        return "ShellScript"


class PBXCopyFilesBuildPhase(XCBuildPhase):
    _schema = XCBuildPhase._schema.copy()
    _schema.update(
        {
            "dstPath": [0, str, 0, 1],
            "dstSubfolderSpec": [0, int, 0, 1],
            "name": [0, str, 0, 0],
        }
    )

    # path_tree_re matches "$(DIR)/path", "$(DIR)/$(DIR2)/path" or just "$(DIR)".
    # Match group 1 is "DIR", group 3 is "path" or "$(DIR2") or "$(DIR2)/path"
    # or None. If group 3 is "path", group 4 will be None otherwise group 4 is
    # "DIR2" and group 6 is "path".
    path_tree_re = re.compile(r"^\$\((.*?)\)(/(\$\((.*?)\)(/(.*)|)|(.*)|)|)$")

    # path_tree_{first,second}_to_subfolder map names of Xcode variables to the
    # associated dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase
    # object.
    path_tree_first_to_subfolder = {
        # Types that can be chosen via the Xcode UI.
        "BUILT_PRODUCTS_DIR": 16,  # Products Directory
        "BUILT_FRAMEWORKS_DIR": 10,  # Not an official Xcode macro.
        # Existed before support for the
        # names below was added. Maps to
        # "Frameworks".
    }

    path_tree_second_to_subfolder = {
        "WRAPPER_NAME": 1,  # Wrapper
        # Although Xcode's friendly name is "Executables", the destination
        # is demonstrably the value of the build setting
        # EXECUTABLE_FOLDER_PATH not EXECUTABLES_FOLDER_PATH.
        "EXECUTABLE_FOLDER_PATH": 6,  # Executables.
        "UNLOCALIZED_RESOURCES_FOLDER_PATH": 7,  # Resources
        "JAVA_FOLDER_PATH": 15,  # Java Resources
        "FRAMEWORKS_FOLDER_PATH": 10,  # Frameworks
        "SHARED_FRAMEWORKS_FOLDER_PATH": 11,  # Shared Frameworks
        "SHARED_SUPPORT_FOLDER_PATH": 12,  # Shared Support
        "PLUGINS_FOLDER_PATH": 13,  # PlugIns
        # For XPC Services, Xcode sets both dstPath and dstSubfolderSpec.
        # Note that it re-uses the BUILT_PRODUCTS_DIR value for
        # dstSubfolderSpec. dstPath is set below.
        "XPCSERVICES_FOLDER_PATH": 16,  # XPC Services.
    }

    def Name(self):
        if "name" in self._properties:
            return self._properties["name"]

        return "CopyFiles"

    def FileGroup(self, path):
        return self.PBXProjectAncestor().RootGroupForPath(path)

    def SetDestination(self, path):
        """Set the dstSubfolderSpec and dstPath properties from path.

    path may be specified in the same notation used for XCHierarchicalElements,
    specifically, "$(DIR)/path".
    """

        path_tree_match = self.path_tree_re.search(path)
        if path_tree_match:
            path_tree = path_tree_match.group(1)
            if path_tree in self.path_tree_first_to_subfolder:
                subfolder = self.path_tree_first_to_subfolder[path_tree]
                relative_path = path_tree_match.group(3)
                if relative_path is None:
                    relative_path = ""

                if subfolder == 16 and path_tree_match.group(4) is not None:
                    # BUILT_PRODUCTS_DIR (16) is the first element in a path whose
                    # second element is possibly one of the variable names in
                    # path_tree_second_to_subfolder. Xcode sets the values of all these
                    # variables to relative paths so .gyp files must prefix them with
                    # BUILT_PRODUCTS_DIR, e.g.
                    # $(BUILT_PRODUCTS_DIR)/$(PLUGINS_FOLDER_PATH). Then
                    # xcode_emulation.py can export these variables with the same values
                    # as Xcode yet make & ninja files can determine the absolute path
                    # to the target. Xcode uses the dstSubfolderSpec value set here
                    # to determine the full path.
                    #
                    # An alternative of xcode_emulation.py setting the values to
                    # absolute paths when exporting these variables has been
                    # ruled out because then the values would be different
                    # depending on the build tool.
                    #
                    # Another alternative is to invent new names for the variables used
                    # to match to the subfolder indices in the second table. .gyp files
                    # then will not need to prepend $(BUILT_PRODUCTS_DIR) because
                    # xcode_emulation.py can set the values of those variables to
                    # the absolute paths when exporting. This is possibly the thinking
                    # behind BUILT_FRAMEWORKS_DIR which is used in exactly this manner.
                    #
                    # Requiring prepending BUILT_PRODUCTS_DIR has been chosen because
                    # this same way could be used to specify destinations in .gyp files
                    # that pre-date this addition to GYP. However they would only work
                    # with the Xcode generator.
                    # The previous version of xcode_emulation.py
                    # does not export these variables. Such files will get the benefit
                    # of the Xcode UI showing the proper destination name simply by
                    # regenerating the projects with this version of GYP.
                    path_tree = path_tree_match.group(4)
                    relative_path = path_tree_match.group(6)
                    separator = "/"

                    if path_tree in self.path_tree_second_to_subfolder:
                        subfolder = self.path_tree_second_to_subfolder[path_tree]
                        if relative_path is None:
                            relative_path = ""
                            separator = ""
                        if path_tree == "XPCSERVICES_FOLDER_PATH":
                            relative_path = (
                                "$(CONTENTS_FOLDER_PATH)/XPCServices"
                                + separator
                                + relative_path
                            )
                    else:
                        # subfolder = 16 from above
                        # The second element of the path is an unrecognized variable.
                        # Include it and any remaining elements in relative_path.
                        relative_path = path_tree_match.group(3)

            else:
                # The path starts with an unrecognized Xcode variable
                # name like $(SRCROOT).  Xcode will still handle this
                # as an "absolute path" that starts with the variable.
                subfolder = 0
                relative_path = path
        elif path.startswith("/"):
            # Special case.  Absolute paths are in dstSubfolderSpec 0.
            subfolder = 0
            relative_path = path[1:]
        else:
            raise ValueError(
                f"Can't use path {path} in a {self.__class__.__name__}"
            )

        self._properties["dstPath"] = relative_path
        self._properties["dstSubfolderSpec"] = subfolder


class PBXBuildRule(XCObject):
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "compilerSpec": [0, str, 0, 1],
            "filePatterns": [0, str, 0, 0],
            "fileType": [0, str, 0, 1],
            "isEditable": [0, int, 0, 1, 1],
            "outputFiles": [1, str, 0, 1, []],
            "script": [0, str, 0, 0],
        }
    )

    def Name(self):
        # Not very inspired, but it's what Xcode uses.
        return self.__class__.__name__

    def Hashables(self):
        # super
        hashables = XCObject.Hashables(self)

        # Use the hashables of the weak objects that this object refers to.
        hashables.append(self._properties["fileType"])
        if "filePatterns" in self._properties:
            hashables.append(self._properties["filePatterns"])
        return hashables


class PBXContainerItemProxy(XCObject):
    # When referencing an item in this project file, containerPortal is the
    # PBXProject root object of this project file.  When referencing an item in
    # another project file, containerPortal is a PBXFileReference identifying
    # the other project file.
    #
    # When serving as a proxy to an XCTarget (in this project file or another),
    # proxyType is 1.  When serving as a proxy to a PBXFileReference (in another
    # project file), proxyType is 2.  Type 2 is used for references to the
    # producs of the other project file's targets.
    #
    # Xcode is weird about remoteGlobalIDString.  Usually, it's printed without
    # a comment, indicating that it's tracked internally simply as a string, but
    # sometimes it's printed with a comment (usually when the object is initially
    # created), indicating that it's tracked as a project file object at least
    # sometimes.  This module always tracks it as an object, but contains a hack
    # to prevent it from printing the comment in the project file output.  See
    # _XCKVPrint.
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "containerPortal": [0, XCContainerPortal, 0, 1],
            "proxyType": [0, int, 0, 1],
            "remoteGlobalIDString": [0, XCRemoteObject, 0, 1],
            "remoteInfo": [0, str, 0, 1],
        }
    )

    def __repr__(self):
        props = self._properties
        name = "{}.gyp:{}".format(props["containerPortal"].Name(), props["remoteInfo"])
        return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"

    def Name(self):
        # Admittedly not the best name, but it's what Xcode uses.
        return self.__class__.__name__

    def Hashables(self):
        # super
        hashables = XCObject.Hashables(self)

        # Use the hashables of the weak objects that this object refers to.
        hashables.extend(self._properties["containerPortal"].Hashables())
        hashables.extend(self._properties["remoteGlobalIDString"].Hashables())
        return hashables


class PBXTargetDependency(XCObject):
    # The "target" property accepts an XCTarget object, and obviously not
    # NoneType.  But XCTarget is defined below, so it can't be put into the
    # schema yet.  The definition of PBXTargetDependency can't be moved below
    # XCTarget because XCTarget's own schema references PBXTargetDependency.
    # Python doesn't deal well with this circular relationship, and doesn't have
    # a real way to do forward declarations.  To work around, the type of
    # the "target" property is reset below, after XCTarget is defined.
    #
    # At least one of "name" and "target" is required.
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "name": [0, str, 0, 0],
            "target": [0, None.__class__, 0, 0],
            "targetProxy": [0, PBXContainerItemProxy, 1, 1],
        }
    )

    def __repr__(self):
        name = self._properties.get("name") or self._properties["target"].Name()
        return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>"

    def Name(self):
        # Admittedly not the best name, but it's what Xcode uses.
        return self.__class__.__name__

    def Hashables(self):
        # super
        hashables = XCObject.Hashables(self)

        # Use the hashables of the weak objects that this object refers to.
        hashables.extend(self._properties["targetProxy"].Hashables())
        return hashables


class PBXReferenceProxy(XCFileLikeElement):
    _schema = XCFileLikeElement._schema.copy()
    _schema.update(
        {
            "fileType": [0, str, 0, 1],
            "path": [0, str, 0, 1],
            "remoteRef": [0, PBXContainerItemProxy, 1, 1],
        }
    )


class XCTarget(XCRemoteObject):
    # An XCTarget is really just an XCObject, the XCRemoteObject thing is just
    # to allow PBXProject to be used in the remoteGlobalIDString property of
    # PBXContainerItemProxy.
    #
    # Setting a "name" property at instantiation may also affect "productName",
    # which may in turn affect the "PRODUCT_NAME" build setting in children of
    # "buildConfigurationList".  See __init__ below.
    _schema = XCRemoteObject._schema.copy()
    _schema.update(
        {
            "buildConfigurationList": [
                0,
                XCConfigurationList,
                1,
                1,
                XCConfigurationList(),
            ],
            "buildPhases": [1, XCBuildPhase, 1, 1, []],
            "dependencies": [1, PBXTargetDependency, 1, 1, []],
            "name": [0, str, 0, 1],
            "productName": [0, str, 0, 1],
        }
    )

    def __init__(
        self,
        properties=None,
        id=None,
        parent=None,
        force_outdir=None,
        force_prefix=None,
        force_extension=None,
    ):
        # super
        XCRemoteObject.__init__(self, properties, id, parent)

        # Set up additional defaults not expressed in the schema.  If a "name"
        # property was supplied, set "productName" if it is not present.  Also set
        # the "PRODUCT_NAME" build setting in each configuration, but only if
        # the setting is not present in any build configuration.
        if "name" in self._properties and "productName" not in self._properties:
            self.SetProperty("productName", self._properties["name"])

        if "productName" in self._properties:
            if "buildConfigurationList" in self._properties:
                configs = self._properties["buildConfigurationList"]
                if configs.HasBuildSetting("PRODUCT_NAME") == 0:
                    configs.SetBuildSetting(
                        "PRODUCT_NAME", self._properties["productName"]
                    )

    def AddDependency(self, other):
        pbxproject = self.PBXProjectAncestor()
        other_pbxproject = other.PBXProjectAncestor()
        if pbxproject == other_pbxproject:
            # Add a dependency to another target in the same project file.
            container = PBXContainerItemProxy(
                {
                    "containerPortal": pbxproject,
                    "proxyType": 1,
                    "remoteGlobalIDString": other,
                    "remoteInfo": other.Name(),
                }
            )
            dependency = PBXTargetDependency(
                {"target": other, "targetProxy": container}
            )
            self.AppendProperty("dependencies", dependency)
        else:
            # Add a dependency to a target in a different project file.
            other_project_ref = pbxproject.AddOrGetProjectReference(other_pbxproject)[1]
            container = PBXContainerItemProxy(
                {
                    "containerPortal": other_project_ref,
                    "proxyType": 1,
                    "remoteGlobalIDString": other,
                    "remoteInfo": other.Name(),
                }
            )
            dependency = PBXTargetDependency(
                {"name": other.Name(), "targetProxy": container}
            )
            self.AppendProperty("dependencies", dependency)

    # Proxy all of these through to the build configuration list.

    def ConfigurationNamed(self, name):
        return self._properties["buildConfigurationList"].ConfigurationNamed(name)

    def DefaultConfiguration(self):
        return self._properties["buildConfigurationList"].DefaultConfiguration()

    def HasBuildSetting(self, key):
        return self._properties["buildConfigurationList"].HasBuildSetting(key)

    def GetBuildSetting(self, key):
        return self._properties["buildConfigurationList"].GetBuildSetting(key)

    def SetBuildSetting(self, key, value):
        return self._properties["buildConfigurationList"].SetBuildSetting(key, value)

    def AppendBuildSetting(self, key, value):
        return self._properties["buildConfigurationList"].AppendBuildSetting(key, value)

    def DelBuildSetting(self, key):
        return self._properties["buildConfigurationList"].DelBuildSetting(key)


# Redefine the type of the "target" property.  See PBXTargetDependency._schema
# above.
PBXTargetDependency._schema["target"][1] = XCTarget


class PBXNativeTarget(XCTarget):
    # buildPhases is overridden in the schema to be able to set defaults.
    #
    # NOTE: Contrary to most objects, it is advisable to set parent when
    # constructing PBXNativeTarget.  A parent of an XCTarget must be a PBXProject
    # object.  A parent reference is required for a PBXNativeTarget during
    # construction to be able to set up the target defaults for productReference,
    # because a PBXBuildFile object must be created for the target and it must
    # be added to the PBXProject's mainGroup hierarchy.
    _schema = XCTarget._schema.copy()
    _schema.update(
        {
            "buildPhases": [
                1,
                XCBuildPhase,
                1,
                1,
                [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()],
            ],
            "buildRules": [1, PBXBuildRule, 1, 1, []],
            "productReference": [0, PBXFileReference, 0, 1],
            "productType": [0, str, 0, 1],
        }
    )

    # Mapping from Xcode product-types to settings.  The settings are:
    #  filetype : used for explicitFileType in the project file
    #  prefix : the prefix for the file name
    #  suffix : the suffix for the file name
    _product_filetypes = {
        "com.apple.product-type.application": ["wrapper.application", "", ".app"],
        "com.apple.product-type.application.watchapp": [
            "wrapper.application",
            "",
            ".app",
        ],
        "com.apple.product-type.watchkit-extension": [
            "wrapper.app-extension",
            "",
            ".appex",
        ],
        "com.apple.product-type.app-extension": ["wrapper.app-extension", "", ".appex"],
        "com.apple.product-type.bundle": ["wrapper.cfbundle", "", ".bundle"],
        "com.apple.product-type.framework": ["wrapper.framework", "", ".framework"],
        "com.apple.product-type.library.dynamic": [
            "compiled.mach-o.dylib",
            "lib",
            ".dylib",
        ],
        "com.apple.product-type.library.static": ["archive.ar", "lib", ".a"],
        "com.apple.product-type.tool": ["compiled.mach-o.executable", "", ""],
        "com.apple.product-type.bundle.unit-test": ["wrapper.cfbundle", "", ".xctest"],
        "com.apple.product-type.bundle.ui-testing": ["wrapper.cfbundle", "", ".xctest"],
        "com.googlecode.gyp.xcode.bundle": ["compiled.mach-o.dylib", "", ".so"],
        "com.apple.product-type.kernel-extension": ["wrapper.kext", "", ".kext"],
    }

    def __init__(
        self,
        properties=None,
        id=None,
        parent=None,
        force_outdir=None,
        force_prefix=None,
        force_extension=None,
    ):
        # super
        XCTarget.__init__(self, properties, id, parent)

        if (
            "productName" in self._properties
            and "productType" in self._properties
            and "productReference" not in self._properties
            and self._properties["productType"] in self._product_filetypes
        ):
            products_group = None
            pbxproject = self.PBXProjectAncestor()
            if pbxproject is not None:
                products_group = pbxproject.ProductsGroup()

            if products_group is not None:
                (filetype, prefix, suffix) = self._product_filetypes[
                    self._properties["productType"]
                ]
                # Xcode does not have a distinct type for loadable modules that are
                # pure BSD targets (not in a bundle wrapper). GYP allows such modules
                # to be specified by setting a target type to loadable_module without
                # having mac_bundle set. These are mapped to the pseudo-product type
                # com.googlecode.gyp.xcode.bundle.
                #
                # By picking up this special type and converting it to a dynamic
                # library (com.apple.product-type.library.dynamic) with fix-ups,
                # single-file loadable modules can be produced.
                #
                # MACH_O_TYPE is changed to mh_bundle to produce the proper file type
                # (as opposed to mh_dylib). In order for linking to succeed,
                # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be
                # cleared. They are meaningless for type mh_bundle.
                #
                # Finally, the .so extension is forcibly applied over the default
                # (.dylib), unless another forced extension is already selected.
                # .dylib is plainly wrong, and .bundle is used by loadable_modules in
                # bundle wrappers (com.apple.product-type.bundle). .so seems an odd
                # choice because it's used as the extension on many other systems that
                # don't distinguish between linkable shared libraries and non-linkable
                # loadable modules, but there's precedent: Python loadable modules on
                # Mac OS X use an .so extension.
                if self._properties["productType"] == "com.googlecode.gyp.xcode.bundle":
                    self._properties[
                        "productType"
                    ] = "com.apple.product-type.library.dynamic"
                    self.SetBuildSetting("MACH_O_TYPE", "mh_bundle")
                    self.SetBuildSetting("DYLIB_CURRENT_VERSION", "")
                    self.SetBuildSetting("DYLIB_COMPATIBILITY_VERSION", "")
                    if force_extension is None:
                        force_extension = suffix[1:]

                if (
                    self._properties["productType"] in {
                        "com.apple.product-type-bundle.unit.test",
                        "com.apple.product-type-bundle.ui-testing"
                    }
                ) and force_extension is None:
                    force_extension = suffix[1:]

                if force_extension is not None:
                    # If it's a wrapper (bundle), set WRAPPER_EXTENSION.
                    # Extension override.
                    suffix = "." + force_extension
                    if filetype.startswith("wrapper."):
                        self.SetBuildSetting("WRAPPER_EXTENSION", force_extension)
                    else:
                        self.SetBuildSetting("EXECUTABLE_EXTENSION", force_extension)

                    if filetype.startswith("compiled.mach-o.executable"):
                        product_name = self._properties["productName"]
                        product_name += suffix
                        suffix = ""
                        self.SetProperty("productName", product_name)
                        self.SetBuildSetting("PRODUCT_NAME", product_name)

                # Xcode handles most prefixes based on the target type, however there
                # are exceptions.  If a "BSD Dynamic Library" target is added in the
                # Xcode UI, Xcode sets EXECUTABLE_PREFIX.  This check duplicates that
                # behavior.
                if force_prefix is not None:
                    prefix = force_prefix
                if filetype.startswith("wrapper."):
                    self.SetBuildSetting("WRAPPER_PREFIX", prefix)
                else:
                    self.SetBuildSetting("EXECUTABLE_PREFIX", prefix)

                if force_outdir is not None:
                    self.SetBuildSetting("TARGET_BUILD_DIR", force_outdir)

                # TODO(tvl): Remove the below hack.
                #    http://code.google.com/p/gyp/issues/detail?id=122

                # Some targets include the prefix in the target_name.  These targets
                # really should just add a product_name setting that doesn't include
                # the prefix.  For example:
                #  target_name = 'libevent', product_name = 'event'
                # This check cleans up for them.
                product_name = self._properties["productName"]
                prefix_len = len(prefix)
                if prefix_len and (product_name[:prefix_len] == prefix):
                    product_name = product_name[prefix_len:]
                    self.SetProperty("productName", product_name)
                    self.SetBuildSetting("PRODUCT_NAME", product_name)

                ref_props = {
                    "explicitFileType": filetype,
                    "includeInIndex": 0,
                    "path": prefix + product_name + suffix,
                    "sourceTree": "BUILT_PRODUCTS_DIR",
                }
                file_ref = PBXFileReference(ref_props)
                products_group.AppendChild(file_ref)
                self.SetProperty("productReference", file_ref)

    def GetBuildPhaseByType(self, type):
        if "buildPhases" not in self._properties:
            return None

        the_phase = None
        for phase in self._properties["buildPhases"]:
            if isinstance(phase, type):
                # Some phases may be present in multiples in a well-formed project file,
                # but phases like PBXSourcesBuildPhase may only be present singly, and
                # this function is intended as an aid to GetBuildPhaseByType.  Loop
                # over the entire list of phases and assert if more than one of the
                # desired type is found.
                assert the_phase is None
                the_phase = phase

        return the_phase

    def HeadersPhase(self):
        headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase)
        if headers_phase is None:
            headers_phase = PBXHeadersBuildPhase()

            # The headers phase should come before the resources, sources, and
            # frameworks phases, if any.
            insert_at = len(self._properties["buildPhases"])
            for index, phase in enumerate(self._properties["buildPhases"]):
                if isinstance(
                    phase,
                    (
                        PBXResourcesBuildPhase,
                        PBXSourcesBuildPhase,
                        PBXFrameworksBuildPhase,
                    ),
                ):
                    insert_at = index
                    break

            self._properties["buildPhases"].insert(insert_at, headers_phase)
            headers_phase.parent = self

        return headers_phase

    def ResourcesPhase(self):
        resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase)
        if resources_phase is None:
            resources_phase = PBXResourcesBuildPhase()

            # The resources phase should come before the sources and frameworks
            # phases, if any.
            insert_at = len(self._properties["buildPhases"])
            for index, phase in enumerate(self._properties["buildPhases"]):
                if isinstance(phase, (PBXSourcesBuildPhase, PBXFrameworksBuildPhase)):
                    insert_at = index
                    break

            self._properties["buildPhases"].insert(insert_at, resources_phase)
            resources_phase.parent = self

        return resources_phase

    def SourcesPhase(self):
        sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase)
        if sources_phase is None:
            sources_phase = PBXSourcesBuildPhase()
            self.AppendProperty("buildPhases", sources_phase)

        return sources_phase

    def FrameworksPhase(self):
        frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase)
        if frameworks_phase is None:
            frameworks_phase = PBXFrameworksBuildPhase()
            self.AppendProperty("buildPhases", frameworks_phase)

        return frameworks_phase

    def AddDependency(self, other):
        # super
        XCTarget.AddDependency(self, other)

        static_library_type = "com.apple.product-type.library.static"
        shared_library_type = "com.apple.product-type.library.dynamic"
        framework_type = "com.apple.product-type.framework"
        if (
            isinstance(other, PBXNativeTarget)
            and "productType" in self._properties
            and self._properties["productType"] != static_library_type
            and "productType" in other._properties
            and (
                other._properties["productType"] == static_library_type
                or (
                    (
                        other._properties["productType"] in {
                            shared_library_type,
                            framework_type
                        }
                    )
                    and (
                        (not other.HasBuildSetting("MACH_O_TYPE"))
                        or other.GetBuildSetting("MACH_O_TYPE") != "mh_bundle"
                    )
                )
            )
        ):

            file_ref = other.GetProperty("productReference")

            pbxproject = self.PBXProjectAncestor()
            other_pbxproject = other.PBXProjectAncestor()
            if pbxproject != other_pbxproject:
                other_project_product_group = pbxproject.AddOrGetProjectReference(
                    other_pbxproject
                )[0]
                file_ref = other_project_product_group.GetChildByRemoteObject(file_ref)

            self.FrameworksPhase().AppendProperty(
                "files", PBXBuildFile({"fileRef": file_ref})
            )


class PBXAggregateTarget(XCTarget):
    pass


class PBXProject(XCContainerPortal):
    # A PBXProject is really just an XCObject, the XCContainerPortal thing is
    # just to allow PBXProject to be used in the containerPortal property of
    # PBXContainerItemProxy.
    """

  Attributes:
    path: "sample.xcodeproj".  TODO(mark) Document me!
    _other_pbxprojects: A dictionary, keyed by other PBXProject objects.  Each
                        value is a reference to the dict in the
                        projectReferences list associated with the keyed
                        PBXProject.
  """

    _schema = XCContainerPortal._schema.copy()
    _schema.update(
        {
            "attributes": [0, dict, 0, 0],
            "buildConfigurationList": [
                0,
                XCConfigurationList,
                1,
                1,
                XCConfigurationList(),
            ],
            "compatibilityVersion": [0, str, 0, 1, "Xcode 3.2"],
            "hasScannedForEncodings": [0, int, 0, 1, 1],
            "mainGroup": [0, PBXGroup, 1, 1, PBXGroup()],
            "projectDirPath": [0, str, 0, 1, ""],
            "projectReferences": [1, dict, 0, 0],
            "projectRoot": [0, str, 0, 1, ""],
            "targets": [1, XCTarget, 1, 1, []],
        }
    )

    def __init__(self, properties=None, id=None, parent=None, path=None):
        self.path = path
        self._other_pbxprojects = {}
        # super
        XCContainerPortal.__init__(self, properties, id, parent)

    def Name(self):
        name = self.path
        if name[-10:] == ".xcodeproj":
            name = name[:-10]
        return posixpath.basename(name)

    def Path(self):
        return self.path

    def Comment(self):
        return "Project object"

    def Children(self):
        # super
        children = XCContainerPortal.Children(self)

        # Add children that the schema doesn't know about.  Maybe there's a more
        # elegant way around this, but this is the only case where we need to own
        # objects in a dictionary (that is itself in a list), and three lines for
        # a one-off isn't that big a deal.
        if "projectReferences" in self._properties:
            for reference in self._properties["projectReferences"]:
                children.append(reference["ProductGroup"])

        return children

    def PBXProjectAncestor(self):
        return self

    def _GroupByName(self, name):
        if "mainGroup" not in self._properties:
            self.SetProperty("mainGroup", PBXGroup())

        main_group = self._properties["mainGroup"]
        group = main_group.GetChildByName(name)
        if group is None:
            group = PBXGroup({"name": name})
            main_group.AppendChild(group)

        return group

    # SourceGroup and ProductsGroup are created by default in Xcode's own
    # templates.
    def SourceGroup(self):
        return self._GroupByName("Source")

    def ProductsGroup(self):
        return self._GroupByName("Products")

    # IntermediatesGroup is used to collect source-like files that are generated
    # by rules or script phases and are placed in intermediate directories such
    # as DerivedSources.
    def IntermediatesGroup(self):
        return self._GroupByName("Intermediates")

    # FrameworksGroup and ProjectsGroup are top-level groups used to collect
    # frameworks and projects.
    def FrameworksGroup(self):
        return self._GroupByName("Frameworks")

    def ProjectsGroup(self):
        return self._GroupByName("Projects")

    def RootGroupForPath(self, path):
        """Returns a PBXGroup child of this object to which path should be added.

    This method is intended to choose between SourceGroup and
    IntermediatesGroup on the basis of whether path is present in a source
    directory or an intermediates directory.  For the purposes of this
    determination, any path located within a derived file directory such as
    PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates
    directory.

    The returned value is a two-element tuple.  The first element is the
    PBXGroup, and the second element specifies whether that group should be
    organized hierarchically (True) or as a single flat list (False).
    """

        # TODO(mark): make this a class variable and bind to self on call?
        # Also, this list is nowhere near exhaustive.
        # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by
        # gyp.generator.xcode.  There should probably be some way for that module
        # to push the names in, rather than having to hard-code them here.
        source_tree_groups = {
            "DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
            "INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
            "PROJECT_DERIVED_FILE_DIR": (self.IntermediatesGroup, True),
            "SHARED_INTERMEDIATE_DIR": (self.IntermediatesGroup, True),
        }

        (source_tree, path) = SourceTreeAndPathFromPath(path)
        if source_tree is not None and source_tree in source_tree_groups:
            (group_func, hierarchical) = source_tree_groups[source_tree]
            group = group_func()
            return (group, hierarchical)

        # TODO(mark): make additional choices based on file extension.

        return (self.SourceGroup(), True)

    def AddOrGetFileInRootGroup(self, path):
        """Returns a PBXFileReference corresponding to path in the correct group
    according to RootGroupForPath's heuristics.

    If an existing PBXFileReference for path exists, it will be returned.
    Otherwise, one will be created and returned.
    """

        (group, hierarchical) = self.RootGroupForPath(path)
        return group.AddOrGetFileByPath(path, hierarchical)

    def RootGroupsTakeOverOnlyChildren(self, recurse=False):
        """Calls TakeOverOnlyChild for all groups in the main group."""

        for group in self._properties["mainGroup"]._properties["children"]:
            if isinstance(group, PBXGroup):
                group.TakeOverOnlyChild(recurse)

    def SortGroups(self):
        # Sort the children of the mainGroup (like "Source" and "Products")
        # according to their defined order.
        self._properties["mainGroup"]._properties["children"] = sorted(
            self._properties["mainGroup"]._properties["children"],
            key=cmp_to_key(lambda x, y: x.CompareRootGroup(y)),
        )

        # Sort everything else by putting group before files, and going
        # alphabetically by name within sections of groups and files.  SortGroup
        # is recursive.
        for group in self._properties["mainGroup"]._properties["children"]:
            if not isinstance(group, PBXGroup):
                continue

            if group.Name() == "Products":
                # The Products group is a special case.  Instead of sorting
                # alphabetically, sort things in the order of the targets that
                # produce the products.  To do this, just build up a new list of
                # products based on the targets.
                products = []
                for target in self._properties["targets"]:
                    if not isinstance(target, PBXNativeTarget):
                        continue
                    product = target._properties["productReference"]
                    # Make sure that the product is already in the products group.
                    assert product in group._properties["children"]
                    products.append(product)

                # Make sure that this process doesn't miss anything that was already
                # in the products group.
                assert len(products) == len(group._properties["children"])
                group._properties["children"] = products
            else:
                group.SortGroup()

    def AddOrGetProjectReference(self, other_pbxproject):
        """Add a reference to another project file (via PBXProject object) to this
    one.

    Returns [ProductGroup, ProjectRef].  ProductGroup is a PBXGroup object in
    this project file that contains a PBXReferenceProxy object for each
    product of each PBXNativeTarget in the other project file.  ProjectRef is
    a PBXFileReference to the other project file.

    If this project file already references the other project file, the
    existing ProductGroup and ProjectRef are returned.  The ProductGroup will
    still be updated if necessary.
    """

        if "projectReferences" not in self._properties:
            self._properties["projectReferences"] = []

        product_group = None
        project_ref = None

        if other_pbxproject not in self._other_pbxprojects:
            # This project file isn't yet linked to the other one.  Establish the
            # link.
            product_group = PBXGroup({"name": "Products"})

            # ProductGroup is strong.
            product_group.parent = self

            # There's nothing unique about this PBXGroup, and if left alone, it will
            # wind up with the same set of hashables as all other PBXGroup objects
            # owned by the projectReferences list.  Add the hashables of the
            # remote PBXProject that it's related to.
            product_group._hashables.extend(other_pbxproject.Hashables())

            # The other project reports its path as relative to the same directory
            # that this project's path is relative to.  The other project's path
            # is not necessarily already relative to this project.  Figure out the
            # pathname that this project needs to use to refer to the other one.
            this_path = posixpath.dirname(self.Path())
            projectDirPath = self.GetProperty("projectDirPath")
            if projectDirPath:
                if posixpath.isabs(projectDirPath[0]):
                    this_path = projectDirPath
                else:
                    this_path = posixpath.join(this_path, projectDirPath)
            other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path)

            # ProjectRef is weak (it's owned by the mainGroup hierarchy).
            project_ref = PBXFileReference(
                {
                    "lastKnownFileType": "wrapper.pb-project",
                    "path": other_path,
                    "sourceTree": "SOURCE_ROOT",
                }
            )
            self.ProjectsGroup().AppendChild(project_ref)

            ref_dict = {"ProductGroup": product_group, "ProjectRef": project_ref}
            self._other_pbxprojects[other_pbxproject] = ref_dict
            self.AppendProperty("projectReferences", ref_dict)

            # Xcode seems to sort this list case-insensitively
            self._properties["projectReferences"] = sorted(
                self._properties["projectReferences"],
                key=lambda x: x["ProjectRef"].Name().lower()
            )
        else:
            # The link already exists.  Pull out the relevnt data.
            project_ref_dict = self._other_pbxprojects[other_pbxproject]
            product_group = project_ref_dict["ProductGroup"]
            project_ref = project_ref_dict["ProjectRef"]

        self._SetUpProductReferences(other_pbxproject, product_group, project_ref)

        inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False)
        targets = other_pbxproject.GetProperty("targets")
        if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets):
            dir_path = project_ref._properties["path"]
            product_group._hashables.extend(dir_path)

        return [product_group, project_ref]

    def _AllSymrootsUnique(self, target, inherit_unique_symroot):
        # Returns True if all configurations have a unique 'SYMROOT' attribute.
        # The value of inherit_unique_symroot decides, if a configuration is assumed
        # to inherit a unique 'SYMROOT' attribute from its parent, if it doesn't
        # define an explicit value for 'SYMROOT'.
        symroots = self._DefinedSymroots(target)
        for s in self._DefinedSymroots(target):
            if (
                s is not None
                and not self._IsUniqueSymrootForTarget(s)
                or s is None
                and not inherit_unique_symroot
            ):
                return False
        return True if symroots else inherit_unique_symroot

    def _DefinedSymroots(self, target):
        # Returns all values for the 'SYMROOT' attribute defined in all
        # configurations for this target. If any configuration doesn't define the
        # 'SYMROOT' attribute, None is added to the returned set. If all
        # configurations don't define the 'SYMROOT' attribute, an empty set is
        # returned.
        config_list = target.GetProperty("buildConfigurationList")
        symroots = set()
        for config in config_list.GetProperty("buildConfigurations"):
            setting = config.GetProperty("buildSettings")
            if "SYMROOT" in setting:
                symroots.add(setting["SYMROOT"])
            else:
                symroots.add(None)
        if len(symroots) == 1 and None in symroots:
            return set()
        return symroots

    def _IsUniqueSymrootForTarget(self, symroot):
        # This method returns True if all configurations in target contain a
        # 'SYMROOT' attribute that is unique for the given target. A value is
        # unique, if the Xcode macro '$SRCROOT' appears in it in any form.
        uniquifier = ["$SRCROOT", "$(SRCROOT)"]
        if any(x in symroot for x in uniquifier):
            return True
        return False

    def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref):
        # TODO(mark): This only adds references to products in other_pbxproject
        # when they don't exist in this pbxproject.  Perhaps it should also
        # remove references from this pbxproject that are no longer present in
        # other_pbxproject.  Perhaps it should update various properties if they
        # change.
        for target in other_pbxproject._properties["targets"]:
            if not isinstance(target, PBXNativeTarget):
                continue

            other_fileref = target._properties["productReference"]
            if product_group.GetChildByRemoteObject(other_fileref) is None:
                # Xcode sets remoteInfo to the name of the target and not the name
                # of its product, despite this proxy being a reference to the product.
                container_item = PBXContainerItemProxy(
                    {
                        "containerPortal": project_ref,
                        "proxyType": 2,
                        "remoteGlobalIDString": other_fileref,
                        "remoteInfo": target.Name(),
                    }
                )
                # TODO(mark): Does sourceTree get copied straight over from the other
                # project?  Can the other project ever have lastKnownFileType here
                # instead of explicitFileType?  (Use it if so?)  Can path ever be
                # unset?  (I don't think so.)  Can other_fileref have name set, and
                # does it impact the PBXReferenceProxy if so?  These are the questions
                # that perhaps will be answered one day.
                reference_proxy = PBXReferenceProxy(
                    {
                        "fileType": other_fileref._properties["explicitFileType"],
                        "path": other_fileref._properties["path"],
                        "sourceTree": other_fileref._properties["sourceTree"],
                        "remoteRef": container_item,
                    }
                )

                product_group.AppendChild(reference_proxy)

    def SortRemoteProductReferences(self):
        # For each remote project file, sort the associated ProductGroup in the
        # same order that the targets are sorted in the remote project file.  This
        # is the sort order used by Xcode.

        def CompareProducts(x, y, remote_products):
            # x and y are PBXReferenceProxy objects.  Go through their associated
            # PBXContainerItem to get the remote PBXFileReference, which will be
            # present in the remote_products list.
            x_remote = x._properties["remoteRef"]._properties["remoteGlobalIDString"]
            y_remote = y._properties["remoteRef"]._properties["remoteGlobalIDString"]
            x_index = remote_products.index(x_remote)
            y_index = remote_products.index(y_remote)

            # Use the order of each remote PBXFileReference in remote_products to
            # determine the sort order.
            return cmp(x_index, y_index)

        for other_pbxproject, ref_dict in self._other_pbxprojects.items():
            # Build up a list of products in the remote project file, ordered the
            # same as the targets that produce them.
            remote_products = []
            for target in other_pbxproject._properties["targets"]:
                if not isinstance(target, PBXNativeTarget):
                    continue
                remote_products.append(target._properties["productReference"])

            # Sort the PBXReferenceProxy children according to the list of remote
            # products.
            product_group = ref_dict["ProductGroup"]
            product_group._properties["children"] = sorted(
                product_group._properties["children"],
                key=cmp_to_key(
                    lambda x, y, rp=remote_products: CompareProducts(x, y, rp)),
            )


class XCProjectFile(XCObject):
    _schema = XCObject._schema.copy()
    _schema.update(
        {
            "archiveVersion": [0, int, 0, 1, 1],
            "classes": [0, dict, 0, 1, {}],
            "objectVersion": [0, int, 0, 1, 46],
            "rootObject": [0, PBXProject, 1, 1],
        }
    )

    def ComputeIDs(self, recursive=True, overwrite=True, hash=None):
        # Although XCProjectFile is implemented here as an XCObject, it's not a
        # proper object in the Xcode sense, and it certainly doesn't have its own
        # ID.  Pass through an attempt to update IDs to the real root object.
        if recursive:
            self._properties["rootObject"].ComputeIDs(recursive, overwrite, hash)

    def Print(self, file=sys.stdout):
        self.VerifyHasRequiredProperties()

        # Add the special "objects" property, which will be caught and handled
        # separately during printing.  This structure allows a fairly standard
        # loop do the normal printing.
        self._properties["objects"] = {}
        self._XCPrint(file, 0, "// !$*UTF8*$!\n")
        if self._should_print_single_line:
            self._XCPrint(file, 0, "{ ")
        else:
            self._XCPrint(file, 0, "{\n")
        for property, value in sorted(
            self._properties.items()
        ):
            if property == "objects":
                self._PrintObjects(file)
            else:
                self._XCKVPrint(file, 1, property, value)
        self._XCPrint(file, 0, "}\n")
        del self._properties["objects"]

    def _PrintObjects(self, file):
        if self._should_print_single_line:
            self._XCPrint(file, 0, "objects = {")
        else:
            self._XCPrint(file, 1, "objects = {\n")

        objects_by_class = {}
        for object in self.Descendants():
            if object == self:
                continue
            class_name = object.__class__.__name__
            if class_name not in objects_by_class:
                objects_by_class[class_name] = []
            objects_by_class[class_name].append(object)

        for class_name in sorted(objects_by_class):
            self._XCPrint(file, 0, "\n")
            self._XCPrint(file, 0, "/* Begin " + class_name + " section */\n")
            for object in sorted(
                objects_by_class[class_name], key=attrgetter("id")
            ):
                object.Print(file)
            self._XCPrint(file, 0, "/* End " + class_name + " section */\n")

        if self._should_print_single_line:
            self._XCPrint(file, 0, "}; ")
        else:
            self._XCPrint(file, 1, "};\n")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       {"version":3,"file":"index.mjs","names":["fatfs","asyncMapSettled","filter","find","flatMap","flatten","isEmpty","keyBy","mapToArray","mixin","ms","noop","once","pick","semver","tarStream","uniq","asyncMap","vmdkToVhd","vhdToVMDK","writeOvaOn","cancelable","CancelToken","fromEvents","ignoreErrors","pRetry","createLogger","decorateWith","defer","deferrable","limitConcurrency","parseDuration","PassThrough","pipeline","forbiddenOperation","operationFailed","parseDateTime","Xapi","XapiBase","XapiDiskSource","Ref","synchronized","fatfsBuffer","addMbr","init","fatfsBufferInit","camelToSnakeCase","forEach","map","pDelay","promisifyAll","debounceWithKey","mixins","OTHER_CONFIG_TEMPLATE","asInteger","canSrHaveNewVdiOfSize","isVmHvm","isVmRunning","prepareXapiParam","toQcow2Stream","log","AggregateError","Error","constructor","errors","message","VDI_FORMAT_VHD","VDI_FORMAT_RAW","IPV4_CONFIG_MODES","IPV6_CONFIG_MODES","_dec","Object","values","_dec2","onError","warn","_dec3","_dec4","_dec5","_dec6","_dec7","_dec8","_dec9","_dec10","_dec11","hostRef","_class","_class2","guessVhdSizeOnImport","maxUncoalescedVdis","restartHostTimeout","vdiExportConcurrency","vmEvacuationConcurrency","vmExportConcurrency","vmMigrationConcurrency","vmSnapshotConcurrency","opts","_guessVhdSizeOnImport","_maxUncoalescedVdis","_restartHostTimeout","_vmEvacuationConcurrency","waitStreamEnd","stream","VDI_exportContent","VM_export","_migrateVmWithStorageMotion","VM_snapshot","getObject","args","tmp","_xapiId","apply","_waitObjectState","idOrUuidOrRef","predicate","object","loop","waitObject","then","_getOrWaitObject","_setObjectProperties","props","_context","$ref","ref","$type","type","Promise","all","value","name","call","setDefaultSr","srId","pool","set_default_SR","setPoolMaster","hostId","disableHa","enableHa","heartbeatSrs","configuration","joinPool","masterAddress","masterUsername","masterPassword","force","emergencyShutdownHost","host","debug","name_label","$resident_VMs","vm","is_control_domain","callAsync","clearHost","$pool","migrationNetworkRef","id","undefined","network","other_config","params","EMPTY","popParamsAndTrim","n","last","i","length","pop","delay","when","code","onRetry","error","disableHost","forgetHost","ejectHostFromPool","enableHost","installCertificateOnHost","certificate","chain","privateKey","setHostMultipathing","$defer","multipathing","enabled","pluggedPbds","$PBDs","pbd","currently_attached","unplugPbd","plugPbd","update_other_config","multipathhandle","powerOnHost","rebootHost","setRemoteSyslogHost","syslogDestination","set_logging","syslog_destination","shutdownHost","bypassEvacuate","_cloneVm","nameLabel","_copyVm","sr","snapshotRef","VM_destroy","cloneVm","vmId","fast","cloneRef","copyVm","srOrSrId","remoteCopyVm","targetXapi","targetSrId","compress","body","onVmCreation","set_name_label","VM_import","getVmConsole","disable_pv_vnc","console","$consoles","protocol","exportVmOva","$cancelToken","vmRef","useSnapshot","exportedVm","cancelToken","collectedDisks","blockDevice","$VBDs","vdi","$VDI","push","getStream","$exportContent","format","fileName","description","name_description","capacityMB","Math","ceil","virtual_size","nics","vif","$VIFs","macAddress","MAC_autogenerated","MAC","networkName","writeStream","disks","vmName","vmDescription","cpuCount","VCPUs_at_startup","vmMemoryMB","memory_dynamic_max","firmware","HVM_boot_params","statusCode","headers","statusMessage","destroyed","destroySnapshot","_context2","cancel","destroy","hostXapi","migrationNetwork","$PIFs","pif","management","$network","mapVdisSrs","mapVifsNetworks","bypassAssert","srRef","getDefaultSrRef","defaultSr","$default_SR","getMigrationSrRef","$id","isSrConnected","$SR","hostPbds","Set","PBDs","connectedSrs","Map","isConnected","get","some","has","set","vdis","vbds","$snapshots","concat","vbd","is_a_snapshot","$snapshot_of","vifsMap","defaultNetworkRef","vmVifs","vifDevices","_","device","vifs","err","_failOnCbtError","VM_disableChangedBlockTracking","_callInstallationPlugin","catch","_error$params","_error$params$include","includes","installSupplementalPack","createTemporaryVdiOnHost","$destroy","uuid","installSupplementalPackOnAllHosts","isSrAvailable","content_type","physical_size","physical_utilisation","hosts","objects","findAvailableSharedSr","createTemporaryVdiOnSr","pt","pipe","_importOvaVm","descriptionLabel","memory","networks","nCpus","tables","VM_create","memory_dynamic_min","memory_static_max","memory_static_min","VCPUs_max","onFailure","op","update_blocked_operations","compression","objectId","networkId","VIF_create","VM","resolve","reject","extract","on","entry","cb","diskMetadata","path","resume","nodeStream","table","vhdStream","grainLogicalAddressList","grainFileOffsetList","size","VDI_create","SR","_rawLength","VBD_create","userdevice","String","position","VDI","$importContent","e","start","start_on","importVm","data","migrateVm","migrationNetworkId","accrossPools","useStorageMotion","_startVm","bypassMacAddressesCheck","vmMacAddresses","existingMacAddresses","obj","power_state","mac","assign","hostNameLabel","retry","startVm","startOnly","options","status","unpauseVm","resumeVm","startVmOnCd","order","update_HVM_boot_params","templateNameLabel","base_template_name","template","is_a_template","bootloader","PV_bootloader","bootables","promises","cdDrive","_getVmCdDrive","set_bootable","Boolean","bootable","set_PV_bootloader","_context3","_context4","_cloneVdi","moveVdi","vdiId","barrier","$VM","newVdi","_resizeVdi","_ejectCdFromVm","_insertCdIntoVm","cd","_context5","connectVbd","vbdId","destroyVbdsFromVm","VBDs","VBD_destroy","resizeVdi","ejectCdFromVm","insertCdIntoVm","cdId","snapshotVdi","snap","exportVdiAsVmdk","filename","none","base","nbdConcurrency","preferNbd","vhdResult","vmdkStream","exportVdiAsQcow2","disk","vdiRef","xapi","$xapi","createNetwork","pifId","mtu","vlan","networkRef","MTU","automatic","editPif","physPif","physical","bond_master_of","pifs","wasAttached","vlans","VLAN_master_of","isNotEmpty","newPifs","pifRef","_context6","createBondedNetwork","bondMode","pifIds","masterPifIds","deleteNetwork","pifsByHost","bonds","bond","tunnels","tunnel","access_PIF","_doDockerAction","action","containerId","$resident_on","$master","vmuuid","container","registerDockerContainer","deregisterDockerContainer","startDockerContainer","stopDockerContainer","restartDockerContainer","pauseDockerContainer","unpauseDockerContainer","getCloudInitConfig","templateId","config","templateuuid","slice","createCoreOsCloudInitConfigDrive","vdiUuid","sruuid","replace","createCloudInitConfigDrive","userConfig","networkConfig","fsLabel","buffer","label","createLabel","mkdir","writeFile","createFileSystem","JSON","stringify","platform","viridian","minSize","shared","findAvailableSr","_getHostServerTimeShift","abs","Date","now","isHostServerTimeConsistent","assertConsistentHostServerTime","isHyperThreadingEnabled","threads_per_core","cpu_info","getSmartctlHealth","parse","getSmartctlInformation","deviceNames","informations","getHostBiosInfo","cache","_biosData$systemManu","biosData","currentBiosVersion","hostServerName","toLowerCase","servers","response","fetch","json","serverData","latestBiosVersion","biosLink","isUpToDate","eq","loose","_applyDecoratedDescriptor","prototype","getOwnPropertyDescriptor","default"],"sources":["../../src/xapi/index.mjs"],"sourcesContent":["/* eslint eslint-comments/disable-enable-pair: [error, {allowWholeFile: true}] */\n/* eslint-disable camelcase */\nimport fatfs from '@vates/fatfs'\nimport asyncMapSettled from '@xen-orchestra/async-map/legacy.js'\nimport filter from 'lodash/filter.js'\nimport find from 'lodash/find.js'\nimport flatMap from 'lodash/flatMap.js'\nimport flatten from 'lodash/flatten.js'\nimport isEmpty from 'lodash/isEmpty.js'\nimport keyBy from 'lodash/keyBy.js'\nimport mapToArray from 'lodash/map.js'\nimport mixin from '@xen-orchestra/mixin/legacy.js'\nimport ms from 'ms'\nimport noop from 'lodash/noop.js'\nimport once from 'lodash/once.js'\nimport pick from 'lodash/pick.js'\nimport semver from 'semver'\nimport tarStream from 'tar-stream'\nimport uniq from 'lodash/uniq.js'\nimport { asyncMap } from '@xen-orchestra/async-map'\nimport { vmdkToVhd, vhdToVMDK, writeOvaOn } from 'xo-vmdk-to-vhd'\nimport { cancelable, CancelToken, fromEvents, ignoreErrors, pRetry } from 'promise-toolbox'\nimport { createLogger } from '@xen-orchestra/log'\nimport { decorateWith } from '@vates/decorate-with'\nimport { defer as deferrable } from 'golike-defer'\nimport { limitConcurrency } from 'limit-concurrency-decorator'\nimport { parseDuration } from '@vates/parse-duration'\nimport { PassThrough, pipeline } from 'stream'\nimport { forbiddenOperation, operationFailed } from 'xo-common/api-errors.js'\nimport { parseDateTime, Xapi as XapiBase, XapiDiskSource } from '@xen-orchestra/xapi'\nimport { Ref } from 'xen-api'\nimport { synchronized } from 'decorator-synchronized'\n\nimport fatfsBuffer, { addMbr, init as fatfsBufferInit } from '../fatfs-buffer.mjs'\nimport { camelToSnakeCase, forEach, map, pDelay, promisifyAll } from '../utils.mjs'\nimport { debounceWithKey } from '../_pDebounceWithKey.mjs'\n\nimport mixins from './mixins/index.mjs'\nimport OTHER_CONFIG_TEMPLATE from './other-config-template.mjs'\nimport { asInteger, canSrHaveNewVdiOfSize, isVmHvm, isVmRunning, prepareXapiParam } from './utils.mjs'\nimport { toQcow2Stream } from '@xen-orchestra/qcow2'\n\nconst log = createLogger('xo:xapi')\n\nclass AggregateError extends Error {\n  constructor(errors, message) {\n    super(message)\n    this.errors = errors\n  }\n}\n\n// ===================================================================\n\nexport * from './utils.mjs'\n\n// VDI formats. (Raw is not available for delta vdi.)\nexport const VDI_FORMAT_VHD = 'vhd'\nexport const VDI_FORMAT_RAW = 'raw'\n\nexport const IPV4_CONFIG_MODES = ['None', 'DHCP', 'Static']\nexport const IPV6_CONFIG_MODES = ['None', 'DHCP', 'Static', 'Autoconf']\n\n// ===================================================================\n\n@mixin(Object.values(mixins))\nexport default class Xapi extends XapiBase {\n  constructor({\n    guessVhdSizeOnImport,\n    maxUncoalescedVdis,\n    restartHostTimeout,\n    vdiExportConcurrency,\n    vmEvacuationConcurrency,\n    vmExportConcurrency,\n    vmMigrationConcurrency = 3,\n    vmSnapshotConcurrency,\n    ...opts\n  }) {\n    super(opts)\n\n    this._guessVhdSizeOnImport = guessVhdSizeOnImport\n    this._maxUncoalescedVdis = maxUncoalescedVdis\n    this._restartHostTimeout = parseDuration(restartHostTimeout)\n    this._vmEvacuationConcurrency = vmEvacuationConcurrency\n\n    //  close event is emitted when the export is canceled via browser. See https://github.com/vatesfr/xen-orchestra/issues/5535\n    const waitStreamEnd = async stream => fromEvents(await stream, ['end', 'close'])\n    this.VDI_exportContent = limitConcurrency(vdiExportConcurrency, waitStreamEnd)(this.VDI_exportContent)\n    this.VM_export = limitConcurrency(vmExportConcurrency, waitStreamEnd)(this.VM_export)\n\n    this._migrateVmWithStorageMotion = limitConcurrency(vmMigrationConcurrency)(this._migrateVmWithStorageMotion)\n    this.VM_snapshot = limitConcurrency(vmSnapshotConcurrency)(this.VM_snapshot)\n\n    // Patch getObject to resolve _xapiId property.\n    this.getObject = (\n      getObject =>\n      (...args) => {\n        let tmp\n        if ((tmp = args[0]) != null && (tmp = tmp._xapiId) != null) {\n          args[0] = tmp\n        }\n        return getObject.apply(this, args)\n      }\n    )(this.getObject)\n  }\n\n  // Wait for an object to be in a given state.\n  //\n  // Faster than waitObject() with a function.\n  async _waitObjectState(idOrUuidOrRef, predicate) {\n    const object = this.getObject(idOrUuidOrRef, null)\n    if (object && predicate(object)) {\n      return object\n    }\n\n    const loop = () => this.waitObject(idOrUuidOrRef).then(object => (predicate(object) ? object : loop()))\n\n    return loop()\n  }\n\n  // Returns the objects if already presents or waits for it.\n  async _getOrWaitObject(idOrUuidOrRef) {\n    return this.getObject(idOrUuidOrRef, null) || this.waitObject(idOrUuidOrRef)\n  }\n\n  // =================================================================\n\n  _setObjectProperties(object, props) {\n    const { $ref: ref, $type: type } = object\n\n    // TODO: the thrown error should contain the name of the\n    // properties that failed to be set.\n    return Promise.all(\n      mapToArray(props, (value, name) => {\n        if (value != null) {\n          return this.call(`${type}.set_${camelToSnakeCase(name)}`, ref, prepareXapiParam(value))\n        }\n      })\n    )::ignoreErrors()\n  }\n\n  // =================================================================\n\n  setDefaultSr(srId) {\n    return this.pool.set_default_SR(this.getObject(srId).$ref)\n  }\n\n  // =================================================================\n\n  async setPoolMaster(hostId) {\n    await this.call('pool.designate_new_master', this.getObject(hostId).$ref)\n  }\n\n  // =================================================================\n\n  async disableHa() {\n    await this.call('pool.disable_ha')\n  }\n\n  // =================================================================\n\n  async enableHa(heartbeatSrs, configuration) {\n    await this.call(\n      'pool.enable_ha',\n      heartbeatSrs.map(srId => this.getObject(srId).$ref),\n      configuration\n    )\n  }\n\n  // =================================================================\n\n  async joinPool(masterAddress, masterUsername, masterPassword, force = false) {\n    await this.call(force ? 'pool.join_force' : 'pool.join', masterAddress, masterUsername, masterPassword)\n  }\n\n  // =================================================================\n\n  async emergencyShutdownHost(hostId) {\n    const host = this.getObject(hostId)\n    log.debug(`Emergency shutdown: ${host.name_label}`)\n\n    await this.call('host.disable', host.$ref)\n\n    await asyncMap(host.$resident_VMs, vm => {\n      if (!vm.is_control_domain) {\n        return ignoreErrors.call(this.callAsync('VM.suspend', vm.$ref))\n      }\n    })\n\n    await this.callAsync('host.shutdown', host.$ref)\n  }\n\n  // =================================================================\n\n  // Disable the host and evacuate all its VMs.\n  //\n  // If `force` is false and the evacuation failed, the host is re-\n  // enabled and the error is thrown.\n  async clearHost({ $ref: hostRef, $pool: pool }, force) {\n    await this.call('host.disable', hostRef)\n\n    const migrationNetworkRef = (id => {\n      if (id !== undefined) {\n        const network = this.getObject(id, undefined)\n        if (network === undefined) {\n          throw new Error('could not find migration network ' + id)\n        }\n        return network.$ref\n      }\n    })(pool.other_config['xo:migrationNetwork'])\n\n    // host ref\n    // migration network: optional and might not be supported\n    // batch size: optional and might not be supported\n    const params = [hostRef, migrationNetworkRef ?? Ref.EMPTY, this._vmEvacuationConcurrency]\n\n    // Removes n params from the end and keeps removing until a non-empty param is found\n    const popParamsAndTrim = (n = 0) => {\n      let last\n      let i = 0\n      while (i < n || (last = params[params.length - 1]) === undefined || last === Ref.EMPTY) {\n        if (params.length <= 1) {\n          throw new Error('not enough params left')\n        }\n        params.pop()\n        i++\n      }\n    }\n\n    popParamsAndTrim()\n\n    try {\n      await pRetry(() => this.callAsync('host.evacuate', ...params), {\n        delay: 0,\n        when: { code: 'MESSAGE_PARAMETER_COUNT_MISMATCH' },\n        onRetry: error => {\n          log.warn(error)\n          popParamsAndTrim(1)\n        },\n      })\n    } catch (error) {\n      if (!force) {\n        await this.call('host.enable', hostRef)\n\n        throw error\n      }\n    }\n  }\n\n  async disableHost(hostId) {\n    await this.call('host.disable', this.getObject(hostId).$ref)\n  }\n\n  async forgetHost(hostId) {\n    await this.callAsync('host.destroy', this.getObject(hostId).$ref)\n  }\n\n  async ejectHostFromPool(hostId) {\n    await this.call('pool.eject', this.getObject(hostId).$ref)\n  }\n\n  async enableHost(hostId) {\n    await this.call('host.enable', this.getObject(hostId).$ref)\n  }\n\n  async installCertificateOnHost(hostId, { certificate, chain = '', privateKey }) {\n    try {\n      await this.call('host.install_server_certificate', this.getObject(hostId).$ref, certificate, privateKey, chain)\n    } catch (error) {\n      // CH/XCP-ng reset the connection on the certificate install\n      if (error.code !== 'ECONNRESET') {\n        throw error\n      }\n    }\n  }\n\n  // Resources:\n  // - Citrix XenServer ® 7.0 Administrator's Guide ch. 5.4\n  // - https://github.com/xcp-ng/xenadmin/blob/60dd70fc36faa0ec91654ec97e24b7af36acff9f/XenModel/Actions/Host/EditMultipathAction.cs\n  // - https://github.com/serencorbett1/xenadmin/blob/1c3fb0c1112e4e316423afc6a028066001d3dea1/XenModel/XenAPI-Extensions/SR.cs\n  @decorateWith(deferrable.onError(log.warn))\n  async setHostMultipathing($defer, hostId, multipathing) {\n    const host = this.getObject(hostId)\n\n    if (host.enabled) {\n      await this.disableHost(hostId)\n      $defer(() => this.enableHost(hostId))\n    }\n\n    // Xen center evacuate running VMs before unplugging the PBDs.\n    // The evacuate method uses the live migration to migrate running VMs\n    // from host to another. It only works when a shared SR is present\n    // in the host. For this reason we chose to show a warning instead.\n    const pluggedPbds = host.$PBDs.filter(pbd => pbd.currently_attached)\n    await asyncMapSettled(pluggedPbds, async pbd => {\n      const ref = pbd.$ref\n      await this.unplugPbd(ref)\n      $defer(() => this.plugPbd(ref))\n    })\n\n    return host.update_other_config(\n      multipathing\n        ? {\n            multipathing: 'true',\n            multipathhandle: 'dmp',\n          }\n        : {\n            multipathing: 'false',\n          }\n    )\n  }\n\n  async powerOnHost(hostId) {\n    await this.callAsync('host.power_on', this.getObject(hostId).$ref)\n  }\n\n  async rebootHost(hostId, force = false) {\n    const host = this.getObject(hostId)\n\n    await this.clearHost(host, force)\n    await this.callAsync('host.reboot', host.$ref)\n  }\n\n  async setRemoteSyslogHost(hostId, syslogDestination) {\n    const host = this.getObject(hostId)\n    await host.set_logging(\n      syslogDestination === null\n        ? {}\n        : {\n            syslog_destination: syslogDestination,\n          }\n    )\n    await this.call('host.syslog_reconfigure', host.$ref)\n  }\n\n  async shutdownHost(hostId, { force = false, bypassEvacuate = false } = {}) {\n    const host = this.getObject(hostId)\n    if (bypassEvacuate) {\n      await this.call('host.disable', host.$ref)\n    } else {\n      await this.clearHost(host, force)\n    }\n    await this.callAsync('host.shutdown', host.$ref)\n  }\n\n  // =================================================================\n\n  // Clone a VM: make a fast copy by fast copying each of its VDIs\n  // (using snapshots where possible) on the same SRs.\n  _cloneVm(vm, nameLabel = vm.name_label) {\n    log.debug(`Cloning VM ${vm.name_label}${nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''}`)\n\n    return this.callAsync('VM.clone', vm.$ref, nameLabel)\n  }\n\n  // Copy a VM: make a normal copy of a VM and all its VDIs.\n  //\n  // If a SR is specified, it will contains the copies of the VDIs,\n  // otherwise they will use the SRs they are on.\n  async _copyVm(vm, nameLabel = vm.name_label, sr = undefined) {\n    let snapshotRef\n    if (isVmRunning(vm)) {\n      snapshotRef = await this.VM_snapshot(vm.$ref)\n    }\n\n    log.debug(\n      `Copying VM ${vm.name_label}${nameLabel !== vm.name_label ? ` as ${nameLabel}` : ''}${\n        sr ? ` on ${sr.name_label}` : ''\n      }`\n    )\n\n    try {\n      return await this.callAsync('VM.copy', snapshotRef || vm.$ref, nameLabel, sr ? sr.$ref : '')\n    } finally {\n      if (snapshotRef) {\n        await this.VM_destroy(snapshotRef)\n      }\n    }\n  }\n\n  async cloneVm(vmId, { nameLabel = undefined, fast = true } = {}) {\n    const vm = this.getObject(vmId)\n\n    const cloneRef = await (fast ? this._cloneVm(vm, nameLabel) : this._copyVm(vm, nameLabel))\n\n    return /* await */ this._getOrWaitObject(cloneRef)\n  }\n\n  async copyVm(vmId, { nameLabel = undefined, srOrSrId = undefined } = {}) {\n    return /* await */ this._getOrWaitObject(\n      await this._copyVm(this.getObject(vmId), nameLabel, srOrSrId !== undefined ? this.getObject(srOrSrId) : undefined)\n    )\n  }\n\n  async remoteCopyVm(vmId, targetXapi, targetSrId, { compress, nameLabel = undefined } = {}) {\n    // Fall back on local copy if possible.\n    if (targetXapi === this) {\n      return {\n        vm: await this.copyVm(vmId, { nameLabel, srOrSrId: targetSrId }),\n      }\n    }\n\n    const sr = targetXapi.getObject(targetSrId)\n    const stream = (\n      await this.VM_export(this.getObject(vmId).$ref, {\n        compress,\n      })\n    ).body\n\n    const onVmCreation = nameLabel !== undefined ? vm => vm.set_name_label(nameLabel) : null\n\n    const vm = await targetXapi._getOrWaitObject(await targetXapi.VM_import(stream, sr.$ref, onVmCreation))\n\n    return {\n      vm,\n    }\n  }\n\n  getVmConsole(vmId) {\n    const vm = this.getObject(vmId)\n\n    if (vm.other_config.disable_pv_vnc === '1') {\n      throw new Error('console is disabled for this VM')\n    }\n\n    const console = find(vm.$consoles, { protocol: 'rfb' })\n    if (!console) {\n      throw new Error('no RFB console found')\n    }\n\n    return console\n  }\n\n  @cancelable\n  async exportVmOva($cancelToken, vmRef) {\n    const vm = this.getObject(vmRef)\n    const useSnapshot = isVmRunning(vm)\n    let exportedVm\n    if (useSnapshot) {\n      const snapshotRef = await this.VM_snapshot(vmRef, {\n        name_label: vm.name_label,\n        cancelToken: $cancelToken,\n      })\n      exportedVm = this.getObject(snapshotRef)\n    } else {\n      exportedVm = vm\n    }\n\n    const collectedDisks = []\n    for (const blockDevice of exportedVm.$VBDs) {\n      if (blockDevice.type === 'Disk') {\n        const vdi = blockDevice.$VDI\n        collectedDisks.push({\n          getStream: () => {\n            return vdi.$exportContent({ cancelToken: $cancelToken, format: VDI_FORMAT_VHD })\n          },\n          name: vdi.name_label,\n          fileName: vdi.name_label + '.vmdk',\n          description: vdi.name_description,\n          capacityMB: Math.ceil(vdi.virtual_size / 1024 / 1024),\n        })\n      }\n    }\n    const nics = []\n    for (const vif of exportedVm.$VIFs) {\n      nics.push({\n        macAddress: vif.MAC_autogenerated ? '' : vif.MAC,\n        networkName: this.getObject(vif.network).name_label,\n      })\n    }\n\n    const writeStream = new PassThrough()\n    writeOvaOn(writeStream, {\n      disks: collectedDisks,\n      vmName: exportedVm.name_label,\n      vmDescription: exportedVm.name_description,\n      cpuCount: exportedVm.VCPUs_at_startup,\n      vmMemoryMB: Math.ceil(exportedVm.memory_dynamic_max / 1024 / 1024),\n      firmware: exportedVm.HVM_boot_params.firmware,\n      nics,\n    })\n\n    writeStream.statusCode = 200\n    writeStream.headers = { 'content-type': 'application/ova' }\n    writeStream.statusMessage = 'OK'\n\n    let destroyed = false\n    const destroySnapshot = () => {\n      if (useSnapshot && !destroyed) {\n        destroyed = true\n        this.VM_destroy(exportedVm.$ref)::ignoreErrors()\n      }\n    }\n    writeStream.cancel = () => {\n      destroySnapshot()\n      return writeStream.destroy()\n    }\n    writeStream.once('end', destroySnapshot)\n    writeStream.once('error', destroySnapshot)\n    return writeStream\n  }\n\n  async _migrateVmWithStorageMotion(\n    vm,\n    hostXapi,\n    host,\n    {\n      migrationNetwork = find(host.$PIFs, pif => pif.management).$network, // TODO: handle not found\n      sr,\n      mapVdisSrs = {},\n      mapVifsNetworks,\n      force = false,\n      bypassAssert = false,\n    }\n  ) {\n    const srRef = sr !== undefined ? hostXapi.getObject(sr).$ref : undefined\n    const getDefaultSrRef = once(() => {\n      const defaultSr = host.$pool.$default_SR\n      if (defaultSr === undefined) {\n        throw new Error(`This operation requires a default SR to be set on the pool ${host.$pool.name_label}`)\n      }\n      return defaultSr.$ref\n    })\n\n    // VDIs/SRs mapping\n    // For VDI:\n    // - If a map of VDI -> SR was explicitly passed: use it\n    // - Else if SR was explicitly passed: use it\n    // - Else if VDI SR is reachable from the destination host: use it\n    // - Else: use the migration main SR or the pool's default SR (error if none of them is defined)\n    function getMigrationSrRef(vdi) {\n      if (mapVdisSrs[vdi.$id] !== undefined) {\n        return hostXapi.getObject(mapVdisSrs[vdi.$id]).$ref\n      }\n\n      if (srRef !== undefined) {\n        return srRef\n      }\n\n      if (isSrConnected(vdi.$SR)) {\n        return vdi.$SR.$ref\n      }\n\n      return getDefaultSrRef()\n    }\n\n    const hostPbds = new Set(host.PBDs)\n    const connectedSrs = new Map()\n    const isSrConnected = sr => {\n      let isConnected = connectedSrs.get(sr.$ref)\n      if (isConnected === undefined) {\n        isConnected = sr.PBDs.some(ref => hostPbds.has(ref))\n        connectedSrs.set(sr.$ref, isConnected)\n      }\n      return isConnected\n    }\n\n    // VDIs/SRs mapping\n    // For VDI-snapshot:\n    // - If VDI-snapshot is an orphan snapshot: same logic as a VDI\n    // - Else: don't add it to the map (VDI -> SR). It will be managed by the XAPI (snapshot will be migrated to the same SR as its parent active VDI)\n    const vdis = {}\n    const vbds = flatMap(vm.$snapshots, '$VBDs').concat(vm.$VBDs)\n    for (const vbd of vbds) {\n      if (vbd.type === 'Disk') {\n        const vdi = vbd.$VDI\n        // We need to explicitly test VDI.is_a_snapshot because there is a problem with XAPI itself (observed on\n        // an XCP-ng 8.1 host, might be related to CBT), where some non-snapshot VDIs have a snapshot_of\n        // property not equal to OpaqueRef:NULL as expected but containing a reference to an existing VDI.\n        //\n        // https://team.vates.fr/vates/pl/9m4u5rsr7tfcdroykwq6i6mcmo\n        if (vdi.is_a_snapshot && vdi.$snapshot_of !== undefined) {\n          continue\n        }\n        vdis[vdi.$ref] = getMigrationSrRef(vdi)\n      }\n    }\n\n    // VIFs/Networks mapping\n    const vifsMap = {}\n    if (vm.$pool !== host.$pool) {\n      const defaultNetworkRef = find(host.$PIFs, pif => pif.management).$network.$ref\n      // Add snapshots' VIFs which VM has no VIFs on these devices\n      const vmVifs = vm.$VIFs\n      const vifDevices = new Set(vmVifs.map(_ => _.device))\n      const vifs = flatMap(vm.$snapshots, '$VIFs')\n        .filter(vif => !vifDevices.has(vif.device))\n        .concat(vmVifs)\n      for (const vif of vifs) {\n        vifsMap[vif.$ref] =\n          mapVifsNetworks && mapVifsNetworks[vif.$id]\n            ? hostXapi.getObject(mapVifsNetworks[vif.$id]).$ref\n            : defaultNetworkRef\n      }\n    }\n\n    const params = [\n      vm.$ref,\n      await hostXapi.call('host.migrate_receive', host.$ref, migrationNetwork.$ref, {}), // token\n      true, // Live migration.\n      vdis,\n      vifsMap,\n      {\n        force: force ? 'true' : 'false',\n      },\n      // FIXME: missing param `vgu_map`, it does not cause issues ATM but it\n      // might need to be changed one day.\n      // {},\n    ]\n\n    if (!bypassAssert) {\n      try {\n        await this.callAsync('VM.assert_can_migrate', ...params)\n      } catch (err) {\n        if (err.code !== 'VDI_CBT_ENABLED') {\n          // cbt disabling is handled later, by the migrate_end call\n          throw err\n        }\n      }\n    }\n    const loop = async (_failOnCbtError = false) => {\n      try {\n        await this.callAsync('VM.migrate_send', ...params)\n      } catch (err) {\n        if (err.code === 'VDI_CBT_ENABLED' && !_failOnCbtError) {\n          // as of 20240619, CBT must be disabled on all disks to allow migration to go through\n          // it will be re enabled if needed by backups\n          // the next backup after a storage migration will be a full backup\n          await this.VM_disableChangedBlockTracking(vm.$ref)\n          return loop(true)\n        }\n        if (err.code === 'TOO_MANY_STORAGE_MIGRATES') {\n          await pDelay(1e4)\n          return loop()\n        }\n        throw err\n      }\n    }\n    return loop().then(noop)\n  }\n\n  @synchronized()\n  _callInstallationPlugin(hostRef, vdi) {\n    return this.call('host.call_plugin', hostRef, 'install-supp-pack', 'install', { vdi }).catch(error => {\n      if (error.code !== 'XENAPI_PLUGIN_FAILURE' || !error.params?.[2]?.includes?.('UPDATE_ALREADY_APPLIED')) {\n        throw error\n      }\n      log.warn('_callInstallationPlugin', { error })\n    })\n  }\n\n  @decorateWith(deferrable)\n  async installSupplementalPack($defer, stream, { hostId }) {\n    if (!stream.length) {\n      throw new Error('stream must have a length')\n    }\n\n    const vdi = await this.createTemporaryVdiOnHost(\n      stream,\n      hostId,\n      '[XO] Supplemental pack ISO',\n      'small temporary VDI to store a supplemental pack ISO'\n    )\n    $defer(() => vdi.$destroy())\n\n    await this._callInstallationPlugin(this.getObject(hostId).$ref, vdi.uuid)\n  }\n\n  @decorateWith(deferrable)\n  async installSupplementalPackOnAllHosts($defer, stream) {\n    if (!stream.length) {\n      throw new Error('stream must have a length')\n    }\n\n    const isSrAvailable = sr =>\n      sr && sr.content_type === 'user' && sr.physical_size - sr.physical_utilisation >= stream.length\n\n    const hosts = filter(this.objects.all, { $type: 'host' })\n\n    const sr = this.findAvailableSharedSr(stream.length)\n\n    // Shared SR available: create only 1 VDI for all the installations\n    if (sr) {\n      const vdi = await this.createTemporaryVdiOnSr(\n        stream,\n        sr,\n        '[XO] Supplemental pack ISO',\n        'small temporary VDI to store a supplemental pack ISO'\n      )\n      $defer(() => vdi.$destroy())\n\n      // Install pack sequentially to prevent concurrent access to the unique VDI\n      for (const host of hosts) {\n        await this._callInstallationPlugin(host.$ref, vdi.uuid)\n      }\n\n      return\n    }\n\n    // No shared SR available: find an available local SR on each host\n    return Promise.all(\n      hosts.map(\n        deferrable(async ($defer, host) => {\n          // pipe stream synchronously to several PassThroughs to be able to pipe them asynchronously later\n          const pt = stream.pipe(new PassThrough())\n          pt.length = stream.length\n\n          const sr = find(\n            host.$PBDs.map(_ => _.$SR),\n            isSrAvailable\n          )\n\n          if (!sr) {\n            throw new Error('no SR available to store installation file')\n          }\n\n          const vdi = await this.createTemporaryVdiOnSr(\n            pt,\n            sr,\n            '[XO] Supplemental pack ISO',\n            'small temporary VDI to store a supplemental pack ISO'\n          )\n          $defer(() => vdi.$destroy())\n\n          await this._callInstallationPlugin(host.$ref, vdi.uuid)\n        })\n      )\n    )\n  }\n\n  @decorateWith(deferrable)\n  async _importOvaVm($defer, stream, { descriptionLabel, disks, memory, nameLabel, networks, nCpus, tables }, sr) {\n    // 1. Create VM.\n    const vm = await this._getOrWaitObject(\n      await this.VM_create({\n        ...OTHER_CONFIG_TEMPLATE,\n        memory_dynamic_max: memory,\n        memory_dynamic_min: memory,\n        memory_static_max: memory,\n        memory_static_min: memory,\n        name_description: descriptionLabel,\n        name_label: nameLabel,\n        VCPUs_at_startup: nCpus,\n        VCPUs_max: nCpus,\n      })\n    )\n    $defer.onFailure(() => this.VM_destroy(vm.$ref))\n    // Disable start and change the VM name label during import.\n    await Promise.all([\n      asyncMapSettled(['start', 'start_on'], op => vm.update_blocked_operations(op, 'OVA import in progress...')),\n      vm.set_name_label(`[Importing...] ${nameLabel}`),\n    ])\n\n    // 2. Create VDIs & Vifs.\n    const vdis = {}\n    const compression = {}\n    const vifDevices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)\n    if (networks.length > vifDevices.length) {\n      throw operationFailed({ objectId: vm.id, code: 'TOO_MANY_VIFs' })\n    }\n    await Promise.all(\n      map(networks, (networkId, i) =>\n        this.VIF_create({\n          device: vifDevices[i],\n          network: this.getObject(networkId).$ref,\n          VM: vm.$ref,\n        })\n      )\n    )\n\n    // 3. Import VDIs contents.\n    await new Promise((resolve, reject) => {\n      const extract = tarStream.extract()\n\n      stream.on('error', reject)\n\n      extract.on('finish', resolve)\n      extract.on('error', reject)\n      extract.on('entry', async (entry, stream, cb) => {\n        const diskMetadata = disks.find(({ path }) => path === entry.name)\n        // Not a disk to import\n        if (!diskMetadata) {\n          stream.on('end', cb)\n          stream.resume()\n          return\n        }\n        const nodeStream = new PassThrough()\n        pipeline(stream, nodeStream, () => {})\n        const table = tables[entry.name]\n        const vhdStream = await vmdkToVhd(\n          nodeStream, // tar-stream stream are not node stream\n          table.grainLogicalAddressList,\n          table.grainFileOffsetList,\n          compression[entry.name] === 'gzip',\n          entry.size\n        )\n\n        try {\n          // vmdk size can be wrong in ova\n          // we use the size in the vmdk descriptor to create the vdi\n          const vdi = (vdis[diskMetadata.path] = await this._getOrWaitObject(\n            await this.VDI_create({\n              name_description: diskMetadata.descriptionLabel,\n              name_label: diskMetadata.nameLabel,\n              SR: sr.$ref,\n              virtual_size: vhdStream._rawLength,\n            })\n          ))\n          $defer.onFailure(() => vdi.$destroy())\n          compression[diskMetadata.path] = diskMetadata.compression\n          await this.VBD_create({\n            userdevice: String(diskMetadata.position),\n            VDI: vdi.$ref,\n            VM: vm.$ref,\n          })\n\n          await vdi.$importContent(vhdStream, { format: VDI_FORMAT_VHD })\n          // See: https://github.com/mafintosh/tar-stream#extracting\n          // No import parallelization.\n        } catch (e) {\n          reject(e)\n        } finally {\n          cb()\n        }\n      })\n      stream.pipe(extract)\n    })\n\n    // Enable start and restore the VM name label after import.\n    await Promise.all([vm.update_blocked_operations({ start: null, start_on: null }), vm.set_name_label(nameLabel)])\n    return vm\n  }\n\n  // TODO: an XVA can contain multiple VMs\n  async importVm(stream, { data, srId, type = 'xva' } = {}) {\n    const sr = srId && this.getObject(srId)\n\n    if (type === 'xva') {\n      return /* await */ this._getOrWaitObject(await this.VM_import(stream, sr?.$ref))\n    }\n\n    if (type === 'ova') {\n      return this._getOrWaitObject(await this._importOvaVm(stream, data, sr))\n    }\n\n    throw new Error(`unsupported type: '${type}'`)\n  }\n\n  async migrateVm(\n    vmId,\n    hostXapi,\n    hostId,\n    { force = false, mapVdisSrs, mapVifsNetworks, migrationNetworkId, sr, bypassAssert } = {}\n  ) {\n    const vm = this.getObject(vmId)\n    const host = hostXapi.getObject(hostId)\n\n    const accrossPools = vm.$pool !== host.$pool\n    const useStorageMotion =\n      accrossPools ||\n      sr !== undefined ||\n      migrationNetworkId !== undefined ||\n      !isEmpty(mapVifsNetworks) ||\n      !isEmpty(mapVdisSrs)\n\n    if (useStorageMotion) {\n      await this._migrateVmWithStorageMotion(vm, hostXapi, host, {\n        migrationNetwork: migrationNetworkId && hostXapi.getObject(migrationNetworkId),\n        sr,\n        mapVdisSrs,\n        mapVifsNetworks,\n        force,\n        bypassAssert,\n      })\n    } else {\n      try {\n        await this.callAsync('VM.pool_migrate', vm.$ref, host.$ref, {\n          force: force ? 'true' : 'false',\n        })\n      } catch (error) {\n        if (error.code !== 'VM_REQUIRES_SR') {\n          throw error\n        }\n\n        // Retry using motion storage.\n        await this._migrateVmWithStorageMotion(vm, hostXapi, host, { force })\n      }\n    }\n  }\n\n  async _startVm(vm, { force = false, bypassMacAddressesCheck = force, hostId } = {}) {\n    if (!bypassMacAddressesCheck) {\n      const vmMacAddresses = vm.$VIFs.map(vif => vif.MAC)\n      if (new Set(vmMacAddresses).size !== vmMacAddresses.length) {\n        throw operationFailed({ objectId: vm.id, code: 'DUPLICATED_MAC_ADDRESS' })\n      }\n\n      const existingMacAddresses = new Set(\n        filter(\n          this.objects.all,\n          obj => obj.id !== vm.id && obj.$type === 'VM' && obj.power_state === 'Running'\n        ).flatMap(vm => vm.$VIFs.map(vif => vif.MAC))\n      )\n      if (vmMacAddresses.some(mac => existingMacAddresses.has(mac))) {\n        throw operationFailed({ objectId: vm.id, code: 'DUPLICATED_MAC_ADDRESS' })\n      }\n    }\n\n    log.debug(`Starting VM ${vm.name_label}`)\n\n    if (force) {\n      await vm.update_blocked_operations({ start: null, start_on: null })\n    }\n\n    const vmRef = vm.$ref\n    if (hostId === undefined) {\n      try {\n        await this.call(\n          'VM.start',\n          vmRef,\n          false, // Start paused?\n          false // Skip pre-boot checks?\n        )\n      } catch (error) {\n        if (error.code !== 'NO_HOSTS_AVAILABLE') {\n          throw error\n        }\n\n        throw Object.assign(\n          new AggregateError(\n            await asyncMap(await this.call('host.get_all'), async hostRef => {\n              const hostNameLabel = await this.call('host.get_name_label', hostRef)\n              try {\n                await this.call('VM.assert_can_boot_here', vmRef, hostRef)\n                return `${hostNameLabel}: OK`\n              } catch (error) {\n                return `${hostNameLabel}: ${error.message}`\n              }\n            }),\n            error.message\n          ),\n          { code: error.code, params: error.params }\n        )\n      }\n    } else {\n      const hostRef = this.getObject(hostId).$ref\n      let retry\n      do {\n        retry = false\n\n        try {\n          await this.callAsync('VM.start_on', vmRef, hostRef, false, false)\n        } catch (error) {\n          if (error.code !== 'NO_HOSTS_AVAILABLE') {\n            throw error\n          }\n\n          await this.call('VM.assert_can_boot_here', vmRef, hostRef)\n\n          // Something has changed between the last two calls, starting the VM should be retried\n          retry = true\n        }\n      } while (retry)\n    }\n  }\n\n  /**\n   *\n   * @param {string} vmId\n   * @param {object} options\n   * @param {boolean} [options.startOnly] - If true, don't try to unpause/resume the VM if VM_BAD_POWER_STATE is thrown\n   *\n   */\n  async startVm(vmId, { startOnly = false, ...options } = {}) {\n    try {\n      await this._startVm(this.getObject(vmId), options)\n    } catch (e) {\n      if (e.code === 'OPERATION_BLOCKED') {\n        throw forbiddenOperation('Start', e.params[1])\n      }\n      if (e.code === 'VM_BAD_POWER_STATE' && !startOnly) {\n        const status = e.params[2]\n        if (status === 'running') {\n          throw e\n        }\n\n        return status === 'paused' ? this.unpauseVm(vmId) : this.resumeVm(vmId)\n      }\n      throw e\n    }\n  }\n\n  async startVmOnCd(vmId) {\n    const vm = this.getObject(vmId)\n\n    if (isVmHvm(vm)) {\n      const { order } = vm.HVM_boot_params\n\n      await vm.update_HVM_boot_params('order', 'd')\n\n      try {\n        await this._startVm(vm)\n      } finally {\n        await vm.update_HVM_boot_params('order', order)\n      }\n    } else {\n      // Find the original template by name (*sigh*).\n      const templateNameLabel = vm.other_config.base_template_name\n      const template =\n        templateNameLabel &&\n        find(this.objects.all, obj => obj.$type === 'VM' && obj.is_a_template && obj.name_label === templateNameLabel)\n\n      const bootloader = vm.PV_bootloader\n      const bootables = []\n      try {\n        const promises = []\n\n        const cdDrive = this._getVmCdDrive(vm)\n        forEach(vm.$VBDs, vbd => {\n          promises.push(vbd.set_bootable(vbd === cdDrive))\n\n          bootables.push([vbd, Boolean(vbd.bootable)])\n        })\n\n        promises.push(\n          vm.set_PV_bootloader('eliloader'),\n          vm.update_other_config({\n            'install-distro': template && template.other_config['install-distro'],\n            'install-repository': 'cdrom',\n          })\n        )\n\n        await Promise.all(promises)\n\n        await this._startVm(vm)\n      } finally {\n        vm.set_PV_bootloader(bootloader)::ignoreErrors()\n\n        forEach(bootables, ([vbd, bootable]) => {\n          vbd.set_bootable(bootable)::ignoreErrors()\n        })\n      }\n    }\n  }\n\n  // =================================================================\n\n  _cloneVdi(vdi) {\n    log.debug(`Cloning VDI ${vdi.name_label}`)\n\n    return this.callAsync('VDI.clone', vdi.$ref)\n  }\n\n  async moveVdi(vdiId, srId, { _failOnCbtError = false } = {}) {\n    const vdi = this.getObject(vdiId)\n    const sr = this.getObject(srId)\n\n    if (vdi.SR === sr.$ref) {\n      return vdi\n    }\n\n    log.debug(`Moving VDI ${vdi.name_label} from ${vdi.$SR.name_label} to ${sr.name_label}`)\n    try {\n      return this.barrier(\n        await pRetry(() => this.callAsync('VDI.pool_migrate', vdi.$ref, sr.$ref, {}), {\n          when: { code: 'TOO_MANY_STORAGE_MIGRATES' },\n        })\n      )\n    } catch (error) {\n      const { code } = error\n      if (code === 'VDI_CBT_ENABLED' && !_failOnCbtError) {\n        log.debug(`${vdi.name_label} has CBT enabled`)\n        // disks attached to dom0 are a xapi internal\n        // it can be, for example, during an export\n        // we shouldn't consider these VBDs are relevant here\n        const vbds = vdi.$VBDs.filter(({ $VM }) => $VM.is_control_domain === false)\n        if (vbds.length === 0) {\n          log.debug(`will disable CBT on ${vdi.name_label}  `)\n          await this.callAsync('VDI.disable_cbt', vdi.$ref)\n        } else {\n          if (vbds.length > 1) {\n            // no implicit workaround if vdi is attached to multiple VMs\n            throw error\n          }\n          // 20240629 we need to disable CBT on all disks of the VM since the xapi\n          // checks all disk of a VM even to migrate only one disk\n          const vbd = vbds[0]\n          log.debug(`will disable CBT on the full VM ${vbd.$VM.name_label}, containing disk ${vdi.name_label}  `)\n          await this.VM_disableChangedBlockTracking(vbd.VM)\n        }\n\n        // cbt will be re enabled when needed on next backup\n        // after a migration the next delta backup is always a base copy\n        // and this will only enabled cbt on needed disks\n\n        // retry migrating disk\n        return this.moveVdi(vdiId, srId, { _failOnCbtError: true })\n      }\n      if (code !== 'NO_HOSTS_AVAILABLE' && code !== 'LICENCE_RESTRICTION' && code !== 'VDI_NEEDS_VM_FOR_MIGRATE') {\n        throw error\n      }\n      const newVdi = await this.barrier(await this.callAsync('VDI.copy', vdi.$ref, sr.$ref))\n      await asyncMapSettled(vdi.$VBDs, async vbd => {\n        await this.call('VBD.destroy', vbd.$ref)\n        await this.VBD_create({\n          ...vbd,\n          VDI: newVdi.$ref,\n        })\n      })\n      await vdi.$destroy()\n\n      return newVdi\n    }\n  }\n\n  _resizeVdi(vdi, size) {\n    log.debug(`Resizing VDI ${vdi.name_label} from ${vdi.virtual_size} to ${size}`)\n\n    return this.callAsync('VDI.resize', vdi.$ref, size)\n  }\n\n  _getVmCdDrive(vm) {\n    for (const vbd of vm.$VBDs) {\n      if (vbd.type === 'CD') {\n        return vbd\n      }\n    }\n  }\n\n  async _ejectCdFromVm(vm) {\n    const cdDrive = this._getVmCdDrive(vm)\n    if (cdDrive) {\n      await this.callAsync('VBD.eject', cdDrive.$ref)\n    }\n  }\n\n  async _insertCdIntoVm(cd, vm, { bootable = false, force = false } = {}) {\n    const cdDrive = await this._getVmCdDrive(vm)\n    if (cdDrive) {\n      try {\n        await this.callAsync('VBD.insert', cdDrive.$ref, cd.$ref)\n      } catch (error) {\n        if (!force || error.code !== 'VBD_NOT_EMPTY') {\n          throw error\n        }\n\n        await this.callAsync('VBD.eject', cdDrive.$ref)::ignoreErrors()\n\n        // Retry.\n        await this.callAsync('VBD.insert', cdDrive.$ref, cd.$ref)\n      }\n\n      if (bootable !== Boolean(cdDrive.bootable)) {\n        await cdDrive.set_bootable(bootable)\n      }\n    } else {\n      await this.VBD_create({\n        bootable,\n        type: 'CD',\n        VDI: cd.$ref,\n        VM: vm.$ref,\n      })\n    }\n  }\n\n  async connectVbd(vbdId) {\n    await this.callAsync('VBD.plug', vbdId)\n  }\n\n  // TODO: remove when no longer used.\n  async destroyVbdsFromVm(vmId) {\n    await Promise.all(this.getObject(vmId).VBDs.map(async ref => this.VBD_destroy(ref)))\n  }\n\n  async resizeVdi(vdiId, size) {\n    await this._resizeVdi(this.getObject(vdiId), size)\n  }\n\n  async ejectCdFromVm(vmId) {\n    await this._ejectCdFromVm(this.getObject(vmId))\n  }\n\n  async insertCdIntoVm(cdId, vmId, opts = undefined) {\n    await this._insertCdIntoVm(this.getObject(cdId), this.getObject(vmId), opts)\n  }\n\n  // -----------------------------------------------------------------\n\n  async snapshotVdi(vdiId, nameLabel) {\n    const vdi = this.getObject(vdiId)\n\n    const snap = await this._getOrWaitObject(await this.callAsync('VDI.snapshot', vdi.$ref))\n\n    if (nameLabel) {\n      await snap.set_name_label(nameLabel)\n    }\n\n    return snap\n  }\n\n  async exportVdiAsVmdk(vdi, filename, { cancelToken = CancelToken.none, base, nbdConcurrency, preferNbd } = {}) {\n    vdi = this.getObject(vdi)\n    const params = { cancelToken, format: VDI_FORMAT_VHD, nbdConcurrency, preferNbd }\n    if (base !== undefined) {\n      params.base = base\n    }\n    let vhdResult\n    const vmdkStream = await vhdToVMDK(`${vdi.name_label}.vmdk`, async () => {\n      vhdResult = await this.VDI_exportContent(vdi.$ref, params)\n      return vhdResult\n    })\n    return vmdkStream\n  }\n\n  async exportVdiAsQcow2(vdi, filename, { cancelToken = CancelToken.none, base, nbdConcurrency, preferNbd } = {}) {\n    vdi = this.getObject(vdi)\n\n    const disk = new XapiDiskSource({\n      vdiRef: vdi.$ref,\n      xapi: vdi.$xapi,\n      nbdConcurrency,\n      preferNbd,\n    })\n    await disk.init()\n    const stream = toQcow2Stream(disk)\n    return stream\n  }\n\n  // =================================================================\n\n  @decorateWith(deferrable)\n  async createNetwork($defer, { name, description = 'Created with Xen Orchestra', pifId, mtu, vlan }) {\n    const networkRef = await this.call('network.create', {\n      name_label: name,\n      name_description: description,\n      MTU: mtu,\n      // Set automatic to false so XenCenter does not get confused\n      // https://citrix.github.io/xenserver-sdk/#network\n      other_config: { automatic: 'false' },\n    })\n    $defer.onFailure(() => this.callAsync('network.destroy', networkRef))\n    if (pifId) {\n      await this.call('pool.create_VLAN_from_PIF', this.getObject(pifId).$ref, networkRef, asInteger(vlan))\n    }\n\n    return this._getOrWaitObject(networkRef)\n  }\n\n  async editPif(pifId, { vlan }) {\n    const pif = this.getObject(pifId)\n    const physPif = find(\n      this.objects.all,\n      obj =>\n        obj.$type === 'PIF' &&\n        (obj.physical || !isEmpty(obj.bond_master_of)) &&\n        obj.$pool === pif.$pool &&\n        obj.device === pif.device\n    )\n\n    if (!physPif) {\n      throw new Error('PIF not found')\n    }\n\n    const pifs = this.getObject(pif.network).$PIFs\n\n    const wasAttached = {}\n    forEach(pifs, pif => {\n      wasAttached[pif.host] = pif.currently_attached\n    })\n\n    const vlans = uniq(pifs.map(pif => pif.VLAN_master_of))\n    await Promise.all(vlans.map(vlan => Ref.isNotEmpty(vlan) && this.callAsync('VLAN.destroy', vlan)))\n\n    const newPifs = await this.call('pool.create_VLAN_from_PIF', physPif.$ref, pif.network, asInteger(vlan))\n    await Promise.all(\n      newPifs.map(\n        pifRef => !wasAttached[this.getObject(pifRef).host] && this.callAsync('PIF.unplug', pifRef)::ignoreErrors()\n      )\n    )\n  }\n\n  @decorateWith(deferrable)\n  async createBondedNetwork($defer, { bondMode, pifIds: masterPifIds, ...params }) {\n    const network = await this.createNetwork(params)\n    $defer.onFailure(() => this.deleteNetwork(network))\n\n    const pifsByHost = {}\n    masterPifIds.forEach(pifId => {\n      this.getObject(pifId).$network.$PIFs.forEach(pif => {\n        if (pifsByHost[pif.host] === undefined) {\n          pifsByHost[pif.host] = []\n        }\n        pifsByHost[pif.host].push(pif.$ref)\n      })\n    })\n\n    await asyncMapSettled(pifsByHost, pifs => this.call('Bond.create', network.$ref, pifs, '', bondMode))\n\n    return network\n  }\n\n  async deleteNetwork(networkId) {\n    const network = this.getObject(networkId)\n    const pifs = network.$PIFs\n\n    const vlans = uniq(pifs.map(pif => pif.VLAN_master_of))\n    await Promise.all(vlans.map(vlan => Ref.isNotEmpty(vlan) && this.callAsync('VLAN.destroy', vlan)))\n\n    const bonds = uniq(flatten(pifs.map(pif => pif.bond_master_of)))\n    await Promise.all(bonds.map(bond => this.call('Bond.destroy', bond)))\n\n    const tunnels = filter(this.objects.all, { $type: 'tunnel' })\n    await Promise.all(\n      pifs.map(async pif => {\n        const tunnel = find(tunnels, { access_PIF: pif.$ref })\n        if (tunnel != null) {\n          await this.callAsync('tunnel.destroy', tunnel.$ref)\n        }\n      })\n    )\n\n    await this.callAsync('network.destroy', network.$ref)\n  }\n\n  // =================================================================\n\n  async _doDockerAction(vmId, action, containerId) {\n    const vm = this.getObject(vmId)\n    const host = vm.$resident_on || this.pool.$master\n\n    return /* await */ this.call('host.call_plugin', host.$ref, 'xscontainer', action, {\n      vmuuid: vm.uuid,\n      container: containerId,\n    })\n  }\n\n  async registerDockerContainer(vmId) {\n    await this._doDockerAction(vmId, 'register')\n  }\n\n  async deregisterDockerContainer(vmId) {\n    await this._doDockerAction(vmId, 'deregister')\n  }\n\n  async startDockerContainer(vmId, containerId) {\n    await this._doDockerAction(vmId, 'start', containerId)\n  }\n\n  async stopDockerContainer(vmId, containerId) {\n    await this._doDockerAction(vmId, 'stop', containerId)\n  }\n\n  async restartDockerContainer(vmId, containerId) {\n    await this._doDockerAction(vmId, 'restart', containerId)\n  }\n\n  async pauseDockerContainer(vmId, containerId) {\n    await this._doDockerAction(vmId, 'pause', containerId)\n  }\n\n  async unpauseDockerContainer(vmId, containerId) {\n    await this._doDockerAction(vmId, 'unpause', containerId)\n  }\n\n  async getCloudInitConfig(templateId) {\n    const template = this.getObject(templateId)\n    const host = this.pool.$master\n\n    const config = await this.call('host.call_plugin', host.$ref, 'xscontainer', 'get_config_drive_default', {\n      templateuuid: template.uuid,\n    })\n    return config.slice(4) // FIXME remove the \"True\" string on the beginning\n  }\n\n  // Specific CoreOS Config Drive\n  async createCoreOsCloudInitConfigDrive(vmId, srId, config) {\n    const vm = this.getObject(vmId)\n    const host = this.pool.$master\n    const sr = this.getObject(srId)\n\n    // See https://github.com/xenserver/xscontainer/blob/master/src/scripts/xscontainer-pluginexample\n    const vdiUuid = (\n      await this.call('host.call_plugin', host.$ref, 'xscontainer', 'create_config_drive', {\n        vmuuid: vm.uuid,\n        sruuid: sr.uuid,\n        configuration: config,\n      })\n    ).replace(/^True/, '')\n    await this.registerDockerContainer(vmId)\n\n    return vdiUuid\n  }\n\n  // Generic Config Drive\n  @decorateWith(deferrable)\n  async createCloudInitConfigDrive($defer, vmId, srId, userConfig, networkConfig) {\n    const vm = this.getObject(vmId)\n    const sr = this.getObject(srId)\n\n    // First, create a small VDI (10MB) which will become the ConfigDrive\n    const fsLabel = 'cidata     '\n    let buffer = fatfsBufferInit({ label: fsLabel })\n\n    // Then, generate a FAT fs\n    const { createLabel, mkdir, writeFile } = promisifyAll(fatfs.createFileSystem(fatfsBuffer(buffer)))\n\n    await Promise.all([\n      // preferred datasource: NoCloud\n      //\n      // https://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html\n      writeFile('meta-data', 'instance-id: ' + vm.uuid + '\\n'),\n      writeFile('user-data', userConfig),\n      networkConfig !== undefined && writeFile('network-config', networkConfig),\n\n      // fallback datasource: Config Drive 2\n      //\n      // https://cloudinit.readthedocs.io/en/latest/topics/datasources/configdrive.html#version-2\n      mkdir('openstack').then(() =>\n        mkdir('openstack/latest').then(() =>\n          Promise.all([\n            writeFile('openstack/latest/meta_data.json', JSON.stringify({ uuid: vm.uuid })),\n            writeFile('openstack/latest/user_data', userConfig),\n          ])\n        )\n      ),\n      createLabel(fsLabel),\n    ])\n    // only add the MBR for windows VM\n    if (vm.platform.viridian === 'true') {\n      buffer = addMbr(buffer)\n    }\n    const vdi = await this._getOrWaitObject(\n      await this.VDI_create({\n        name_label: 'XO CloudConfigDrive',\n        SR: sr.$ref,\n        virtual_size: buffer.length,\n      })\n    )\n    $defer.onFailure(() => vdi.$destroy())\n\n    // ignore errors, I (JFT) don't understand why they are emitted\n    // because it works\n    await vdi.$importContent(buffer, { format: VDI_FORMAT_RAW }).catch(error => {\n      log.warn('importVdiContent: ', { error })\n    })\n\n    await this.VBD_create({ VDI: vdi.$ref, VM: vm.$ref })\n\n    return vdi.uuid\n  }\n\n  @decorateWith(deferrable)\n  async createTemporaryVdiOnSr($defer, stream, sr, name_label, name_description) {\n    const vdi = await this._getOrWaitObject(\n      await this.VDI_create({\n        name_description,\n        name_label,\n        SR: sr.$ref,\n        virtual_size: stream.length,\n      })\n    )\n    $defer.onFailure(() => vdi.$destroy())\n\n    await vdi.$importContent(stream, { format: VDI_FORMAT_RAW })\n\n    return vdi\n  }\n\n  // Create VDI on an adequate local SR\n  async createTemporaryVdiOnHost(stream, hostId, name_label, name_description) {\n    const pbd = find(this.getObject(hostId).$PBDs, pbd => canSrHaveNewVdiOfSize(pbd.$SR, stream.length))\n\n    if (pbd == null) {\n      throw new Error('no SR available')\n    }\n\n    return this.createTemporaryVdiOnSr(stream, pbd.$SR, name_label, name_description)\n  }\n\n  findAvailableSharedSr(minSize) {\n    return find(this.objects.all, obj => obj.$type === 'SR' && obj.shared && canSrHaveNewVdiOfSize(obj, minSize))\n  }\n\n  // Main purpose: upload update on VDI\n  // Is a local SR on a non master host OK?\n  findAvailableSr(minSize) {\n    return find(this.objects.all, obj => obj.$type === 'SR' && canSrHaveNewVdiOfSize(obj, minSize))\n  }\n\n  @decorateWith(debounceWithKey, 60e3, hostRef => hostRef)\n  async _getHostServerTimeShift(hostRef) {\n    return Math.abs(parseDateTime(await this.call('host.get_servertime', hostRef)) * 1e3 - Date.now())\n  }\n\n  async isHostServerTimeConsistent(hostRef) {\n    return (await this._getHostServerTimeShift(hostRef)) < 30e3\n  }\n\n  async assertConsistentHostServerTime(hostRef) {\n    if (!(await this.isHostServerTimeConsistent(hostRef))) {\n      throw new Error(\n        `host server time and XOA date are not consistent with each other (${ms(\n          await this._getHostServerTimeShift(hostRef)\n        )})`\n      )\n    }\n  }\n\n  async isHyperThreadingEnabled(hostId) {\n    const host = this.getObject(hostId)\n\n    // For XCP-ng >=8.3, data is already available in XAPI\n    const { threads_per_core } = host.cpu_info\n    if (threads_per_core !== undefined) {\n      return threads_per_core > 1\n    }\n\n    try {\n      return (await this.call('host.call_plugin', host.$ref, 'hyperthreading.py', 'get_hyperthreading', {})) !== 'false'\n    } catch (error) {\n      if (error.code === 'XENAPI_MISSING_PLUGIN' || error.code === 'UNKNOWN_XENAPI_PLUGIN_FUNCTION') {\n        return null\n      } else {\n        throw error\n      }\n    }\n  }\n\n  async getSmartctlHealth(hostId) {\n    try {\n      return JSON.parse(await this.call('host.call_plugin', this.getObject(hostId).$ref, 'smartctl.py', 'health', {}))\n    } catch (error) {\n      if (error.code === 'XENAPI_MISSING_PLUGIN' || error.code === 'UNKNOWN_XENAPI_PLUGIN_FUNCTION') {\n        return null\n      } else {\n        throw error\n      }\n    }\n  }\n\n  async getSmartctlInformation(hostId, deviceNames) {\n    try {\n      const informations = JSON.parse(\n        await this.call('host.call_plugin', this.getObject(hostId).$ref, 'smartctl.py', 'information', {})\n      )\n      if (deviceNames === undefined) {\n        return informations\n      }\n      return pick(informations, deviceNames)\n    } catch (error) {\n      if (error.code === 'XENAPI_MISSING_PLUGIN' || error.code === 'UNKNOWN_XENAPI_PLUGIN_FUNCTION') {\n        return null\n      } else {\n        throw error\n      }\n    }\n  }\n\n  async getHostBiosInfo(ref, { cache } = {}) {\n    const biosData = await this.call('host.get_bios_strings', ref)\n\n    const { 'bios-version': currentBiosVersion, 'system-product-name': hostServerName } = biosData\n\n    if (biosData['system-manufacturer']?.toLowerCase() !== '2crsi') {\n      return\n    }\n\n    // this code has race conditions which might lead to multiple fetches in parallel\n    // but it's no big deal\n    let servers\n    if (!cache?.has('servers')) {\n      const response = await fetch(\n        'https://pictures.2cr.si/Images_site_web_Odoo/Pages_produit/VATES-BIOS_BMC_last-version.json'\n      )\n      const json = await response.json()\n      servers = keyBy(json[0]['2CRSi_Servers'], 'Server_Name')\n\n      cache?.set('servers', servers)\n    } else {\n      servers = cache.get('servers')\n    }\n\n    const serverData = servers[hostServerName]\n\n    if (serverData === undefined) {\n      return\n    }\n\n    const { 'BIOS-Version': latestBiosVersion, 'BIOS-link': biosLink } = serverData\n\n    // Compare versions loosely to handle non-standard formats\n    const isUpToDate = semver.eq(currentBiosVersion, latestBiosVersion, { loose: true })\n\n    return { currentBiosVersion, latestBiosVersion, biosLink, isUpToDate }\n  }\n}\n"],"mappings":";;AAEA,OA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,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,wCAAAre,KAAA,GAAAP,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,wCAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,mBAAApe,KAAA,GAAAR,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,mBAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,oBAAAne,KAAA,GAAAT,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,oBAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,0BAAAle,KAAA,GAAAV,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,0BAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,iCAAAje,KAAA,GAAAX,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,iCAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,6BAAAhe,MAAA,GAAAZ,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,6BAAA5d,OAAA,CAAA4d,SAAA,GAAAD,yBAAA,CAAA3d,OAAA,CAAA4d,SAAA,8BAAA/d,MAAA,GAAAb,MAAA,CAAA6e,wBAAA,CAAA7d,OAAA,CAAA4d,SAAA,8BAAA5d,OAAA,CAAA4d,SAAA,GAAA5d,OAAA,MAAAD,MAAA;AAAA,SA/WQjD,IAAI,IAAAghB,OAAA","ignoreList":[]}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         const Definition = require('./definition.js')

const ciInfo = require('ci-info')
const querystring = require('node:querystring')
const { join } = require('node:path')

const isWindows = process.platform === 'win32'

// used by cafile flattening to flatOptions.ca
const { readFileSync } = require('node:fs')
const maybeReadFile = file => {
  try {
    return readFileSync(file, 'utf8')
  } catch (er) {
    if (er.code !== 'ENOENT') {
      throw er
    }
    return null
  }
}

const buildOmitList = obj => {
  const include = obj.include || []
  const omit = obj.omit || []

  const only = obj.only
  if (/^prod(uction)?$/.test(only) || obj.production) {
    omit.push('dev')
  } else if (obj.production === false) {
    include.push('dev')
  }

  if (/^dev/.test(obj.also)) {
    include.push('dev')
  }

  if (obj.dev) {
    include.push('dev')
  }

  if (obj.optional === false) {
    omit.push('optional')
  } else if (obj.optional === true) {
    include.push('optional')
  }

  obj.omit = [...new Set(omit)].filter(type => !include.includes(type))
  obj.include = [...new Set(include)]

  if (obj.omit.includes('dev')) {
    process.env.NODE_ENV = 'production'
  }

  return obj.omit
}

const editor = process.env.EDITOR ||
  process.env.VISUAL ||
  (isWindows ? `${process.env.SYSTEMROOT}\\notepad.exe` : 'vi')

const shell = isWindows ? process.env.ComSpec || 'cmd'
  : process.env.SHELL || 'sh'

const { networkInterfaces } = require('node:os')
const getLocalAddresses = () => {
  try {
    return Object.values(networkInterfaces()).map(
      int => int.map(({ address }) => address)
    ).reduce((set, addrs) => set.concat(addrs), [null])
  } catch (e) {
    return [null]
  }
}

const unicode = /UTF-?8$/i.test(
  process.env.LC_ALL ||
  process.env.LC_CTYPE ||
  process.env.LANG
)

// use LOCALAPPDATA on Windows, if set
// https://github.com/npm/cli/pull/899
const cacheRoot = (isWindows && process.env.LOCALAPPDATA) || '~'
const cacheExtra = isWindows ? 'npm-cache' : '.npm'
const cache = `${cacheRoot}/${cacheExtra}`

// TODO: refactor these type definitions so that they are less
// weird to pull out of the config module.
// TODO: use better type definition/validation API, nopt's is so weird.
const {
  semver: { type: Semver },
  Umask: { type: Umask },
  url: { type: url },
  path: { type: path },
} = require('../type-defs.js')

// basic flattening function, just copy it over camelCase
const flatten = (key, obj, flatOptions) => {
  const camel = key.replace(/-([a-z])/g, (_0, _1) => _1.toUpperCase())
  flatOptions[camel] = obj[key]
}

// TODO:
// Instead of having each definition provide a flatten method,
// provide the (?list of?) flat option field(s?) that it impacts.
// When that config is set, we mark the relevant flatOption fields
// dirty.  Then, a getter for that field defines how we actually
// set it.
//
// So, `save-dev`, `save-optional`, `save-prod`, et al would indicate
// that they affect the `saveType` flat option.  Then the config.flat
// object has a `get saveType () { ... }` that looks at the "real"
// config settings from files etc and returns the appropriate value.
//
// Getters will also (maybe?) give us a hook to audit flat option
// usage, so we can document and group these more appropriately.
//
// This will be a problem with cases where we currently do:
// const opts = { ...npm.flatOptions, foo: 'bar' }, but we can maybe
// instead do `npm.config.set('foo', 'bar')` prior to passing the
// config object down where it needs to go.
//
// This way, when we go hunting for "where does saveType come from anyway!?"
// while fixing some Arborist bug, we won't have to hunt through too
// many places.

// XXX: We should really deprecate all these `--save-blah` switches
// in favor of a single `--save-type` option.  The unfortunate shortcut
// we took for `--save-peer --save-optional` being `--save-type=peerOptional`
// makes this tricky, and likely a breaking change.

// Define all config keys we know about.  They are indexed by their own key for
// ease of lookup later.  This duplication is an optimization so that we don't
// have to do an extra function call just to "reuse" the key in both places.

const definitions = {
  _auth: new Definition('_auth', {
    default: null,
    type: [null, String],
    description: `
    A basic-auth string to use when authenticating against the npm registry.
    This will ONLY be used to authenticate against the npm registry.  For other
    registries you will need to scope it like "//other-registry.tld/:_auth"

    Warning: This should generally not be set via a command-line option.  It
    is safer to use a registry-provided authentication bearer token stored in
    the ~/.npmrc file by running \`npm login\`.
  `,
    flatten,
  }),
  access: new Definition('access', {
    default: null,
    defaultDescription: `
    'public' for new packages, existing packages it will not change the current level
  `,
    type: [null, 'restricted', 'public'],
    description: `
    If you do not want your scoped package to be publicly viewable (and
    installable) set \`--access=restricted\`.

    Unscoped packages can not be set to \`restricted\`.

    Note: This defaults to not changing the current access level for existing
    packages.  Specifying a value of \`restricted\` or \`public\` during
    publish will change the access for an existing package the same way that
    \`npm access set status\` would.
  `,
    flatten,
  }),
  all: new Definition('all', {
    default: false,
    type: Boolean,
    short: 'a',
    description: `
    When running \`npm outdated\` and \`npm ls\`, setting \`--all\` will show
    all outdated or installed packages, rather than only those directly
    depended upon by the current project.
  `,
    flatten,
  }),
  'allow-same-version': new Definition('allow-same-version', {
    default: false,
    type: Boolean,
    description: `
    Prevents throwing an error when \`npm version\` is used to set the new
    version to the same value as the current version.
  `,
    flatten,
  }),
  also: new Definition('also', {
    default: null,
    type: [null, 'dev', 'development'],
    description: `
      When set to \`dev\` or \`development\`, this is an alias for
      \`--include=dev\`.
    `,
    deprecated: 'Please use --include=dev instead.',
    flatten (key, obj, flatOptions) {
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  audit: new Definition('audit', {
    default: true,
    type: Boolean,
    description: `
      When "true" submit audit reports alongside the current npm command to the
      default registry and all registries configured for scopes.  See the
      documentation for [\`npm audit\`](/commands/npm-audit) for details on what
      is submitted.
    `,
    flatten,
  }),
  'audit-level': new Definition('audit-level', {
    default: null,
    type: [null, 'info', 'low', 'moderate', 'high', 'critical', 'none'],
    description: `
    The minimum level of vulnerability for \`npm audit\` to exit with
    a non-zero exit code.
    `,
    flatten,
  }),
  'auth-type': new Definition('auth-type', {
    default: 'web',
    type: ['legacy', 'web'],
    description: `
      What authentication strategy to use with \`login\`.
      Note that if an \`otp\` config is given, this value will always be set to \`legacy\`.
    `,
    flatten,
  }),
  before: new Definition('before', {
    default: null,
    type: [null, Date],
    description: `
      If passed to \`npm install\`, will rebuild the npm tree such that only
      versions that were available **on or before** the \`--before\` time get
      installed.  If there's no versions available for the current set of
      direct dependencies, the command will error.

      If the requested version is a \`dist-tag\` and the given tag does not
      pass the \`--before\` filter, the most recent version less than or equal
      to that tag will be used. For example, \`foo@latest\` might install
      \`foo@1.2\` even though \`latest\` is \`2.0\`.
    `,
    flatten,
  }),
  'bin-links': new Definition('bin-links', {
    default: true,
    type: Boolean,
    description: `
      Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package
      executables.

      Set to false to have it not do this.  This can be used to work around the
      fact that some file systems don't support symlinks, even on ostensibly
      Unix systems.
    `,
    flatten,
  }),
  browser: new Definition('browser', {
    default: null,
    defaultDescription: `
    OS X: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\`
    `,
    type: [null, Boolean, String],
    description: `
    The browser that is called by npm commands to open websites.

    Set to \`false\` to suppress browser behavior and instead print urls to
    terminal.

    Set to \`true\` to use default system URL opener.
    `,
    flatten,
  }),
  ca: new Definition('ca', {
    default: null,
    type: [null, String, Array],
    description: `
    The Certificate Authority signing certificate that is trusted for SSL
    connections to the registry. Values should be in PEM format (Windows
      calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the
    string "\\n". For example:

    \`\`\`ini
    ca="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
    \`\`\`

    Set to \`null\` to only allow "known" registrars, or to a specific CA
    cert to trust only that specific signing authority.

    Multiple CAs can be trusted by specifying an array of certificates:

    \`\`\`ini
    ca[]="..."
    ca[]="..."
    \`\`\`

    See also the \`strict-ssl\` config.
  `,
    flatten,
  }),
  cache: new Definition('cache', {
    default: cache,
    defaultDescription: `
      Windows: \`%LocalAppData%\\npm-cache\`, Posix: \`~/.npm\`
    `,
    type: path,
    description: `
      The location of npm's cache directory.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.cache = join(obj.cache, '_cacache')
      flatOptions.npxCache = join(obj.cache, '_npx')
      flatOptions.tufCache = join(obj.cache, '_tuf')
    },
  }),
  'cache-max': new Definition('cache-max', {
    default: Infinity,
    type: Number,
    description: `
      \`--cache-max=0\` is an alias for \`--prefer-online\`
    `,
    deprecated: `
      This option has been deprecated in favor of \`--prefer-online\`
    `,
    flatten (key, obj, flatOptions) {
      if (obj[key] <= 0) {
        flatOptions.preferOnline = true
      }
    },
  }),
  'cache-min': new Definition('cache-min', {
    default: 0,
    type: Number,
    description: `
      \`--cache-min=9999 (or bigger)\` is an alias for \`--prefer-offline\`.
    `,
    deprecated: `
      This option has been deprecated in favor of \`--prefer-offline\`.
    `,
    flatten (key, obj, flatOptions) {
      if (obj[key] >= 9999) {
        flatOptions.preferOffline = true
      }
    },
  }),
  cafile: new Definition('cafile', {
    default: null,
    type: path,
    description: `
      A path to a file containing one or multiple Certificate Authority signing
      certificates. Similar to the \`ca\` setting, but allows for multiple
      CA's, as well as for the CA information to be stored in a file on disk.
    `,
    flatten (key, obj, flatOptions) {
      // always set to null in defaults
      if (!obj.cafile) {
        return
      }

      const raw = maybeReadFile(obj.cafile)
      if (!raw) {
        return
      }

      const delim = '-----END CERTIFICATE-----'
      flatOptions.ca = raw.replace(/\r\n/g, '\n').split(delim)
        .filter(section => section.trim())
        .map(section => section.trimLeft() + delim)
    },
  }),
  call: new Definition('call', {
    default: '',
    type: String,
    short: 'c',
    description: `
      Optional companion option for \`npm exec\`, \`npx\` that allows for
      specifying a custom command to be run along with the installed packages.

      \`\`\`bash
      npm exec --package yo --package generator-node --call "yo node"
      \`\`\`
    `,
    flatten,
  }),
  cert: new Definition('cert', {
    default: null,
    type: [null, String],
    description: `
      A client certificate to pass when accessing the registry.  Values should
      be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with
      newlines replaced by the string "\\n". For example:

      \`\`\`ini
      cert="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----"
      \`\`\`

      It is _not_ the path to a certificate file, though you can set a registry-scoped
      "certfile" path like "//other-registry.tld/:certfile=/path/to/cert.pem".
    `,
    deprecated: `
      \`key\` and \`cert\` are no longer used for most registry operations.
      Use registry scoped \`keyfile\` and \`certfile\` instead.
      Example:
      //other-registry.tld/:keyfile=/path/to/key.pem
      //other-registry.tld/:certfile=/path/to/cert.crt
    `,
    flatten,
  }),
  cidr: new Definition('cidr', {
    default: null,
    type: [null, String, Array],
    description: `
      This is a list of CIDR address to be used when configuring limited access
      tokens with the \`npm token create\` command.
    `,
    flatten,
  }),
  // This should never be directly used, the flattened value is the derived value
  // and is sent to other modules, and is also exposed as `npm.color` for use
  // inside npm itself.
  color: new Definition('color', {
    default: !process.env.NO_COLOR || process.env.NO_COLOR === '0',
    usage: '--color|--no-color|--color always',
    defaultDescription: `
      true unless the NO_COLOR environ is set to something other than '0'
    `,
    type: ['always', Boolean],
    description: `
      If false, never shows colors.  If \`"always"\` then always shows colors.
      If true, then only prints color codes for tty file descriptors.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.color = !obj.color ? false
        : obj.color === 'always' ? true
        : !!process.stdout.isTTY
      flatOptions.logColor = !obj.color ? false
        : obj.color === 'always' ? true
        : !!process.stderr.isTTY
    },
  }),
  'commit-hooks': new Definition('commit-hooks', {
    default: true,
    type: Boolean,
    description: `
      Run git commit hooks when using the \`npm version\` command.
    `,
    flatten,
  }),
  cpu: new Definition('cpu', {
    default: null,
    type: [null, String],
    description: `
      Override CPU architecture of native modules to install.
      Acceptable values are same as \`cpu\` field of package.json,
      which comes from \`process.arch\`.
    `,
    flatten,
  }),
  depth: new Definition('depth', {
    default: null,
    defaultDescription: `
      \`Infinity\` if \`--all\` is set, otherwise \`1\`
    `,
    type: [null, Number],
    description: `
      The depth to go when recursing packages for \`npm ls\`.

      If not set, \`npm ls\` will show only the immediate dependencies of the
      root project.  If \`--all\` is set, then npm will show all dependencies
      by default.
    `,
    flatten,
  }),
  description: new Definition('description', {
    default: true,
    type: Boolean,
    usage: '--no-description',
    description: `
      Show the description in \`npm search\`
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.search = flatOptions.search || { limit: 20 }
      flatOptions.search[key] = obj[key]
    },
  }),
  dev: new Definition('dev', {
    default: false,
    type: Boolean,
    description: `
      Alias for \`--include=dev\`.
    `,
    deprecated: 'Please use --include=dev instead.',
    flatten (key, obj, flatOptions) {
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  diff: new Definition('diff', {
    default: [],
    hint: '<package-spec>',
    type: [String, Array],
    description: `
      Define arguments to compare in \`npm diff\`.
    `,
    flatten,
  }),
  'diff-ignore-all-space': new Definition('diff-ignore-all-space', {
    default: false,
    type: Boolean,
    description: `
      Ignore whitespace when comparing lines in \`npm diff\`.
    `,
    flatten,
  }),
  'diff-name-only': new Definition('diff-name-only', {
    default: false,
    type: Boolean,
    description: `
      Prints only filenames when using \`npm diff\`.
    `,
    flatten,
  }),
  'diff-no-prefix': new Definition('diff-no-prefix', {
    default: false,
    type: Boolean,
    description: `
      Do not show any source or destination prefix in \`npm diff\` output.

      Note: this causes \`npm diff\` to ignore the \`--diff-src-prefix\` and
      \`--diff-dst-prefix\` configs.
    `,
    flatten,
  }),
  'diff-dst-prefix': new Definition('diff-dst-prefix', {
    default: 'b/',
    hint: '<path>',
    type: String,
    description: `
      Destination prefix to be used in \`npm diff\` output.
    `,
    flatten,
  }),
  'diff-src-prefix': new Definition('diff-src-prefix', {
    default: 'a/',
    hint: '<path>',
    type: String,
    description: `
      Source prefix to be used in \`npm diff\` output.
    `,
    flatten,
  }),
  'diff-text': new Definition('diff-text', {
    default: false,
    type: Boolean,
    description: `
      Treat all files as text in \`npm diff\`.
    `,
    flatten,
  }),
  'diff-unified': new Definition('diff-unified', {
    default: 3,
    type: Number,
    description: `
      The number of lines of context to print in \`npm diff\`.
    `,
    flatten,
  }),
  'dry-run': new Definition('dry-run', {
    default: false,
    type: Boolean,
    description: `
      Indicates that you don't want npm to make any changes and that it should
      only report what it would have done.  This can be passed into any of the
      commands that modify your local installation, eg, \`install\`,
      \`update\`, \`dedupe\`, \`uninstall\`, as well as \`pack\` and
      \`publish\`.

      Note: This is NOT honored by other network related commands, eg
      \`dist-tags\`, \`owner\`, etc.
    `,
    flatten,
  }),
  editor: new Definition('editor', {
    default: editor,
    defaultDescription: `
      The EDITOR or VISUAL environment variables, or '%SYSTEMROOT%\\notepad.exe' on Windows,
      or 'vi' on Unix systems
    `,
    type: String,
    description: `
      The command to run for \`npm edit\` and \`npm config edit\`.
    `,
    flatten,
  }),
  'engine-strict': new Definition('engine-strict', {
    default: false,
    type: Boolean,
    description: `
      If set to true, then npm will stubbornly refuse to install (or even
      consider installing) any package that claims to not be compatible with
      the current Node.js version.

      This can be overridden by setting the \`--force\` flag.
    `,
    flatten,
  }),
  'expect-result-count': new Definition('expect-result-count', {
    default: null,
    type: [null, Number],
    hint: '<count>',
    exclusive: ['expect-results'],
    description: `
      Tells to expect a specific number of results from the command.
    `,
  }),
  'expect-results': new Definition('expect-results', {
    default: null,
    type: [null, Boolean],
    exclusive: ['expect-result-count'],
    description: `
      Tells npm whether or not to expect results from the command.
      Can be either true (expect some results) or false (expect no results).
    `,
  }),
  'fetch-retries': new Definition('fetch-retries', {
    default: 2,
    type: Number,
    description: `
      The "retries" config for the \`retry\` module to use when fetching
      packages from the registry.

      npm will retry idempotent read requests to the registry in the case
      of network failures or 5xx HTTP errors.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.retry = flatOptions.retry || {}
      flatOptions.retry.retries = obj[key]
    },
  }),
  'fetch-retry-factor': new Definition('fetch-retry-factor', {
    default: 10,
    type: Number,
    description: `
      The "factor" config for the \`retry\` module to use when fetching
      packages.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.retry = flatOptions.retry || {}
      flatOptions.retry.factor = obj[key]
    },
  }),
  'fetch-retry-maxtimeout': new Definition('fetch-retry-maxtimeout', {
    default: 60000,
    defaultDescription: '60000 (1 minute)',
    type: Number,
    description: `
      The "maxTimeout" config for the \`retry\` module to use when fetching
      packages.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.retry = flatOptions.retry || {}
      flatOptions.retry.maxTimeout = obj[key]
    },
  }),
  'fetch-retry-mintimeout': new Definition('fetch-retry-mintimeout', {
    default: 10000,
    defaultDescription: '10000 (10 seconds)',
    type: Number,
    description: `
      The "minTimeout" config for the \`retry\` module to use when fetching
      packages.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.retry = flatOptions.retry || {}
      flatOptions.retry.minTimeout = obj[key]
    },
  }),
  'fetch-timeout': new Definition('fetch-timeout', {
    default: 5 * 60 * 1000,
    defaultDescription: `${5 * 60 * 1000} (5 minutes)`,
    type: Number,
    description: `
      The maximum amount of time to wait for HTTP requests to complete.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.timeout = obj[key]
    },
  }),
  force: new Definition('force', {
    default: false,
    type: Boolean,
    short: 'f',
    description: `
      Removes various protections against unfortunate side effects, common
      mistakes, unnecessary performance degradation, and malicious input.

      * Allow clobbering non-npm files in global installs.
      * Allow the \`npm version\` command to work on an unclean git repository.
      * Allow deleting the cache folder with \`npm cache clean\`.
      * Allow installing packages that have an \`engines\` declaration
        requiring a different version of npm.
      * Allow installing packages that have an \`engines\` declaration
        requiring a different version of \`node\`, even if \`--engine-strict\`
        is enabled.
      * Allow \`npm audit fix\` to install modules outside your stated
        dependency range (including SemVer-major changes).
      * Allow unpublishing all versions of a published package.
      * Allow conflicting peerDependencies to be installed in the root project.
      * Implicitly set \`--yes\` during \`npm init\`.
      * Allow clobbering existing values in \`npm pkg\`
      * Allow unpublishing of entire packages (not just a single version).

      If you don't have a clear idea of what you want to do, it is strongly
      recommended that you do not use this option!
    `,
    flatten,
  }),
  'foreground-scripts': new Definition('foreground-scripts', {
    default: false,
    defaultDescription: `\`false\` unless when using \`npm pack\` or \`npm publish\` where it
    defaults to \`true\``,
    type: Boolean,
    description: `
      Run all build scripts (ie, \`preinstall\`, \`install\`, and
      \`postinstall\`) scripts for installed packages in the foreground
      process, sharing standard input, output, and error with the main npm
      process.

      Note that this will generally make installs run slower, and be much
      noisier, but can be useful for debugging.
    `,
    flatten,
  }),
  'format-package-lock': new Definition('format-package-lock', {
    default: true,
    type: Boolean,
    description: `
      Format \`package-lock.json\` or \`npm-shrinkwrap.json\` as a human
      readable file.
    `,
    flatten,
  }),
  fund: new Definition('fund', {
    default: true,
    type: Boolean,
    description: `
      When "true" displays the message at the end of each \`npm install\`
      acknowledging the number of dependencies looking for funding.
      See [\`npm fund\`](/commands/npm-fund) for details.
    `,
    flatten,
  }),
  git: new Definition('git', {
    default: 'git',
    type: String,
    description: `
      The command to use for git commands.  If git is installed on the
      computer, but is not in the \`PATH\`, then set this to the full path to
      the git binary.
    `,
    flatten,
  }),
  'git-tag-version': new Definition('git-tag-version', {
    default: true,
    type: Boolean,
    description: `
      Tag the commit when using the \`npm version\` command.  Setting this to
      false results in no commit being made at all.
    `,
    flatten,
  }),
  global: new Definition('global', {
    default: false,
    type: Boolean,
    short: 'g',
    description: `
      Operates in "global" mode, so that packages are installed into the
      \`prefix\` folder instead of the current working directory.  See
      [folders](/configuring-npm/folders) for more on the differences in
      behavior.

      * packages are installed into the \`{prefix}/lib/node_modules\` folder,
        instead of the current working directory.
      * bin files are linked to \`{prefix}/bin\`
      * man pages are linked to \`{prefix}/share/man\`
    `,
    flatten: (key, obj, flatOptions) => {
      flatten(key, obj, flatOptions)
      if (flatOptions.global) {
        flatOptions.location = 'global'
      }
    },
  }),
  // the globalconfig has its default defined outside of this module
  globalconfig: new Definition('globalconfig', {
    type: path,
    default: '',
    defaultDescription: `
      The global --prefix setting plus 'etc/npmrc'. For example,
      '/usr/local/etc/npmrc'
    `,
    description: `
      The config file to read for global config options.
    `,
    flatten,
  }),
  'global-style': new Definition('global-style', {
    default: false,
    type: Boolean,
    description: `
      Only install direct dependencies in the top level \`node_modules\`,
      but hoist on deeper dependencies.
      Sets \`--install-strategy=shallow\`.
    `,
    deprecated: `
      This option has been deprecated in favor of \`--install-strategy=shallow\`
    `,
    flatten (key, obj, flatOptions) {
      if (obj[key]) {
        obj['install-strategy'] = 'shallow'
        flatOptions.installStrategy = 'shallow'
      }
    },
  }),
  heading: new Definition('heading', {
    default: 'npm',
    type: String,
    description: `
      The string that starts all the debugging log output.
    `,
    flatten,
  }),
  'https-proxy': new Definition('https-proxy', {
    default: null,
    type: [null, url],
    description: `
      A proxy to use for outgoing https requests. If the \`HTTPS_PROXY\` or
      \`https_proxy\` or \`HTTP_PROXY\` or \`http_proxy\` environment variables
      are set, proxy settings will be honored by the underlying
      \`make-fetch-happen\` library.
    `,
    flatten,
  }),
  'if-present': new Definition('if-present', {
    default: false,
    type: Boolean,
    envExport: false,
    description: `
      If true, npm will not exit with an error code when \`run-script\` is
      invoked for a script that isn't defined in the \`scripts\` section of
      \`package.json\`. This option can be used when it's desirable to
      optionally run a script when it's present and fail if the script fails.
      This is useful, for example, when running scripts that may only apply for
      some builds in an otherwise generic CI setup.
    `,
    flatten,
  }),
  'ignore-scripts': new Definition('ignore-scripts', {
    default: false,
    type: Boolean,
    description: `
      If true, npm does not run scripts specified in package.json files.

      Note that commands explicitly intended to run a particular script, such
      as \`npm start\`, \`npm stop\`, \`npm restart\`, \`npm test\`, and \`npm
      run-script\` will still run their intended script if \`ignore-scripts\` is
      set, but they will *not* run any pre- or post-scripts.
    `,
    flatten,
  }),
  include: new Definition('include', {
    default: [],
    type: [Array, 'prod', 'dev', 'optional', 'peer'],
    description: `
      Option that allows for defining which types of dependencies to install.

      This is the inverse of \`--omit=<type>\`.

      Dependency types specified in \`--include\` will not be omitted,
      regardless of the order in which omit/include are specified on the
      command-line.
    `,
    flatten (key, obj, flatOptions) {
      // just call the omit flattener, it reads from obj.include
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  'include-staged': new Definition('include-staged', {
    default: false,
    type: Boolean,
    description: `
      Allow installing "staged" published packages, as defined by [npm RFC PR
      #92](https://github.com/npm/rfcs/pull/92).

      This is experimental, and not implemented by the npm public registry.
    `,
    flatten,
  }),
  'include-workspace-root': new Definition('include-workspace-root', {
    default: false,
    type: Boolean,
    envExport: false,
    description: `
      Include the workspace root when workspaces are enabled for a command.

      When false, specifying individual workspaces via the \`workspace\` config,
      or all workspaces via the \`workspaces\` flag, will cause npm to operate only
      on the specified workspaces, and not on the root project.
    `,
    flatten,
  }),
  'init-author-email': new Definition('init-author-email', {
    default: '',
    hint: '<email>',
    type: String,
    description: `
      The value \`npm init\` should use by default for the package author's
      email.
    `,
  }),
  'init-author-name': new Definition('init-author-name', {
    default: '',
    hint: '<name>',
    type: String,
    description: `
      The value \`npm init\` should use by default for the package author's name.
    `,
  }),
  'init-author-url': new Definition('init-author-url', {
    default: '',
    type: ['', url],
    hint: '<url>',
    description: `
      The value \`npm init\` should use by default for the package author's homepage.
    `,
  }),
  'init-license': new Definition('init-license', {
    default: 'ISC',
    hint: '<license>',
    type: String,
    description: `
      The value \`npm init\` should use by default for the package license.
    `,
  }),
  'init-module': new Definition('init-module', {
    default: '~/.npm-init.js',
    type: path,
    hint: '<module>',
    description: `
      A module that will be loaded by the \`npm init\` command.  See the
      documentation for the
      [init-package-json](https://github.com/npm/init-package-json) module for
      more information, or [npm init](/commands/npm-init).
    `,
  }),
  'init-version': new Definition('init-version', {
    default: '1.0.0',
    type: Semver,
    hint: '<version>',
    description: `
      The value that \`npm init\` should use by default for the package
      version number, if not already set in package.json.
    `,
  }),
  // these "aliases" are historically supported in .npmrc files, unfortunately
  // They should be removed in a future npm version.
  'init.author.email': new Definition('init.author.email', {
    default: '',
    type: String,
    deprecated: `
      Use \`--init-author-email\` instead.`,
    description: `
      Alias for \`--init-author-email\`
    `,
  }),
  'init.author.name': new Definition('init.author.name', {
    default: '',
    type: String,
    deprecated: `
      Use \`--init-author-name\` instead.
    `,
    description: `
      Alias for \`--init-author-name\`
    `,
  }),
  'init.author.url': new Definition('init.author.url', {
    default: '',
    type: ['', url],
    deprecated: `
      Use \`--init-author-url\` instead.
    `,
    description: `
      Alias for \`--init-author-url\`
    `,
  }),
  'init.license': new Definition('init.license', {
    default: 'ISC',
    type: String,
    deprecated: `
      Use \`--init-license\` instead.
    `,
    description: `
      Alias for \`--init-license\`
    `,
  }),
  'init.module': new Definition('init.module', {
    default: '~/.npm-init.js',
    type: path,
    deprecated: `
      Use \`--init-module\` instead.
    `,
    description: `
      Alias for \`--init-module\`
    `,
  }),
  'init.version': new Definition('init.version', {
    default: '1.0.0',
    type: Semver,
    deprecated: `
      Use \`--init-version\` instead.
    `,
    description: `
      Alias for \`--init-version\`
    `,
  }),
  'install-links': new Definition('install-links', {
    default: false,
    type: Boolean,
    description: `
      When set file: protocol dependencies will be packed and installed as
      regular dependencies instead of creating a symlink. This option has
      no effect on workspaces.
    `,
    flatten,
  }),
  'install-strategy': new Definition('install-strategy', {
    default: 'hoisted',
    type: ['hoisted', 'nested', 'shallow', 'linked'],
    description: `
      Sets the strategy for installing packages in node_modules.
      hoisted (default): Install non-duplicated in top-level, and duplicated as
        necessary within directory structure.
      nested: (formerly --legacy-bundling) install in place, no hoisting.
      shallow (formerly --global-style) only install direct deps at top-level.
      linked: (experimental) install in node_modules/.store, link in place,
        unhoisted.
    `,
    flatten,
  }),
  json: new Definition('json', {
    default: false,
    type: Boolean,
    description: `
      Whether or not to output JSON data, rather than the normal output.

      * In \`npm pkg set\` it enables parsing set values with JSON.parse()
      before saving them to your \`package.json\`.

      Not supported by all npm commands.
    `,
    flatten,
  }),
  key: new Definition('key', {
    default: null,
    type: [null, String],
    description: `
      A client key to pass when accessing the registry.  Values should be in
      PEM format with newlines replaced by the string "\\n". For example:

      \`\`\`ini
      key="-----BEGIN PRIVATE KEY-----\\nXXXX\\nXXXX\\n-----END PRIVATE KEY-----"
      \`\`\`

      It is _not_ the path to a key file, though you can set a registry-scoped
      "keyfile" path like "//other-registry.tld/:keyfile=/path/to/key.pem".
    `,
    deprecated: `
      \`key\` and \`cert\` are no longer used for most registry operations.
      Use registry scoped \`keyfile\` and \`certfile\` instead.
      Example:
      //other-registry.tld/:keyfile=/path/to/key.pem
      //other-registry.tld/:certfile=/path/to/cert.crt
    `,
    flatten,
  }),
  'legacy-bundling': new Definition('legacy-bundling', {
    default: false,
    type: Boolean,
    description: `
      Instead of hoisting package installs in \`node_modules\`, install packages
      in the same manner that they are depended on. This may cause very deep
      directory structures and duplicate package installs as there is no
      de-duplicating.
      Sets \`--install-strategy=nested\`.
    `,
    deprecated: `
      This option has been deprecated in favor of \`--install-strategy=nested\`
    `,
    flatten (key, obj, flatOptions) {
      if (obj[key]) {
        obj['install-strategy'] = 'nested'
        flatOptions.installStrategy = 'nested'
      }
    },
  }),
  'legacy-peer-deps': new Definition('legacy-peer-deps', {
    default: false,
    type: Boolean,
    description: `
      Causes npm to completely ignore \`peerDependencies\` when building a
      package tree, as in npm versions 3 through 6.

      If a package cannot be installed because of overly strict
      \`peerDependencies\` that collide, it provides a way to move forward
      resolving the situation.

      This differs from \`--omit=peer\`, in that \`--omit=peer\` will avoid
      unpacking \`peerDependencies\` on disk, but will still design a tree such
      that \`peerDependencies\` _could_ be unpacked in a correct place.

      Use of \`legacy-peer-deps\` is not recommended, as it will not enforce
      the \`peerDependencies\` contract that meta-dependencies may rely on.
    `,
    flatten,
  }),
  libc: new Definition('libc', {
    default: null,
    type: [null, String],
    description: `
      Override libc of native modules to install.
      Acceptable values are same as \`libc\` field of package.json
    `,
    flatten,
  }),
  link: new Definition('link', {
    default: false,
    type: Boolean,
    description: `
      Used with \`npm ls\`, limiting output to only those packages that are
      linked.
    `,
  }),
  'local-address': new Definition('local-address', {
    default: null,
    type: getLocalAddresses(),
    typeDescription: 'IP Address',
    description: `
      The IP address of the local interface to use when making connections to
      the npm registry.  Must be IPv4 in versions of Node prior to 0.12.
    `,
    flatten,
  }),
  location: new Definition('location', {
    default: 'user',
    short: 'L',
    type: [
      'global',
      'user',
      'project',
    ],
    defaultDescription: `
      "user" unless \`--global\` is passed, which will also set this value to "global"
    `,
    description: `
      When passed to \`npm config\` this refers to which config file to use.

      When set to "global" mode, packages are installed into the \`prefix\` folder
      instead of the current working directory. See
      [folders](/configuring-npm/folders) for more on the differences in behavior.

      * packages are installed into the \`{prefix}/lib/node_modules\` folder,
        instead of the current working directory.
      * bin files are linked to \`{prefix}/bin\`
      * man pages are linked to \`{prefix}/share/man\`
    `,
    flatten: (key, obj, flatOptions) => {
      flatten(key, obj, flatOptions)
      if (flatOptions.global) {
        flatOptions.location = 'global'
      }
      if (obj.location === 'global') {
        flatOptions.global = true
      }
    },
  }),
  'lockfile-version': new Definition('lockfile-version', {
    default: null,
    type: [null, 1, 2, 3, '1', '2', '3'],
    defaultDescription: `
      Version 3 if no lockfile, auto-converting v1 lockfiles to v3, otherwise
      maintain current lockfile version.`,
    description: `
      Set the lockfile format version to be used in package-lock.json and
      npm-shrinkwrap-json files.  Possible options are:

      1: The lockfile version used by npm versions 5 and 6.  Lacks some data that
      is used during the install, resulting in slower and possibly less
      deterministic installs.  Prevents lockfile churn when interoperating with
      older npm versions.

      2: The default lockfile version used by npm version 7 and 8.  Includes both
      the version 1 lockfile data and version 3 lockfile data, for maximum
      determinism and interoperability, at the expense of more bytes on disk.

      3: Only the new lockfile information introduced in npm version 7.  Smaller
      on disk than lockfile version 2, but not interoperable with older npm
      versions.  Ideal if all users are on npm version 7 and higher.
    `,
    flatten: (key, obj, flatOptions) => {
      flatOptions.lockfileVersion = obj[key] && parseInt(obj[key], 10)
    },
  }),
  loglevel: new Definition('loglevel', {
    default: 'notice',
    type: [
      'silent',
      'error',
      'warn',
      'notice',
      'http',
      'info',
      'verbose',
      'silly',
    ],
    description: `
      What level of logs to report.  All logs are written to a debug log,
      with the path to that file printed if the execution of a command fails.

      Any logs of a higher level than the setting are shown. The default is
      "notice".

      See also the \`foreground-scripts\` config.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.silent = obj[key] === 'silent'
    },
  }),
  'logs-dir': new Definition('logs-dir', {
    default: null,
    type: [null, path],
    defaultDescription: `
      A directory named \`_logs\` inside the cache
  `,
    description: `
      The location of npm's log directory.  See [\`npm
      logging\`](/using-npm/logging) for more information.
    `,
  }),
  'logs-max': new Definition('logs-max', {
    default: 10,
    type: Number,
    description: `
      The maximum number of log files to store.

      If set to 0, no log files will be written for the current run.
    `,
  }),
  long: new Definition('long', {
    default: false,
    type: Boolean,
    short: 'l',
    description: `
      Show extended information in \`ls\`, \`search\`, and \`help-search\`.
    `,
  }),
  maxsockets: new Definition('maxsockets', {
    default: 15,
    type: Number,
    description: `
      The maximum number of connections to use per origin (protocol/host/port
      combination).
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.maxSockets = obj[key]
    },
  }),
  message: new Definition('message', {
    default: '%s',
    type: String,
    short: 'm',
    description: `
      Commit message which is used by \`npm version\` when creating version commit.

      Any "%s" in the message will be replaced with the version number.
    `,
    flatten,
  }),
  'node-options': new Definition('node-options', {
    default: null,
    type: [null, String],
    description: `
      Options to pass through to Node.js via the \`NODE_OPTIONS\` environment
      variable.  This does not impact how npm itself is executed but it does
      impact how lifecycle scripts are called.
    `,
  }),
  noproxy: new Definition('noproxy', {
    default: '',
    defaultDescription: `
      The value of the NO_PROXY environment variable
    `,
    type: [String, Array],
    description: `
      Domain extensions that should bypass any proxies.

      Also accepts a comma-delimited string.
    `,
    flatten (key, obj, flatOptions) {
      if (Array.isArray(obj[key])) {
        flatOptions.noProxy = obj[key].join(',')
      } else {
        flatOptions.noProxy = obj[key]
      }
    },
  }),
  offline: new Definition('offline', {
    default: false,
    type: Boolean,
    description: `
      Force offline mode: no network requests will be done during install. To allow
      the CLI to fill in missing cache data, see \`--prefer-offline\`.
    `,
    flatten,
  }),
  omit: new Definition('omit', {
    default: process.env.NODE_ENV === 'production' ? ['dev'] : [],
    defaultDescription: `
      'dev' if the \`NODE_ENV\` environment variable is set to 'production',
      otherwise empty.
    `,
    type: [Array, 'dev', 'optional', 'peer'],
    description: `
      Dependency types to omit from the installation tree on disk.

      Note that these dependencies _are_ still resolved and added to the
      \`package-lock.json\` or \`npm-shrinkwrap.json\` file.  They are just
      not physically installed on disk.

      If a package type appears in both the \`--include\` and \`--omit\`
      lists, then it will be included.

      If the resulting omit list includes \`'dev'\`, then the \`NODE_ENV\`
      environment variable will be set to \`'production'\` for all lifecycle
      scripts.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.omit = buildOmitList(obj)
    },
  }),
  'omit-lockfile-registry-resolved': new Definition('omit-lockfile-registry-resolved', {
    default: false,
    type: Boolean,
    description: `
      This option causes npm to create lock files without a \`resolved\` key for
      registry dependencies. Subsequent installs will need to resolve tarball
      endpoints with the configured registry, likely resulting in a longer install
      time.
    `,
    flatten,
  }),
  only: new Definition('only', {
    default: null,
    type: [null, 'prod', 'production'],
    deprecated: `
      Use \`--omit=dev\` to omit dev dependencies from the install.
    `,
    description: `
      When set to \`prod\` or \`production\`, this is an alias for
      \`--omit=dev\`.
    `,
    flatten (key, obj, flatOptions) {
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  optional: new Definition('optional', {
    default: null,
    type: [null, Boolean],
    deprecated: `
      Use \`--omit=optional\` to exclude optional dependencies, or
      \`--include=optional\` to include them.

      Default value does install optional deps unless otherwise omitted.
    `,
    description: `
      Alias for --include=optional or --omit=optional
    `,
    flatten (key, obj, flatOptions) {
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  os: new Definition('os', {
    default: null,
    type: [null, String],
    description: `
      Override OS of native modules to install.
      Acceptable values are same as \`os\` field of package.json,
      which comes from \`process.platform\`.
    `,
    flatten,
  }),
  otp: new Definition('otp', {
    default: null,
    type: [null, String],
    description: `
      This is a one-time password from a two-factor authenticator.  It's needed
      when publishing or changing package permissions with \`npm access\`.

      If not set, and a registry response fails with a challenge for a one-time
      password, npm will prompt on the command line for one.
    `,
    flatten (key, obj, flatOptions) {
      flatten(key, obj, flatOptions)
      if (obj.otp) {
        obj['auth-type'] = 'legacy'
        flatten('auth-type', obj, flatOptions)
      }
    },
  }),
  package: new Definition('package', {
    default: [],
    hint: '<package-spec>',
    type: [String, Array],
    description: `
      The package or packages to install for [\`npm exec\`](/commands/npm-exec)
    `,
    flatten,
  }),
  'package-lock': new Definition('package-lock', {
    default: true,
    type: Boolean,
    description: `
      If set to false, then ignore \`package-lock.json\` files when installing.
      This will also prevent _writing_ \`package-lock.json\` if \`save\` is
      true.
    `,
    flatten: (key, obj, flatOptions) => {
      flatten(key, obj, flatOptions)
      if (flatOptions.packageLockOnly) {
        flatOptions.packageLock = true
      }
    },
  }),
  'package-lock-only': new Definition('package-lock-only', {
    default: false,
    type: Boolean,
    description: `
      If set to true, the current operation will only use the \`package-lock.json\`,
      ignoring \`node_modules\`.

      For \`update\` this means only the \`package-lock.json\` will be updated,
      instead of checking \`node_modules\` and downloading dependencies.

      For \`list\` this means the output will be based on the tree described by the
      \`package-lock.json\`, rather than the contents of \`node_modules\`.
    `,
    flatten: (key, obj, flatOptions) => {
      flatten(key, obj, flatOptions)
      if (flatOptions.packageLockOnly) {
        flatOptions.packageLock = true
      }
    },
  }),
  'pack-destination': new Definition('pack-destination', {
    default: '.',
    type: String,
    description: `
      Directory in which \`npm pack\` will save tarballs.
    `,
    flatten,
  }),
  parseable: new Definition('parseable', {
    default: false,
    type: Boolean,
    short: 'p',
    description: `
      Output parseable results from commands that write to standard output. For
      \`npm search\`, this will be tab-separated table format.
    `,
    flatten,
  }),
  'prefer-dedupe': new Definition('prefer-dedupe', {
    default: false,
    type: Boolean,
    description: `
      Prefer to deduplicate packages if possible, rather than
      choosing a newer version of a dependency.
    `,
    flatten,
  }),
  'prefer-offline': new Definition('prefer-offline', {
    default: false,
    type: Boolean,
    description: `
      If true, staleness checks for cached data will be bypassed, but missing
      data will be requested from the server. To force full offline mode, use
      \`--offline\`.
    `,
    flatten,
  }),
  'prefer-online': new Definition('prefer-online', {
    default: false,
    type: Boolean,
    description: `
      If true, staleness checks for cached data will be forced, making the CLI
      look for updates immediately even for fresh package data.
    `,
    flatten,
  }),
  // `prefix` has its default defined outside of this module
  prefix: new Definition('prefix', {
    type: path,
    short: 'C',
    default: '',
    defaultDescription: `
      In global mode, the folder where the node executable is installed.
      Otherwise, the nearest parent folder containing either a package.json
      file or a node_modules folder.
    `,
    description: `
      The location to install global items.  If set on the command line, then
      it forces non-global commands to run in the specified folder.
    `,
  }),
  preid: new Definition('preid', {
    default: '',
    hint: 'prerelease-id',
    type: String,
    description: `
      The "prerelease identifier" to use as a prefix for the "prerelease" part
      of a semver. Like the \`rc\` in \`1.2.0-rc.8\`.
    `,
    flatten,
  }),
  production: new Definition('production', {
    default: null,
    type: [null, Boolean],
    deprecated: 'Use `--omit=dev` instead.',
    description: 'Alias for `--omit=dev`',
    flatten (key, obj, flatOptions) {
      definitions.omit.flatten('omit', obj, flatOptions)
    },
  }),
  progress: new Definition('progress', {
    default: !ciInfo.isCI,
    defaultDescription: `
      \`true\` unless running in a known CI system
    `,
    type: Boolean,
    description: `
      When set to \`true\`, npm will display a progress bar during time
      intensive operations, if \`process.stderr\` and \`process.stdout\` are a TTY.

      Set to \`false\` to suppress the progress bar.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.progress = !obj.progress ? false
        // progress is only written to stderr but we disable it unless stdout is a tty
        // also. This prevents the progress from appearing when piping output to another
        // command which doesn't break anything, but does look very odd to users.
        : !!process.stderr.isTTY && !!process.stdout.isTTY && process.env.TERM !== 'dumb'
    },
  }),
  provenance: new Definition('provenance', {
    default: false,
    type: Boolean,
    exclusive: ['provenance-file'],
    description: `
      When publishing from a supported cloud CI/CD system, the package will be
      publicly linked to where it was built and published from.
    `,
    flatten,
  }),
  'provenance-file': new Definition('provenance-file', {
    default: null,
    type: path,
    hint: '<file>',
    exclusive: ['provenance'],
    description: `
      When publishing, the provenance bundle at the given path will be used.
    `,
    flatten,
  }),
  proxy: new Definition('proxy', {
    default: null,
    type: [null, false, url], // allow proxy to be disabled explicitly
    description: `
      A proxy to use for outgoing http requests. If the \`HTTP_PROXY\` or
      \`http_proxy\` environment variables are set, proxy settings will be
      honored by the underlying \`request\` library.
    `,
    flatten,
  }),
  'read-only': new Definition('read-only', {
    default: false,
    type: Boolean,
    description: `
      This is used to mark a token as unable to publish when configuring
      limited access tokens with the \`npm token create\` command.
    `,
    flatten,
  }),
  'rebuild-bundle': new Definition('rebuild-bundle', {
    default: true,
    type: Boolean,
    description: `
      Rebuild bundled dependencies after installation.
    `,
    flatten,
  }),
  registry: new Definition('registry', {
    default: 'https://registry.npmjs.org/',
    type: url,
    description: `
      The base URL of the npm registry.
    `,
    flatten,
  }),
  'replace-registry-host': new Definition('replace-registry-host', {
    default: 'npmjs',
    hint: '<npmjs|never|always> | hostname',
    type: ['npmjs', 'never', 'always', String],
    description: `
      Defines behavior for replacing the registry host in a lockfile with the
      configured registry.

      The default behavior is to replace package dist URLs from the default
      registry (https://registry.npmjs.org) to the configured registry. If set to
      "never", then use the registry value. If set to "always", then replace the
      registry host with the configured host every time.

      You may also specify a bare hostname (e.g., "registry.npmjs.org").
    `,
    flatten,
  }),
  save: new Definition('save', {
    default: true,
    defaultDescription: `\`true\` unless when using \`npm update\` where it
    defaults to \`false\``,
    usage: '-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle',
    type: Boolean,
    short: 'S',
    description: `
      Save installed packages to a \`package.json\` file as dependencies.

      When used with the \`npm rm\` command, removes the dependency from
      \`package.json\`.

      Will also prevent writing to \`package-lock.json\` if set to \`false\`.
    `,
    flatten,
  }),
  'save-bundle': new Definition('save-bundle', {
    default: false,
    type: Boolean,
    short: 'B',
    description: `
      If a package would be saved at install time by the use of \`--save\`,
      \`--save-dev\`, or \`--save-optional\`, then also put it in the
      \`bundleDependencies\` list.

      Ignored if \`--save-peer\` is set, since peerDependencies cannot be bundled.
    `,
    flatten (key, obj, flatOptions) {
      // XXX update arborist to just ignore it if resulting saveType is peer
      // otherwise this won't have the expected effect:
      //
      // npm config set save-peer true
      // npm i foo --save-bundle --save-prod <-- should bundle
      flatOptions.saveBundle = obj['save-bundle'] && !obj['save-peer']
    },
  }),
  'save-dev': new Definition('save-dev', {
    default: false,
    type: Boolean,
    short: 'D',
    description: `
      Save installed packages to a package.json file as \`devDependencies\`.
    `,
    flatten (key, obj, flatOptions) {
      if (!obj[key]) {
        if (flatOptions.saveType === 'dev') {
          delete flatOptions.saveType
        }
        return
      }

      flatOptions.saveType = 'dev'
    },
  }),
  'save-exact': new Definition('save-exact', {
    default: false,
    type: Boolean,
    short: 'E',
    description: `
      Dependencies saved to package.json will be configured with an exact
      version rather than using npm's default semver range operator.
    `,
    flatten (key, obj, flatOptions) {
      // just call the save-prefix flattener, it reads from obj['save-exact']
      definitions['save-prefix'].flatten('save-prefix', obj, flatOptions)
    },
  }),
  'save-optional': new Definition('save-optional', {
    default: false,
    type: Boolean,
    short: 'O',
    description: `
      Save installed packages to a package.json file as
      \`optionalDependencies\`.
    `,
    flatten (key, obj, flatOptions) {
      if (!obj[key]) {
        if (flatOptions.saveType === 'optional') {
          delete flatOptions.saveType
        } else if (flatOptions.saveType === 'peerOptional') {
          flatOptions.saveType = 'peer'
        }
        return
      }

      if (flatOptions.saveType === 'peerOptional') {
        return
      }

      if (flatOptions.saveType === 'peer') {
        flatOptions.saveType = 'peerOptional'
      } else {
        flatOptions.saveType = 'optional'
      }
    },
  }),
  'save-peer': new Definition('save-peer', {
    default: false,
    type: Boolean,
    description: `
      Save installed packages to a package.json file as \`peerDependencies\`
    `,
    flatten (key, obj, flatOptions) {
      if (!obj[key]) {
        if (flatOptions.saveType === 'peer') {
          delete flatOptions.saveType
        } else if (flatOptions.saveType === 'peerOptional') {
          flatOptions.saveType = 'optional'
        }
        return
      }

      if (flatOptions.saveType === 'peerOptional') {
        return
      }

      if (flatOptions.saveType === 'optional') {
        flatOptions.saveType = 'peerOptional'
      } else {
        flatOptions.saveType = 'peer'
      }
    },
  }),
  'save-prefix': new Definition('save-prefix', {
    default: '^',
    type: String,
    description: `
      Configure how versions of packages installed to a package.json file via
      \`--save\` or \`--save-dev\` get prefixed.

      For example if a package has version \`1.2.3\`, by default its version is
      set to \`^1.2.3\` which allows minor upgrades for that package, but after
      \`npm config set save-prefix='~'\` it would be set to \`~1.2.3\` which
      only allows patch upgrades.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.savePrefix = obj['save-exact'] ? '' : obj['save-prefix']
      obj['save-prefix'] = flatOptions.savePrefix
    },
  }),
  'save-prod': new Definition('save-prod', {
    default: false,
    type: Boolean,
    short: 'P',
    description: `
      Save installed packages into \`dependencies\` specifically. This is
      useful if a package already exists in \`devDependencies\` or
      \`optionalDependencies\`, but you want to move it to be a non-optional
      production dependency.

      This is the default behavior if \`--save\` is true, and neither
      \`--save-dev\` or \`--save-optional\` are true.
    `,
    flatten (key, obj, flatOptions) {
      if (!obj[key]) {
        if (flatOptions.saveType === 'prod') {
          delete flatOptions.saveType
        }
        return
      }

      flatOptions.saveType = 'prod'
    },
  }),
  'sbom-format': new Definition('sbom-format', {
    default: null,
    type: [
      'cyclonedx',
      'spdx',
    ],
    description: `
      SBOM format to use when generating SBOMs.
    `,
    flatten,
  }),
  'sbom-type': new Definition('sbom-type', {
    default: 'library',
    type: [
      'library',
      'application',
      'framework',
    ],
    description: `
      The type of package described by the generated SBOM. For SPDX, this is the
      value for the \`primaryPackagePurpose\` field. For CycloneDX, this is the
      value for the \`type\` field.
    `,
    flatten,
  }),
  scope: new Definition('scope', {
    default: '',
    defaultDescription: `
      the scope of the current project, if any, or ""
    `,
    type: String,
    hint: '<@scope>',
    description: `
      Associate an operation with a scope for a scoped registry.

      Useful when logging in to or out of a private registry:

      \`\`\`
      # log in, linking the scope to the custom registry
      npm login --scope=@mycorp --registry=https://registry.mycorp.com

      # log out, removing the link and the auth token
      npm logout --scope=@mycorp
      \`\`\`

      This will cause \`@mycorp\` to be mapped to the registry for future
      installation of packages specified according to the pattern
      \`@mycorp/package\`.

      This will also cause \`npm init\` to create a scoped package.

      \`\`\`
      # accept all defaults, and create a package named "@foo/whatever",
      # instead of just named "whatever"
      npm init --scope=@foo --yes
      \`\`\`
    `,
    flatten (key, obj, flatOptions) {
      const value = obj[key]
      const scope = value && !/^@/.test(value) ? `@${value}` : value
      flatOptions.scope = scope
      // projectScope is kept for compatibility with npm-registry-fetch
      flatOptions.projectScope = scope
    },
  }),
  'script-shell': new Definition('script-shell', {
    default: null,
    defaultDescription: `
      '/bin/sh' on POSIX systems, 'cmd.exe' on Windows
    `,
    type: [null, String],
    description: `
      The shell to use for scripts run with the \`npm exec\`,
      \`npm run\` and \`npm init <package-spec>\` commands.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.scriptShell = obj[key] || undefined
    },
  }),
  searchexclude: new Definition('searchexclude', {
    default: '',
    type: String,
    description: `
      Space-separated options that limit the results from search.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.search = flatOptions.search || { limit: 20 }
      flatOptions.search.exclude = obj[key].toLowerCase()
    },
  }),
  searchlimit: new Definition('searchlimit', {
    default: 20,
    type: Number,
    description: `
      Number of items to limit search results to. Will not apply at all to
      legacy searches.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.search = flatOptions.search || {}
      flatOptions.search.limit = obj[key]
    },
  }),
  searchopts: new Definition('searchopts', {
    default: '',
    type: String,
    description: `
      Space-separated options that are always passed to search.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.search = flatOptions.search || { limit: 20 }
      flatOptions.search.opts = querystring.parse(obj[key])
    },
  }),
  searchstaleness: new Definition('searchstaleness', {
    default: 15 * 60,
    type: Number,
    description: `
      The age of the cache, in seconds, before another registry request is made
      if using legacy search endpoint.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.search = flatOptions.search || { limit: 20 }
      flatOptions.search.staleness = obj[key]
    },
  }),
  shell: new Definition('shell', {
    default: shell,
    defaultDescription: `
      SHELL environment variable, or "bash" on Posix, or "cmd.exe" on Windows
    `,
    type: String,
    description: `
      The shell to run for the \`npm explore\` command.
    `,
    flatten,
  }),
  shrinkwrap: new Definition('shrinkwrap', {
    default: true,
    type: Boolean,
    deprecated: `
      Use the --package-lock setting instead.
    `,
    description: `
      Alias for --package-lock
    `,
    flatten (key, obj, flatOptions) {
      obj['package-lock'] = obj.shrinkwrap
      definitions['package-lock'].flatten('package-lock', obj, flatOptions)
    },
  }),
  'sign-git-commit': new Definition('sign-git-commit', {
    default: false,
    type: Boolean,
    description: `
      If set to true, then the \`npm version\` command will commit the new
      package version using \`-S\` to add a signature.

      Note that git requires you to have set up GPG keys in your git configs
      for this to work properly.
    `,
    flatten,
  }),
  'sign-git-tag': new Definition('sign-git-tag', {
    default: false,
    type: Boolean,
    description: `
      If set to true, then the \`npm version\` command will tag the version
      using \`-s\` to add a signature.

      Note that git requires you to have set up GPG keys in your git configs
      for this to work properly.
    `,
    flatten,
  }),
  'strict-peer-deps': new Definition('strict-peer-deps', {
    default: false,
    type: Boolean,
    description: `
      If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_
      conflicting \`peerDependencies\` will be treated as an install failure,
      even if npm could reasonably guess the appropriate resolution based on
      non-peer dependency relationships.

      By default, conflicting \`peerDependencies\` deep in the dependency graph
      will be resolved using the nearest non-peer dependency specification,
      even if doing so will result in some packages receiving a peer dependency
      outside the range set in their package's \`peerDependencies\` object.

      When such an override is performed, a warning is printed, explaining the
      conflict and the packages involved.  If \`--strict-peer-deps\` is set,
      then this warning is treated as a failure.
    `,
    flatten,
  }),
  'strict-ssl': new Definition('strict-ssl', {
    default: true,
    type: Boolean,
    description: `
      Whether or not to do SSL key validation when making requests to the
      registry via https.

      See also the \`ca\` config.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.strictSSL = obj[key]
    },
  }),
  tag: new Definition('tag', {
    default: 'latest',
    type: String,
    description: `
      If you ask npm to install a package and don't tell it a specific version,
      then it will install the specified tag.

      It is the tag added to the package@version specified in the
      \`npm dist-tag add\` command, if no explicit tag is given.

      When used by the \`npm diff\` command, this is the tag used to fetch the
      tarball that will be compared with the local files by default.

      If used in the \`npm publish\` command, this is the tag that will be
      added to the package submitted to the registry.
    `,
    flatten (key, obj, flatOptions) {
      flatOptions.defaultTag = obj[key]
    },
  }),
  'tag-version-prefix': new Definition('tag-version-prefix', {
    default: 'v',
    type: String,
    description: `
      If set, alters the prefix used when tagging a new version when performing
      a version increment using  \`npm version\`. To remove the prefix
      altogether, set it to the empty string: \`""\`.

      Because other tools may rely on the convention that npm version tags look
      like \`v1.0.0\`, _only use this property if it is absolutely necessary_.
      In particular, use care when overriding this setting for public packages.
    `,
    flatten,
  }),
  timing: new Definition('timing', {
    default: false,
    type: Boolean,
    description: `
      If true, writes timing information to a process specific json file in
      the cache or \`logs-dir\`. The file name ends with \`-timing.json\`.

      You can quickly view it with this [json](https://npm.im/json) command
      line: \`cat ~/.npm/_logs/*-timing.json | npm exec -- json -g\`.

      Timing information will also be reported in the terminal. To suppress this
      while still writing the timing file, use \`--silent\`.
    `,
  }),
  umask: new Definition('umask', {
    default: 0,
    type: Umask,
    description: `
      The "umask" value to use when setting the file creation mode on files and
      folders.

      Folders and executables are given a mode which is \`0o777\` masked
      against this value.  Other files are given a mode which is \`0o666\`
      masked against this value.

      Note that the underlying system will _also_ apply its own umask value to
      files and folders that are created, and npm does not circumvent this, but
      rather adds the \`--umask\` config to it.

      Thus, the effective default umask value on most POSIX systems is 0o22,
      meaning that folders and executables are created with a mode of 0o755 and
      other files are created with a mode of 0o644.
    `,
    flatten,
  }),
  unicode: new Definition('unicode', {
    default: unicode,
    defaultDescription: `
      false on windows, true on mac/unix systems with a unicode locale, as
      defined by the \`LC_ALL\`, \`LC_CTYPE\`, or \`LANG\` environment variables.
    `,
    type: Boolean,
    description: `
      When set to true, npm uses unicode characters in the tree output.  When
      false, it uses ascii characters instead of unicode glyphs.
    `,
    flatten,
  }),
  'update-notifier': new Definition('update-notifier', {
    default: true,
    type: Boolean,
    description: `
      Set to false to suppress the update notification when using an older
      version of npm than the latest.
    `,
  }),
  usage: new Definition('usage', {
    default: false,
    type: Boolean,
    short: ['?', 'H', 'h'],
    description: `
      Show short usage output about the command specified.
    `,
  }),
  'user-agent': new Definition('user-agent', {
    default: 'npm/{npm-version} ' +
            'node/{node-version} ' +
            '{platform} ' +
            '{arch} ' +
            'workspaces/{workspaces} ' +
            '{ci}',
    type: String,
    description: `
      Sets the User-Agent request header.  The following fields are replaced
      with their actual counterparts:

      * \`{npm-version}\` - The npm version in use
      * \`{node-version}\` - The Node.js version in use
      * \`{platform}\` - The value of \`process.platform\`
      * \`{arch}\` - The value of \`process.arch\`
      * \`{workspaces}\` - Set to \`true\` if the \`workspaces\` or \`workspace\`
        options are set.
      * \`{ci}\` - The value of the \`ci-name\` config, if set, prefixed with
        \`ci/\`, or an empty string if \`ci-name\` is empty.
    `,
    flatten (key, obj, flatOptions) {
      const value = obj[key]
      const ciName = ciInfo.name?.toLowerCase().split(' ').join('-') || null
      let inWorkspaces = false
      if (obj.workspaces || obj.workspace && obj.workspace.length) {
        inWorkspaces = true
      }
      flatOptions.userAgent =
        value.replace(/\{node-version\}/gi, process.version)
          .replace(/\{npm-version\}/gi, obj['npm-version'])
          .replace(/\{platform\}/gi, process.platform)
          .replace(/\{arch\}/gi, process.arch)
          .replace(/\{workspaces\}/gi, inWorkspaces)
          .replace(/\{ci\}/gi, ciName ? `ci/${ciName}` : '')
          .trim()

      // We can't clobber the original or else subsequent flattening will fail
      // (i.e. when we change the underlying config values)
      // obj[key] = flatOptions.userAgent

      // user-agent is a unique kind of config item that gets set from a template
      // and ends up translated.  Because of this, the normal "should we set this
      // to process.env also doesn't work
      process.env.npm_config_user_agent = flatOptions.userAgent
    },
  }),
  userconfig: new Definition('userconfig', {
    default: '~/.npmrc',
    type: path,
    description: `
      The location of user-level configuration settings.

      This may be overridden by the \`npm_config_userconfig\` environment
      variable or the \`--userconfig\` command line option, but may _not_
      be overridden by settings in the \`globalconfig\` file.
    `,
  }),
  version: new Definition('version', {
    default: false,
    type: Boolean,
    short: 'v',
    description: `
      If true, output the npm version and exit successfully.

      Only relevant when specified explicitly on the command line.
    `,
  }),
  versions: new Definition('versions', {
    default: false,
    type: Boolean,
    description: `
      If true, output the npm version as well as node's \`process.versions\`
      map and the version in the current working directory's \`package.json\`
      file if one exists, and exit successfully.

      Only relevant when specified explicitly on the command line.
    `,
  }),
  viewer: new Definition('viewer', {
    default: isWindows ? 'browser' : 'man',
    defaultDescription: `
      "man" on Posix, "browser" on Windows
    `,
    type: String,
    description: `
      The program to use to view help content.

      Set to \`"browser"\` to view html help content in the default web browser.
    `,
  }),
  which: new Definition('which', {
    default: null,
    hint: '<fundingSourceNumber>',
    type: [null, Number],
    description: `
      If there are multiple funding sources, which 1-indexed source URL to open.
    `,
  }),
  workspace: new Definition('workspace', {
    default: [],
    type: [String, Array],
    hint: '<workspace-name>',
    short: 'w',
    envExport: false,
    description: `
      Enable running a command in the context of the configured workspaces of the
      current project while filtering by running only the workspaces defined by
      this configuration option.

      Valid values for the \`workspace\` config are either:

      * Workspace names
      * Path to a workspace directory
      * Path to a parent workspace directory (will result in selecting all
        workspaces within that folder)

      When set for the \`npm init\` command, this may be set to the folder of
      a workspace which does not yet exist, to create the folder and set it
      up as a brand new workspace within the project.
    `,
    flatten: (key, obj, flatOptions) => {
      definitions['user-agent'].flatten('user-agent', obj, flatOptions)
    },
  }),
  workspaces: new Definition('workspaces', {
    default: null,
    type: [null, Boolean],
    short: 'ws',
    envExport: false,
    description: `
      Set to true to run the command in the context of **all** configured
      workspaces.

      Explicitly setting this to false will cause commands like \`install\` to
      ignore workspaces altogether.
      When not set explicitly:

      - Commands that operate on the \`node_modules\` tree (install, update,
        etc.) will link workspaces into the \`node_modules\` folder.
      - Commands that do other things (test, exec, publish, etc.) will operate
        on the root project, _unless_ one or more workspaces are specified in
        the \`workspace\` config.
    `,
    flatten: (key, obj, flatOptions) => {
      definitions['user-agent'].flatten('user-agent', obj, flatOptions)

      // TODO: this is a derived value, and should be reworked when we have a
      // pattern for derived value

      // workspacesEnabled is true whether workspaces is null or true
      // commands contextually work with workspaces or not regardless of
      // configuration, so we need an option specifically to disable workspaces
      flatOptions.workspacesEnabled = obj[key] !== false
    },
  }),
  'workspaces-update': new Definition('workspaces-update', {
    default: true,
    type: Boolean,
    description: `
      If set to true, the npm cli will run an update after operations that may
      possibly change the workspaces installed to the \`node_modules\` folder.
    `,
    flatten,
  }),
  yes: new Definition('yes', {
    default: null,
    type: [null, Boolean],
    short: 'y',
    description: `
      Automatically answer "yes" to any prompts that npm might print on
      the command line.
    `,
  }),
}

module.exports = definitions
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               #!/usr/bin/env python3

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for the MSVSSettings.py file."""

import unittest
import gyp.MSVSSettings as MSVSSettings

from io import StringIO


class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.stderr = StringIO()

    def _ExpectedWarnings(self, expected):
        """Compares recorded lines to expected warnings."""
        self.stderr.seek(0)
        actual = self.stderr.read().split("\n")
        actual = [line for line in actual if line]
        self.assertEqual(sorted(expected), sorted(actual))

    def testValidateMSVSSettings_tool_names(self):
        """Tests that only MSVS tool names are allowed."""
        MSVSSettings.ValidateMSVSSettings(
            {
                "VCCLCompilerTool": {},
                "VCLinkerTool": {},
                "VCMIDLTool": {},
                "foo": {},
                "VCResourceCompilerTool": {},
                "VCLibrarianTool": {},
                "VCManifestTool": {},
                "ClCompile": {},
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            ["Warning: unrecognized tool foo", "Warning: unrecognized tool ClCompile"]
        )

    def testValidateMSVSSettings_settings(self):
        """Tests that for invalid MSVS settings."""
        MSVSSettings.ValidateMSVSSettings(
            {
                "VCCLCompilerTool": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": ["string1", "string2"],
                    "AdditionalUsingDirectories": "folder1;folder2",
                    "AssemblerListingLocation": "a_file_name",
                    "AssemblerOutput": "0",
                    "BasicRuntimeChecks": "5",
                    "BrowseInformation": "fdkslj",
                    "BrowseInformationFile": "a_file_name",
                    "BufferSecurityCheck": "true",
                    "CallingConvention": "-1",
                    "CompileAs": "1",
                    "DebugInformationFormat": "2",
                    "DefaultCharIsUnsigned": "true",
                    "Detect64BitPortabilityProblems": "true",
                    "DisableLanguageExtensions": "true",
                    "DisableSpecificWarnings": "string1;string2",
                    "EnableEnhancedInstructionSet": "1",
                    "EnableFiberSafeOptimizations": "true",
                    "EnableFunctionLevelLinking": "true",
                    "EnableIntrinsicFunctions": "true",
                    "EnablePREfast": "true",
                    "Enableprefast": "bogus",
                    "ErrorReporting": "1",
                    "ExceptionHandling": "1",
                    "ExpandAttributedSource": "true",
                    "FavorSizeOrSpeed": "1",
                    "FloatingPointExceptions": "true",
                    "FloatingPointModel": "1",
                    "ForceConformanceInForLoopScope": "true",
                    "ForcedIncludeFiles": "file1;file2",
                    "ForcedUsingFiles": "file1;file2",
                    "GeneratePreprocessedFile": "1",
                    "GenerateXMLDocumentationFiles": "true",
                    "IgnoreStandardIncludePath": "true",
                    "InlineFunctionExpansion": "1",
                    "KeepComments": "true",
                    "MinimalRebuild": "true",
                    "ObjectFile": "a_file_name",
                    "OmitDefaultLibName": "true",
                    "OmitFramePointers": "true",
                    "OpenMP": "true",
                    "Optimization": "1",
                    "PrecompiledHeaderFile": "a_file_name",
                    "PrecompiledHeaderThrough": "a_file_name",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProgramDataBaseFileName": "a_file_name",
                    "RuntimeLibrary": "1",
                    "RuntimeTypeInfo": "true",
                    "ShowIncludes": "true",
                    "SmallerTypeCheck": "true",
                    "StringPooling": "true",
                    "StructMemberAlignment": "1",
                    "SuppressStartupBanner": "true",
                    "TreatWChar_tAsBuiltInType": "true",
                    "UndefineAllPreprocessorDefinitions": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "UseFullPaths": "true",
                    "UsePrecompiledHeader": "1",
                    "UseUnicodeResponseFiles": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                    "WholeProgramOptimization": "true",
                    "XMLDocumentationFileName": "a_file_name",
                    "ZZXYZ": "bogus",
                },
                "VCLinkerTool": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalDependencies_excluded": "file3",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalManifestDependencies": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AddModuleNamesToAssembly": "file1;file2",
                    "AllowIsolation": "true",
                    "AssemblyDebug": "2",
                    "AssemblyLinkResource": "file1;file2",
                    "BaseAddress": "a string1",
                    "CLRImageType": "2",
                    "CLRThreadAttribute": "2",
                    "CLRUnmanagedCodeCheck": "true",
                    "DataExecutionPrevention": "2",
                    "DelayLoadDLLs": "file1;file2",
                    "DelaySign": "true",
                    "Driver": "2",
                    "EmbedManagedResourceFile": "file1;file2",
                    "EnableCOMDATFolding": "2",
                    "EnableUAC": "true",
                    "EntryPointSymbol": "a string1",
                    "ErrorReporting": "2",
                    "FixedBaseAddress": "2",
                    "ForceSymbolReferences": "file1;file2",
                    "FunctionOrder": "a_file_name",
                    "GenerateDebugInformation": "true",
                    "GenerateManifest": "true",
                    "GenerateMapFile": "true",
                    "HeapCommitSize": "a string1",
                    "HeapReserveSize": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreDefaultLibraryNames": "file1;file2",
                    "IgnoreEmbeddedIDL": "true",
                    "IgnoreImportLibrary": "true",
                    "ImportLibrary": "a_file_name",
                    "KeyContainer": "a_file_name",
                    "KeyFile": "a_file_name",
                    "LargeAddressAware": "2",
                    "LinkIncremental": "2",
                    "LinkLibraryDependencies": "true",
                    "LinkTimeCodeGeneration": "2",
                    "ManifestFile": "a_file_name",
                    "MapExports": "true",
                    "MapFileName": "a_file_name",
                    "MergedIDLBaseFileName": "a_file_name",
                    "MergeSections": "a string1",
                    "MidlCommandFile": "a_file_name",
                    "ModuleDefinitionFile": "a_file_name",
                    "OptimizeForWindows98": "1",
                    "OptimizeReferences": "2",
                    "OutputFile": "a_file_name",
                    "PerUserRedirection": "true",
                    "Profile": "true",
                    "ProfileGuidedDatabase": "a_file_name",
                    "ProgramDatabaseFile": "a_file_name",
                    "RandomizedBaseAddress": "2",
                    "RegisterOutput": "true",
                    "ResourceOnlyDLL": "true",
                    "SetChecksum": "true",
                    "ShowProgress": "2",
                    "StackCommitSize": "a string1",
                    "StackReserveSize": "a string1",
                    "StripPrivateSymbols": "a_file_name",
                    "SubSystem": "2",
                    "SupportUnloadOfDelayLoadedDLL": "true",
                    "SuppressStartupBanner": "true",
                    "SwapRunFromCD": "true",
                    "SwapRunFromNet": "true",
                    "TargetMachine": "2",
                    "TerminalServerAware": "2",
                    "TurnOffAssemblyGeneration": "true",
                    "TypeLibraryFile": "a_file_name",
                    "TypeLibraryResourceID": "33",
                    "UACExecutionLevel": "2",
                    "UACUIAccess": "true",
                    "UseLibraryDependencyInputs": "true",
                    "UseUnicodeResponseFiles": "true",
                    "Version": "a string1",
                },
                "VCMIDLTool": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "CPreprocessOptions": "a string1",
                    "DefaultCharType": "1",
                    "DLLDataFileName": "a_file_name",
                    "EnableErrorChecks": "1",
                    "ErrorCheckAllocations": "true",
                    "ErrorCheckBounds": "true",
                    "ErrorCheckEnumRange": "true",
                    "ErrorCheckRefPointers": "true",
                    "ErrorCheckStubData": "true",
                    "GenerateStublessProxies": "true",
                    "GenerateTypeLibrary": "true",
                    "HeaderFileName": "a_file_name",
                    "IgnoreStandardIncludePath": "true",
                    "InterfaceIdentifierFileName": "a_file_name",
                    "MkTypLibCompatible": "true",
                    "notgood": "bogus",
                    "OutputDirectory": "a string1",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProxyFileName": "a_file_name",
                    "RedirectOutputAndErrors": "a_file_name",
                    "StructMemberAlignment": "1",
                    "SuppressStartupBanner": "true",
                    "TargetEnvironment": "1",
                    "TypeLibraryName": "a_file_name",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "ValidateParameters": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                },
                "VCResourceCompilerTool": {
                    "AdditionalOptions": "a string1",
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "Culture": "1003",
                    "IgnoreStandardIncludePath": "true",
                    "notgood2": "bogus",
                    "PreprocessorDefinitions": "string1;string2",
                    "ResourceOutputFileName": "a string1",
                    "ShowProgress": "true",
                    "SuppressStartupBanner": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                },
                "VCLibrarianTool": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "ExportNamedFunctions": "string1;string2",
                    "ForceSymbolReferences": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreSpecificDefaultLibraries": "file1;file2",
                    "LinkLibraryDependencies": "true",
                    "ModuleDefinitionFile": "a_file_name",
                    "OutputFile": "a_file_name",
                    "SuppressStartupBanner": "true",
                    "UseUnicodeResponseFiles": "true",
                },
                "VCManifestTool": {
                    "AdditionalManifestFiles": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AssemblyIdentity": "a string1",
                    "ComponentFileName": "a_file_name",
                    "DependencyInformationFile": "a_file_name",
                    "GenerateCatalogFiles": "true",
                    "InputResourceManifests": "a string1",
                    "ManifestResourceFile": "a_file_name",
                    "OutputManifestFile": "a_file_name",
                    "RegistrarScriptFile": "a_file_name",
                    "ReplacementsFile": "a_file_name",
                    "SuppressStartupBanner": "true",
                    "TypeLibraryFile": "a_file_name",
                    "UpdateFileHashes": "truel",
                    "UpdateFileHashesSearchPath": "a_file_name",
                    "UseFAT32Workaround": "true",
                    "UseUnicodeResponseFiles": "true",
                    "VerboseOutput": "true",
                },
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            [
                "Warning: for VCCLCompilerTool/BasicRuntimeChecks, "
                "index value (5) not in expected range [0, 4)",
                "Warning: for VCCLCompilerTool/BrowseInformation, "
                "invalid literal for int() with base 10: 'fdkslj'",
                "Warning: for VCCLCompilerTool/CallingConvention, "
                "index value (-1) not in expected range [0, 4)",
                "Warning: for VCCLCompilerTool/DebugInformationFormat, "
                "converted value for 2 not specified.",
                "Warning: unrecognized setting VCCLCompilerTool/Enableprefast",
                "Warning: unrecognized setting VCCLCompilerTool/ZZXYZ",
                "Warning: for VCLinkerTool/TargetMachine, "
                "converted value for 2 not specified.",
                "Warning: unrecognized setting VCMIDLTool/notgood",
                "Warning: unrecognized setting VCResourceCompilerTool/notgood2",
                "Warning: for VCManifestTool/UpdateFileHashes, "
                "expected bool; got 'truel'"
                "",
            ]
        )

    def testValidateMSBuildSettings_settings(self):
        """Tests that for invalid MSBuild settings."""
        MSVSSettings.ValidateMSBuildSettings(
            {
                "ClCompile": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": ["string1", "string2"],
                    "AdditionalUsingDirectories": "folder1;folder2",
                    "AssemblerListingLocation": "a_file_name",
                    "AssemblerOutput": "NoListing",
                    "BasicRuntimeChecks": "StackFrameRuntimeCheck",
                    "BrowseInformation": "false",
                    "BrowseInformationFile": "a_file_name",
                    "BufferSecurityCheck": "true",
                    "BuildingInIDE": "true",
                    "CallingConvention": "Cdecl",
                    "CompileAs": "CompileAsC",
                    "CompileAsManaged": "true",
                    "CreateHotpatchableImage": "true",
                    "DebugInformationFormat": "ProgramDatabase",
                    "DisableLanguageExtensions": "true",
                    "DisableSpecificWarnings": "string1;string2",
                    "EnableEnhancedInstructionSet": "StreamingSIMDExtensions",
                    "EnableFiberSafeOptimizations": "true",
                    "EnablePREfast": "true",
                    "Enableprefast": "bogus",
                    "ErrorReporting": "Prompt",
                    "ExceptionHandling": "SyncCThrow",
                    "ExpandAttributedSource": "true",
                    "FavorSizeOrSpeed": "Neither",
                    "FloatingPointExceptions": "true",
                    "FloatingPointModel": "Precise",
                    "ForceConformanceInForLoopScope": "true",
                    "ForcedIncludeFiles": "file1;file2",
                    "ForcedUsingFiles": "file1;file2",
                    "FunctionLevelLinking": "false",
                    "GenerateXMLDocumentationFiles": "true",
                    "IgnoreStandardIncludePath": "true",
                    "InlineFunctionExpansion": "OnlyExplicitInline",
                    "IntrinsicFunctions": "false",
                    "MinimalRebuild": "true",
                    "MultiProcessorCompilation": "true",
                    "ObjectFileName": "a_file_name",
                    "OmitDefaultLibName": "true",
                    "OmitFramePointers": "true",
                    "OpenMPSupport": "true",
                    "Optimization": "Disabled",
                    "PrecompiledHeader": "NotUsing",
                    "PrecompiledHeaderFile": "a_file_name",
                    "PrecompiledHeaderOutputFile": "a_file_name",
                    "PreprocessKeepComments": "true",
                    "PreprocessorDefinitions": "string1;string2",
                    "PreprocessOutputPath": "a string1",
                    "PreprocessSuppressLineNumbers": "false",
                    "PreprocessToFile": "false",
                    "ProcessorNumber": "33",
                    "ProgramDataBaseFileName": "a_file_name",
                    "RuntimeLibrary": "MultiThreaded",
                    "RuntimeTypeInfo": "true",
                    "ShowIncludes": "true",
                    "SmallerTypeCheck": "true",
                    "StringPooling": "true",
                    "StructMemberAlignment": "1Byte",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "TreatSpecificWarningsAsErrors": "string1;string2",
                    "TreatWarningAsError": "true",
                    "TreatWChar_tAsBuiltInType": "true",
                    "UndefineAllPreprocessorDefinitions": "true",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "UseFullPaths": "true",
                    "UseUnicodeForAssemblerListing": "true",
                    "WarningLevel": "TurnOffAllWarnings",
                    "WholeProgramOptimization": "true",
                    "XMLDocumentationFileName": "a_file_name",
                    "ZZXYZ": "bogus",
                },
                "Link": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalManifestDependencies": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AddModuleNamesToAssembly": "file1;file2",
                    "AllowIsolation": "true",
                    "AssemblyDebug": "",
                    "AssemblyLinkResource": "file1;file2",
                    "BaseAddress": "a string1",
                    "BuildingInIDE": "true",
                    "CLRImageType": "ForceIJWImage",
                    "CLRSupportLastError": "Enabled",
                    "CLRThreadAttribute": "MTAThreadingAttribute",
                    "CLRUnmanagedCodeCheck": "true",
                    "CreateHotPatchableImage": "X86Image",
                    "DataExecutionPrevention": "false",
                    "DelayLoadDLLs": "file1;file2",
                    "DelaySign": "true",
                    "Driver": "NotSet",
                    "EmbedManagedResourceFile": "file1;file2",
                    "EnableCOMDATFolding": "false",
                    "EnableUAC": "true",
                    "EntryPointSymbol": "a string1",
                    "FixedBaseAddress": "false",
                    "ForceFileOutput": "Enabled",
                    "ForceSymbolReferences": "file1;file2",
                    "FunctionOrder": "a_file_name",
                    "GenerateDebugInformation": "true",
                    "GenerateMapFile": "true",
                    "HeapCommitSize": "a string1",
                    "HeapReserveSize": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreEmbeddedIDL": "true",
                    "IgnoreSpecificDefaultLibraries": "a_file_list",
                    "ImageHasSafeExceptionHandlers": "true",
                    "ImportLibrary": "a_file_name",
                    "KeyContainer": "a_file_name",
                    "KeyFile": "a_file_name",
                    "LargeAddressAware": "false",
                    "LinkDLL": "true",
                    "LinkErrorReporting": "SendErrorReport",
                    "LinkStatus": "true",
                    "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                    "ManifestFile": "a_file_name",
                    "MapExports": "true",
                    "MapFileName": "a_file_name",
                    "MergedIDLBaseFileName": "a_file_name",
                    "MergeSections": "a string1",
                    "MidlCommandFile": "a_file_name",
                    "MinimumRequiredVersion": "a string1",
                    "ModuleDefinitionFile": "a_file_name",
                    "MSDOSStubFileName": "a_file_name",
                    "NoEntryPoint": "true",
                    "OptimizeReferences": "false",
                    "OutputFile": "a_file_name",
                    "PerUserRedirection": "true",
                    "PreventDllBinding": "true",
                    "Profile": "true",
                    "ProfileGuidedDatabase": "a_file_name",
                    "ProgramDatabaseFile": "a_file_name",
                    "RandomizedBaseAddress": "false",
                    "RegisterOutput": "true",
                    "SectionAlignment": "33",
                    "SetChecksum": "true",
                    "ShowProgress": "LinkVerboseREF",
                    "SpecifySectionAttributes": "a string1",
                    "StackCommitSize": "a string1",
                    "StackReserveSize": "a string1",
                    "StripPrivateSymbols": "a_file_name",
                    "SubSystem": "Console",
                    "SupportNobindOfDelayLoadedDLL": "true",
                    "SupportUnloadOfDelayLoadedDLL": "true",
                    "SuppressStartupBanner": "true",
                    "SwapRunFromCD": "true",
                    "SwapRunFromNET": "true",
                    "TargetMachine": "MachineX86",
                    "TerminalServerAware": "false",
                    "TrackerLogDirectory": "a_folder",
                    "TreatLinkerWarningAsErrors": "true",
                    "TurnOffAssemblyGeneration": "true",
                    "TypeLibraryFile": "a_file_name",
                    "TypeLibraryResourceID": "33",
                    "UACExecutionLevel": "AsInvoker",
                    "UACUIAccess": "true",
                    "Version": "a string1",
                },
                "ResourceCompile": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "Culture": "0x236",
                    "IgnoreStandardIncludePath": "true",
                    "NullTerminateStrings": "true",
                    "PreprocessorDefinitions": "string1;string2",
                    "ResourceOutputFileName": "a string1",
                    "ShowProgress": "true",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                },
                "Midl": {
                    "AdditionalIncludeDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "ApplicationConfigurationMode": "true",
                    "ClientStubFile": "a_file_name",
                    "CPreprocessOptions": "a string1",
                    "DefaultCharType": "Signed",
                    "DllDataFileName": "a_file_name",
                    "EnableErrorChecks": "EnableCustom",
                    "ErrorCheckAllocations": "true",
                    "ErrorCheckBounds": "true",
                    "ErrorCheckEnumRange": "true",
                    "ErrorCheckRefPointers": "true",
                    "ErrorCheckStubData": "true",
                    "GenerateClientFiles": "Stub",
                    "GenerateServerFiles": "None",
                    "GenerateStublessProxies": "true",
                    "GenerateTypeLibrary": "true",
                    "HeaderFileName": "a_file_name",
                    "IgnoreStandardIncludePath": "true",
                    "InterfaceIdentifierFileName": "a_file_name",
                    "LocaleID": "33",
                    "MkTypLibCompatible": "true",
                    "OutputDirectory": "a string1",
                    "PreprocessorDefinitions": "string1;string2",
                    "ProxyFileName": "a_file_name",
                    "RedirectOutputAndErrors": "a_file_name",
                    "ServerStubFile": "a_file_name",
                    "StructMemberAlignment": "NotSet",
                    "SuppressCompilerWarnings": "true",
                    "SuppressStartupBanner": "true",
                    "TargetEnvironment": "Itanium",
                    "TrackerLogDirectory": "a_folder",
                    "TypeLibFormat": "NewFormat",
                    "TypeLibraryName": "a_file_name",
                    "UndefinePreprocessorDefinitions": "string1;string2",
                    "ValidateAllParameters": "true",
                    "WarnAsError": "true",
                    "WarningLevel": "1",
                },
                "Lib": {
                    "AdditionalDependencies": "file1;file2",
                    "AdditionalLibraryDirectories": "folder1;folder2",
                    "AdditionalOptions": "a string1",
                    "DisplayLibrary": "a string1",
                    "ErrorReporting": "PromptImmediately",
                    "ExportNamedFunctions": "string1;string2",
                    "ForceSymbolReferences": "a string1",
                    "IgnoreAllDefaultLibraries": "true",
                    "IgnoreSpecificDefaultLibraries": "file1;file2",
                    "LinkTimeCodeGeneration": "true",
                    "MinimumRequiredVersion": "a string1",
                    "ModuleDefinitionFile": "a_file_name",
                    "Name": "a_file_name",
                    "OutputFile": "a_file_name",
                    "RemoveObjects": "file1;file2",
                    "SubSystem": "Console",
                    "SuppressStartupBanner": "true",
                    "TargetMachine": "MachineX86i",
                    "TrackerLogDirectory": "a_folder",
                    "TreatLibWarningAsErrors": "true",
                    "UseUnicodeResponseFiles": "true",
                    "Verbose": "true",
                },
                "Manifest": {
                    "AdditionalManifestFiles": "file1;file2",
                    "AdditionalOptions": "a string1",
                    "AssemblyIdentity": "a string1",
                    "ComponentFileName": "a_file_name",
                    "EnableDPIAwareness": "fal",
                    "GenerateCatalogFiles": "truel",
                    "GenerateCategoryTags": "true",
                    "InputResourceManifests": "a string1",
                    "ManifestFromManagedAssembly": "a_file_name",
                    "notgood3": "bogus",
                    "OutputManifestFile": "a_file_name",
                    "OutputResourceManifests": "a string1",
                    "RegistrarScriptFile": "a_file_name",
                    "ReplacementsFile": "a_file_name",
                    "SuppressDependencyElement": "true",
                    "SuppressStartupBanner": "true",
                    "TrackerLogDirectory": "a_folder",
                    "TypeLibraryFile": "a_file_name",
                    "UpdateFileHashes": "true",
                    "UpdateFileHashesSearchPath": "a_file_name",
                    "VerboseOutput": "true",
                },
                "ProjectReference": {
                    "LinkLibraryDependencies": "true",
                    "UseLibraryDependencyInputs": "true",
                },
                "ManifestResourceCompile": {"ResourceOutputFileName": "a_file_name"},
                "": {
                    "EmbedManifest": "true",
                    "GenerateManifest": "true",
                    "IgnoreImportLibrary": "true",
                    "LinkIncremental": "false",
                },
            },
            self.stderr,
        )
        self._ExpectedWarnings(
            [
                "Warning: unrecognized setting ClCompile/Enableprefast",
                "Warning: unrecognized setting ClCompile/ZZXYZ",
                "Warning: unrecognized setting Manifest/notgood3",
                "Warning: for Manifest/GenerateCatalogFiles, "
                "expected bool; got 'truel'",
                "Warning: for Lib/TargetMachine, unrecognized enumerated value "
                "MachineX86i",
                "Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'",
            ]
        )

    def testConvertToMSBuildSettings_empty(self):
        """Tests an empty conversion."""
        msvs_settings = {}
        expected_msbuild_settings = {}
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_minimal(self):
        """Tests a minimal conversion."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/foo",
                "BasicRuntimeChecks": "0",
            },
            "VCLinkerTool": {
                "LinkTimeCodeGeneration": "1",
                "ErrorReporting": "1",
                "DataExecutionPrevention": "2",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/foo",
                "BasicRuntimeChecks": "Default",
            },
            "Link": {
                "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                "LinkErrorReporting": "PromptImmediately",
                "DataExecutionPrevention": "true",
            },
        }
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_warnings(self):
        """Tests conversion that generates warnings."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "1",
                "AdditionalOptions": "2",
                # These are incorrect values:
                "BasicRuntimeChecks": "12",
                "BrowseInformation": "21",
                "UsePrecompiledHeader": "13",
                "GeneratePreprocessedFile": "14",
            },
            "VCLinkerTool": {
                # These are incorrect values:
                "Driver": "10",
                "LinkTimeCodeGeneration": "31",
                "ErrorReporting": "21",
                "FixedBaseAddress": "6",
            },
            "VCResourceCompilerTool": {
                # Custom
                "Culture": "1003"
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "1",
                "AdditionalOptions": "2",
            },
            "Link": {},
            "ResourceCompile": {
                # Custom
                "Culture": "0x03eb"
            },
        }
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings(
            [
                "Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to "
                "MSBuild, index value (12) not in expected range [0, 4)",
                "Warning: while converting VCCLCompilerTool/BrowseInformation to "
                "MSBuild, index value (21) not in expected range [0, 3)",
                "Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to "
                "MSBuild, index value (13) not in expected range [0, 3)",
                "Warning: while converting "
                "VCCLCompilerTool/GeneratePreprocessedFile to "
                "MSBuild, value must be one of [0, 1, 2]; got 14",
                "Warning: while converting VCLinkerTool/Driver to "
                "MSBuild, index value (10) not in expected range [0, 4)",
                "Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to "
                "MSBuild, index value (31) not in expected range [0, 5)",
                "Warning: while converting VCLinkerTool/ErrorReporting to "
                "MSBuild, index value (21) not in expected range [0, 3)",
                "Warning: while converting VCLinkerTool/FixedBaseAddress to "
                "MSBuild, index value (6) not in expected range [0, 3)",
            ]
        )

    def testConvertToMSBuildSettings_full_synthetic(self):
        """Tests conversion of all the MSBuild settings."""
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "AdditionalUsingDirectories": "folder1;folder2;folder3",
                "AssemblerListingLocation": "a_file_name",
                "AssemblerOutput": "0",
                "BasicRuntimeChecks": "1",
                "BrowseInformation": "2",
                "BrowseInformationFile": "a_file_name",
                "BufferSecurityCheck": "true",
                "CallingConvention": "0",
                "CompileAs": "1",
                "DebugInformationFormat": "4",
                "DefaultCharIsUnsigned": "true",
                "Detect64BitPortabilityProblems": "true",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "d1;d2;d3",
                "EnableEnhancedInstructionSet": "0",
                "EnableFiberSafeOptimizations": "true",
                "EnableFunctionLevelLinking": "true",
                "EnableIntrinsicFunctions": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "1",
                "ExceptionHandling": "2",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "0",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "1",
                "ForceConformanceInForLoopScope": "true",
                "ForcedIncludeFiles": "file1;file2;file3",
                "ForcedUsingFiles": "file1;file2;file3",
                "GeneratePreprocessedFile": "1",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "2",
                "KeepComments": "true",
                "MinimalRebuild": "true",
                "ObjectFile": "a_file_name",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMP": "true",
                "Optimization": "3",
                "PrecompiledHeaderFile": "a_file_name",
                "PrecompiledHeaderThrough": "a_file_name",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProgramDataBaseFileName": "a_file_name",
                "RuntimeLibrary": "0",
                "RuntimeTypeInfo": "true",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "1",
                "SuppressStartupBanner": "true",
                "TreatWChar_tAsBuiltInType": "true",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "UseFullPaths": "true",
                "UsePrecompiledHeader": "1",
                "UseUnicodeResponseFiles": "true",
                "WarnAsError": "true",
                "WarningLevel": "2",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "a_file_name",
            },
            "VCLinkerTool": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3",
                "AdditionalManifestDependencies": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AddModuleNamesToAssembly": "file1;file2;file3",
                "AllowIsolation": "true",
                "AssemblyDebug": "0",
                "AssemblyLinkResource": "file1;file2;file3",
                "BaseAddress": "a_string",
                "CLRImageType": "1",
                "CLRThreadAttribute": "2",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "0",
                "DelayLoadDLLs": "file1;file2;file3",
                "DelaySign": "true",
                "Driver": "1",
                "EmbedManagedResourceFile": "file1;file2;file3",
                "EnableCOMDATFolding": "0",
                "EnableUAC": "true",
                "EntryPointSymbol": "a_string",
                "ErrorReporting": "0",
                "FixedBaseAddress": "1",
                "ForceSymbolReferences": "file1;file2;file3",
                "FunctionOrder": "a_file_name",
                "GenerateDebugInformation": "true",
                "GenerateManifest": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "a_string",
                "HeapReserveSize": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreDefaultLibraryNames": "file1;file2;file3",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreImportLibrary": "true",
                "ImportLibrary": "a_file_name",
                "KeyContainer": "a_file_name",
                "KeyFile": "a_file_name",
                "LargeAddressAware": "2",
                "LinkIncremental": "1",
                "LinkLibraryDependencies": "true",
                "LinkTimeCodeGeneration": "2",
                "ManifestFile": "a_file_name",
                "MapExports": "true",
                "MapFileName": "a_file_name",
                "MergedIDLBaseFileName": "a_file_name",
                "MergeSections": "a_string",
                "MidlCommandFile": "a_file_name",
                "ModuleDefinitionFile": "a_file_name",
                "OptimizeForWindows98": "1",
                "OptimizeReferences": "0",
                "OutputFile": "a_file_name",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "a_file_name",
                "ProgramDatabaseFile": "a_file_name",
                "RandomizedBaseAddress": "1",
                "RegisterOutput": "true",
                "ResourceOnlyDLL": "true",
                "SetChecksum": "true",
                "ShowProgress": "0",
                "StackCommitSize": "a_string",
                "StackReserveSize": "a_string",
                "StripPrivateSymbols": "a_file_name",
                "SubSystem": "2",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "true",
                "SwapRunFromCD": "true",
                "SwapRunFromNet": "true",
                "TargetMachine": "3",
                "TerminalServerAware": "2",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "a_file_name",
                "TypeLibraryResourceID": "33",
                "UACExecutionLevel": "1",
                "UACUIAccess": "true",
                "UseLibraryDependencyInputs": "false",
                "UseUnicodeResponseFiles": "true",
                "Version": "a_string",
            },
            "VCResourceCompilerTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "Culture": "1003",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ResourceOutputFileName": "a_string",
                "ShowProgress": "true",
                "SuppressStartupBanner": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
            },
            "VCMIDLTool": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "CPreprocessOptions": "a_string",
                "DefaultCharType": "0",
                "DLLDataFileName": "a_file_name",
                "EnableErrorChecks": "2",
                "ErrorCheckAllocations": "true",
                "ErrorCheckBounds": "true",
                "ErrorCheckEnumRange": "true",
                "ErrorCheckRefPointers": "true",
                "ErrorCheckStubData": "true",
                "GenerateStublessProxies": "true",
                "GenerateTypeLibrary": "true",
                "HeaderFileName": "a_file_name",
                "IgnoreStandardIncludePath": "true",
                "InterfaceIdentifierFileName": "a_file_name",
                "MkTypLibCompatible": "true",
                "OutputDirectory": "a_string",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProxyFileName": "a_file_name",
                "RedirectOutputAndErrors": "a_file_name",
                "StructMemberAlignment": "3",
                "SuppressStartupBanner": "true",
                "TargetEnvironment": "1",
                "TypeLibraryName": "a_file_name",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "ValidateParameters": "true",
                "WarnAsError": "true",
                "WarningLevel": "4",
            },
            "VCLibrarianTool": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "ExportNamedFunctions": "d1;d2;d3",
                "ForceSymbolReferences": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "LinkLibraryDependencies": "true",
                "ModuleDefinitionFile": "a_file_name",
                "OutputFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "UseUnicodeResponseFiles": "true",
            },
            "VCManifestTool": {
                "AdditionalManifestFiles": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AssemblyIdentity": "a_string",
                "ComponentFileName": "a_file_name",
                "DependencyInformationFile": "a_file_name",
                "EmbedManifest": "true",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "a_string",
                "ManifestResourceFile": "my_name",
                "OutputManifestFile": "a_file_name",
                "RegistrarScriptFile": "a_file_name",
                "ReplacementsFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "TypeLibraryFile": "a_file_name",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "a_file_name",
                "UseFAT32Workaround": "true",
                "UseUnicodeResponseFiles": "true",
                "VerboseOutput": "true",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string /J",
                "AdditionalUsingDirectories": "folder1;folder2;folder3",
                "AssemblerListingLocation": "a_file_name",
                "AssemblerOutput": "NoListing",
                "BasicRuntimeChecks": "StackFrameRuntimeCheck",
                "BrowseInformation": "true",
                "BrowseInformationFile": "a_file_name",
                "BufferSecurityCheck": "true",
                "CallingConvention": "Cdecl",
                "CompileAs": "CompileAsC",
                "DebugInformationFormat": "EditAndContinue",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "d1;d2;d3",
                "EnableEnhancedInstructionSet": "NotSet",
                "EnableFiberSafeOptimizations": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "Prompt",
                "ExceptionHandling": "Async",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "Neither",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "Strict",
                "ForceConformanceInForLoopScope": "true",
                "ForcedIncludeFiles": "file1;file2;file3",
                "ForcedUsingFiles": "file1;file2;file3",
                "FunctionLevelLinking": "true",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "AnySuitable",
                "IntrinsicFunctions": "true",
                "MinimalRebuild": "true",
                "ObjectFileName": "a_file_name",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMPSupport": "true",
                "Optimization": "Full",
                "PrecompiledHeader": "Create",
                "PrecompiledHeaderFile": "a_file_name",
                "PrecompiledHeaderOutputFile": "a_file_name",
                "PreprocessKeepComments": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "PreprocessSuppressLineNumbers": "false",
                "PreprocessToFile": "true",
                "ProgramDataBaseFileName": "a_file_name",
                "RuntimeLibrary": "MultiThreaded",
                "RuntimeTypeInfo": "true",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "1Byte",
                "SuppressStartupBanner": "true",
                "TreatWarningAsError": "true",
                "TreatWChar_tAsBuiltInType": "true",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "UseFullPaths": "true",
                "WarningLevel": "Level2",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "a_file_name",
            },
            "Link": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalManifestDependencies": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AddModuleNamesToAssembly": "file1;file2;file3",
                "AllowIsolation": "true",
                "AssemblyDebug": "",
                "AssemblyLinkResource": "file1;file2;file3",
                "BaseAddress": "a_string",
                "CLRImageType": "ForceIJWImage",
                "CLRThreadAttribute": "STAThreadingAttribute",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "",
                "DelayLoadDLLs": "file1;file2;file3",
                "DelaySign": "true",
                "Driver": "Driver",
                "EmbedManagedResourceFile": "file1;file2;file3",
                "EnableCOMDATFolding": "",
                "EnableUAC": "true",
                "EntryPointSymbol": "a_string",
                "FixedBaseAddress": "false",
                "ForceSymbolReferences": "file1;file2;file3",
                "FunctionOrder": "a_file_name",
                "GenerateDebugInformation": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "a_string",
                "HeapReserveSize": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "ImportLibrary": "a_file_name",
                "KeyContainer": "a_file_name",
                "KeyFile": "a_file_name",
                "LargeAddressAware": "true",
                "LinkErrorReporting": "NoErrorReport",
                "LinkTimeCodeGeneration": "PGInstrument",
                "ManifestFile": "a_file_name",
                "MapExports": "true",
                "MapFileName": "a_file_name",
                "MergedIDLBaseFileName": "a_file_name",
                "MergeSections": "a_string",
                "MidlCommandFile": "a_file_name",
                "ModuleDefinitionFile": "a_file_name",
                "NoEntryPoint": "true",
                "OptimizeReferences": "",
                "OutputFile": "a_file_name",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "a_file_name",
                "ProgramDatabaseFile": "a_file_name",
                "RandomizedBaseAddress": "false",
                "RegisterOutput": "true",
                "SetChecksum": "true",
                "ShowProgress": "NotSet",
                "StackCommitSize": "a_string",
                "StackReserveSize": "a_string",
                "StripPrivateSymbols": "a_file_name",
                "SubSystem": "Windows",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "true",
                "SwapRunFromCD": "true",
                "SwapRunFromNET": "true",
                "TargetMachine": "MachineARM",
                "TerminalServerAware": "true",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "a_file_name",
                "TypeLibraryResourceID": "33",
                "UACExecutionLevel": "HighestAvailable",
                "UACUIAccess": "true",
                "Version": "a_string",
            },
            "ResourceCompile": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "Culture": "0x03eb",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ResourceOutputFileName": "a_string",
                "ShowProgress": "true",
                "SuppressStartupBanner": "true",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
            },
            "Midl": {
                "AdditionalIncludeDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "CPreprocessOptions": "a_string",
                "DefaultCharType": "Unsigned",
                "DllDataFileName": "a_file_name",
                "EnableErrorChecks": "All",
                "ErrorCheckAllocations": "true",
                "ErrorCheckBounds": "true",
                "ErrorCheckEnumRange": "true",
                "ErrorCheckRefPointers": "true",
                "ErrorCheckStubData": "true",
                "GenerateStublessProxies": "true",
                "GenerateTypeLibrary": "true",
                "HeaderFileName": "a_file_name",
                "IgnoreStandardIncludePath": "true",
                "InterfaceIdentifierFileName": "a_file_name",
                "MkTypLibCompatible": "true",
                "OutputDirectory": "a_string",
                "PreprocessorDefinitions": "d1;d2;d3",
                "ProxyFileName": "a_file_name",
                "RedirectOutputAndErrors": "a_file_name",
                "StructMemberAlignment": "4",
                "SuppressStartupBanner": "true",
                "TargetEnvironment": "Win32",
                "TypeLibraryName": "a_file_name",
                "UndefinePreprocessorDefinitions": "d1;d2;d3",
                "ValidateAllParameters": "true",
                "WarnAsError": "true",
                "WarningLevel": "4",
            },
            "Lib": {
                "AdditionalDependencies": "file1;file2;file3",
                "AdditionalLibraryDirectories": "folder1;folder2;folder3",
                "AdditionalOptions": "a_string",
                "ExportNamedFunctions": "d1;d2;d3",
                "ForceSymbolReferences": "a_string",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreSpecificDefaultLibraries": "file1;file2;file3",
                "ModuleDefinitionFile": "a_file_name",
                "OutputFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "UseUnicodeResponseFiles": "true",
            },
            "Manifest": {
                "AdditionalManifestFiles": "file1;file2;file3",
                "AdditionalOptions": "a_string",
                "AssemblyIdentity": "a_string",
                "ComponentFileName": "a_file_name",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "a_string",
                "OutputManifestFile": "a_file_name",
                "RegistrarScriptFile": "a_file_name",
                "ReplacementsFile": "a_file_name",
                "SuppressStartupBanner": "true",
                "TypeLibraryFile": "a_file_name",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "a_file_name",
                "VerboseOutput": "true",
            },
            "ManifestResourceCompile": {"ResourceOutputFileName": "my_name"},
            "ProjectReference": {
                "LinkLibraryDependencies": "true",
                "UseLibraryDependencyInputs": "false",
            },
            "": {
                "EmbedManifest": "true",
                "GenerateManifest": "true",
                "IgnoreImportLibrary": "true",
                "LinkIncremental": "false",
            },
        }
        self.maxDiff = 9999  # on failure display a long diff
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])

    def testConvertToMSBuildSettings_actual(self):
        """Tests the conversion of an actual project.

    A VS2008 project with most of the options defined was created through the
    VS2008 IDE.  It was then converted to VS2010.  The tool settings found in
    the .vcproj and .vcxproj files were converted to the two dictionaries
    msvs_settings and expected_msbuild_settings.

    Note that for many settings, the VS2010 converter adds macros like
    %(AdditionalIncludeDirectories) to make sure than inherited values are
    included.  Since the Gyp projects we generate do not use inheritance,
    we removed these macros.  They were:
        ClCompile:
            AdditionalIncludeDirectories:  ';%(AdditionalIncludeDirectories)'
            AdditionalOptions:  ' %(AdditionalOptions)'
            AdditionalUsingDirectories:  ';%(AdditionalUsingDirectories)'
            DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
            ForcedIncludeFiles:  ';%(ForcedIncludeFiles)',
            ForcedUsingFiles:  ';%(ForcedUsingFiles)',
            PreprocessorDefinitions:  ';%(PreprocessorDefinitions)',
            UndefinePreprocessorDefinitions:
                ';%(UndefinePreprocessorDefinitions)',
        Link:
            AdditionalDependencies:  ';%(AdditionalDependencies)',
            AdditionalLibraryDirectories:  ';%(AdditionalLibraryDirectories)',
            AdditionalManifestDependencies:
                ';%(AdditionalManifestDependencies)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            AddModuleNamesToAssembly:  ';%(AddModuleNamesToAssembly)',
            AssemblyLinkResource:  ';%(AssemblyLinkResource)',
            DelayLoadDLLs:  ';%(DelayLoadDLLs)',
            EmbedManagedResourceFile:  ';%(EmbedManagedResourceFile)',
            ForceSymbolReferences:  ';%(ForceSymbolReferences)',
            IgnoreSpecificDefaultLibraries:
                ';%(IgnoreSpecificDefaultLibraries)',
        ResourceCompile:
            AdditionalIncludeDirectories:  ';%(AdditionalIncludeDirectories)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            PreprocessorDefinitions:  ';%(PreprocessorDefinitions)',
        Manifest:
            AdditionalManifestFiles:  ';%(AdditionalManifestFiles)',
            AdditionalOptions:  ' %(AdditionalOptions)',
            InputResourceManifests:  ';%(InputResourceManifests)',
    """
        msvs_settings = {
            "VCCLCompilerTool": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/more",
                "AdditionalUsingDirectories": "test",
                "AssemblerListingLocation": "$(IntDir)\\a",
                "AssemblerOutput": "1",
                "BasicRuntimeChecks": "3",
                "BrowseInformation": "1",
                "BrowseInformationFile": "$(IntDir)\\e",
                "BufferSecurityCheck": "false",
                "CallingConvention": "1",
                "CompileAs": "1",
                "DebugInformationFormat": "4",
                "DefaultCharIsUnsigned": "true",
                "Detect64BitPortabilityProblems": "true",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "abc",
                "EnableEnhancedInstructionSet": "1",
                "EnableFiberSafeOptimizations": "true",
                "EnableFunctionLevelLinking": "true",
                "EnableIntrinsicFunctions": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "2",
                "ExceptionHandling": "2",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "2",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "1",
                "ForceConformanceInForLoopScope": "false",
                "ForcedIncludeFiles": "def",
                "ForcedUsingFiles": "ge",
                "GeneratePreprocessedFile": "2",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "1",
                "KeepComments": "true",
                "MinimalRebuild": "true",
                "ObjectFile": "$(IntDir)\\b",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMP": "true",
                "Optimization": "3",
                "PrecompiledHeaderFile": "$(IntDir)\\$(TargetName).pche",
                "PrecompiledHeaderThrough": "StdAfx.hd",
                "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE",
                "ProgramDataBaseFileName": "$(IntDir)\\vc90b.pdb",
                "RuntimeLibrary": "3",
                "RuntimeTypeInfo": "false",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "3",
                "SuppressStartupBanner": "false",
                "TreatWChar_tAsBuiltInType": "false",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "wer",
                "UseFullPaths": "true",
                "UsePrecompiledHeader": "0",
                "UseUnicodeResponseFiles": "false",
                "WarnAsError": "true",
                "WarningLevel": "3",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "$(IntDir)\\c",
            },
            "VCLinkerTool": {
                "AdditionalDependencies": "zx",
                "AdditionalLibraryDirectories": "asd",
                "AdditionalManifestDependencies": "s2",
                "AdditionalOptions": "/mor2",
                "AddModuleNamesToAssembly": "d1",
                "AllowIsolation": "false",
                "AssemblyDebug": "1",
                "AssemblyLinkResource": "d5",
                "BaseAddress": "23423",
                "CLRImageType": "3",
                "CLRThreadAttribute": "1",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "0",
                "DelayLoadDLLs": "d4",
                "DelaySign": "true",
                "Driver": "2",
                "EmbedManagedResourceFile": "d2",
                "EnableCOMDATFolding": "1",
                "EnableUAC": "false",
                "EntryPointSymbol": "f5",
                "ErrorReporting": "2",
                "FixedBaseAddress": "1",
                "ForceSymbolReferences": "d3",
                "FunctionOrder": "fssdfsd",
                "GenerateDebugInformation": "true",
                "GenerateManifest": "false",
                "GenerateMapFile": "true",
                "HeapCommitSize": "13",
                "HeapReserveSize": "12",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreDefaultLibraryNames": "flob;flok",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreImportLibrary": "true",
                "ImportLibrary": "f4",
                "KeyContainer": "f7",
                "KeyFile": "f6",
                "LargeAddressAware": "2",
                "LinkIncremental": "0",
                "LinkLibraryDependencies": "false",
                "LinkTimeCodeGeneration": "1",
                "ManifestFile": "$(IntDir)\\$(TargetFileName).2intermediate.manifest",
                "MapExports": "true",
                "MapFileName": "d5",
                "MergedIDLBaseFileName": "f2",
                "MergeSections": "f5",
                "MidlCommandFile": "f1",
                "ModuleDefinitionFile": "sdsd",
                "OptimizeForWindows98": "2",
                "OptimizeReferences": "2",
                "OutputFile": "$(OutDir)\\$(ProjectName)2.exe",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd",
                "ProgramDatabaseFile": "Flob.pdb",
                "RandomizedBaseAddress": "1",
                "RegisterOutput": "true",
                "ResourceOnlyDLL": "true",
                "SetChecksum": "false",
                "ShowProgress": "1",
                "StackCommitSize": "15",
                "StackReserveSize": "14",
                "StripPrivateSymbols": "d3",
                "SubSystem": "1",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "false",
                "SwapRunFromCD": "true",
                "SwapRunFromNet": "true",
                "TargetMachine": "1",
                "TerminalServerAware": "1",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "f3",
                "TypeLibraryResourceID": "12",
                "UACExecutionLevel": "2",
                "UACUIAccess": "true",
                "UseLibraryDependencyInputs": "true",
                "UseUnicodeResponseFiles": "false",
                "Version": "333",
            },
            "VCResourceCompilerTool": {
                "AdditionalIncludeDirectories": "f3",
                "AdditionalOptions": "/more3",
                "Culture": "3084",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "_UNICODE;UNICODE2",
                "ResourceOutputFileName": "$(IntDir)/$(InputName)3.res",
                "ShowProgress": "true",
            },
            "VCManifestTool": {
                "AdditionalManifestFiles": "sfsdfsd",
                "AdditionalOptions": "afdsdafsd",
                "AssemblyIdentity": "sddfdsadfsa",
                "ComponentFileName": "fsdfds",
                "DependencyInformationFile": "$(IntDir)\\mt.depdfd",
                "EmbedManifest": "false",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "asfsfdafs",
                "ManifestResourceFile":
                    "$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf",
                "OutputManifestFile": "$(TargetPath).manifestdfs",
                "RegistrarScriptFile": "sdfsfd",
                "ReplacementsFile": "sdffsd",
                "SuppressStartupBanner": "false",
                "TypeLibraryFile": "sfsd",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "sfsd",
                "UseFAT32Workaround": "true",
                "UseUnicodeResponseFiles": "false",
                "VerboseOutput": "true",
            },
        }
        expected_msbuild_settings = {
            "ClCompile": {
                "AdditionalIncludeDirectories": "dir1",
                "AdditionalOptions": "/more /J",
                "AdditionalUsingDirectories": "test",
                "AssemblerListingLocation": "$(IntDir)a",
                "AssemblerOutput": "AssemblyCode",
                "BasicRuntimeChecks": "EnableFastChecks",
                "BrowseInformation": "true",
                "BrowseInformationFile": "$(IntDir)e",
                "BufferSecurityCheck": "false",
                "CallingConvention": "FastCall",
                "CompileAs": "CompileAsC",
                "DebugInformationFormat": "EditAndContinue",
                "DisableLanguageExtensions": "true",
                "DisableSpecificWarnings": "abc",
                "EnableEnhancedInstructionSet": "StreamingSIMDExtensions",
                "EnableFiberSafeOptimizations": "true",
                "EnablePREfast": "true",
                "ErrorReporting": "Queue",
                "ExceptionHandling": "Async",
                "ExpandAttributedSource": "true",
                "FavorSizeOrSpeed": "Size",
                "FloatingPointExceptions": "true",
                "FloatingPointModel": "Strict",
                "ForceConformanceInForLoopScope": "false",
                "ForcedIncludeFiles": "def",
                "ForcedUsingFiles": "ge",
                "FunctionLevelLinking": "true",
                "GenerateXMLDocumentationFiles": "true",
                "IgnoreStandardIncludePath": "true",
                "InlineFunctionExpansion": "OnlyExplicitInline",
                "IntrinsicFunctions": "true",
                "MinimalRebuild": "true",
                "ObjectFileName": "$(IntDir)b",
                "OmitDefaultLibName": "true",
                "OmitFramePointers": "true",
                "OpenMPSupport": "true",
                "Optimization": "Full",
                "PrecompiledHeader": "NotUsing",  # Actual conversion gives ''
                "PrecompiledHeaderFile": "StdAfx.hd",
                "PrecompiledHeaderOutputFile": "$(IntDir)$(TargetName).pche",
                "PreprocessKeepComments": "true",
                "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE",
                "PreprocessSuppressLineNumbers": "true",
                "PreprocessToFile": "true",
                "ProgramDataBaseFileName": "$(IntDir)vc90b.pdb",
                "RuntimeLibrary": "MultiThreadedDebugDLL",
                "RuntimeTypeInfo": "false",
                "ShowIncludes": "true",
                "SmallerTypeCheck": "true",
                "StringPooling": "true",
                "StructMemberAlignment": "4Bytes",
                "SuppressStartupBanner": "false",
                "TreatWarningAsError": "true",
                "TreatWChar_tAsBuiltInType": "false",
                "UndefineAllPreprocessorDefinitions": "true",
                "UndefinePreprocessorDefinitions": "wer",
                "UseFullPaths": "true",
                "WarningLevel": "Level3",
                "WholeProgramOptimization": "true",
                "XMLDocumentationFileName": "$(IntDir)c",
            },
            "Link": {
                "AdditionalDependencies": "zx",
                "AdditionalLibraryDirectories": "asd",
                "AdditionalManifestDependencies": "s2",
                "AdditionalOptions": "/mor2",
                "AddModuleNamesToAssembly": "d1",
                "AllowIsolation": "false",
                "AssemblyDebug": "true",
                "AssemblyLinkResource": "d5",
                "BaseAddress": "23423",
                "CLRImageType": "ForceSafeILImage",
                "CLRThreadAttribute": "MTAThreadingAttribute",
                "CLRUnmanagedCodeCheck": "true",
                "DataExecutionPrevention": "",
                "DelayLoadDLLs": "d4",
                "DelaySign": "true",
                "Driver": "UpOnly",
                "EmbedManagedResourceFile": "d2",
                "EnableCOMDATFolding": "false",
                "EnableUAC": "false",
                "EntryPointSymbol": "f5",
                "FixedBaseAddress": "false",
                "ForceSymbolReferences": "d3",
                "FunctionOrder": "fssdfsd",
                "GenerateDebugInformation": "true",
                "GenerateMapFile": "true",
                "HeapCommitSize": "13",
                "HeapReserveSize": "12",
                "IgnoreAllDefaultLibraries": "true",
                "IgnoreEmbeddedIDL": "true",
                "IgnoreSpecificDefaultLibraries": "flob;flok",
                "ImportLibrary": "f4",
                "KeyContainer": "f7",
                "KeyFile": "f6",
                "LargeAddressAware": "true",
                "LinkErrorReporting": "QueueForNextLogin",
                "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration",
                "ManifestFile": "$(IntDir)$(TargetFileName).2intermediate.manifest",
                "MapExports": "true",
                "MapFileName": "d5",
                "MergedIDLBaseFileName": "f2",
                "MergeSections": "f5",
                "MidlCommandFile": "f1",
                "ModuleDefinitionFile": "sdsd",
                "NoEntryPoint": "true",
                "OptimizeReferences": "true",
                "OutputFile": "$(OutDir)$(ProjectName)2.exe",
                "PerUserRedirection": "true",
                "Profile": "true",
                "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd",
                "ProgramDatabaseFile": "Flob.pdb",
                "RandomizedBaseAddress": "false",
                "RegisterOutput": "true",
                "SetChecksum": "false",
                "ShowProgress": "LinkVerbose",
                "StackCommitSize": "15",
                "StackReserveSize": "14",
                "StripPrivateSymbols": "d3",
                "SubSystem": "Console",
                "SupportUnloadOfDelayLoadedDLL": "true",
                "SuppressStartupBanner": "false",
                "SwapRunFromCD": "true",
                "SwapRunFromNET": "true",
                "TargetMachine": "MachineX86",
                "TerminalServerAware": "false",
                "TurnOffAssemblyGeneration": "true",
                "TypeLibraryFile": "f3",
                "TypeLibraryResourceID": "12",
                "UACExecutionLevel": "RequireAdministrator",
                "UACUIAccess": "true",
                "Version": "333",
            },
            "ResourceCompile": {
                "AdditionalIncludeDirectories": "f3",
                "AdditionalOptions": "/more3",
                "Culture": "0x0c0c",
                "IgnoreStandardIncludePath": "true",
                "PreprocessorDefinitions": "_UNICODE;UNICODE2",
                "ResourceOutputFileName": "$(IntDir)%(Filename)3.res",
                "ShowProgress": "true",
            },
            "Manifest": {
                "AdditionalManifestFiles": "sfsdfsd",
                "AdditionalOptions": "afdsdafsd",
                "AssemblyIdentity": "sddfdsadfsa",
                "ComponentFileName": "fsdfds",
                "GenerateCatalogFiles": "true",
                "InputResourceManifests": "asfsfdafs",
                "OutputManifestFile": "$(TargetPath).manifestdfs",
                "RegistrarScriptFile": "sdfsfd",
                "ReplacementsFile": "sdffsd",
                "SuppressStartupBanner": "false",
                "TypeLibraryFile": "sfsd",
                "UpdateFileHashes": "true",
                "UpdateFileHashesSearchPath": "sfsd",
                "VerboseOutput": "true",
            },
            "ProjectReference": {
                "LinkLibraryDependencies": "false",
                "UseLibraryDependencyInputs": "true",
            },
            "": {
                "EmbedManifest": "false",
                "GenerateManifest": "false",
                "IgnoreImportLibrary": "true",
                "LinkIncremental": "",
            },
            "ManifestResourceCompile": {
                "ResourceOutputFileName":
                    "$(IntDir)$(TargetFileName).embed.manifest.resfdsf"
            },
        }
        self.maxDiff = 9999  # on failure display a long diff
        actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
            msvs_settings, self.stderr
        )
        self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
        self._ExpectedWarnings([])


if __name__ == "__main__":
    unittest.main()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    /*
 * WARNING: do not edit!
 * Generated by Makefile from include/openssl/x509.h.in
 *
 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */



#ifndef OPENSSL_X509_H
# define OPENSSL_X509_H
# pragma once

# include <openssl/macros.h>
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  define HEADER_X509_H
# endif

# include <openssl/e_os2.h>
# include <openssl/types.h>
# include <openssl/symhacks.h>
# include <openssl/buffer.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/asn1.h>
# include <openssl/safestack.h>
# include <openssl/ec.h>

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  include <openssl/rsa.h>
#  include <openssl/dsa.h>
#  include <openssl/dh.h>
# endif

# include <openssl/sha.h>
# include <openssl/x509err.h>

#ifdef  __cplusplus
extern "C" {
#endif

/* Needed stacks for types defined in other headers */
SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))


/* Flags for X509_get_signature_info() */
/* Signature info is valid */
# define X509_SIG_INFO_VALID     0x1
/* Signature is suitable for TLS use */
# define X509_SIG_INFO_TLS       0x2

# define X509_FILETYPE_PEM       1
# define X509_FILETYPE_ASN1      2
# define X509_FILETYPE_DEFAULT   3

# define X509v3_KU_DIGITAL_SIGNATURE     0x0080
# define X509v3_KU_NON_REPUDIATION       0x0040
# define X509v3_KU_KEY_ENCIPHERMENT      0x0020
# define X509v3_KU_DATA_ENCIPHERMENT     0x0010
# define X509v3_KU_KEY_AGREEMENT         0x0008
# define X509v3_KU_KEY_CERT_SIGN         0x0004
# define X509v3_KU_CRL_SIGN              0x0002
# define X509v3_KU_ENCIPHER_ONLY         0x0001
# define X509v3_KU_DECIPHER_ONLY         0x8000
# define X509v3_KU_UNDEF                 0xffff

struct X509_algor_st {
    ASN1_OBJECT *algorithm;
    ASN1_TYPE *parameter;
} /* X509_ALGOR */ ;

typedef STACK_OF(X509_ALGOR) X509_ALGORS;

typedef struct X509_val_st {
    ASN1_TIME *notBefore;
    ASN1_TIME *notAfter;
} X509_VAL;

typedef struct X509_sig_st X509_SIG;

typedef struct X509_name_entry_st X509_NAME_ENTRY;

SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))


# define X509_EX_V_NETSCAPE_HACK         0x8000
# define X509_EX_V_INIT                  0x0001
typedef struct X509_extension_st X509_EXTENSION;
SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))

typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
typedef struct x509_attributes_st X509_ATTRIBUTE;
SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))

typedef struct X509_req_info_st X509_REQ_INFO;
typedef struct X509_req_st X509_REQ;
typedef struct x509_cert_aux_st X509_CERT_AUX;
typedef struct x509_cinf_st X509_CINF;

/* Flags for X509_print_ex() */

# define X509_FLAG_COMPAT                0
# define X509_FLAG_NO_HEADER             1L
# define X509_FLAG_NO_VERSION            (1L << 1)
# define X509_FLAG_NO_SERIAL             (1L << 2)
# define X509_FLAG_NO_SIGNAME            (1L << 3)
# define X509_FLAG_NO_ISSUER             (1L << 4)
# define X509_FLAG_NO_VALIDITY           (1L << 5)
# define X509_FLAG_NO_SUBJECT            (1L << 6)
# define X509_FLAG_NO_PUBKEY             (1L << 7)
# define X509_FLAG_NO_EXTENSIONS         (1L << 8)
# define X509_FLAG_NO_SIGDUMP            (1L << 9)
# define X509_FLAG_NO_AUX                (1L << 10)
# define X509_FLAG_NO_ATTRIBUTES         (1L << 11)
# define X509_FLAG_NO_IDS                (1L << 12)
# define X509_FLAG_EXTENSIONS_ONLY_KID   (1L << 13)

/* Flags specific to X509_NAME_print_ex() */

/* The field separator information */

# define XN_FLAG_SEP_MASK        (0xf << 16)

# define XN_FLAG_COMPAT          0/* Traditional; use old X509_NAME_print */
# define XN_FLAG_SEP_COMMA_PLUS  (1 << 16)/* RFC2253 ,+ */
# define XN_FLAG_SEP_CPLUS_SPC   (2 << 16)/* ,+ spaced: more readable */
# define XN_FLAG_SEP_SPLUS_SPC   (3 << 16)/* ;+ spaced */
# define XN_FLAG_SEP_MULTILINE   (4 << 16)/* One line per field */

# define XN_FLAG_DN_REV          (1 << 20)/* Reverse DN order */

/* How the field name is shown */

# define XN_FLAG_FN_MASK         (0x3 << 21)

# define XN_FLAG_FN_SN           0/* Object short name */
# define XN_FLAG_FN_LN           (1 << 21)/* Object long name */
# define XN_FLAG_FN_OID          (2 << 21)/* Always use OIDs */
# define XN_FLAG_FN_NONE         (3 << 21)/* No field names */

# define XN_FLAG_SPC_EQ          (1 << 23)/* Put spaces round '=' */

/*
 * This determines if we dump fields we don't recognise: RFC2253 requires
 * this.
 */

# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)

# define XN_FLAG_FN_ALIGN        (1 << 25)/* Align field names to 20
                                           * characters */

/* Complete set of RFC2253 flags */

# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
                        XN_FLAG_SEP_COMMA_PLUS | \
                        XN_FLAG_DN_REV | \
                        XN_FLAG_FN_SN | \
                        XN_FLAG_DUMP_UNKNOWN_FIELDS)

/* readable oneline form */

# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
                        ASN1_STRFLGS_ESC_QUOTE | \
                        XN_FLAG_SEP_CPLUS_SPC | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_SN)

/* readable multiline form */

# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
                        ASN1_STRFLGS_ESC_MSB | \
                        XN_FLAG_SEP_MULTILINE | \
                        XN_FLAG_SPC_EQ | \
                        XN_FLAG_FN_LN | \
                        XN_FLAG_FN_ALIGN)

typedef struct X509_crl_info_st X509_CRL_INFO;

typedef struct private_key_st {
    int version;
    /* The PKCS#8 data types */
    X509_ALGOR *enc_algor;
    ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
    /* When decrypted, the following will not be NULL */
    EVP_PKEY *dec_pkey;
    /* used to encrypt and decrypt */
    int key_length;
    char *key_data;
    int key_free;               /* true if we should auto free key_data */
    /* expanded version of 'enc_algor' */
    EVP_CIPHER_INFO cipher;
} X509_PKEY;

typedef struct X509_info_st {
    X509 *x509;
    X509_CRL *crl;
    X509_PKEY *x_pkey;
    EVP_CIPHER_INFO enc_cipher;
    int enc_len;
    char *enc_data;
} X509_INFO;
SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))


/*
 * The next 2 structures and their 8 routines are used to manipulate Netscape's
 * spki structures - useful if you are writing a CA web page
 */
typedef struct Netscape_spkac_st {
    X509_PUBKEY *pubkey;
    ASN1_IA5STRING *challenge;  /* challenge sent in atlas >= PR2 */
} NETSCAPE_SPKAC;

typedef struct Netscape_spki_st {
    NETSCAPE_SPKAC *spkac;      /* signed public key and challenge */
    X509_ALGOR sig_algor;
    ASN1_BIT_STRING *signature;
} NETSCAPE_SPKI;

/* Netscape certificate sequence structure */
typedef struct Netscape_certificate_sequence {
    ASN1_OBJECT *type;
    STACK_OF(X509) *certs;
} NETSCAPE_CERT_SEQUENCE;

/*- Unused (and iv length is wrong)
typedef struct CBCParameter_st
        {
        unsigned char iv[8];
        } CBC_PARAM;
*/

/* Password based encryption structure */

typedef struct PBEPARAM_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *iter;
} PBEPARAM;

/* Password based encryption V2 structures */

typedef struct PBE2PARAM_st {
    X509_ALGOR *keyfunc;
    X509_ALGOR *encryption;
} PBE2PARAM;

typedef struct PBKDF2PARAM_st {
/* Usually OCTET STRING but could be anything */
    ASN1_TYPE *salt;
    ASN1_INTEGER *iter;
    ASN1_INTEGER *keylength;
    X509_ALGOR *prf;
} PBKDF2PARAM;

#ifndef OPENSSL_NO_SCRYPT
typedef struct SCRYPT_PARAMS_st {
    ASN1_OCTET_STRING *salt;
    ASN1_INTEGER *costParameter;
    ASN1_INTEGER *blockSize;
    ASN1_INTEGER *parallelizationParameter;
    ASN1_INTEGER *keyLength;
} SCRYPT_PARAMS;
#endif

#ifdef  __cplusplus
}
#endif

# include <openssl/x509_vfy.h>
# include <openssl/pkcs7.h>

#ifdef  __cplusplus
extern "C" {
#endif

# define X509_EXT_PACK_UNKNOWN   1
# define X509_EXT_PACK_STRING    2

# define         X509_extract_key(x)     X509_get_pubkey(x)/*****/
# define         X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
# define         X509_name_cmp(a,b)      X509_NAME_cmp((a),(b))

void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
                                     int (*crl_free) (X509_CRL *crl),
                                     int (*crl_lookup) (X509_CRL *crl,
                                                        X509_REVOKED **ret,
                                                        const
                                                        ASN1_INTEGER *serial,
                                                        const
                                                        X509_NAME *issuer),
                                     int (*crl_verify) (X509_CRL *crl,
                                                        EVP_PKEY *pk));
void X509_CRL_METHOD_free(X509_CRL_METHOD *m);

void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
void *X509_CRL_get_meth_data(X509_CRL *crl);

const char *X509_verify_cert_error_string(long n);

int X509_verify(X509 *a, EVP_PKEY *r);
int X509_self_signed(X509 *cert, int verify_signature);

int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
                       const char *propq);
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);

NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);

int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);

int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
                         const ASN1_STRING *sig);

int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);

int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
                       unsigned char *md, unsigned int *len);
int X509_digest(const X509 *data, const EVP_MD *type,
                unsigned char *md, unsigned int *len);
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
                                   EVP_MD **md_used, int *md_is_fallback);
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
                    unsigned char *md, unsigned int *len);
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
                     unsigned char *md, unsigned int *len);

X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  include <openssl/http.h> /* OSSL_HTTP_REQ_CTX_nbio_d2i */
#  define X509_http_nbio(rctx, pcert) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
#  define X509_CRL_http_nbio(rctx, pcrl) \
      OSSL_HTTP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
# endif

# ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509);
int i2d_X509_fp(FILE *fp, const X509 *x509);
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
#   endif
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
                                                PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                               const char *propq);
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
# endif

X509 *d2i_X509_bio(BIO *bp, X509 **x509);
int i2d_X509_bio(BIO *bp, const X509 *x509);
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
#  ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
#  endif
#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_DSA
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
#   endif
#  endif

#  ifndef OPENSSL_NO_DEPRECATED_3_0
#   ifndef OPENSSL_NO_EC
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
#   endif /* OPENSSL_NO_EC */
#  endif /* OPENSSL_NO_DEPRECATED_3_0 */

X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
                                                 PKCS8_PRIV_KEY_INFO **p8inf);
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
                                const char *propq);
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);

DECLARE_ASN1_DUP_FUNCTION(X509)
DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
                    void *pval);
void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
                     const void **ppval, const X509_ALGOR *algor);
void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);

DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)

int X509_cmp_time(const ASN1_TIME *s, time_t *t);
int X509_cmp_current_time(const ASN1_TIME *s);
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
                       const ASN1_TIME *start, const ASN1_TIME *end);
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
                            int offset_day, long offset_sec, time_t *t);
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);

const char *X509_get_default_cert_area(void);
const char *X509_get_default_cert_dir(void);
const char *X509_get_default_cert_file(void);
const char *X509_get_default_cert_dir_env(void);
const char *X509_get_default_cert_file_env(void);
const char *X509_get_default_private_dir(void);

X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);

DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
DECLARE_ASN1_FUNCTIONS(X509_VAL)

DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)

X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
long X509_get_pathlen(X509 *x);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
                        OSSL_LIB_CTX *libctx, const char *propq);
# ifndef OPENSSL_NO_DEPRECATED_3_0
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_DSA
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
#  endif
# endif
# ifndef OPENSSL_NO_DEPRECATED_3_0
#  ifndef OPENSSL_NO_EC
DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
#  endif
# endif

DECLARE_ASN1_FUNCTIONS(X509_SIG)
void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
                   const ASN1_OCTET_STRING **pdigest);
void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
                   ASN1_OCTET_STRING **pdigest);

DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
DECLARE_ASN1_FUNCTIONS(X509_REQ)
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);

DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)

DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)

DECLARE_ASN1_FUNCTIONS(X509_NAME)

int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(X509_CINF)
DECLARE_ASN1_FUNCTIONS(X509)
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)

#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
    CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
int X509_set_ex_data(X509 *r, int idx, void *arg);
void *X509_get_ex_data(const X509 *r, int idx);
DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)

int i2d_re_X509_tbs(X509 *x, unsigned char **pp);

int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
                      int *secbits, uint32_t *flags);
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
                       int secbits, uint32_t flags);

int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
                            uint32_t *flags);

void X509_get0_signature(const ASN1_BIT_STRING **psig,
                         const X509_ALGOR **palg, const X509 *x);
int X509_get_signature_nid(const X509 *x);

void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);

int X509_alias_set1(X509 *x, const unsigned char *name, int len);
int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
unsigned char *X509_alias_get0(X509 *x, int *len);
unsigned char *X509_keyid_get0(X509 *x, int *len);

DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
DECLARE_ASN1_FUNCTIONS(X509_CRL)
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);

int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
int X509_CRL_get0_by_serial(X509_CRL *crl,
                            X509_REVOKED **ret, const ASN1_INTEGER *serial);
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);

X509_PKEY *X509_PKEY_new(void);
void X509_PKEY_free(X509_PKEY *a);

DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)

X509_INFO *X509_INFO_new(void);
void X509_INFO_free(X509_INFO *a);
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);

#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_DEPRECATEDIN_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
                ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
OSSL_DEPRECATEDIN_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
                unsigned char *md, unsigned int *len);
OSSL_DEPRECATEDIN_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
              ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
              const EVP_MD *type);
#endif
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
                     unsigned char *md, unsigned int *len);
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
                     const ASN1_BIT_STRING *signature, const void *data,
                     EVP_PKEY *pkey);
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
                         const ASN1_BIT_STRING *signature, const void *data,
                         EVP_MD_CTX *ctx);
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
                   ASN1_BIT_STRING *signature, const void *data,
                   EVP_PKEY *pkey, const EVP_MD *md);
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
                       X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
                       const void *data, EVP_MD_CTX *ctx);

#define X509_VERSION_1 0
#define X509_VERSION_2 1
#define X509_VERSION_3 2

long X509_get_version(const X509 *x);
int X509_set_version(X509 *x, long version);
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
ASN1_INTEGER *X509_get_serialNumber(X509 *x);
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
int X509_set_issuer_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_issuer_name(const X509 *a);
int X509_set_subject_name(X509 *x, const X509_NAME *name);
X509_NAME *X509_get_subject_name(const X509 *a);
const ASN1_TIME * X509_get0_notBefore(const X509 *x);
ASN1_TIME *X509_getm_notBefore(const X509 *x);
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
const ASN1_TIME *X509_get0_notAfter(const X509 *x);
ASN1_TIME *X509_getm_notAfter(const X509 *x);
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
int X509_up_ref(X509 *x);
int X509_get_signature_type(const X509 *x);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_get_notBefore X509_getm_notBefore
#  define X509_get_notAfter X509_getm_notAfter
#  define X509_set_notBefore X509_set1_notBefore
#  define X509_set_notAfter X509_set1_notAfter
#endif


/*
 * This one is only used so that a binary form can output, as in
 * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
 */
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
                    const ASN1_BIT_STRING **psuid);
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);

EVP_PKEY *X509_get0_pubkey(const X509 *x);
EVP_PKEY *X509_get_pubkey(X509 *x);
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);

#define X509_REQ_VERSION_1 0

long X509_REQ_get_version(const X509_REQ *req);
int X509_REQ_set_version(X509_REQ *x, long version);
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
int X509_REQ_get_signature_nid(const X509_REQ *req);
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
int X509_REQ_extension_nid(int nid);
int *X509_REQ_get_extension_nids(void);
void X509_REQ_set_extension_nids(int *nids);
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
int X509_REQ_add_extensions_nid(X509_REQ *req,
                                const STACK_OF(X509_EXTENSION) *exts, int nid);
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
int X509_REQ_get_attr_count(const X509_REQ *req);
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

#define X509_CRL_VERSION_1 0
#define X509_CRL_VERSION_2 1

int X509_CRL_set_version(X509_CRL *x, long version);
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
int X509_CRL_sort(X509_CRL *crl);
int X509_CRL_up_ref(X509_CRL *crl);

# ifndef OPENSSL_NO_DEPRECATED_1_1_0
#  define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
#  define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
#endif

long X509_CRL_get_version(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
                             const X509_ALGOR **palg);
int X509_CRL_get_signature_nid(const X509_CRL *crl);
int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);

const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
const STACK_OF(X509_EXTENSION) *
X509_REVOKED_get0_extensions(const X509_REVOKED *r);

X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
                        EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);

int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);

int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
int X509_chain_check_suiteb(int *perror_depth,
                            X509 *x, STACK_OF(X509) *chain,
                            unsigned long flags);
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);

int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_and_serial_hash(X509 *a);

int X509_issuer_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_issuer_name_hash(X509 *a);

int X509_subject_name_cmp(const X509 *a, const X509 *b);
unsigned long X509_subject_name_hash(X509 *x);

# ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *a);
unsigned long X509_subject_name_hash_old(X509 *x);
# endif

# define X509_ADD_FLAG_DEFAULT  0
# define X509_ADD_FLAG_UP_REF   0x1
# define X509_ADD_FLAG_PREPEND  0x2
# define X509_ADD_FLAG_NO_DUP   0x4
# define X509_ADD_FLAG_NO_SS    0x8
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);

int X509_cmp(const X509 *a, const X509 *b);
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
                                                const EVP_PKEY *pubkey);
#endif
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
                                const char *propq, int *ok);
unsigned long X509_NAME_hash_old(const X509_NAME *x);

int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
int X509_aux_print(BIO *out, X509 *x, int indent);
# ifndef OPENSSL_NO_STDIO
int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
                     unsigned long cflag);
int X509_print_fp(FILE *bp, X509 *x);
int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
                          unsigned long flags);
# endif

int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
                       unsigned long flags);
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
                  unsigned long cflag);
int X509_print(BIO *bp, X509 *x);
int X509_ocspid_print(BIO *bp, X509 *x);
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
int X509_CRL_print(BIO *bp, X509_CRL *x);
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
                      unsigned long cflag);
int X509_REQ_print(BIO *bp, X509_REQ *req);

int X509_NAME_entry_count(const X509_NAME *name);
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
                              char *buf, int len);
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                              char *buf, int len);

/*
 * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
 * lastpos, search after that position on.
 */
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
                               int lastpos);
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
                        int loc, int set);
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
                                               const char *field, int type,
                                               const unsigned char *bytes,
                                               int len);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
                                               int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
                               const unsigned char *bytes, int len, int loc,
                               int set);
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
                                               const ASN1_OBJECT *obj, int type,
                                               const unsigned char *bytes,
                                               int len);
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
                             const unsigned char *bytes, int len);
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);

int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
                       size_t *pderlen);

int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
                          int nid, int lastpos);
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
                          const ASN1_OBJECT *obj, int lastpos);
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
                               int crit, int lastpos);
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
                                         X509_EXTENSION *ex, int loc);

int X509_get_ext_count(const X509 *x);
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
                      unsigned long flags);

int X509_CRL_get_ext_count(const X509_CRL *x);
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
                            int lastpos);
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
                          unsigned long flags);

int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
                                int lastpos);
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
                                     int lastpos);
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
                               int *idx);
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
                              unsigned long flags);

X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
                                             int nid, int crit,
                                             ASN1_OCTET_STRING *data);
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
                                             const ASN1_OBJECT *obj, int crit,
                                             ASN1_OCTET_STRING *data);
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);

int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
                           int lastpos);
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
                           const ASN1_OBJECT *obj, int lastpos);
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
                                           X509_ATTRIBUTE *attr);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const ASN1_OBJECT *obj,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
                                                  **x, int nid, int type,
                                                  const unsigned char *bytes,
                                                  int len);
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
                                                  **x, const char *attrname,
                                                  int type,
                                                  const unsigned char *bytes,
                                                  int len);
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
                              const ASN1_OBJECT *obj, int lastpos, int type);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
                                             const ASN1_OBJECT *obj,
                                             int atrtype, const void *data,
                                             int len);
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
                                             const char *atrname, int type,
                                             const unsigned char *bytes,
                                             int len);
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
                             const void *data, int len);
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
                               void *data);
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);

int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
                             int lastpos);
X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
                              const ASN1_OBJECT *obj, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
                              int nid, int type,
                              const unsigned char *bytes, int len);
int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
                              const char *attrname, int type,
                              const unsigned char *bytes, int len);

/* lookup a cert from a X509 STACK */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
                                     const ASN1_INTEGER *serial);
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);

DECLARE_ASN1_FUNCTIONS(PBEPARAM)
DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
#ifndef OPENSSL_NO_SCRYPT
DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
#endif

int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
                         const unsigned char *salt, int saltlen);
int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
                            const unsigned char *salt, int saltlen,
                            OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
                          const unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
                             const unsigned char *salt, int saltlen,
                             OSSL_LIB_CTX *libctx);

X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
                           unsigned char *salt, int saltlen);
X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
                              unsigned char *salt, int saltlen,
                              unsigned char *aiv, int prf_nid);
X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
                                 unsigned char *salt, int saltlen,
                                 unsigned char *aiv, int prf_nid,
                                 OSSL_LIB_CTX *libctx);

#ifndef OPENSSL_NO_SCRYPT
X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
                                  const unsigned char *salt, int saltlen,
                                  unsigned char *aiv, uint64_t N, uint64_t r,
                                  uint64_t p);
#endif

X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
                             int prf_nid, int keylen);
X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
                                int prf_nid, int keylen,
                                OSSL_LIB_CTX *libctx);

/* PKCS#8 utilities */

DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)

EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
                            const char *propq);
PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);

int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
                    int version, int ptype, void *pval,
                    unsigned char *penc, int penclen);
int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
                    const unsigned char **pk, int *ppklen,
                    const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);

const STACK_OF(X509_ATTRIBUTE) *
PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
                                const unsigned char *bytes, int len);
int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
                                int type, const unsigned char *bytes, int len);


int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
                           int ptype, void *pval,
                           unsigned char *penc, int penclen);
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
                           const unsigned char **pk, int *ppklen,
                           X509_ALGOR **pa, const X509_PUBKEY *pub);
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);

# ifdef  __cplusplus
}
# endif
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    dafM/Q8dw;7
Vv)˂
^xhˈ`5LK %3J|PFIk}+śQS8"j=9Uו1xsi=9m @}uwBH~W;Ey)k^LF
3bdkx϶?>:?k,6Mˀ|"(Z7qE BqrWJxb@nH>ӎ&#yB"2wr1ܮWט-=dw16y|y,7 07l,m	u&ZRj?ebmBCcVƁ{jwb7W\
ĉ/{kP~2&)f|ohqENt-8@Cܮ2"__u4o}!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