o 6a@Q@s~UdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddl mZddl mZddl mZddl mZddlZddlZddlmZdd lmZdd lmZdd lmZdd lmZe jd ZerddlZe e!Z"e#ddZ$e#ddZ%dZ&dZ'dZ(ej)*dZ+e,Z-iZ.ee/ej0fe1d<ddZ2e"j3fddZ4ddZ5ddZ6dd Z7d!d"Z8d]d%d&Z9d^d(e/d)e/d*efd+d,Z:d-d.Z;d_d0d1Zd7d8Z?d9d:Z@d;d<ZAd=d>ZBdad@dAZCdBdCZDdbdDdEZEe FdFZGdGdHZHGdIdJdJejIZJdKdLZKdMdNZLdOdPZMdQdRZNdSdTZOdUdVZPdWdXZQdYdZZRd[d\ZSdS)czUtilities for all Certbot.N)Dict)IO)Text)Tuple)Union)errors) constants)lock) filesystem)oslinuxKeyzfile pemCSRzfile data formzzz)z$The following error was encountered:z{0}zWEither run as root, or set --config-dir, --work-dir, and --logs-dir to writeable paths._LOCKScsZtjdvs dvrSdD]}|vr*dfdd|dD|<qS)a When Certbot is run inside a Snap, certain environment variables are modified. But Certbot sometimes calls out to external programs, since it uses classic confinement. When we do that, we must modify the env to remove our modifications so it will use the system's libraries, since they may be incompatible with the versions of libraries included in the Snap. For example, apachectl, Nginx, and anything run from inside a hook should call this function and pass the results into the ``env`` argument of ``subprocess.Popen``. :returns: A modified copy of os.environ ready to pass to Popen :rtype: dict SNAPCERTBOT_SNAPPED)PATHLD_LIBRARY_PATH:c3s |] }d|vr|VqdS)rN).0xenvr./usr/lib/python3/dist-packages/certbot/util.py Wsz1env_no_snap_for_external_calls..)r environcopyjoinsplit) path_namerrrenv_no_snap_for_external_callsBs &r!c Csztj|dtjtjdtd}Wnttfy)dd|}||t|w|j dkrDdd||j |j f}||t||j |j fS)zRun the script with the given params. :param list params: List of parameters to pass to subprocess.run :param callable log: Logger method to use for errors FT)checkstdoutstderruniversal_newlinesrzUnable to run the command: %s rzError while running %s. %s %s) subprocessrunPIPEr!OSError ValueErrorrrSubprocessError returncoder#r$)paramslogprocmsgrrr run_script[s(     r2cCsTtj|\}}|rt|StjdtjD]}ttj||r'dSqdS)zDetermine whether path/name refers to an executable. :param str exe: Executable path or name :returns: If exe is a valid executable :rtype: bool rTF)r pathrr is_executablerpathsepr)exer3_rrr exe_existsys  r8cCs*tstt|tvrt|t|<dSdS)zLock 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 N)ratexit_register_release_locksr lock_dir)dir_pathrrrlock_dir_until_exits r=cCsHtD]}z|Wqd|}tj|ddYqtdS)Nz(Exception occurred releasing lock: {0!r}Texc_info)rvaluesreleaseformatloggerdebugclear)dir_lockr1rrrr:s    r:c CsRz t|||t|WdSty(}ztjdddtt|d}~ww)ahEnsure directory exists with proper permissions and is locked. :param str directory: Path to a directory. :param int mode: Directory mode. :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 zException was:Tr>N) make_or_verify_dirr=r*rCrDrError PERM_ERR_FMTrB) directorymodestricterrorrrrset_up_core_dirs rNFc Cspz t||WdSty7}z"|jtjkr+|r*t||s*td|t|fnWYd}~dSd}~ww)aMake sure directory exists with proper permissions. :param str directory: Path to a directory. :param int mode: Directory mode. :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. zE%s exists, but it should be owned by current user with permissions %sN) r makedirsr*errnoEEXISTcheck_permissionsrrHoct)rJrKrL exceptionrrrrGs  rGwr3rKreturncCsLd}|dur |f}d}tj|tjtjBtjBg|R}tj||g|RS)zSafely 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 `filesystem.open`, uses Python defaults if ``None``. rN)r openr O_CREATO_EXCLO_RDWRfdopen)r3rKchmod open_args fdopen_argsfdrrr safe_opens  "rac Csn tj|||}zt|||dtj|fWSty1}z |jtjkr'WYd}~nd}~ww|d7}q)NT)r]rK)r r3rraabspathr*rQrR)r3 filename_patcountr]rK current_patherrrrr _unique_files    rhcs*tj|\}t|fddd||dS)zSafely 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 cs d|fS)Nz%04d_%srretailrr zunique_file..rrdrer]rK)r r3rrh)r3r]rKrrkr unique_files   rpc srtj|d}z t||d|fWSty+}z |jtjkr!WYd}~nd}~wwt|fddd||dS)aSafely 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. z%s.conf)r]Ncs d|fS)Nz %s-%04d.confrrjfilenamerrrmrnz%unique_lineage_name..rbro)r r3rrar*rQrRrh)r3rsr]rKpreferred_pathrgrrrrunique_lineage_names   ruc CsFzt|WdSty"}z|jtjkrWYd}~dSd}~ww)z!Remove a file that may not exist.N)r remover*rQENOENT)r3rgrrr safely_removes rxc CsJt}|D]}z |t|Wqtjy"tjd|ddYqw|S)zRemoves 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 zNot suggesting name "%s"Tr>)setaddenforce_le_validityrConfigurationErrorrCrD) all_namesfiltered_namesnamerrrget_filtered_names%s rcCs tddS)zc Get OS name and version :returns: (os_name, os_version) :rtype: `tuple` of `str` Fpretty)get_python_os_inforrrr get_os_info6s rcCs,trtjdd}tr |sdtddS|S)z^ Get OS name and version string for User Agent :returns: os_ua :rtype: `str` Trr&) _USE_DISTROdistrorrr)os_inforrrget_os_info_ua@s  rcCstr tdSgS)z Get a list of strings that indicate the distribution likeness to other distributions. :returns: List of distribution acronyms :rtype: `list` of `str` r&)rrlikerrrrrget_systemd_os_likeNs r/etc/os-releasecCs|d}tj|s dSt|d }|}Wdn1s wY|D]}||r>t|t|dSq'dS)z Get single value from a file formatted like 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` =rN) r r3isfilerX readlinesstrip startswith_normalize_stringlen)varnamefilepath var_stringfhcontentslinerrrget_var_from_file[s   rcCs|ddddS)zV Helper function for get_var_from_file() to remove quotes and whitespaces "r')replacer)origrrrrqsrc Cs@tttt}|\}}}|}|dr8tr8|r#t nt t}}|r0|}|r4|}||fS|drszt j ddgt j t j ddtd}Wntyht j ddgt j t j ddtd}Ynw|jd }||fS|d r|d d }|d d }||fStdrtd}||fSd}||fS)z Get Operating System type/distribution and major version using python platform module :param bool pretty: If the returned OS name should be in longer (pretty) form :returns: (os_name, os_version) :rtype: `tuple` of `str` r darwinz/usr/bin/sw_versz-productVersionFT)r#r$r"r%rsw_vers freebsd-r.rbr)platform system_aliassystemrAversionlowerrrrridr'r(r)r!r*r#rstrip partition win32_ver)rinfoos_typeos_verr7 distro_namedistro_versionr0rrrrxsR        rz![a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$cCs2t|dur|d od|vStd|dS)z$Scrub email address before using it.Nrz..zInvalid email address: %s.F) EMAIL_REGEXmatchrrCrM)emailrrr safe_emails rc@seZdZdZdddZdS)DeprecatedArgumentActionz1Action to log a warning when an argument is used.NcCstd|tdS)NzUse of %s is deprecated.)warningswarnDeprecationWarning)selfunused1unused2unused3 option_stringrrr__call__sz!DeprecatedArgumentAction.__call__N)__name__ __module__ __qualname____doc__rrrrrrsrcCsJttjvrttjtrtjtntjtf7_||ttj|ddS)aAdds 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. )actionhelpnargsN)rconfigargparse#ACTION_TYPES_THAT_DONT_NEED_A_VALUE isinstanceryrzargparseSUPPRESS) add_argument argument_namerrrradd_deprecated_arguments  rcCst|}td|std||d}t|dkr%td||D]}|dr7td||| drEtd||q'|S) auChecks 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 z^[A-Za-z0-9.-]*$zP{0} contains an invalid character. Valid characters are A-Z, a-z, 0-9, ., and -.rz{0} needs at least two labelsrz1label "{0}" in domain "{1}" cannot start with "-"z/label "{0}" in domain "{1}" cannot end with "-") enforce_domain_sanityrerrr|rBrrrendswith)domainlabelslabelrrrr{s4     r{cCszt|tr |d}|dWn tytdw|}|dr-|ddn|}dD]}| d |rDtd ||q1t |rQtd |d |}t |d krdtd || d}|D]}|swtd |t |dkrtd ||qk|S)aMethod 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 zutf-8asciizbNon-ASCII domain names not supported. To issue for an Internationalized Domain Name, use Punycode.rN)httphttpsz{0}://z[Requested name {0} appears to be a URL, not a FQDN. Try again without the leading "{1}://".zRequested name {0} is an IP address. The Let's Encrypt certificate authority will not issue certificates for a bare IP address.z*Requested domain {0} is not a FQDN becausez{0} it is too long.z{0} it contains an empty label.?z{0} label {1} is too long.)rbytesdecodeencode UnicodeErrorrr|rrrrB is_ipaddressrr)rschemer1rlrrrrsD        rc CsVz ttj|WdStjy*z ttj|WYdStjy)YYdSww)zIs given address string form of IP(v4 or v6) address? :param address: address to check :type address: `str` or `unicode` :returns: True if address is valid IP address, otherwise return False. :rtype: bool TF)socket inet_ptonAF_INETrMAF_INET6)addressrrrr7s rcCsd}t|tr d}||S)z"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 s*.z*.)rstrr)rwildcard_markerrrris_wildcard_domainNs  rcCstj|ddS)zConverts a normalized version to a strict version. :param str normalized: normalized version string :returns: An equivalent strict version :rtype: distutils.version.StrictVersion z.deva) distutilsr StrictVersionr) normalizedrrrget_strict_version^s rcCs|tjkpd|vS)z 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: staging)r STAGING_URI)srvrrr is_stagingksrcOstjt|g|Ri|dS)aSets 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 N)atexitregister _atexit_callfuncargskwargsrrrr9vs r9cOs"ttkr||i|dSdSr) _INITIAL_PIDr getpidrrrrrs r)rOF)rVN)rirV)rqrV)r)F)Trrr collectionsdistutils.versionrrQloggingrrrr'systypingrrrrrrrcertbotrcertbot._internalrr certbot.compatr r rrr getLoggerrrC namedtupler r ANSI_SGR_BOLD ANSI_SGR_REDANSI_SGR_RESETlineseprrIrrrrLockFile__annotations__r!rMr2r8r=r:rNrGrarhrprurxrrrrrrrcompilerrActionrrr{rrrrrr9rrrrrs                      8!;