
    M/e(                     <   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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 dd	lmZ dd
lmZ ddlmZ ej*                  dk\  rddlmZ nddlZ ej2                  e      Zdedee   fdZdedee   fdZdedefdZdedeeef   fdZ dededeeef   fdZ!defdZ"dedee   de#fdZ$dee   deeef   fdZ%dee   dee   fdZ&dee   dee   fdZ'd ee   d!edee   fd"Z(d ee   defd#Z)d$edefd%Z*y)&z- Utility functions for certbot-apache plugin     N)	ExitStack)Dict)Iterable)List)Optional)Tuple)errors)util)os)   	   mod_namereturnc                 2    dddgi}|j                  | g       S )a  Get known module dependencies.

    .. note:: This does not need to be accurate in order for the client to
        run.  This simply keeps things clean if the user decides to revert
        changes.
    .. warning:: If all deps are not included, it may cause incorrect parsing
        behavior, due to enable_mod's shortcut for updating the parser's
        currently defined modules (`.ApacheParser.add_mod`)
        This would only present a major problem in extremely atypical
        configs that use ifmod for the missing deps.

    sslsetenvifmime)get)r   depss     F/usr/lib/python3/dist-packages/certbot_apache/_internal/apache_util.pyget_mod_depsr      s(     	
F#D 88Hb!!    
vhost_pathc                 F    | r| j                  d      syt        |       d   S )zGet file path from augeas_vhost_path.

    Takes in Augeas path and returns the file name

    :param str vhost_path: Augeas virtual host path

    :returns: filename of vhost
    :rtype: str

    z/files/Nr   )
startswith_split_aug_pathr   s    r   get_file_pathr   0   s'     Z229=:&q))r   c                     t        |       d   S )zGet the Augeas path for a vhost with the file path removed.

    :param str vhost_path: Augeas virtual host path

    :returns: Augeas path to vhost relative to the containing file
    :rtype: str

       )r   r   s    r   get_internal_aug_pathr!   A   s     :&q))r   c                    | dd }g }t         j                  j                  |      sF|j                  d      \  }}}|j	                  |       t         j                  j                  |      sF|dj                  t        |            fS )a:  Splits an Augeas path into a file path and an internal path.

    After removing "/files", this function splits vhost_path into the
    file path and the remaining Augeas path.

    :param str vhost_path: Augeas virtual host path

    :returns: file path and internal Augeas path
    :rtype: `tuple` of `str`

       N/)r   pathexists
rpartitionappendjoinreversed)r   	file_pathinternal_path_internal_path_parts        r   r   r   M   sz     12I!M ggnnY'+4+?+?+D(	1(/0 ggnnY' chhx6777r   filepathvarnamec                 j   i }t        j                  ||       j                         }t        |      D ]~  \  }}|dk(  r4t	        |      |dz   k\  r#||dz      j                  d      }|d   ||d   <   ?t	        |      dkD  sN|j                  d      s`|dd j                  d      }|d   ||d   <    |S )z Parses Defines from a variable in configuration file

    :param str filepath: Path of file to parse
    :param str varname: Name of the variable

    :returns: Dict of Define:Value pairs
    :rtype: `dict`

    z-D   r    =r   N)r
   get_var_from_filesplit	enumeratelen	partitionr   )r/   r0   return_varsa_optsiv	var_partss          r   parse_define_filer>   e   s     #%K##GX6<<>F&! 519V!+qs--c2I(1!K	!%VaZALL.!",I(1!K	!%5 r   c                  p    t        j                  t        j                  d            j	                  d      S )z< Returns an unique id to be used as a VirtualHost identifier   zutf-8)binasciihexlifyr   urandomdecode r   r   	unique_idrF   ~   s&    BJJrN+227;;r   pathsc                 ,     t         fd|D              S )a*  
    Returns true if the filepath is included in the list of paths
    that may contain full paths or wildcard paths that need to be
    expanded.

    :param str filepath: Filepath to check
    :param list paths: List of paths to check against

    :returns: True if included
    :rtype: bool
    c              3   J   K   | ]  }t        j                   |        y w)N)fnmatch).0r%   r/   s     r   	<genexpr>z$included_in_paths.<locals>.<genexpr>   s     A4wx.As    #)any)r/   rG   s   ` r   included_in_pathsrN      s     A5AAAr   
define_cmdc                     i }t        | d      }	 |j                  d       |D ]1  }|j                  dd      }t	        |      dk(  r|d   nd}|||d   <   3 |S # t        $ r i cY S w xY w)z
    Gets Defines from httpd process and returns a dictionary of
    the defined variables.

    :param list define_cmd: httpd command to dump defines

    :returns: dictionary of defined variables
    :rtype: dict
    zDefine: ([^ \n]*)DUMP_RUN_CFGr3   r    r2    r   )parse_from_subprocessremove
ValueErrorr5   r7   )rO   	variablesmatchesmatchpartsvalues         r   parse_definesr[      s     !#I#J0DEG~&  $C#J!Oa#	%(	$   	s   A A'&A'inc_cmdc                     t        | d      S )z
    Gets Include directives from httpd process and returns a list of
    their values.

    :param list inc_cmd: httpd command to dump includes

    :returns: list of found Include directive values
    :rtype: list of str
    z\(.*\) (.*)rS   )r\   s    r   parse_includesr_           !.99r   mod_cmdc                     t        | d      S )z
    Get loaded modules from httpd process, and return the list
    of loaded module names.

    :param list mod_cmd: httpd command to dump loaded modules

    :returns: list of found LoadModule module names
    :rtype: list of str
    z(.*)_moduler^   )ra   s    r   parse_modulesrc      r`   r   commandregexpc                 `    t        |       }t        j                  |      j                  |      S )zGet values from stdout of subprocess command

    :param list command: Command to run
    :param str regexp: Regexp for parsing

    :returns: list parsed from command output
    :rtype: list

    )_get_runtime_cfgrecompilefindall)rd   re   stdouts      r   rS   rS      s(     g&F::f%%f--r   c           	         	 t        j                  | t         j                  t         j                  ddt        j                               }|j
                  |j                  }}|j                   dk7  r+t        j#                  d|       t        j                  d      |S # t        t        f$ rJ t        j                  d| t        j                         t        j                  dj                  |             w xY w)	zq
    Get runtime configuration info.

    :param command: Command to run

    :returns: stdout from command

    TF)rk   stderruniversal_newlinescheckenvz2Error running command %s for runtime parameters!%sz-Error accessing loaded Apache parameters: {0}r   z$Error in checking parameter list: %sz^Apache is unable to check whether or not the module is loaded because Apache is misconfigured.)
subprocessrunPIPEr
   env_no_snap_for_external_callsrk   rm   OSErrorrU   loggererrorr   linesepr	   MisconfigurationErrorformat
returncodewarning)rd   procrk   rm   s       r   rg   rg      s    ~~????#3357 dkk !=vF**67 	7 M Z  @RZZ	! **;BB 		s   A!B AC8prefixc                 P   t               }t        j                  |j                         t	        j
                  d      j                  d      j                  d      j                  dj                  |             }t        |j                  t	        j                  |                  S )z
    Find a TLS Apache config file in the dedicated storage.
    :param str prefix: prefix of the TLS Apache config file to find
    :return: the path the TLS Apache config file
    :rtype: str
    certbot_apache	_internaltls_configsz{0}-options-ssl-apache.conf)r   atexitregistercloseimportlib_resourcesfilesjoinpathrz   strenter_contextas_file)r~   file_managerrefs      r   find_ssl_apache_confr      s~     ;L
OOL&&'$$%56??LH]#HH-J-Q-QRX-Y$Z |))*=*E*Ec*JKLLr   )+__doc__r   rA   rJ   loggingrh   rq   sys
contextlibr   typingr   r   r   r   r   certbotr	   r
   certbot.compatr   version_infoimportlib.resources	resourcesr   	getLogger__name__rv   r   r   r   r!   r   r>   rF   boolrN   r[   r_   rc   rS   rg   r   rE   r   r   <module>r      s   3     	  
          v5 
		8	$"3 "49 "&*c *hsm *"	*c 	*c 	*8 8c3h 80 c d38n 2<3 <
B BHSM Bd Bd3i DcN 6:DI :$s) ::49 :c :.49 .c .d3i .!d3i !C !HM M Mr   