Coverage for certbot/util.py : 95%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Utilities for all Certbot.""" # distutils.version under virtualenv confuses pylint # For more info, see: https://github.com/PyCQA/pylint/issues/73
# Note: form is the type of data, "pem" or "der"
# ANSI SGR escape codes # Formats text as bold or with increased intensity # Colors text red # Resets output format
"The following error was encountered:", "{0}", "Either run as root, or set --config-dir, " "--work-dir, and --logs-dir to writeable paths."))
# Stores importing process ID to be used by atexit_register() # Maps paths to locked directories to their lock object. All locks in # the dict are attempted to be cleaned up at program exit. If the # program exits before the lock is cleaned up, it is automatically # released, but the file isn't deleted.
"""Run the script with the given params.
:param list params: List of parameters to pass to Popen :param logging.Logger log: Logger to use for errors
""" stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
" ".join(params), stdout, stderr) # Enter recovery routine...
"""Is path an executable file?
:param str path: path to test
:returns: True iff path is an executable file :rtype: bool
"""
"""Determine whether path/name refers to an executable.
:param str exe: Executable path or name
:returns: If exe is a valid executable :rtype: bool
""" else:
"""Lock the directory at dir_path until program exit.
:param str dir_path: path to directory
:raises errors.LockError: if the lock is held by another process
"""
except: # pylint: disable=bare-except msg = 'Exception occurred releasing lock: {0!r}'.format(dir_lock) logger.debug(msg, exc_info=True)
"""Ensure directory exists with proper permissions and is locked.
:param str directory: Path to a directory. :param int mode: Directory mode. :param int uid: Directory owner. :param bool strict: require directory to be owned by current user
:raises .errors.LockError: if the directory cannot be locked :raises .errors.Error: if the directory cannot be made or verified
"""
"""Make sure directory exists with proper permissions.
:param str directory: Path to a directory. :param int mode: Directory mode. :param int uid: Directory owner. :param bool strict: require directory to be owned by current user
:raises .errors.Error: if a directory already exists, but has wrong permissions or owner
:raises OSError: if invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
""" "%s exists, but it should be owned by user %d with" "permissions %s" % (directory, uid, oct(mode))) else:
"""Check file or directory permissions.
:param str filepath: Path to the tested file (or directory). :param int mode: Expected file mode. :param int uid: Expected file owner.
:returns: True if `mode` and `uid` match, False otherwise. :rtype: bool
"""
"""Safely open a file.
:param str path: Path to a file. :param str mode: Same os `mode` for `open`. :param int chmod: Same as `mode` for `os.open`, uses Python defaults if ``None``. :param int buffering: Same as `bufsize` for `os.fdopen`, uses Python defaults if ``None``.
""" # pylint: disable=star-args fdopen_args = (buffering,) os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, *open_args), mode, *fdopen_args)
os.path.abspath(current_path) # "File exists," is okay, try a different name.
"""Safely finds a unique file.
:param str path: path/filename.ext :param int chmod: File mode :param str mode: Open mode
:returns: tuple of file object and file name
""" path, filename_pat=(lambda count: "%04d_%s" % (count, tail)), count=0, chmod=chmod, mode=mode)
"""Safely finds a unique file using lineage convention.
:param str path: directory path :param str filename: proposed filename :param int chmod: file mode :param str mode: open mode
:returns: tuple of file object and file name (which may be modified from the requested one by appending digits to ensure uniqueness)
:raises OSError: if writing files fails for an unanticipated reason, such as a full disk or a lack of permission to write to specified location.
""" path, filename_pat=(lambda count: "%s-%04d.conf" % (filename, count)), count=1, chmod=chmod, mode=mode)
"""Remove a file that may not exist."""
"""Removes names that aren't considered valid by Let's Encrypt.
:param set all_names: all names found in the configuration
:returns: all found names that are considered valid by LE :rtype: set
""" filtered_names = set() for name in all_names: try: filtered_names.add(enforce_le_validity(name)) except errors.ConfigurationError: logger.debug('Not suggesting name "%s"', name, exc_info=True) return filtered_names
""" Get OS name and version
:param str filepath: File path of os-release file :returns: (os_name, os_version) :rtype: `tuple` of `str` """
# Systemd os-release parsing might be viable
# Fallback to platform module
""" Get OS name and version string for User Agent
:param str filepath: File path of os-release file :returns: os_ua :rtype: `str` """
# Fallback
""" Parse systemd /etc/os-release for distribution information
:param str filepath: File path of os-release file :returns: (os_name, os_version) :rtype: `tuple` of `str` """
""" Get a list of strings that indicate the distribution likeness to other distributions.
:param str filepath: File path of os-release file :returns: List of distribution acronyms :rtype: `list` of `str` """
""" Get single value from systemd /etc/os-release
:param str varname: Name of variable to fetch :param str filepath: File path of os-release file :returns: requested value :rtype: `str` """
# Return the value of var, normalized
""" Helper function for get_var_from_file() to remove quotes and whitespaces """
""" Get Operating System type/distribution and major version using python platform module
:returns: (os_name, os_version) :rtype: `tuple` of `str` """ platform.system(), platform.release(), platform.version() ) # On arch, platform.linux_distribution() is reportedly ('','',''), # so handle it defensively ["/usr/bin/sw_vers", "-productVersion"], stdout=subprocess.PIPE, universal_newlines=True, ) except OSError: proc = subprocess.Popen( ["sw_vers", "-productVersion"], stdout=subprocess.PIPE, universal_newlines=True, ) # eg "9.3-RC3-p1" else: # Cases known to fall here: Cygwin python
# Just make sure we don't get pwned... Make sure that it also doesn't # start with a period or have two consecutive periods <- this needs to # be done in addition to the regex
"""Scrub email address before using it.""" else:
"""Action to log a warning when an argument is used.""" "Use of {0} is deprecated.\n".format(option_string))
"""Adds a deprecated argument with the name argument_name.
Deprecated arguments are not shown in the help. If they are used on the command line, a warning is shown stating that the argument is deprecated and no other action is taken.
:param callable add_argument: Function that adds arguments to an argument parser/group. :param str argument_name: Name of deprecated argument. :param nargs: Value for nargs when adding the argument to argparse.
""" # In version 0.12.0 ACTION_TYPES_THAT_DONT_NEED_A_VALUE was # changed from a set to a tuple. # pylint: disable=no-member _ShowWarning) else: _ShowWarning,) help=argparse.SUPPRESS, nargs=nargs)
"""Checks that Let's Encrypt will consider domain to be valid.
:param str domain: FQDN to check :type domain: `str` or `unicode` :returns: The domain cast to `str`, with ASCII-only contents :rtype: str :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates
""" "{0} contains an invalid character. " "Valid characters are A-Z, a-z, 0-9, ., and -.".format(domain))
"{0} needs at least two labels".format(domain)) 'label "{0}" in domain "{1}" cannot start with "-"'.format( label, domain)) 'label "{0}" in domain "{1}" cannot end with "-"'.format( label, domain))
"""Method which validates domain value and errors out if the requirements are not met.
:param domain: Domain to check :type domain: `str` or `unicode` :raises ConfigurationError: for invalid domains and cases where Let's Encrypt currently will not issue certificates
:returns: The domain cast to `str`, with ASCII-only contents :rtype: str """ # Unicode "To issue for an Internationalized Domain Name, use Punycode.")
# Remove trailing dot
# Separately check for odd "domains" like "http://example.com" to fail # fast and provide a clear error message "Requested name {0} appears to be a URL, not a FQDN. " "Try again without the leading \"{1}://\".".format( domain, scheme ) )
# Explain separately that IP addresses aren't allowed (apart from not # being FQDNs) because hope springs eternal concerning this point "Requested name {0} is an IP address. The Let's Encrypt " "certificate authority will not issue certificates for a " "bare IP address.".format(domain)) # It wasn't an IP address, so that's good
# FQDN checks according to RFC 2181: domain name should be less than 255 # octets (inclusive). And each label is 1 - 63 octets (inclusive). # https://tools.ietf.org/html/rfc2181#section-11
""""Is domain a wildcard domain?
:param domain: domain to check :type domain: `bytes` or `str` or `unicode`
:returns: True if domain is a wildcard, otherwise, False :rtype: bool
""" else:
"""Converts a normalized version to a strict version.
:param str normalized: normalized version string
:returns: An equivalent strict version :rtype: distutils.version.StrictVersion
""" # strict version ending with "a" and a number designates a pre-release # pylint: disable=no-member
""" Determine whether a given ACME server is a known test / staging server.
:param str srv: the URI for the ACME server :returns: True iff srv is a known test / staging server :rtype bool: """
"""Sets func to be called before the program exits.
Special care is taken to ensure func is only called when the process that first imports this module exits rather than any child processes.
:param function func: function to be called in case of an error
"""
|