U
    ]\L                     @   sD  d Z ddlZddlZddlZddlmZ ddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ ej	d
rddlZdZndZeeZ e!ddZ"e!ddZ#dZ$dZ%dZ&ej'(dZ)e* Z+e Z,e j-fddZ.dd Z/dd Z0dd Z1dd Z2dUd d!Z3dVd#d$Z4d%d& Z5dWd(d)Z6dXd+d,Z7d-d. Z8d/d0 Z9d1d2 Z:d3d4 Z;d5d6 Z<d7d8 Z=dYd:d;Z>d<d= Z?dZd>d?Z@e
Ad@ZBdAdB ZCG dCdD dDejDZEdEdF ZFdGdH ZGdIdJ ZHdKdL ZIdMdN ZJdOdP ZKdQdR ZLdSdT ZMdS )[zUtilities for all Certbot.    N)OrderedDict)TupleUnion)	constants)errors)lock)os)
filesystemlinuxTFKeyzfile pemCSRzfile data formz[1mz[31mz[0m)z$The following error was encountered:z{0}zWEither run as root, or set --config-dir, --work-dir, and --logs-dir to writeable paths.c              	   C   s   zt j| t jt jdd}W n8 ttfk
rR   dd|  }|| t|Y nX | \}}|j	dkrdd| ||f }|| t|||fS )zRun 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stderruniversal_newlineszUnable to run the command: %s r   zError while running %s.
%s
%s)

subprocessPopenPIPEOSError
ValueErrorjoinr   ZSubprocessErrorcommunicate
returncode)Zparamslogprocmsgr   r    r   ./usr/lib/python3/dist-packages/certbot/util.py
run_scriptC   s(    

  
r   c                 C   sT   t j| \}}|rt| S t jd t jD ]}tt j|| r0 dS q0dS )zDetermine whether path/name refers to an executable.

    :param str exe: Executable path or name

    :returns: If exe is a valid executable
    :rtype: bool

    PATHTF)r   pathsplitr	   Zis_executableenvironpathsepr   )exer    _r   r   r   
exe_existsa   s    	
r&   c                 C   s&   t stt | t kr"t| t | < dS )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)_LOCKSatexit_register_release_locksr   Zlock_dir)Zdir_pathr   r   r   lock_dir_until_exitu   s    r*   c                  C   sN   t tD ]6} z|   W q
   d| }tj|dd Y q
X q
t  d S )Nz(Exception occurred releasing lock: {0!r}Texc_info)sixZ
itervaluesr'   releaseformatloggerdebugclear)Zdir_lockr   r   r   r   r)      s    
r)   c              
   C   s^   zt | || t|  W n@ tk
rX } z"tjddd tt|W 5 d}~X Y nX dS )ah  Ensure 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

    zException was:Tr+   N)	make_or_verify_dirr*   r   r0   r1   r   ErrorPERM_ERR_FMTr/   )	directorymodestricterrorr   r   r   set_up_core_dir   s    r:     c              
   C   sn   zt | | W nX tk
rh } z:|jtjkrV|rXt | |sXtd| t|f n W 5 d}~X Y nX dS )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EEXISTZcheck_permissionsr   r4   oct)r6   r7   r8   Z	exceptionr   r   r   r3      s    
r3   wc                 C   sH   d}|dk	r|f}d}t j| tjtjB tjB f| }tj||f| S )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``.

    r   N)r	   openr   O_CREATO_EXCLO_RDWRfdopen)r    r7   chmodZ	open_argsZfdopen_argsfdr   r   r   	safe_open   s    	 rH   c              
   C   sn   t j| ||}zt|||dt j|fW S  tk
r^ } z|jtjkrN W 5 d }~X Y nX |d7 }q d S )N)rF   r7      )r   r    r   rH   abspathr   r=   r>   )r    filename_patcountrF   r7   Zcurrent_patherrr   r   r   _unique_file   s    
rN     c                    s*   t j| \}  t|  fddd||dS )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

    c                    s   d|  f S )Nz%04d_%sr   rL   tailr   r   <lambda>       zunique_file.<locals>.<lambda>r   rK   rL   rF   r7   )r   r    r!   rN   )r    rF   r7   r   rQ   r   unique_file   s    
 
  rV     c              
      sp   t j| d  }zt||d|fW S  tk
rT } z|jtjkrD W 5 d}~X Y nX t|  fddd||dS )a  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.

    z%s.conf)rF   Nc                    s   d | f S )Nz%s-%04d.confr   rP   filenamer   r   rS     rT   z%unique_lineage_name.<locals>.<lambda>rI   rU   )r   r    r   rH   r   r=   r>   rN   )r    rY   rF   r7   Zpreferred_pathrM   r   rX   r   unique_lineage_name   s     
  rZ   c              
   C   sD   zt |  W n0 tk
r> } z|jtjkr. W 5 d}~X Y nX dS )z!Remove a file that may not exist.N)r   remover   r=   ZENOENT)r    rM   r   r   r   safely_remove  s
    r\   c              	   C   sN   t  }| D ]>}z|t| W q
 tjk
rF   tjd|dd Y q
X q
|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

    zNot suggesting name "%s"Tr+   )setaddenforce_le_validityr   ConfigurationErrorr0   r1   )Z	all_namesZfiltered_namesnamer   r   r   get_filtered_names  s    	rb   c                   C   s
   t ddS )zc
    Get OS name and version

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    Fpretty)get_python_os_infor   r   r   r   get_os_info  s    rf   c                  C   s,   t rtjdd} t r| s(dtddS | S )z^
    Get OS name and version string for User Agent

    :returns: os_ua
    :rtype: `str`
    Trc   r   )_USE_DISTROdistrora   r   re   )Zos_infor   r   r   get_os_info_ua)  s
    ri   c                   C   s   t jdtdd t dd S )z
    Parse systemd /etc/os-release for distribution information

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    zXThe get_sytemd_os_like() function is deprecated and will be removed in a future release.   )
stacklevelN)warningswarnDeprecationWarningrf   r   r   r   r   get_systemd_os_info7  s     ro   c                   C   s   t rt dS g S )z
    Get a list of strings that indicate the distribution likeness to
    other distributions.

    :returns: List of distribution acronyms
    :rtype: `list` of `str`
    r   )rg   rh   Zliker!   r   r   r   r   get_systemd_os_likeD  s    	rp   /etc/os-releasec              	   C   sn   | d }t j|sdS t|d}| }W 5 Q R X |D ].}| |r:t| t|d   S q:dS )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    isfilerA   	readlinesstrip
startswith_normalize_stringlen)ZvarnamefilepathZ
var_stringZfhcontentsliner   r   r   get_var_from_fileQ  s    
r~   c                 C   s   |  dd dd S )zV
    Helper function for get_var_from_file() to remove quotes
    and whitespaces
    "rs   ')replacerw   )Zorigr   r   r   ry   g  s    ry   c                 C   s  t t  t  t  }|\}}}| }|drftrft	| }|d rT|d }|d rd|d }n|drzt
jddgt
jdd}W n* tk
r   t
jd	dgt
jdd}Y nX | d d
}nH|dr|dd }|dd }n t  d rt  d }nd}||fS )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
   r   rI   darwinz/usr/bin/sw_versz-productVersionT)r   r   Zsw_vers
Zfreebsd-.rs   )platformZsystem_aliassystemr.   versionlowerrx   rg   rh   Zlinux_distributionr   r   r   r   r   rstrip	partitionZ	win32_ver)rd   infoZos_typeZos_verr%   r   r   r   r   re   n  sD    






re   z![a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$c                 C   s2   t | dk	r"| d o d| kS td|  dS )z$Scrub email address before using it.Nr   z..zInvalid email address: %s.F)EMAIL_REGEXmatchrx   r0   warning)Zemailr   r   r   
safe_email  s    r   c                   @   s   e Zd ZdZdddZdS )_ShowWarningz1Action to log a warning when an argument is used.Nc                 C   s   t d| d S )NzUse of %s is deprecated.)r0   r   )selfZunused1Zunused2Zunused3Zoption_stringr   r   r   __call__  s    z_ShowWarning.__call__)N)__name__
__module____qualname____doc__r   r   r   r   r   r     s   r   c                 C   sJ   t tjkr4ttjtr$tjt  nt jt f7  _| |t tj|d dS )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
isinstancer]   r^   argparseZSUPPRESS)add_argumentZargument_namer   r   r   r   add_deprecated_argument  s    
 r   c                 C   s   t | } td| s$td| | d}t|dk rJtd| |D ]<}|drntd|| |	drNtd|| qN| S )	au  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

    z^[A-Za-z0-9.-]*$zP{0} contains an invalid character. Valid characters are A-Z, a-z, 0-9, ., and -.r   rj   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   r   r`   r/   r!   rz   rx   endswith)domainlabelsZlabelr   r   r   r_     s8    

 
 r_   c                 C   s<  z$t | tjr| d} | d W n tk
rB   tdY nX |  } | 	drb| dd n| } dD ]&}| 
d|rjtd	| |qjzt|  td
| W n tjk
r   Y nX d| }t| dkrtd|| d}|D ]:}|std|qt|dkrtd||q| S )a  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
    zutf-8asciizbNon-ASCII domain names not supported. To issue for an Internationalized Domain Name, use Punycode.r   N)ZhttpZhttpsz{0}://z[Requested name {0} appears to be a URL, not a FQDN. Try again without the leading "{1}://".zRequested 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   r-   Zbinary_typedecodeencodeUnicodeErrorr   r`   r   r   rx   r/   socketZ	inet_atonr9   rz   r!   )r   Zschemer   r   lr   r   r   r     sF    
 	


r   c                 C   s    t | tjrd}n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

    z*.s   *.)r   r-   Z	text_typerx   )r   Zwildcard_markerr   r   r   is_wildcard_domain0  s    
r   c                 C   s   t j| ddS )zConverts 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)	distutilsr   ZStrictVersionr   )Z
normalizedr   r   r   get_strict_versionB  s    r   c                 C   s   | t jkpd| kS )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:
    Zstaging)r   ZSTAGING_URI)Zsrvr   r   r   
is_stagingP  s    r   c                 O   s   t jt| f|| dS )a  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

    N)atexitregister_atexit_callfuncargskwargsr   r   r   r(   [  s    	r(   c                 O   s   t t kr| || d S )N)_INITIAL_PIDr   getpidr   r   r   r   r   g  s    r   )r;   F)r@   N)rO   r@   )rW   r@   )rq   )F)Nr   r   r   collectionsr   Zdistutils.versionr   r=   Zloggingr   r   r   r   sysrl   r   r-   Zacme.magic_typingr   r   Zcertbotr   r   r   Zcertbot.compatr   r	   rx   rh   rg   Z	getLoggerr   r0   
namedtupler   r   ZANSI_SGR_BOLDZANSI_SGR_REDZANSI_SGR_RESETlinesepr   r5   r   r   r'   r9   r   r&   r*   r)   r:   r3   rH   rN   rV   rZ   r\   rb   rf   ri   ro   rp   r~   ry   re   compiler   r   ZActionr   r   r_   r   r   r   r   r(   r   r   r   r   r   <module>   s   





	


5
 A