
Y[c           @   s  d  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 Z d d l Z d d l Z d d l m 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 e j e  Z e j d d	  Z e j d
 d  Z d Z d Z  d Z! e j" j# d9  Z$ e j%   Z& e   Z' e j( d  Z) d   Z* d   Z+ d   Z, d   Z- d   Z. d d e/ d  Z0 d d  Z1 d d d d  Z3 d   Z4 d d d   Z5 d! d d"  Z6 d#   Z7 d$   Z8 d% d&  Z9 d% d'  Z: d% d(  Z; d% d)  Z< d% d*  Z= d+   Z> d,   Z? e
 j@ d-  ZA d.   ZB d/ e jC f d0     YZD d1   ZE d2   ZF d3   ZG d4   ZH d5   ZI d6   ZJ d7   ZK d8   ZL d S(:   s   Utilities for all Certbot.iN(   t   OrderedDict(   t   Tuplet   Union(   t	   constants(   t   errors(   t   lockt   Keys   file pemt   CSRs   file data forms   [1ms   [31ms   [0ms$   The following error was encountered:s   {0}sW   Either run as root, or set --config-dir, --work-dir, and --logs-dir to writeable paths.c         C   s   y+ t  j |  d t  j d t  j d t } WnC t t f k
 rp d d j |   } | |  t j |   n X| j	   \ } } | j
 d k r d d j |   | | f } | |  t j |   n  | | f S(   s   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

    t   stdoutt   stderrt   universal_newliness   Unable to run the command: %st    i    s   Error while running %s.
%s
%s(   t
   subprocesst   Popent   PIPEt   Truet   OSErrort
   ValueErrort   joinR   t   SubprocessErrort   communicatet
   returncode(   t   paramst   logt   proct   msgR   R	   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt
   run_script=   s     		

c         C   s%   t  j j |   o$ t  j |  t  j  S(   s   Is path an executable file?

    :param str path: path to test

    :returns: True iff path is an executable file
    :rtype: bool

    (   t   ost   patht   isfilet   accesst   X_OK(   R   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   is_exe[   s    	c         C   so   t  j j |   \ } } | r( t |   Sx@ t  j d j t  j  D]% } t t  j j | |    rB t SqB Wt S(   s   Determine whether path/name refers to an executable.

    :param str exe: Executable path or name

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

    t   PATH(	   R   R   t   splitR    t   environt   pathsepR   R   t   False(   t   exeR   t   _(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt
   exe_existsg   s    	
 c         C   s9   t  s t t  n  |  t  k r5 t j |   t  |  <n  d S(   s   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(   t   _LOCKSt   atexit_registert   _release_locksR   t   lock_dir(   t   dir_path(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   lock_dir_until_exit{   s    c          C   sX   xQ t  j t  D]@ }  y |  j   Wq d j |   } t j | d t q Xq Wd  S(   Ns(   Exception occurred releasing lock: {0!r}t   exc_info(   t   sixt
   itervaluesR)   t   releaset   formatt   loggert   debugR   (   t   dir_lockR   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR+      s    c         C   sf   y! t  |  | | |  t |   Wn> t k
 ra } t j d d t t j t j	 |    n Xd S(   s  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

    s   Exception was:R/   N(
   t   make_or_verify_dirR.   R   R4   R5   R   R   t   Errort   PERM_ERR_FMTR3   (   t	   directoryt   modet   uidt   strictt   error(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   set_up_core_dir   s    i  i    c         C   s   y t  j |  |  Wni t k
 r } | j t j k ry | r| t |  | |  r| t j d |  | t |  f   q| q   n Xd S(   s  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?   %s exists, but it should be owned by user %d withpermissions %sN(	   R   t   makedirsR   t   errnot   EEXISTt   check_permissionsR   R8   t   oct(   R:   R;   R<   R=   t	   exception(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR7      s    c         C   s4   t  j |   } t j | j  | k o3 | j | k S(   s  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

    (   R   t   statt   S_IMODEt   st_modet   st_uid(   t   filepathR;   R<   t	   file_stat(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyRC      s    t   wc         C   so   d } | d k	 r | f } n  d } | d k	 r< | f } n  t j t j |  t j t j Bt j B|  | |  S(   s4  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``.

    (    N(    (   t   NoneR   t   fdopent   opent   O_CREATt   O_EXCLt   O_RDWR(   R   R;   t   chmodt	   bufferingt	   open_argst   fdopen_args(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt	   safe_open   s    #c         C   s   x t  r t j j |  | |   } y, t | d | d | t j j |  f SWn+ t k
 r} } | j t j k r~   q~ n X| d 7} q Wd  S(   NRS   R;   i   (	   R   R   R   R   RW   t   abspathR   RA   RB   (   R   t   filename_patt   countRS   R;   t   current_patht   err(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   _unique_file   s    	
i  c      
      sC   t  j j |   \ }    t |  d   f d   d d d | d | S(   s   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

    RY   c            s   d |    f S(   Ns   %04d_%s(    (   RZ   (   t   tail(    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   <lambda>  s    RZ   i    RS   R;   (   R   R   R"   R]   (   R   RS   R;   (    (   R^   s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   unique_file   s    
i  c      
      s   t  j j |  d    } y t | d | | f SWn+ t k
 r` } | j t j k ra   qa n Xt |  d   f d   d d d | d | S(   s  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.

    s   %s.confRS   RY   c            s   d   |  f S(   Ns   %s-%04d.conf(    (   RZ   (   t   filename(    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR_     s    RZ   i   R;   (   R   R   R   RW   R   RA   RB   R]   (   R   Ra   RS   R;   t   preferred_pathR\   (    (   Ra   s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   unique_lineage_name  s    
c         C   sC   y t  j |   Wn+ t k
 r> } | j t j k r?   q? n Xd S(   s!   Remove a file that may not exist.N(   R   t   removeR   RA   t   ENOENT(   R   R\   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   safely_remove!  s
    c         C   sb   t    } xR |  D]J } y | j t |   Wq t j k
 rY t j d | d t q Xq W| S(   s   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

    s   Not suggesting name "%s"R/   (   t   sett   addt   enforce_le_validityR   t   ConfigurationErrorR4   R5   R   (   t	   all_namest   filtered_namest   name(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   get_filtered_names*  s    		s   /etc/os-releasec         C   sA   t  j j |   r: t d |   \ } } | r: | | f Sn  t   S(   s   
    Get OS name and version

    :param str filepath: File path of os-release file
    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    RJ   (   R   R   R   t   get_systemd_os_infot   get_python_os_info(   RJ   t   os_namet
   os_version(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   get_os_info<  s
    	c         C   s\   t  j j |   rL t d d |  } | s? t d d |  } n  | rL | Sn  d j t    S(   s   
    Get OS name and version string for User Agent

    :param str filepath: File path of os-release file
    :returns: os_ua
    :rtype: `str`
    t   PRETTY_NAMERJ   t   NAMER   (   R   R   R   t   get_var_from_fileR   Rp   (   RJ   t   os_ua(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   get_os_info_uaO  s    	c         C   s.   t  d d |  } t  d d |  } | | f S(   s   
    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`
    t   IDRJ   t
   VERSION_ID(   Rv   (   RJ   Rq   Rr   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyRo   c  s    	c         C   s   t  d |   j d  S(   s   
    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`
    t   ID_LIKER   (   Rv   R"   (   RJ   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   get_systemd_os_liker  s    
c         C   s   |  d } t  j j |  s  d St | d   } | j   } Wd QXx= | D]5 } | j   j |  rK t | j   t |   SqK Wd S(   s   
    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`
    t   =t    t   rN(	   R   R   R   RO   t	   readlinest   stript
   startswitht   _normalize_stringt   len(   t   varnameRJ   t
   var_stringt   fht   contentst   line(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyRv     s    

c         C   s"   |  j  d d  j  d d  j   S(   sV   
    Helper function for get_var_from_file() to remove quotes
    and whitespaces
    t   "R~   t   '(   t   replaceR   (   t   orig(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR     s    c          C   s  t  j t  j   t  j   t  j    }  |  \ } } } | j   } | j d  r t  j   }  |  d rt |  d } n  |  d rz|  d } qzn | j d  ry( t j	 d d g d t j
 d t } Wn5 t k
 r t j	 d	 d g d t j
 d t } n X| j   d j d
  } na | j d  rQ| j d  d } | j d  d } n) t  j   d rtt  j   d } n d } | | f S(   s   
    Get Operating System type/distribution and major version
    using python platform module

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    t   linuxi    i   t   darwins   /usr/bin/sw_verss   -productVersionR   R
   t   sw_verss   
t   freebsdt   -t   .R~   (   t   platformt   system_aliast   systemR2   t   versiont   lowerR   t   linux_distributionR   R   R   R   R   R   t   rstript	   partitiont	   win32_ver(   t   infot   os_typet   os_verR'   R   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyRp     s>    		

		s!   [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$c         C   sG   t  j |   d k	 r/ |  j d  o. d |  k St j d |   t Sd S(   s$   Scrub email address before using it.R   s   ..s   Invalid email address: %s.N(   t   EMAIL_REGEXt   matchRM   R   R4   t   warningR%   (   t   email(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt
   safe_email  s    t   _ShowWarningc           B   s   e  Z d  Z d d  Z RS(   s1   Action to log a warning when an argument is used.c         C   s   t  j j d j |   d  S(   Ns   Use of {0} is deprecated.
(   t   sysR	   t   writeR3   (   t   selft   unused1t   unused2t   unused3t   option_string(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   __call__  s    	N(   t   __name__t
   __module__t   __doc__RM   R   (    (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR     s   c         C   sl   t  t j k rI t t j t  r4 t j j t   qI t j t  f 7_ n  |  | d t  d t j d | d S(   s  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.

    t   actiont   helpt   nargsN(   R   t   configargparset#   ACTION_TYPES_THAT_DONT_NEED_A_VALUEt
   isinstanceRg   Rh   t   argparset   SUPPRESS(   t   add_argumentt   argument_nameR   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   add_deprecated_argument  s    	
c         C   s   t  |   }  t j d |   s9 t j d j |     n  |  j d  } t |  d k  ru t j d j |     n  xh | D]` } | j d  r t j d j | |     n  | j	 d  r| t j d j | |     q| q| W|  S(	   su  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

    s   ^[A-Za-z0-9.-]*$sP   {0} contains an invalid character. Valid characters are A-Z, a-z, 0-9, ., and -.R   i   s   {0} needs at least two labelsR   s1   label "{0}" in domain "{1}" cannot start with "-"s/   label "{0}" in domain "{1}" cannot end with "-"(
   t   enforce_domain_sanityt   reR   R   Rj   R3   R"   R   R   t   endswith(   t   domaint   labelst   label(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyRi     s&    c         C   s  y5 t  |  t j  r' |  j d  }  n  |  j d  Wn  t k
 rW t j d   n X|  j   }  |  j	 d  r} |  d  n |  }  xJ d d g D]< } |  j
 d j |   r t j d	 j |  |    q q Wy) t j |   t j d
 j |     Wn t j k
 rn Xd j |   } t |   d k rLt j d j |    n  |  j d  } x_ | D]W } | st j d j |    qbt |  d k rbt j d j | |    qbqbW|  S(   s  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
    s   utf-8t   asciisb   Non-ASCII domain names not supported. To issue for an Internationalized Domain Name, use Punycode.u   .it   httpt   httpss   {0}://s[   Requested name {0} appears to be a URL, not a FQDN. Try again without the leading "{1}://".s   Requested name {0} is an IP address. The Let's Encrypt certificate authority will not issue certificates for a bare IP address.s*   Requested domain {0} is not a FQDN becausei   s   {0} it is too long.R   s   {0} it contains an empty label.i?   s   {0} label {1} is too long.(   R   R0   t   binary_typet   decodet   encodet   UnicodeErrorR   Rj   R   R   R   R3   t   sockett	   inet_atonR>   R   R"   (   R   t   schemeR   R   t   l(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR     s<    "c         C   s.   t  |  t j  r d } n d } |  j |  S(   s   "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

    u   *.s   *.(   R   R0   t	   text_typeR   (   R   t   wildcard_marker(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   is_wildcard_domain`  s    
	c         C   s   t  j j |  j d d   S(   s   Converts a normalized version to a strict version.

    :param str normalized: normalized version string

    :returns: An equivalent strict version
    :rtype: distutils.version.StrictVersion

    s   .devt   a(   t	   distutilsR   t   StrictVersionR   (   t
   normalized(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   get_strict_versionr  s    c         C   s   |  t  j k p d |  k S(   s   
    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:
    t   staging(   R   t   STAGING_URI(   t   srv(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt
   is_staging  s    c         O   s   t  j t |  | |  d S(   s  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(   t   atexitt   registert   _atexit_call(   t   funct   argst   kwargs(    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR*     s    	c         O   s&   t  t j   k r" |  | |   n  d  S(   N(   t   _INITIAL_PIDR   t   getpid(   R   R   R   (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyR     s    (   s$   The following error was encountered:s   {0}sW   Either run as root, or set --config-dir, --work-dir, and --logs-dir to writeable paths.(M   R   R   R   t   collectionst   distutils.versionR   RA   t   loggingR   R   R   R0   R   RF   R   R   R    R   t   acme.magic_typingR   R   t   certbotR   R   R   t	   getLoggerR   R4   t
   namedtupleR   R   t   ANSI_SGR_BOLDt   ANSI_SGR_REDt   ANSI_SGR_RESETt   linesepR   R9   R   R   R)   R>   R   R    R(   R.   R+   R?   R%   R7   RC   RM   RW   R]   R`   Rc   Rf   Rn   Rs   Rx   Ro   R|   Rv   R   Rp   t   compileR   R   t   ActionR   R   Ri   R   R   R   R   R*   R   (    (    (    s0   /usr/lib/python2.7/dist-packages/certbot/util.pyt   <module>   s~   	 														3				 	A				