HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/__pycache__/win_iis.cpython-310.pyc
o

�N�g��@s�dZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZe�e
�ZdZdZeedd��ZdZdd	�Zded
d�Zdfdd�Zdd�Zdgdd�Zdd�Zdd�Zdd�Z	dhdd�Zdid d!�Zd"d#�Zd$d%�Z d&d'�Z!d(d)�Z"d*d+�Z#	djd,d-�Z$	dkd.d/�Z%ded0d1�Z&d2d3�Z'dld5d6�Z(dmd7d8�Z)d9d:�Z*d;d<�Z+d=d>�Z,d?d@�Z-dAdB�Z.dCdD�Z/dEdF�Z0dGdH�Z1dIdJ�Z2dndKdL�Z3dMdN�Z4efdOdP�Z5efdQdR�Z6efdSdT�Z7dUdV�Z8dWdX�Z9dYdZ�Z:d[d\�Z;d]d^�Z<d_d`�Z=dadb�Z>dcdd�Z?dS)oa'
Microsoft IIS site management via WebAdministration powershell module

:maintainer:    Shane Lee <slee@saltstack.com>, Robert Booth <rbooth@saltstack.com>
:platform:      Windows
:depends:       PowerShell
:depends:       WebAdministration module (PowerShell) (IIS)

.. versionadded:: 2016.3.0
�N)�CommandExecutionError�SaltInvocationError�/)�ftp�http�https�Zwin_iiscCs>tjj��sdStddd�}|dsdSd|dvrd	StS)
zW
    Load only on Windows
    Requires PowerShell and the WebAdministration module
    )Fz!Only available on Windows systemszcmd.shell_info�
powershellTZ	installed)FzPowerShell not availableZWebAdministration�modules)FzIIS is not installed)�salt�utils�platformZ
is_windows�__salt__�__virtualname__)Zpowershell_info�r�H/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/win_iis.py�__virtual__ sr��*�PcCsd�|t|�|�dd�g�S)a8
    Combine the host header, IP address, and TCP port into bindingInformation
    format. Binding Information specifies information to communicate with a
    site. It includes the IP address, the port number, and an optional host
    header (usually a host name) to communicate with the site.

    Args:
        host_header (str): Usually a hostname
        ip_address (str): The IP address
        port (int): The port

    Returns:
        str: A properly formatted bindingInformation string (IP:port:hostheader)
            eg: 192.168.0.12:80:www.contoso.com
    �:� r)�join�str�replace)Zhost_header�
ip_address�portrrr�_get_binding_info2sr�Myc	Cs�t�}ddg}ddd|�d�ddg}t|d	d
�}z
tjjj|ddd
�}Wnty0td��w|D]/}t�}|D]}||vrH||||��<q:g|d<|dr\dd�|dD�|d<|||d<q3|S)a
    List details of available certificates in the LocalMachine certificate
    store.

    Args:
        certificate_store (str): The name of the certificate store on the local
            machine.

    Returns:
        dict: A dictionary of certificates found in the store
    ZDnsNameListZ
Thumbprint�
Get-ChildItem�-Pathz'Cert:\LocalMachine\�'�|zESelect-Object DnsNameList, SerialNumber, Subject, Thumbprint, VersionT��cmd�return_json�stdoutF��strict�$Unable to parse return data as Json.�dnsnamescSsg|]}|d�qS)ZUnicoder)�.0�namerrr�
<listcomp>lsz_list_certs.<locals>.<listcomp>)	�dict�_srvmgrrr�json�loads�
ValueErrorr�lower)	Zcertificate_store�retZblacklist_keys�ps_cmd�cmd_ret�items�itemZ	cert_info�keyrrr�_list_certsEs2
���r:cCs�g}|�d�|�d�t|dd�}z
tjjj|ddd�}Wnty.t�d�Yd	Swt	�
d
�|dd|dd
��S)Nz6Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\InetStp\\z+ | Select-Object MajorVersion, MinorVersionT)r%r&Fr'r)���z{}.{}rZMajorVersionZMinorVersion)�appendr/rrr0r1r2�log�error�decimalZDecimal�format)�pscmdr6r7rrr�_iisVersionss


��rBFcCsbt|t�r
d�|�}|rd|�d�}d|��}td|ddd�}|d	d
kr/t�d||d�|S)
a:
    Execute a powershell command from the WebAdministration PS module.

    Args:
        cmd (list): The command to execute in a list
        return_json (bool): True formats the return in JSON, False just returns
            the output of the command.

    Returns:
        str: The output from the command
    rz1ConvertTo-Json -Compress -Depth 4 -InputObject @(�)z!Import-Module WebAdministration; zcmd.run_allr	T)�shellZpython_shell�retcoderz'Unable to execute command: %s
Error: %s�stderr)�
isinstance�listrrr=r>)r$r%r4rrrr/�s


r/csRt|||d�g�dd}t|�D]\}�t�fdd�|��D��r&|SqdS)zI
    Returns index of collection item matching the match dictionary.
    )r,�filterr�valuec3s�|]	}|���vVqdS�N)r7)r+r8�Zcollect_dictrr�	<genexpr>�s�z-_collection_match_to_index.<locals>.<genexpr>r;)�get_webconfiguration_settings�	enumerate�allr7)�pspathZ	colfilterr,�matchZ
collection�idxrrLr�_collection_match_to_index�s����rTcCs�g}|D]o}|�dd�durt�d|�q|�dd�dur$t�d|�qt�d|d�}|rn|dd|�d�d�}tjj�	|�
d��}t||d||�}|dkrYt�d	|�q|d�|�
d�t
|��|d<|�|�q|�|�q|S)
z�
    Prepare settings before execution with get or set functions.
    Removes settings with a match parameter when index is not found.
    r,Nz win_iis: Setting has no name: %srIz"win_iis: Setting has no filter: %szCollection\[(\{.*\})\]�r;z'win_iis: No match found for setting: %s)�getr=�warning�re�search�startrrZyaml�load�grouprTrrr<)rQ�settingsZprepared_settings�settingrRr,Z
match_dict�indexrrr�_prepare_settings�s*�r`cCs0t�}gd�}d}t|dd�}z
tjjj|ddd�}Wnty'td��w|D]a}t�}|d	d
D]A}|ddvr>q5t�}|D]}	|	|vrT|�|	�	�||	i�qC|d
�
dd�}
dd�|
D�\}}}
|�|
||d��|||d
<q5|d||d|d|dd�||d<q*|s�t�d|d�|S)z�
    List all the currently deployed websites.

    Returns:
        dict: A dictionary of the IIS sites and their properties.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_sites
    )rr �'IIS:\Sites'r"zFSelect-Object applicationPool, Bindings, ID, Name, PhysicalPath, State)ZcertificateHashZcertificateStoreName�protocolZsslFlagsTr#r&Fr'r)�bindings�
Collectionrb)rrZbindingInformationr�css�|]}|��VqdSrK)�strip)r+�elementrrrrM�s�zlist_sites.<locals>.<genexpr>)�
hostheader�	ipaddressr�applicationPool�id�state�physicalPath)�apppoolrcrkrl�
sourcepathr,zNo sites found in output: %s)
r.r/rrr0r1r2r�updater3�splitr=rW)r4r5Z	keep_keysr6r7r8rc�bindingZfiltered_bindingr9�binding_inforirrhrrr�
list_sites�sD
��
��rtrcCst|���}d|��}t|||�}t�}	||	vr t�d|�dS|tvr.d�|t�}
t|
��ddd|�d�dd|�d�d	d
�||�g}|ro|t	�vrQt�d|�n
t�d|�t
|�|�d
dd|�d�dddd|�d�g�t|�}|ddkr�d�||d�}
t
|
��t�d|�dS)ad
    Create a basic website in IIS.

    .. note::

        This function only validates against the site name, and will return True
        even if the site already exists with a different configuration. It will
        not modify the configuration of an existing site.

    Args:
        name (str): The IIS site name.
        sourcepath (str): The physical path of the IIS site.
        apppool (str): The name of the IIS application pool.
        hostheader (str): The host header of the binding. Usually the hostname
            or website name, ie: www.contoso.com
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.
        protocol (str): The application protocol of the binding. (http, https,
            etc.)

    Returns:
        bool: True if successful, otherwise False.

    .. note::

        If an application pool is specified, and that application pool does not
        already exist, it will be created.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\stage' apppool='TestPool'
    �IIS:\Sites\zSite '%s' already present.T�2Invalid protocol '{}' specified. Valid formats: {}�New-Itemr r!�
-PhysicalPathz	-Bindingsz0@{{ protocol='{0}'; bindingInformation='{1}' }};�+Utilizing pre-existing application pool: %s�$Application pool will be created: %s�Set-ItemProperty�-Name�ApplicationPool�-ValuerErz#Unable to create site: {}
Error: {}rFzSite created successfully: %s)rr3rrtr=�debug�_VALID_PROTOCOLSr@r�
list_apppools�create_apppool�extendr/r)r,rornrhrirrb�	site_pathrs�
current_sites�messager5r6�msgrrr�create_sitesV%
�

��


��r�cCs�d|��}t�}||vrt�d|�dSt�}|r-|�ddd|�d�ddd	d|�d�g�|r`|t�vr;t�d
|�n
t�d|�t|�|rL|�d�|�ddd|�d�dd
d	d|�d�g�t|�}|ddkrvd�	||d�}t
|��t�d|�dS)aU
    Modify a basic website in IIS.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The IIS site name.
        sourcepath (str): The physical path of the IIS site.
        apppool (str): The name of the IIS application pool.

    Returns:
        bool: True if successful, otherwise False.

    .. note::

        If an application pool is specified, and that application pool does not
        already exist, it will be created.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\new_path' apppool='NewTestPool'
    ru�Site '%s' not defined.Fr{r r!r|�PhysicalPathr~ryrz�;r}rErz#Unable to modify site: {}
Error: {}rFzSite modified successfully: %sT)rtr=rrHr�r�r�r<r/r@r)r,rornr�r�r5r6r�rrr�modify_sitelsP


��



��r�cCslt�}||vrt�d|�dSddd|�d�g}t|�}|ddkr.d�||d	�}t|��t�d
|�dS)aQ
    Delete a website from IIS.

    Args:
        name (str): The IIS site name.

    Returns:
        bool: True if successful, otherwise False

    .. note::

        This will not remove the application pool used by the site.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_site name='My Test Site'

    zSite already absent: %sTzRemove-WebSiter|r!rErz#Unable to remove site: {}
Error: {}rFzSite removed successfully: %s)rtr=rr/r@r)r,r�r5r6r�rrr�remove_site�sr�cC�$dd|�d�g}t|�}|ddkS)a%
    Stop a Web Site in IIS.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the website to stop.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.stop_site name='My Test Site'
    zStop-WebSiter!rEr�r/�r,r5r6rrr�	stop_site��r�cCr�)a(
    Start a Web Site in IIS.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the website to start.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.start_site name='My Test Site'
    z
Start-WebSiter!rErr�r�rrr�
start_site�r�r�cCst|�ot|�S)a.
    Restart a Web Site in IIS.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the website to restart.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.restart_site name='My Test Site'
    )r�r�)r,rrr�restart_sitesr�cCsDt�}t�}||vrt�d|�|S||d}|s t�d|�|S)a 
    Get all configured IIS bindings for the specified site.

    Args:
        site (str): The name if the IIS Site

    Returns:
        dict: A dictionary of the binding names and properties.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_bindings site
    �Site not found: %srczNo bindings found for site: %s�r.rtr=rW)�siter4�sitesrrr�
list_bindings+sr�c
Csjt|���}t|||�}|tvrd�|t�}t|��|r1t|�}|tvr1td�|tdtd���t|�}||vrAt	�
d|�dS|rhddd	|�d	�d
d	|�d	�dd	|�d	�dd	|�d	�d
d	|�d	�d|�g
}	n!ddd	|�d	�d
d	|�d	�dd	|�d	�dd	|�d	�d
d	|�d	�g}	t|	�}
|
ddkr�d�||
d�}t|��|t|�vr�t	�
d|�dSt	�
d|�dS)a�
    Create an IIS Web Binding.

    .. note::

        This function only validates against the binding
        ipaddress:port:hostheader combination, and will return True even if the
        binding already exists with a different configuration. It will not
        modify the configuration of an existing binding.

    Args:
        site (str): The IIS site name.
        hostheader (str): The host header of the binding. Usually a hostname.
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.
        protocol (str): The application protocol of the binding.
        sslflags (str): The flags representing certificate type and storage of
            the binding.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
    rv�=Invalid sslflags '{}' specified. Valid sslflags range: {}..{}rr;zBinding already present: %sTzNew-WebBindingr|r!�-HostHeader�
-IpAddress�-Portz	-Protocolz	-SslFlagsrEz&Unable to create binding: {}
Error: {}rFz Binding created successfully: %szUnable to create binding: %sF)rr3rr�r@r�int�_VALID_SSL_FLAGSr�r=rr/rr>)r�rhrirrb�sslflagsr,r��current_bindingsr5r6r�rrr�create_bindingJsn���




�




�r�cCs�|dur|tvrtd�|tdtd���t�}||vr$t�d|�dSt|�}||vr4t�d|�dS|�d�\}}	}
d�|durD|n||durMt	|�nt	|	�|durV|n|
g�}||kr�d	d
d|�d�dd|�d�d
ddd|�d�g	}t
|�}
|
ddkr�d�||
d�}t|��|dur�|||d|dkr�d	d
d|�d�dd|�d�d
ddd|�d�g	}t
|�}
|
ddkr�d�||
d�}t|��t�d|�dS)a�
    Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the
    binding.

    .. versionadded:: 2017.7.0

    Args:
        site (str): The IIS site name.
        binding (str): The binding to edit. This is a combination of the
            IP address, port, and hostheader. It is in the following format:
            ipaddress:port:hostheader. For example, ``*:80:`` or
            ``*:80:salt.com``
        hostheader (str): The host header of the binding. Usually the hostname.
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.
        sslflags (str): The flags representing certificate type and storage of
            the binding.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    The following will seat the host header of binding ``*:80:`` for ``site0``
    to ``example.com``

    .. code-block:: bash

        salt '*' win_iis.modify_binding site='site0' binding='*:80:' hostheader='example.com'
    Nr�rr;r�FzBinding '%s' not defined.rzSet-WebBindingr|r!z-BindingInformationz
-PropertyNameZBindingInformationr~rEz&Unable to modify binding: {}
Error: {}rFrcr�z0Unable to modify binding SSL Flags: {}
Error: {}z!Binding modified successfully: %sT)r�rr@rtr=rr�rqrrr/r)r�rrrhrirr�r�r��i�p�hZnew_bindingr5r6r�rrr�modify_binding�st!����


��


��r�c		Cs�t|||�}t|�}||vrt�d|�dSddd|�d�dd|�d�dd|�d�g}t|�}|dd	krAd
�||d�}t|��|t|�vrOt�d|�dSt�d
|�dS)a�
    Remove an IIS binding.

    Args:
        site (str): The IIS site name.
        hostheader (str): The host header of the binding.
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'
    zBinding already absent: %sTzRemove-WebBindingr�r!r�r�rErz&Unable to remove binding: {}
Error: {}rFz Binding removed successfully: %szUnable to remove binding: %sF)rr�r=rr/r@rr>)	r�rhrirr,r�r5r6r�rrr�remove_bindings,


�
r�cCsrt�}t�}||vrt�d|�|S||dD]}||d|dr.||d|||<q|s7t�d|�|S)a.
    List certificate bindings for an IIS site.

    .. versionadded:: 2016.11.0

    Args:
        site (str): The IIS site name.

    Returns:
        dict: A dictionary of the binding names and properties.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_bindings site
    r�rc�certificatehashz*No certificate bindings found for site: %sr�)r�r4r�rrrrr�list_cert_bindingsOs�r��cCs�t|���}t|||�}t�dkr|�d�dd}d�|�dd��}|tvr4td�|tdtd���t	|�}||vrDt
�d|�d	Sd
}	|D]}
||
krT||
d}	qHt
�d|	�t
�d
|�||	krmt
�d|�dSt
�}||vr|t
�d|�d	St�dkr�|�dd�}|�d�r�|d
d�}ddd|�d�dd|�d�g}
nddd|�d�dd|�d�d|�g}
t|
�}|ddkr�d�||d�}t|��t|�}||vr�t
�d|�d	S|||dkr�t
�d|�dSt
�d|�d	S)a
    Assign a certificate to an IIS Web Binding.

    .. versionadded:: 2016.11.0

    .. note::

        The web binding that the certificate is being assigned to must already
        exist.

    Args:
        name (str): The thumbprint of the certificate.
        site (str): The IIS site name.
        hostheader (str): The host header of the binding.
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.
        sslflags (int): Flags representing certificate type and certificate storage of the binding.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
    �rrzIIS:\SslBindings\{}�!r�r;zBinding not present: %sFNr�z"Current certificate thumbprint: %szNew certificate thumbprint: %sz+Certificate already present for binding: %sTzCertificate not present: %sz\*!z	\0.0.0.0!rwr r!z-Thumbprintz	-SSLFlagsrEz2Unable to create certificate binding: {}
Error: {}rFz,Certificate binding created successfully: %sz(Unable to create certificate binding: %s)r�upperrrB�
rpartitionr@rr�rr�r=r>rr:�endswithr/rr�)r,r�rhrirr�rsZbinding_pathr�Zcurrent_nameZcurrent_binding�certsZiis7pathr5r6r��new_cert_bindingsrrr�create_cert_bindingrs|
���



�	

�
�r�cCs�t|���}t|||�}dddddd|�d�dd	d
|�d�dg
}t|�}||vr0t�d|�d
S|||dkr@t�d|�d
St|�}|ddkrVd�||d�}	t	|	��t|�}
||
vrft�d|�d
S||
|dkrvt�d|�d
St�
d|�dS)a�
    Remove a certificate from an IIS Web Binding.

    .. versionadded:: 2016.11.0

    .. note::

        This function only removes the certificate from the web binding. It does
        not remove the web binding itself.

    Args:
        name (str): The thumbprint of the certificate.
        site (str): The IIS site name.
        hostheader (str): The host header of the binding.
        ipaddress (str): The IP address of the binding.
        port (int): The TCP port of the binding.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'
    z$Site = Get-ChildItemr rar"zWhere-Objectz { $_.Name -Eq 'z' };z$$Binding = $Site.Bindings.Collectionz&| Where-Object { $_.bindingInformationz-Eq 'z$Binding.RemoveSslCertificate()zBinding not found: %sTr�z&Certificate binding already absent: %srErz2Unable to remove certificate binding: {}
Error: {}rFz,Certificate binding removed successfully: %sz(Unable to remove certificate binding: %sF)rr�rr�r=rWrr/r@rr>)r,r�rhrirrsr5Zcurrent_cert_bindingsr6r�r�rrr�remove_cert_binding�sF

��r�cCs8t�}g}|�d�|�d�|�d�|�d�|�d�|�d�|�d�|�d�|�d	�|�d
�|�d�|�d�t|d
d�}z
tjjj|ddd�}Wnty_td��w|D]-}t	�}t
|dt�r}d|dvr|||dd7}n|�|d�|d|d�||d<qb|s�t�d|d�|S)z�
    List all configured IIS application pools.

    Returns:
        dict: A dictionary of IIS application pools and their details.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_apppools
    z?Get-ChildItem -Path 'IIS:\AppPools' | Select-Object Name, Statez>, @{ Name = 'Applications'; Expression = { $AppPool = $_.Name;z%$AppPath = 'machine/webroot/apphost';z?$FilterBase = '/system.applicationHost/sites/site/application';z=$FilterBase += "[@applicationPool = '$($AppPool)' and @path";z0$FilterRoot = "$($FilterBase) = '/']/parent::*";z*$FilterNonRoot = "$($FilterBase) != '/']";zLGet-WebConfigurationProperty -Filter $FilterRoot -PsPath $AppPath -Name Namez| ForEach-Object { $_.Value };zOGet-WebConfigurationProperty -Filter $FilterNonRoot -PsPath $AppPath -Name Pathz;| ForEach-Object { $_.Value } | Where-Object { $_ -ne '/' }z} }Tr#r&Fr'r)ZApplicationsrJrl)rl�applicationsr,z(No application pools found in output: %s)
r.r<r/rrr0r1r2rrHrGr=rW)r4r5r6r7r8r�rrrr�:sF







�
�

��r�cCsvt�}d|��}||vrt�d|�dSddd|�d�g}t|�}|ddkr3d	�||d
�}t|��t�d|�dS)a,
    Create an IIS application pool.

    .. note::

        This function only validates against the application pool name, and will
        return True even if the application pool already exists with a different
        configuration. It will not modify the configuration of an existing
        application pool.

    Args:
        name (str): The name of the IIS application pool.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_apppool name='MyTestPool'
    �IIS:\AppPools\z&Application pool '%s' already present.Trwr r!rErz/Unable to create application pool: {}
Error: {}rFz)Application pool created successfully: %s�r�r=rr/r@r�r,Zcurrent_apppoolsZapppool_pathr5r6r�rrrr�{s
�r�cCsxt�}d|��}||vrt�d|�dSddd|�d�dg}t|�}|dd	kr4d
�||d�}t|��t�d|�dS)
a
    Remove an IIS application pool.

    Args:
        name (str): The name of the IIS application pool.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_apppool name='MyTestPool'
    r�z#Application pool already absent: %sT�Remove-Itemr r!�-RecurserErz/Unable to remove application pool: {}
Error: {}rFz)Application pool removed successfully: %sr�r�rrr�remove_apppool�s
�r�cCr�)a-
    Stop an IIS application pool.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the App Pool to stop.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.stop_apppool name='MyTestPool'
    zStop-WebAppPoolr!rErr�r�rrr�stop_apppool�r�r�cCr�)a0
    Start an IIS application pool.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the App Pool to start.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.start_apppool name='MyTestPool'
    zStart-WebAppPoolr!rErr�r�rrr�
start_apppool�r�r�cCr�)a8
    Restart an IIS application pool.

    .. versionadded:: 2016.11.0

    Args:
        name (str): The name of the IIS application pool.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.restart_apppool name='MyTestPool'
    zRestart-WebAppPoolr!rErr�r�rrr�restart_apppool�r�r�cCsrt�}t�}t�}d|�d|��}|st�d�|S|�d�|D]L}|�ddd|�d�dd|�d�d	d
ddg	�|�d
|�d��|�d|�d��|�d�|�d�|�d�|�d�|�d|�d��|�d�q!t|dd�}|ddkr�d}	t|	��|�d�t|dd�}z"tj	j
j|ddd�}
t|
t�r�|�
|
d�W|S|�
|
�W|Sty�td ��w)!ak
    Get the value of the setting for the IIS container.

    .. versionadded:: 2016.11.0

    Args:
        name (str): The name of the IIS container.
        container (str): The type of IIS container. The container types are:
            AppPools, Sites, SslBindings
        settings (dict): A dictionary of the setting names and their values.

    Returns:
        dict: A dictionary of the provided settings and their values.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.get_container_setting name='MyTestPool' container='AppPools'
            settings="['processModel.identityType']"
    �IIS:\�\�No settings provided�$Settings = @{};zGet-ItemPropertyr r!r|�-ErrorAction�Stopr"�	Out-Null;z$$Property = Get-ItemProperty -Path 'z-Name 'z' -ErrorAction Stop;�8if (([String]::IsNullOrEmpty($Property) -eq $False) -and�:($Property.GetType()).Name -eq 'ConfigurationAttribute') {�%$Property = $Property | Select-Object�-ExpandProperty Value };z$Settings['�'] = [String] $Property;�$Property = $Null;Tr#rEr�MOne or more invalid property names were specified for the provided container.�	$Settingsr&Fr'r))r.rHr=rWr<r�r/rrrr0r1rGrpr2r)r,�	containerr]r4r5�ps_cmd_validate�container_pathr^r6r�r7rrr�get_container_settings\



��



�

���r�cCs�dddddd�}ddd	d
dd�}t�}d
|�d|��}|s$t�d�dS|D]
}t||�||<q&t|||��d�}||krEt�d�dS|D]G}zt||�||}	Wntyfd||�d�}	Ynw|dkrw|||vrw|||}	|�	ddd|�d�dd|�d�d|	�d�g�qGt
|�}
|
ddkr�d|�d|��}t|��t|||��d�}t�}
|D]&}|dkr�|||vr�|||||<t||�t||�kr�|||
|<q�|
r�t�
d|
�dSt�d |���dS)!a^
    Set the value of the setting for an IIS container.

    .. versionadded:: 2016.11.0

    Args:
        name (str): The name of the IIS container.
        container (str): The type of IIS container. The container types are:
            AppPools, Sites, SslBindings
        settings (dict): A dictionary of the setting names and their values.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.set_container_setting name='MyTestPool' container='AppPools'
            settings="{'managedPipeLineMode': 'Integrated'}"
    �LocalSystem�LocalService�NetworkService�SpecificUser�ApplicationPoolIdentity)�0�1�2�3�4r�r�r�r�r�)r�r�r�r�r�r�r�r�F)r,r�r]�-Settings already contain the provided values.Tr!zprocessModel.identityTyper{r r|r~r�rEr�Unable to set settings for z: �Failed to change settings: %s�$Settings configured successfully: %s)rHr=rWrr��keysr�complexr2r�r/rr.r>)r,r�r]ZidentityType_map2stringZidentityType_map2numericr5r�r^�current_settingsrJr6r��new_settings�failed_settingsrrr�set_container_settingos���

�
�

��
��r�cCs
t�}t�}|�d|�d��|�d�|�d�|�d�|�d�t|dd�}z
tjjj|d	d
d�}WntyAt	d��w|D]6}t�}t
|d
t�r_d|d
vr^||d
d7}n|�|d
�|d|d|d||dd�||d<qD|s�t�d|�|S)a
    Get all configured IIS applications for the specified site.

    Args:
        site (str): The IIS site name.

    Returns: A dictionary of the application names and properties.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_apps site
    zGet-WebApplication -Site 'r!zD| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,z;@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },zC@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')z$| Foreach-Object { $_.Trim() } ) } }Tr#r&Fr'r)�	protocolsrJrj�pathZpreloadEnabledr�)rnr�Zpreloadr�ror,zNo apps found in output: %s)
r.rHr<r/rrr0r1r2rrGr=rW)r�r4r5r6r7r8r�rrr�	list_apps�sB�
�
���r�c		Cs�t|�}||vrt�d|�dStj�|�st�d|�dSddd|�d�dd|�d�d	d|�d�g}|r@|�d
d|�d�g�t|�}|ddkrVd
�	||d�}t
|��t|�}||vrft�d|�dSt�d|�dS)a�
    Create an IIS application.

    .. note::

        This function only validates against the application name, and will
        return True even if the application already exists with a different
        configuration. It will not modify the configuration of an existing
        application.

    Args:
        name (str): The IIS application.
        site (str): The IIS site name.
        sourcepath (str): The physical path.
        apppool (str): The name of the IIS application pool.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_app name='app0' site='site0' sourcepath='C:\site0' apppool='site0'
    zApplication already present: %sT�Path is not present: %sFzNew-WebApplicationr|r!�-Siterxz-ApplicationPoolrErz*Unable to create application: {}
Error: {}rFz$Application created successfully: %sz Unable to create application: %s)r�r=r�osr��isdirr>r�r/r@r)	r,r�rorn�current_appsr5r6r��new_appsrrr�
create_app s:


�
�r�cCs�t|�}||vrt�d|�dSddd|�d�dd|�d�g}t|�}|ddkr5d	�||d
�}t|��t|�}||vrEt�d|�dSt�d|�d
S)a*
    Remove an IIS application.

    Args:
        name (str): The application name.
        site (str): The IIS site name.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_app name='app0' site='site0'
    zApplication already absent: %sTzRemove-WebApplicationr|r!r�rErz*Unable to remove application: {}
Error: {}rFz$Application removed successfully: %sz Unable to remove application: %sF)r�r=rr/r@rr>)r,r�r�r5r6r�r�rrr�
remove_appds,

��r�cCs�t�}ddd|�d�dd|�d�dddg}t|dd	�}z
tjjj|d
dd�}Wnty3td
��w|D]}d|di||d<q6|sKt�	d|�|S)a�
    Get all configured IIS virtual directories for the specified site, or for
    the combination of site and application.

    Args:
        site (str): The IIS site name.
        app (str): The IIS application.

    Returns:
        dict: A dictionary of the virtual directory names and properties.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_vdirs site
    zGet-WebVirtualDirectoryr�r!�-Applicationr"z-Select-Object PhysicalPath, @{ Name = 'name';z$Expression = { $_.path.Trim('/') } }Tr#r&Fr'r)rormr,zNo vdirs found in output: %s�
r.r/rrr0r1r2rr=rW)r��appr4r5r6r7r8rrr�
list_vdirs�s*

��r�c		Cs�t||�}||vrt�d|�dStj�|�st�d|�dSddd|�d�dd|�d�d	d|�d�g}|tkrC|�d
d|�d�g�t	|�}|ddkrYd
�
||d�}t|��t||�}||vrjt�d|�dSt�d|�dS)a�
    Create an IIS virtual directory.

    .. note::

        This function only validates against the virtual directory name, and
        will return True even if the virtual directory already exists with a
        different configuration. It will not modify the configuration of an
        existing virtual directory.

    Args:
        name (str): The virtual directory name.
        site (str): The IIS site name.
        sourcepath (str): The physical path.
        app (str): The IIS application.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_vdir name='vd0' site='site0' sourcepath='C:\inetpub\vdirs\vd0'
    z%Virtual directory already present: %sTr�FzNew-WebVirtualDirectoryr|r!r�rxr�rErz0Unable to create virtual directory: {}
Error: {}rFz*Virtual directory created successfully: %sz&Unable to create virtual directory: %s)r�r=rr�r�r�r>�_DEFAULT_APPr�r/r@r)	r,r�ror��
current_vdirsr5r6r��	new_vdirsrrr�create_vdir�s:



�
�
r�c
Cs�t||�}tjj|�d��d��}|r|�d�}d|�d|�|��}||vr.t�d|�dSddd|�d�d	g}t|�}|d
dkrNd�	||d
�}t
|��t||�}	||	vr_t�d|�dSt�d|�dS)a`
    Remove an IIS virtual directory.

    Args:
        name (str): The virtual directory name.
        site (str): The IIS site name.
        app (str): The IIS application.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_vdir name='vdir0' site='site0'
    rr�ruz$Virtual directory already absent: %sTr�r r!r�rErz0Unable to remove virtual directory: {}
Error: {}rFz*Virtual directory removed successfully: %sz&Unable to remove virtual directory: %sF)r�r�r�r�rstriprqr=rr/r@rr>)
r,r�r�r�Zapp_pathZ	vdir_pathr5r6r�r�rrr�remove_vdirs*

�
r�cCs�t�}gd�}t|dd�}z
tjjj|ddd�}Wnty%td��w|D]}|dr7|d||d	<q(|d
||d	<q(|sHt�	d|�|S)a�
    List the IIS Configuration Backups on the System.

    .. versionadded:: 2017.7.0

    .. note::
        Backups are made when a configuration is edited. Manual backups are
        stored in the ``$env:Windir\System32\inetsrv\backup`` folder.

    Returns:
        dict: A dictionary of IIS Configurations backed up on the system.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_backups
    )zGet-WebConfigurationBackupr"zSelect Name, CreationDate,z7@{N="FormattedDate"; E={$_.CreationDate.ToString("G")}}Tr#r&Fr'r)Z
FormattedDate�NameZCreationDate�No backups found in output: %sr�)r4r5r6r7r8rrr�list_backups<s�r�cCs`|t�vrtd|����ddd|�d�g}t|�}|ddkr+d�||d�}t|��|t�vS)	a�
    Backup an IIS Configuration on the System.

    .. versionadded:: 2017.7.0

    .. note::
        Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
        folder.

    Args:
        name (str): The name to give the backup

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.create_backup good_config_20170209
    zBackup already present: zBackup-WebConfigurationr|r!rErz0Unable to backup web configuration: {}
Error: {}rF)r�rr/r@�r,r5r6r�rrr�
create_backupks
�
r�cCsb|t�vr
t�d|�dSddd|�d�g}t|�}|ddkr,d�||d	�}t|��|t�vS)
aA
    Remove an IIS Configuration backup from the System.

    .. versionadded:: 2017.7.0

    Args:
        name (str): The name of the backup to remove

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.remove_backup backup_20170209
    zBackup already removed: %sTzRemove-WebConfigurationBackupr|r!rErz0Unable to remove web configuration: {}
Error: {}rF)r�r=rr/r@rr�rrr�
remove_backup�s
�
r�cCs�dd|�d�g}t|dd�}z
tjjj|ddd�}Wnty&td	��wt�}|D]
}|d
||d<q,|s?t�	d|�|S)
a~
    Returns a list of worker processes that correspond to the passed
    application pool.

    .. versionadded:: 2017.7.0

    Args:
        apppool (str): The application pool to query

    Returns:
        dict: A dictionary of worker processes with their process IDs

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.list_worker_processes 'My App Pool'
    rz'IIS:\AppPools\z\WorkerProcesses'Tr#r&Fr'r)ZappPoolNameZ	processIdr�)
r/rrr0r1r2rr.r=rW)rnr5r6r7r4r8rrr�list_worker_processes�s�rcCs�t�}t�}d}|st�d�|S|�d�|D]f}||vrn|dks&|dkrK|�d�||��|�d|�d��|�d	�|�d
|�d��|�d�|d
ksS|dkrm|�d|�d|�d��|�d
|�d��|�d�qd�|�}d|d|}t|��|�d�td�|�dd�}	zt	j
jj|	ddd�}
t
|
t�r�|�|
d�n|�|
�Wnty�t�d�Ynwd|��vr�d}t|��|S) a�
    .. versionadded:: 2017.7.0

    Get the value of the setting for the IIS web application.

    .. note::
        Params are case sensitive

    :param str name: The name of the IIS web application.
    :param str site: The site name contains the web application.
        Example: Default Web Site
    :param str settings: A dictionary of the setting names and their values.
        Available settings: physicalPath, applicationPool, userName, password
    Returns:
        dict: A dictionary of the provided settings and their values.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.get_webapp_settings name='app0' site='Default Web Site'
            settings="['physicalPath','applicationPool']"
    �rmrj�userName�passwordr�r�rrz� $Property = Get-WebConfigurationProperty -Filter "system.applicationHost/sites/site[@name='{}']/application[@path='/{}']/virtualDirectory[@path='/']"� -Name "z#" -ErrorAction Stop | select Value;z= $Property = $Property | Select-Object -ExpandProperty Value;z $Settings['r�z $Property = $Null;rmrjz! $Property = (get-webapplication z).r��, �Unexpected setting:z. Available settings are: z
 $SettingsrTr#r&Fr'rr)NzhSome values are empty - please validate site and web application names. Some commands are case sensitive)r.rHr=rWr<r@rrr/rrr0r1rGrpr2r>�values)r,r�r]r4rA�availableSettingsr^�availSetStrr�r6r7rrr�get_webapp_settings�sj

���

�
����


���r
c	CsRt�}t|�}t�}d}||vrd|d}t|��||vr(d|d}t|��|s0d}t|��|��D]+}||vrCt||�||<q4d�|�}	t�d|�t�d|	�d	|d
|	}t|��t	|||��d�}
||
krtt�
d�d
S|D]f}zt||�||}Wnty�d||�d�}Ynw|dks�|dkr�|�
d�||��|�
d|�d|�d��|dks�|dkr�|�
d�||||��|dkr�tj�||�s�d||}t|��qvt|�}|ddkr�d|��}t|��t	|||��d�}
t�}|D]}t||�t|
|�k�r||||<q�|�rt�d|�dSt�dt|��d
S)a#
    .. versionadded:: 2017.7.0

    Configure an IIS application.

    .. note::
        This function only configures an existing app. Params are case
        sensitive.

    :param str name: The IIS application.
    :param str site: The IIS site name.
    :param str settings: A dictionary of the setting names and their values.
        - physicalPath: The physical path of the webapp.
        - applicationPool: The application pool for the webapp.
        - userName: "connectAs" user
        - password: "connectAs" password for user
    :return: A boolean representing whether all changes succeeded.
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.set_webapp_settings name='app0' site='site0' settings="{'physicalPath': 'C:\site0', 'apppool': 'site0'}"
    rZApplicationz
doesn't existZSiter�rzUnexpected setting: %s zAvailable settings: %srz Available settings:)r,r�r]r�Tr!rrz� Set-WebConfigurationProperty -Filter "system.applicationHost/sites/site[@name='{}']/application[@path='/{}']/virtualDirectory[@path='/']"rz	" -Value r�rmrjz8 Set-ItemProperty "IIS:\Sites\{}\{}" -Name {} -Value {};zPath is not present: rErz+Unable to set settings for web application r�Fr�)rHr�rtrr�rrr=r>r
rWr�r2r<r@r�r�r�r/r.r)r,r�r]rAr�r�rr�r^r	r�rJr6r�r�rrr�set_webapp_settings5s�

�
������
�rcCs�i}dg}g}t||�}|st�d�|S|D]�}|�ddd|�d�dd�|d�d	d�|d
�ddd
dg�|�d|�d��|�d�|d
|d��|d
�d�ddkr}d|vro|�d�d�t|dd�	�����|�d�|d|d
��n!|�d�|�d�|�d�|�d�|�d�|d|d
��|�d�qt
|dd �}|d!dkr�d"}t|��|�d#�t
|dd �}ztj
jj|d$d%d&�}W|Sty�td'��w)(a!
    Get the webconfiguration settings for the IIS PSPath.

    Args:
        name (str): The PSPath of the IIS webconfiguration settings.
        settings (list): A list of dictionaries containing setting name and filter.

    Returns:
        dict: A list of dictionaries containing setting name, filter and value.

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.get_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication'}]"
    z4$Settings = New-Object System.Collections.ArrayList;r�zGet-WebConfigurationProperty�-PSPathr!�-Filter�'{}'rIr|r,r�r�r"r�z2$Property = Get-WebConfigurationProperty -PSPath 'z*-Name '{}' -Filter '{}' -ErrorAction Stop;�.r;rdrJz-$Property = $Property | select -Property {} ;�,rzh$Settings.add(@{{filter='{0}';name='{1}';value=[System.Collections.ArrayList] @($Property)}})| Out-Null;r�r�r�r�zO$Settings.add(@{{filter='{0}';name='{1}';value=[String] $Property}})| Out-Null;r�Tr#rEr�r�r&Fr'r))r`r=rWr�r@r<rqrrHr�r/rrrr0r1r2r)r,r]r4r5r�r^r6r�rrrrN�sz


�������



��
��rNc
CsVg}t||�}|st�d�dSt|�D]\}}|d�d�ddkr-t|d�||d<qt||d�}||kr?t�d	�d
S|D]y}|d�d�ddkrkzt|d�|d}Wn@t	yjd�
|d�}Yn1wg}|dD]$}g}	|��D]\}
}|	�|
�d|�d
��qy|�dd�
|	�d�qqd�
|�}|�ddd
|�d
�dd�
|d�dd�
|d�d|�d�g	�qAt|�}|ddkr�d|��}t|��t||d�}
g}t|�D]=\}}|d�d�ddk}|s�t|d�t|
|d�k�s|�rttt|d��ttt|
|d��k�r|�|�q�|�r#t�d|�dSt�d|�d
S)a
    Set the value of the setting for an IIS container.

    Args:
        name (str): The PSPath of the IIS webconfiguration settings.
        settings (list): A list of dictionaries containing setting name, filter and value.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' win_iis.set_webconfiguration_settings name='IIS:\' settings="[{'name': 'enabled', 'filter': 'system.webServer/security/authentication/anonymousAuthentication', 'value': False}]"
    r�Fr,rr;rdrJ)r,r]r�Trz='r!z@{r��}rzSet-WebConfigurationPropertyrr
rIr|r~rErr�r�r�)r`r=rWrOrqrrNrr�r2r@r7r<rr�r/rrH�mapr.r>)r,r]r5rSr^r�rJZconfigelement_listZ
value_itemZconfigelement_constructr9r6r�r�r�Z
is_collectionrrr�set_webconfiguration_settings
	s�

�
��

��
���
�r)rrr)r)F)rrrrr)NN)rrrrN)NNNN)rrr�r)rrr�rK)@�__doc__r?�loggingr�rXZsalt.utils.jsonrZsalt.utils.platformZsalt.utils.yamlZsalt.exceptionsrr�	getLogger�__name__r=r�r��tuple�ranger�rrrr:rBr/rTr`rtr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr
rrNrrrrr�<module>sx


.

D
�
]Q' 
�e
�
p1
#
yOA,%Xt
=D1/D4/&#&[uc