a á `†Oã@sJdZddlZddlZddlZddlmZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZe j  d ¡ZerðddlZe e ¡Z!e "d d¡Z#e "dd¡Z$dZ%dZ&dZ'ej( )d¡Z*e +¡Z,eƒZ-dd„Z.e!j/fdd„Z0dd„Z1dd„Z2dd„Z3dd „Z4dVd#d$„Z5dWd&d'„Z6d(d)„Z7dXd+d,„Z8dYd.d/„Z9d0d1„Z:d2d3„Z;d4d5„ZdZd;d<„Z?d=d>„Z@d[d?d@„ZAe  BdA¡ZCdBdC„ZDGdDdE„dEejEƒZFdFdG„ZGdHdI„ZHdJdK„ZIdLdM„ZJdNdO„ZKdPdQ„ZLdRdS„ZMdTdU„ZNdS)\zUtilities for all Certbot.éN)Ú OrderedDict)ÚText)ÚTuple)ÚUnion)Úerrors)Ú constants)Úlock)Ú filesystem)ÚosÚlinuxÚKeyzfile pemÚCSRzfile 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.csZtj ¡‰dˆvsdˆvrˆSdD]2}|ˆvr"d ‡fdd„ˆ| d¡Dƒ¡ˆ|<q"ˆS)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 ÚSNAPZCERTBOT_SNAPPED)ÚPATHZLD_LIBRARY_PATHú:c3s|]}ˆd|vr|VqdS)rN©)Ú.0Úx©Úenvrú./usr/lib/python3/dist-packages/certbot/util.pyÚ Vóz1env_no_snap_for_external_calls..)r ÚenvironÚcopyÚjoinÚsplit)Ú path_namerrrÚenv_no_snap_for_external_callsAs (rc Csšztj|tjtjdtƒd}Wn6ttfyTdd |¡}||ƒt |¡‚Yn0|  ¡\}}|j dkr’dd |¡||f}||ƒt |¡‚||fS)z¡Run the script with the given params. :param list params: List of parameters to pass to Popen :param callable log: Logger method to use for errors T©ÚstdoutÚstderrZuniversal_newlinesrzUnable to run the command: %sú rzError while running %s. %s %s) Ú subprocessÚPopenÚPIPErÚOSErrorÚ ValueErrorrrZSubprocessErrorÚ communicateÚ returncode)ÚparamsÚlogÚprocÚmsgr r!rrrÚ run_scriptZs&ü    ÿ r.cCsTtj |¡\}}|rt |¡Stjd tj¡D]}t tj ||¡¡r0dSq0dS)z¤Determine 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 Z is_executablerÚpathsepr)Zexer/Ú_rrrÚ exe_existsys  r2cCs&ts ttƒ|tvr"t |¡t|<dS)zª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 N)Ú_LOCKSÚatexit_registerÚ_release_locksrZlock_dir)Zdir_pathrrrÚlock_dir_until_exitŒsr6cCsNt t¡D]6}z | ¡Wq d |¡}tj|ddYq 0q t ¡dS)Nz(Exception occurred releasing lock: {0!r}T©Úexc_info)ÚsixZ itervaluesr3ÚreleaseÚformatÚloggerÚdebugÚclear)Zdir_lockr-rrrr5›s  r5c Cs`zt|||ƒt|ƒWnBtyZ}z*tjdddt t |¡¡‚WYd}~n d}~00dS)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:Tr7N) Úmake_or_verify_dirr6r&r<r=rÚErrorÚ PERM_ERR_FMTr;)Ú directoryÚmodeÚstrictÚerrorrrrÚset_up_core_dir¥s   rFéíFc Cspzt ||¡WnZtyj}zB|jtjkrT|rVt ||¡sVt d|t|ƒf¡‚n‚WYd}~n d}~00dS)aîMake 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&ÚerrnoÚEEXISTZcheck_permissionsrr@Úoct)rBrCrDZ exceptionrrrr?¸s  ÿÿr?ÚwcCsLd}|dur|f}d}tj|tjtjBtjBg|¢RŽ}tj||g|¢RŽS)zÕ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 `filesystem.open`, uses Python defaults if ``None``. rN)r Úopenr ÚO_CREATÚO_EXCLÚO_RDWRÚfdopen)r/rCÚchmodZ open_argsZ fdopen_argsÚfdrrrÚ safe_openÓs "rTc Csptj |||ƒ¡}zt|||dtj |¡fWSty`}z|jtjkrL‚WYd}~n d}~00|d7}qdS)N)rRrCé)r r/rrTÚabspathr&rIrJ)r/Ú filename_patÚcountrRrCZ current_pathÚerrrrrÚ _unique_fileäs  ÿ rZéÿcs*tj |¡\}‰t|‡fdd„d||dS)zº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 cs d|ˆfS)Nz%04d_%sr©rX©ÚtailrrÚýrzunique_file..r©rWrXrRrC)r r/rrZ)r/rRrCrr]rÚ unique_fileñs  þraé¤c srtj |dˆ¡}zt||d|fWStyV}z|jtjkrB‚WYd}~n d}~00t|‡fdd„d||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)rRNcs dˆ|fS)Nz %s-%04d.confrr\©Úfilenamerrr_rz%unique_lineage_name..rUr`)r r/rrTr&rIrJrZ)r/rdrRrCZpreferred_pathrYrrcrÚunique_lineage_names  þrec CsFzt |¡Wn2ty@}z|jtjkr,‚WYd}~n d}~00dS)z!Remove a file that may not exist.N)r Úremover&rIZENOENT)r/rYrrrÚ safely_removes  rgc CsLtƒ}|D]<}z| t|ƒ¡Wq tjyDtjd|ddYq 0q |S)zÑ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 zNot suggesting name "%s"Tr7)ÚsetÚaddÚenforce_le_validityrÚConfigurationErrorr<r=)Z all_namesZfiltered_namesÚnamerrrÚget_filtered_names%s rmcCs tddS)zc Get OS name and version :returns: (os_name, os_version) :rtype: `tuple` of `str` F©Úpretty)Úget_python_os_inforrrrÚ get_os_info6srqcCs,trtjdd}tr|s(d tdd¡S|S)z^ Get OS name and version string for User Agent :returns: os_ua :rtype: `str` Trnr")Ú _USE_DISTROÚdistrorlrrp)Zos_inforrrÚget_os_info_ua@s  rtcCstrt ¡ d¡SgS)z¬ Get a list of strings that indicate the distribution likeness to other distributions. :returns: List of distribution acronyms :rtype: `list` of `str` r")rrrsZlikerrrrrÚget_systemd_os_likeNs ruú/etc/os-releasecCs‚|d}tj |¡sdSt|dƒ}| ¡}Wdƒn1s@0Y|D].}| ¡ |¡rNt| ¡t|ƒd…ƒSqNdS)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 r/ÚisfilerMÚ readlinesÚstripÚ startswithÚ_normalize_stringÚlen)ZvarnameÚfilepathZ var_stringZfhÚcontentsÚlinerrrÚget_var_from_file[s   &rƒcCs| dd¡ dd¡ ¡S)zV Helper function for get_var_from_file() to remove quotes and whitespaces ú"rxú')Úreplacer|)Zorigrrrr~qsr~c Cs*t t ¡t ¡t ¡¡}|\}}}| ¡}| d¡rftrft  |¡}|drT|d}|drd|d}n¼| d¡rØz"t j ddgt j t j dt ƒd}Wn0tyÂt j d dgt j t j dt ƒd}Yn0| ¡d d ¡}nJ| d ¡r| d ¡d}| d ¡d}n t ¡drt ¡d}nd}||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 rrUÚdarwinz/usr/bin/sw_versz-productVersionTrZsw_versÚ Zfreebsdú-Ú.rx)ÚplatformZ system_aliasÚsystemr:ÚversionÚlowerr}rrrsZlinux_distributionr#r$r%rr&r(ÚrstripÚ partitionZ win32_ver)roÚinfoZos_typeZos_verr1r,rrrrpxsH ý    ü  ü  rpz![a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$cCs2t |¡dur"| d¡ o d|vSt d|¡dS)z$Scrub email address before using it.NrŠz..zInvalid email address: %s.F)Ú EMAIL_REGEXÚmatchr}r<Úwarning)ZemailrrrÚ safe_email²s r•c@seZdZdZddd„ZdS)ÚDeprecatedArgumentActionz1Action to log a warning when an argument is used.NcCst d|¡dS)NzUse of %s is deprecated.)r<r”)ÚselfZunused1Zunused2Zunused3Z option_stringrrrÚ__call__¼sz!DeprecatedArgumentAction.__call__)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r˜rrrrr–ºsr–cCsJttjvr4ttjtƒr$tj t¡ntjtf7_||ttj|ddS)aá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. )ÚactionÚhelpÚnargsN)r–ÚconfigargparseZ#ACTION_TYPES_THAT_DONT_NEED_A_VALUEÚ isinstancerhriÚargparseZSUPPRESS)Ú add_argumentZ argument_namerŸrrrÚadd_deprecated_argumentÀs  ÿÿÿr¤cCst|ƒ}t d|¡s$t d |¡¡‚| d¡}t|ƒdkrJt d |¡¡‚|D]<}| d¡rnt d ||¡¡‚|  d¡rNt d ||¡¡‚qN|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 -.rŠéz{0} needs at least two labelsr‰z1label "{0}" in domain "{1}" cannot start with "-"z/label "{0}" in domain "{1}" cannot end with "-") Úenforce_domain_sanityÚrer“rrkr;rrr}Úendswith)ÚdomainÚlabelsZlabelrrrrjÚs4  ÿÿ  ÿ ÿÿ ÿÿrjcCs6z$t|tjƒr| d¡}| d¡Wnty@t d¡‚Yn0| ¡}|  d¡r`|dd…n|}dD]&}|  d  |¡¡rht d   ||¡¡‚qhzt   |¡t d   |¡¡‚Wnt jyÂYn0d   |¡}t|ƒd krêt d   |¡¡‚| d¡}|D]8}|st d  |¡¡‚t|ƒdkrøt d  ||¡¡‚qø|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-8ÚasciizbNon-ASCII domain names not supported. To issue for an Internationalized Domain Name, use Punycode.rŠNéÿÿÿÿ)ZhttpZhttpsz{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 becauseéÿz{0} it is too long.z{0} it contains an empty label.é?z{0} label {1} is too long.)r¡r9Z binary_typeÚdecodeÚencodeÚ UnicodeErrorrrkrŽr¨r}r;ÚsocketZ inet_atonrErr)r©Zschemer-rªÚlrrrr¦úsD    þÿ  þÿ    r¦cCsd}t|tjƒrd}| |¡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*.)r¡r9Z text_typer})r©Zwildcard_markerrrrÚis_wildcard_domain;s  r´cCstj | dd¡¡S)zÆConverts a normalized version to a strict version. :param str normalized: normalized version string :returns: An equivalent strict version :rtype: distutils.version.StrictVersion z.devÚa)Ú distutilsrZ StrictVersionr†)Z normalizedrrrÚget_strict_versionKs r·cCs|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: Zstaging)rZ STAGING_URI)ZsrvrrrÚ is_stagingXsr¸cOstjt|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)ÚatexitÚregisterÚ _atexit_call©ÚfuncÚargsÚkwargsrrrr4cs r4cOstt ¡kr||i|¤ŽdS)N)Ú _INITIAL_PIDr Úgetpidr¼rrrr»os r»)rGF)rLN)r[rL)rbrL)rv)F)Orœr¢r¹Ú collectionsrZdistutils.versionr¶rIZloggingr‹r§r²r#Úsysr r9Zacme.magic_typingrrrZcertbotrZcertbot._internalrrZcertbot.compatr r r}rrrsZ getLoggerr™r<Ú namedtupler r Z ANSI_SGR_BOLDZ ANSI_SGR_REDZANSI_SGR_RESETÚlineseprrArÁrÀr3rrEr.r2r6r5rFr?rTrZrarergrmrqrtrurƒr~rpÚcompiler’r•ZActionr–r¤rjr¦r´r·r¸r4r»rrrrÚs€                       7  A