
    Vh                    z   d dl mZ 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	m
Z d dlmZmZ d dlmZ d dlmZ d dlmZ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 dZ dZ!	 d dl"m#Z#m$Z$m%Z% d dl&m'Z'm(Z( d dl)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2m3Z3  e       Z6 G d de      Z7y# e4$ rZ5dZ e5Z!Y dZ5[5!dZ5[5ww xY w)    )annotationsa$  
author: Ansible Core Team
name: psrp
short_description: Run tasks over Microsoft PowerShell Remoting Protocol
description:
- Run commands or put/fetch on a target via PSRP (WinRM plugin)
- This is similar to the P(ansible.builtin.winrm#connection) connection plugin which uses the same
  underlying transport but instead runs in a PowerShell interpreter.
version_added: "2.7"
requirements:
- pypsrp>=0.4.0, <1.0.0 (Python library)
extends_documentation_fragment:
    - connection_pipelining
options:
  # transport options
  remote_addr:
    description:
    - The hostname or IP address of the remote host.
    default: inventory_hostname
    type: str
    vars:
    - name: inventory_hostname
    - name: ansible_host
    - name: ansible_psrp_host
  remote_user:
    description:
    - The user to log in as.
    type: str
    vars:
    - name: ansible_user
    - name: ansible_psrp_user
    keyword:
    - name: remote_user
  remote_password:
    description: Authentication password for the O(remote_user). Can be supplied as CLI option.
    type: str
    vars:
    - name: ansible_password
    - name: ansible_winrm_pass
    - name: ansible_winrm_password
    aliases:
    - password  # Needed for --ask-pass to come through on delegation
  port:
    description:
    - The port for PSRP to connect on the remote target.
    - Default is V(5986) if O(protocol) is not defined or is V(https),
      otherwise the port is V(5985).
    type: int
    vars:
    - name: ansible_port
    - name: ansible_psrp_port
    keyword:
    - name: port
  protocol:
    description:
    - Set the protocol to use for the connection.
    - Default is V(https) if O(port) is not defined or O(port) is not V(5985).
    choices:
    - http
    - https
    type: str
    vars:
    - name: ansible_psrp_protocol
  path:
    description:
    - The URI path to connect to.
    type: str
    vars:
    - name: ansible_psrp_path
    default: 'wsman'
  auth:
    description:
    - The authentication protocol to use when authenticating the remote user.
    - The default, V(negotiate), will attempt to use Kerberos (V(kerberos)) if it is
      available and fall back to NTLM (V(ntlm)) if it isn't.
    type: str
    vars:
    - name: ansible_psrp_auth
    choices:
    - basic
    - certificate
    - negotiate
    - kerberos
    - ntlm
    - credssp
    default: negotiate
  cert_validation:
    description:
    - Whether to validate the remote server's certificate or not.
    - Set to V(ignore) to not validate any certificates.
    - O(ca_cert) can be set to the path of a PEM certificate chain to
      use in the validation.
    choices:
    - validate
    - ignore
    default: validate
    type: str
    vars:
    - name: ansible_psrp_cert_validation
  ca_cert:
    description:
    - The path to a PEM certificate chain to use when validating the server's
      certificate.
    - This value is ignored if O(cert_validation) is set to V(ignore).
    type: path
    vars:
    - name: ansible_psrp_cert_trust_path
    - name: ansible_psrp_ca_cert
    aliases: [ cert_trust_path ]
  connection_timeout:
    description:
    - The connection timeout for making the request to the remote host.
    - This is measured in seconds.
    type: int
    vars:
    - name: ansible_psrp_connection_timeout
    default: 30
  read_timeout:
    description:
    - The read timeout for receiving data from the remote host.
    - This value must always be greater than O(operation_timeout).
    - This option requires pypsrp >= 0.3.
    - This is measured in seconds.
    type: int
    vars:
    - name: ansible_psrp_read_timeout
    default: 30
    version_added: '2.8'
  reconnection_retries:
    description:
    - The number of retries on connection errors.
    type: int
    vars:
    - name: ansible_psrp_reconnection_retries
    default: 0
    version_added: '2.8'
  reconnection_backoff:
    description:
    - The backoff time to use in between reconnection attempts.
      (First sleeps X, then sleeps 2*X, then sleeps 4*X, ...)
    - This is measured in seconds.
    - The C(ansible_psrp_reconnection_backoff) variable was added in Ansible
      2.9.
    type: int
    vars:
    - name: ansible_psrp_connection_backoff
    - name: ansible_psrp_reconnection_backoff
    default: 2
    version_added: '2.8'
  message_encryption:
    description:
    - Controls the message encryption settings, this is different from TLS
      encryption when O(protocol) is V(https).
    - Only the auth protocols V(negotiate), V(kerberos), V(ntlm), and
      V(credssp) can do message encryption. The other authentication protocols
      only support encryption when V(protocol) is set to V(https).
    - V(auto) means means message encryption is only used when not using
      TLS/HTTPS.
    - V(always) is the same as V(auto) but message encryption is always used
      even when running over TLS/HTTPS.
    - V(never) disables any encryption checks that are in place when running
      over HTTP and disables any authentication encryption processes.
    type: str
    vars:
    - name: ansible_psrp_message_encryption
    choices:
    - auto
    - always
    - never
    default: auto
  proxy:
    description:
    - Set the proxy URL to use when connecting to the remote host.
    vars:
    - name: ansible_psrp_proxy
    type: str
  ignore_proxy:
    description:
    - Will disable any environment proxy settings and connect directly to the
      remote host.
    - This option is ignored if O(proxy) is set.
    vars:
    - name: ansible_psrp_ignore_proxy
    type: bool
    default: false

  # auth options
  certificate_key_pem:
    description:
    - The local path to an X509 certificate key to use with certificate auth.
    type: path
    vars:
    - name: ansible_psrp_certificate_key_pem
  certificate_pem:
    description:
    - The local path to an X509 certificate to use with certificate auth.
    type: path
    vars:
    - name: ansible_psrp_certificate_pem
  credssp_auth_mechanism:
    description:
    - The sub authentication mechanism to use with CredSSP auth.
    - When V(auto), both Kerberos and NTLM is attempted with kerberos being
      preferred.
    type: str
    choices:
    - auto
    - kerberos
    - ntlm
    default: auto
    vars:
    - name: ansible_psrp_credssp_auth_mechanism
  credssp_disable_tlsv1_2:
    description:
    - Disables the use of TLSv1.2 on the CredSSP authentication channel.
    - This should not be set to V(yes) unless dealing with a host that does not
      have TLSv1.2.
    default: false
    type: bool
    vars:
    - name: ansible_psrp_credssp_disable_tlsv1_2
  credssp_minimum_version:
    description:
    - The minimum CredSSP server authentication version that will be accepted.
    - Set to V(5) to ensure the server has been patched and is not vulnerable
      to CVE 2018-0886.
    default: 2
    type: int
    vars:
    - name: ansible_psrp_credssp_minimum_version
  negotiate_delegate:
    description:
    - Allow the remote user the ability to delegate it's credentials to another
      server, i.e. credential delegation.
    - Only valid when Kerberos was the negotiated auth or was explicitly set as
      the authentication.
    - Ignored when NTLM was the negotiated auth.
    type: bool
    vars:
    - name: ansible_psrp_negotiate_delegate
  negotiate_hostname_override:
    description:
    - Override the remote hostname when searching for the host in the Kerberos
      lookup.
    - This allows Ansible to connect over IP but authenticate with the remote
      server using it's DNS name.
    - Only valid when Kerberos was the negotiated auth or was explicitly set as
      the authentication.
    - Ignored when NTLM was the negotiated auth.
    type: str
    vars:
    - name: ansible_psrp_negotiate_hostname_override
  negotiate_send_cbt:
    description:
    - Send the Channel Binding Token (CBT) structure when authenticating.
    - CBT is used to provide extra protection against Man in the Middle C(MitM)
      attacks by binding the outer transport channel to the auth channel.
    - CBT is not used when using just C(HTTP), only C(HTTPS).
    default: true
    type: bool
    vars:
    - name: ansible_psrp_negotiate_send_cbt
  negotiate_service:
    description:
    - Override the service part of the SPN used during Kerberos authentication.
    - Only valid when Kerberos was the negotiated auth or was explicitly set as
      the authentication.
    - Ignored when NTLM was the negotiated auth.
    default: WSMAN
    type: str
    vars:
    - name: ansible_psrp_negotiate_service

  # protocol options
  operation_timeout:
    description:
    - Sets the WSMan timeout for each operation.
    - This is measured in seconds.
    - This should not exceed the value for O(connection_timeout).
    type: int
    vars:
    - name: ansible_psrp_operation_timeout
    default: 20
  max_envelope_size:
    description:
    - Sets the maximum size of each WSMan message sent to the remote host.
    - This is measured in bytes.
    - Defaults to C(150KiB) for compatibility with older hosts.
    type: int
    vars:
    - name: ansible_psrp_max_envelope_size
    default: 153600
  configuration_name:
    description:
    - The name of the PowerShell configuration endpoint to connect to.
    type: str
    vars:
    - name: ansible_psrp_configuration_name
    default: Microsoft.PowerShell
N)	constants)AnsibleConnectionFailureAnsibleError)AnsibleFileNotFound)boolean)to_bytes	to_nativeto_text)ConnectionBase)ShellModule)_common_args)Display)sha1T)GenericComplexObjectPSInvocationStateRunspacePoolState)AuthenticationError
WinRMError)PSHostPSHostUserInterface)
PowerShellRunspacePool)WSMan)ConnectionErrorConnectTimeoutFc                       e Zd ZU dZdZdZdZded<   d fdZd fdZ	dd	Z
dd fd
Zd fdZd fdZddZddZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZ xZS )
Connectionpsrp)z.ps1z.exe FTPowerShellPlugin_shellc                   d| _         d| _        d | _        d | _        d | _        d| _        t        t        | "  |i | t        j                  st        j                  d      j                  t        j                         t        j                  d      j                  t        j                         t        j                  d      j                  t        j                         y y )NT
powershellpypsrprequests_credsspurllib3)always_pipeline_moduleshas_native_asyncrunspacehost_last_pipeline_shell_typesuperr   __init__CDEFAULT_DEBUGlogging	getLoggersetLevelWARNINGINFO)selfargskwargs	__class__s      O/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/connection/psrp.pyr/   zConnection.__init__^  s    '+$ $-1#'	15'j$($9&9h'00A01::7<<Hi(11',,?     c           	        t         st        dt        t              z        t        t
        |           | j                          t        j                  d| j                  d| j                  d| j                  | j                         | j                  st        di | j                  }t!               }t#        d d ddd |d       | _        t'        || j$                  | j(                        | _        t        j+                  d	| j,                  d
| j(                  d|j.                  j0                  | j                         	 | j                  j3                          d| _        d | _         | S # t4        $ r}t7        dt        |      z        d }~wt8        $ r}t7        dt        |      z        d }~wt:        t<        f$ r}t7        dt        |      z        d }~ww xY w)Nz,pypsrp or dependencies are not installed: %sz$ESTABLISH PSRP CONNECTION FOR USER: z	 ON PORT  TO r+   FzAnsible PSRP Host)r+   configuration_namezPSRP OPEN RUNSPACE: auth=z configuration=z
 endpoint=z*failed to authenticate with the server: %sz0psrp connection failure during runspace open: %sz*Failed to connect to the host via PSRP: %sT )!
HAS_PYPSRPr   r
   PYPSRP_IMP_ERRr.   r   _connect_build_kwargsdisplayvvv
_psrp_user
_psrp_port
_psrp_hostr*   r   _psrp_conn_kwargsr   r   r+   r   _psrp_configuration_namevvvvv
_psrp_auth	transportendpointopenr   r   r   r   r   
_connectedr,   )r7   
connectionhost_uier:   s       r;   rD   zConnection._connectn  s   M!*>!: ; < <j$(*__dootH 	 	* }}8!7!78J *+GtT52Et&.DI )#'#@#@DM MM$"?"?%%..06:oo  
""$ #DO"&D! ' P. 0@BKA,0O P P .Fl#  $^4 .@l# s0   E2 2	G#;FG#F55G#GG#c                ,   | j                   sd | _        y 	 | j                          t        j                  d| j                         d | _        | j                          y # t        $ r+}t        j                  dt        |      z         Y d }~hd }~ww xY w)Nz*PSRP reset - failed to closed runspace: %szPSRP: Reset Connectionr?   )
rR   r*   close	ExceptionrF   debugr   rM   rJ   rD   )r7   rU   s     r;   resetzConnection.reset  sw     DM	UJJL
 	.T__E  	UMMFQRSTT	Us   A 	B(!BBc                   t         t        |   |||       d }|j                  dj	                  t
              dz         rt        j                  |j                  d      d         }t        |d      }t        |dd      }|rNt        |t              r>|j                  d	      r-t        |j                         d
   dd        }t        d|z        | j                  j!                  ddd      }||k(  rt"        j%                  d       nYt"        j%                  d|z  | j&                         n4t        d|z        }|}t"        j%                  d|z  | j&                         | j)                  ||      \  }	}
}|	|
|fS )N)in_datasudoable z -EncodedCommandz	utf-16-lesurrogate_or_strictpassthru)errors	nonstringz#!r      z=cannot run the interpreter '%s' on the psrp connection pluginr    z!PSRP: EXEC (via pipeline wrapper)zPSRP: EXEC %sr?   z%s
exit $LASTEXITCODE)r.   r   exec_command
startswithjoinr   base64	b64decodesplitr   
isinstancestrr
   
splitlinesr   r"   build_module_commandrF   rG   rJ   _exec_psrp_script)r7   cmdr\   r]   pwsh_in_data	b_commandscriptinterpreterbootstrap_wrapperrcstdoutstderrr:   s               r;   re   zConnection.exec_command  st   j$,S'6> 	- 	@ ,0>>#((<03EEF ((3);<IY4F"73HT^_L
< =,BYBYZ^B_
 ((?(?(A!(DQR(HI" $79D$E F F !% @ @R L C'?@Of44??K 6<=F"LKK(61KH!33FLIFF66!!r<   c                \    t         t                   j                  j	                        t
        j                  dd j                         d}t         j                  j                  j                  dz
  dz  dz        t               t        d	      t        j                  j!                        st#        d
t%              z         fd} j'                  | |       g      \  }}}|dk7  rt)        t%        |            t+        j,                  t/        |            }j1                         }	|j3                  d      }
|
s$t)        dt%        |      dt%        |      d      |
|	k(  s#t)        dt%        |
      dt%        |	            y )NzPUT r>   r?   a  begin {
    $ErrorActionPreference = "Stop"
    $WarningPreference = "Continue"
    $path = $MyInvocation.UnboundArguments[0]
    $fd = [System.IO.File]::Create($path)
    $algo = [System.Security.Cryptography.SHA1CryptoServiceProvider]::Create()
    $bytes = @()

    $bindingFlags = [System.Reflection.BindingFlags]'NonPublic, Instance'
    Function Get-Property {
        <#
        .SYNOPSIS
        Gets the private/internal property specified of the object passed in.
        #>
        Param (
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            [System.Object]
            $Object,

            [Parameter(Mandatory=$true, Position=1)]
            [System.String]
            $Name
        )

        $Object.GetType().GetProperty($Name, $bindingFlags).GetValue($Object, $null)
    }

    Function Set-Property {
        <#
        .SYNOPSIS
        Sets the private/internal property specified on the object passed in.
        #>
        Param (
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            [System.Object]
            $Object,

            [Parameter(Mandatory=$true, Position=1)]
            [System.String]
            $Name,

            [Parameter(Mandatory=$true, Position=2)]
            [AllowNull()]
            [System.Object]
            $Value
        )

        $Object.GetType().GetProperty($Name, $bindingFlags).SetValue($Object, $Value, $null)
    }

    Function Get-Field {
        <#
        .SYNOPSIS
        Gets the private/internal field specified of the object passed in.
        #>
        Param (
            [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
            [System.Object]
            $Object,

            [Parameter(Mandatory=$true, Position=1)]
            [System.String]
            $Name
        )

        $Object.GetType().GetField($Name, $bindingFlags).GetValue($Object)
    }

    # MaximumAllowedMemory is required to be set to so we can send input data that exceeds the limit on a PS
    # Runspace. We use reflection to access/set this property as it is not accessible publicly. This is not ideal
    # but works on all PowerShell versions I've tested with. We originally used WinRS to send the raw bytes to the
    # host but this falls flat if someone is using a custom PS configuration name so this is a workaround. This
    # isn't required for smaller files so if it fails we ignore the error and hope it wasn't needed.
    # https://github.com/PowerShell/PowerShell/blob/c8e72d1e664b1ee04a14f226adf655cced24e5f0/src/System.Management.Automation/engine/serialization.cs#L325
    try {
        $Host | Get-Property 'ExternalHost' | `
            Get-Field '_transportManager' | `
            Get-Property 'Fragmentor' | `
            Get-Property 'DeserializationContext' | `
            Set-Property 'MaximumAllowedMemory' $null
    } catch {}
}
process {
    $bytes = [System.Convert]::FromBase64String($input)
    $algo.TransformBlock($bytes, 0, $bytes.Length, $bytes, 0) > $null
    $fd.Write($bytes, 0, $bytes.Length)
}
end {
    $fd.Close()

    $algo.TransformFinalBlock($bytes, 0, 0) > $null
    $hash = [System.BitConverter]::ToString($algo.Hash).Replace('-', '').ToLowerInvariant()
    Write-Output -InputObject "{`"sha1`":`"$hash`"}"
}
R         r`   rb   z#file or module does not exist: "%s"c            	   3  l  K   d} t        d      5 t        fdd      D ]n  }t        |      }| |z  } 
j                  |       t        j                  d| |fz  	j                         t        j                  |      }t        |      g p | dk(  rdg d d d        y # 1 sw Y   y xY ww)Nr   rbc                 &    j                         S )N)read)buffer_sizesrc_fds   r;   <lambda>z7Connection.put_file.<locals>.read_gen.<locals>.<lambda>J  s    FKK,D r<   r<   z%PSRP PUT %s to %s (offset=%d, size=%dr?   r    )
rQ   iterlenupdaterF   rM   rJ   rh   	b64encoder   )offsetb_datadata_lenb64_datar   	b_in_pathr   in_pathout_pathr7   	sha1_hashs       @r;   read_genz%Connection.put_file.<locals>.read_genF  s     Fi& &"$DsK 
.F"6{Hh&F$$V, MM"IWV^`fhpLq"q'+ " 8%//7H"8,--
. Q;$J  s   B4BB(	B4(B1-B4	argumentsr   r   z'Remote sha1 was not returned, stdout: 'z', stderr: ''zRemote sha1 hash z does not match local hash )r.   r   put_filer"   _unquoterF   rG   rJ   intr*   rS   max_payload_sizer   r	   ospathexistsr   r
   ro   r   jsonloadsr   	hexdigestget)r7   r   r   copy_scriptr   rv   rw   rx   
put_output
local_sha1remote_sha1r   r   r   r:   s   ```        @@@r;   r   zConnection.put_file  s   j$((;;;''1gx8tO^D 4==33DDrIQNQRRSF	W-BC	ww~~i(%&KiX_N`&`aa	 	& "33KX`Wa3bFF7y011ZZ0
((*
 nnV,"+F"3Yv5F H I I j("+K"8)J:O Q R R )r<   c           	     f   t         t        |   ||       t        j	                  d|d|| j
                         | j                  j                  |      }|j                  dd      }t        | j                  j                  j                  | j                  j                  j                  dz  dz  z
        }||dz  z
  }d	}d
}| j                  |d|g      \  }}}	|dk7  rt        d|dt        |	            |j!                         dk(  ry t#        |d      }
d}t%        |
d      5 }	 t        j'                  d|||fz  | j
                         | j                  |||g      \  }}}	|dk7  rt        d|dt        |	            t)        j*                  |j!                               }|j-                  |       t/        |      |k  rn|t/        |      z  }| j                  d      \  }}}	|dk7  r$t        j1                  d|dt        |	             d d d        y # 1 sw Y   y xY w)NzFETCH r>   r?   \/r{   r|   i   a  param([string]$Path)
$ErrorActionPreference = "Stop"

if (Test-Path -LiteralPath $path -PathType Leaf) {
    $fs = New-Object -TypeName System.IO.FileStream -ArgumentList @(
        $path,
        [System.IO.FileMode]::Open,
        [System.IO.FileAccess]::Read,
        [System.IO.FileShare]::Read
    )
} elseif (Test-Path -Path $path -PathType Container) {
    Write-Output -InputObject "[DIR]"
} else {
    Write-Error -Message "$path does not exist"
    $host.SetShouldExit(1)
}a;  param([int64]$Offset, [int]$BufferSize)
$ErrorActionPreference = "Stop"
$fs.Seek($Offset, [System.IO.SeekOrigin]::Begin) > $null
$buffer = New-Object -TypeName byte[] -ArgumentList $BufferSize
$read = $fs.Read($buffer, 0, $buffer.Length)

if ($read -gt 0) {
    [System.Convert]::ToBase64String($buffer, 0, $read)
}F)use_local_scoper   r   z'failed to setup file stream for fetch 'z': z[DIR]r`   r}   wbzPSRP FETCH %s to %s (offset=%dr   zfailed to transfer file to 'z$fs.Close()z,failed to close remote file stream of file ')r.   r   
fetch_filerF   rG   rJ   r"   r   replacer   r*   rS   r   ro   r   r
   stripr	   rQ   rM   rh   ri   writer   warning)r7   r   r   max_b64_sizer   setup_scriptread_scriptrv   rw   rx   
b_out_pathr   out_filedatar:   s                 r;   r   zConnection.fetch_filej  sR   j$*7H=: 	 	* ++&&w/##D#. 4==33DD MM44EEIAMO P"lT&9:$ "33!i 4 
FF
 7"*If,= ? @ @\\^w&h/DE
*d# 	Kx>&&9:@D  Q%)%;%;%{3 &< &"FF 7&*2If4E(G H H ''7t$t9{*#d)# " "&!7!7!FBQw.5y7H!J K)	K 	K 	Ks   -C1H''H0c                8   | j                   ry| j                   j                  t        j                  k(  rRt        j                  d| j                   j                  z  | j                         | j                   j                          d | _         d| _	        d | _
        y )NzPSRP CLOSE RUNSPACE: %sr?   F)r*   stater   OPENEDrF   rM   idrJ   rW   rR   r,   )r7   s    r;   rW   zConnection.close  sq    ==T]]004E4L4LLMM3t}}7G7GH#  0MM!"r<   c           
     V   | j                  d      | _        | j                  d      | _        | j                  d      }| j                  d      }||d}d}n |t        |      dk7  rdnd}n|	|dk(  rdnd}t        |      | _        | j                  d	      | _        | j                  d
      | _        | j                  d      }| j                  d      }|dk(  rd}n||}nd}t        d*i d| j                  d| j                  d| j                  d| j                  d      d|dk(  d| j                  d      d	| j
                  d|d| j                  d      d| j                  d      d| j                  d      dt        | j                  d            d| j                  d      d| j                  d      d| j                  d      d| j                  d      d t        | j                  d             d!| j                  d!      d"| j                  d"      d#| j                  d#      d$| j                  d$      d%| j                  d%      d&| j                  d&      d'| j                  d'      d(| j                  d(      d)| j                  d)      | _
        y )+Nremote_addrremote_userprotocolporthttpsib  ia  httpauthr@   cert_validationca_certignoreFTserverusernamepasswordremote_passwordsslr   connection_timeout
encryptionmessage_encryptionproxyno_proxyignore_proxymax_envelope_sizeoperation_timeoutread_timeoutreconnection_retriesreconnection_backoffcertificate_key_pemcertificate_pemcredssp_auth_mechanismcredssp_disable_tlsv1_2credssp_minimum_versionnegotiate_send_cbtnegotiate_delegatenegotiate_hostname_overridenegotiate_servicerA   )
get_optionrJ   rH   r   rI   rN   rL   dictr   floatrK   )r7   r   r   r   cert_trust_pathpsrp_cert_validations         r;   rE   zConnection._build_kwargs  s   //-8//-8??:.v&HD"%d)t"3wH\#w.4DDd)//&1(,8L(M% //*;<//)4h&#( (#2 #' !% "
??"
"
 __"
 __%67	"

 G#"
 ("
 "
 1"
  $/CD"
 ';<"
 //'*"
 T__^<="
 #oo.AB"
 #oo.AB"
 8"
  "&1G!H!"
" "'t7M'N!O#"
$ !%0E F%"
& !OO,=>'"
( $(??3K#L)"
* %)OO4M$N+"
, %)OO4M$N-"
.  $/CD/"
0  $/CD1"
2 )-8U(V3"
4 #oo.AB5"
r<   c                   | j                   r@t        j                  | j                   _        | j                   j	                          d | _         t        | j                        }|j                  ||       |r|D ]  }|j                  |        |j                  |       | j                  |      \  }}}	|| _         |||	fS )N)r   )input)r,   r   RUNNINGr   stopr   r*   
add_scriptadd_argumentinvoke_parse_pipeline_result)
r7   rs   
input_datar   r   psargrv   rw   rx   s
             r;   ro   zConnection._exec_psrp_script  s      ):(A(AD%$$&"&D&
fo>  %$% 			
	#!88<FF
 !66!!r<   c           	        | j                   j                  xs |j                  rdnd}g }|j                  D ]  }t	        |t
              r|j                  |j                  }|j                  j                         D ]  \  }}|j                  |d|        |j                  j                         D ]  \  }}|j                  |d|        dj                  |      }nt        |d      }|j                  |        t        | j                   j                  j                         dkD  r#|| j                   j                  j                   z  }dj                  |      }	g }
|j"                  j$                  D ]  }|j&                  rd|j&                  z  nd	}|j(                  rd
|j(                  z  nd	}|t+        |      d|d|j,                  d|j.                  }|j0                  }t2        j4                  dk\  r
||d|z  z  }|
j                  |        t        | j                   j                  j6                        dkD  r#|
| j                   j                  j6                  z  }
dj                  |
D cg c]  }t        |       c}      }t2        j9                  d|z  | j:                         t2        j9                  d|	z  | j:                         t2        j9                  d|z  | j:                         d| j                   _        g | j                   j                  _        g | j                   j                  _        |t=        |	d      t=        |d      fS c c}w )a}  
        PSRP doesn't have the same concept as other protocols with its output.
        We need some extra logic to convert the pipeline streams and host
        output into the format that Ansible understands.

        :param pipeline: The finished PowerShell pipeline that invoked our
            commands
        :return: rc, stdout, stderr based on the pipeline output
           r   z: 

simplerepr)rc   z
z%s : r    z%s
z    + CategoryInfo          : z 
    + FullyQualifiedErrorId : r|   z
StackTrace:
%szPSRP RC: %dr?   zPSRP STDOUT: %szPSRP STDERR: %szutf-8)encoding)r+   rv   
had_errorsoutputrk   r   	to_stringproperty_setsadapted_propertiesitemsappendextended_propertiesrg   r   r   uirw   streamserrorcommand_nameinvocation_position_messagerl   messagefq_errorscript_stacktracerF   	verbosityrx   rM   rJ   r	   )r7   pipelinerv   stdout_listr   	obj_lineskeyvalue
output_msgrw   stderr_listr   r   position	error_msg
stacktraceorx   s                     r;   r   z!Connection._parse_pipeline_result  s    YY\\>8#6#6aA oo 	+F &"67F<L<L<T"00	"(";";"A"A"C ?JC$$#u%=>?"("<"<"B"B"D ?JC$$#u%=>?"ZZ	2
$V|D
z*	+  tyy||""#a'499<<...Kk*%%++ 	*E <A;M;M7U%7%77SULGLGhGhx%"C"CCnpH (UX ==%..	:I
 00J  A%**@4zAA	y)	* tyy||""#a'499<<...K;?awqz?@mb(t?'&0tG'&0tG 		 		 		8FW5xQX7YYY @s   ?M&)r8   t.Anyr9   r  returnNone)r  r   )r  r  )NT)rp   rl   r\   zbytes | Noner]   boolr  tuple[int, bytes, bytes])r   rl   r   rl   r  r  )NTN)
rs   rl   r   zbytes | str | t.Iterable | Noner   r  r   zt.Iterable[t.Any] | Noner  r  )r  r   r  r  )__name__
__module____qualname__rO   !module_implementation_preferencesallow_executablehas_pipelining__annotations__r/   rD   rZ   re   r   r   rW   rE   ro   r   __classcell__)r:   s   @r;   r   r   T  s    I(<%N @ -^ '"RRRhQKf#7
x 7; $.2"" 4" 	"
 ," 
""@CZr<   r   )8
__future__r   DOCUMENTATIONrh   r   r2   r   typingtansibler   r0   ansible.errorsr   r   r   )ansible.module_utils.parsing.convert_boolr   +ansible.module_utils.common.text.convertersr	   r
   r   ansible.plugins.connectionr    ansible.plugins.shell.powershellr   r!   r   ansible.utils.displayr   ansible.utils.hashingr   rB   rC   pypsrp.complex_objectsr   r   r   pypsrp.exceptionsr   r   pypsrp.hostr   r   pypsrp.powershellr   r   pypsrp.wsmanr   requests.exceptionsr   r   ImportErrorerrrF   r   rA   r<   r;   <module>r.     s    #kZ	    	  " A . = T T 5 L 9 ) &
	aaA7:"C
 )NZ NZ  JNs   $0B' 'B:,B55B: