| 1 |
#!powershell |
| 2 |
|
| 3 |
# Copyright: (c) 2015, Paul Durivage <[email protected]> |
| 4 |
# Copyright: (c) 2015, Tal Auslander <[email protected]> |
| 5 |
# Copyright: (c) 2017, Dag Wieers <[email protected]> |
| 6 |
# Copyright: (c) 2019, Viktor Utkin <[email protected]> |
| 7 |
# Copyright: (c) 2019, Uladzimir Klybik <[email protected]> |
| 8 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 9 |
|
| 10 |
#AnsibleRequires -CSharpUtil Ansible.Basic |
| 11 |
#Requires -Module Ansible.ModuleUtils.FileUtil |
| 12 |
#Requires -Module Ansible.ModuleUtils.WebRequest |
| 13 |
|
| 14 |
$spec = @{ |
| 15 |
options = @{ |
| 16 |
url = @{ type="str"; required=$true } |
| 17 |
dest = @{ type='path'; required=$true } |
| 18 |
force = @{ type='bool'; default=$true } |
| 19 |
checksum = @{ type='str' } |
| 20 |
checksum_algorithm = @{ type='str'; default='sha1'; choices = @("md5", "sha1", "sha256", "sha384", "sha512") } |
| 21 |
checksum_url = @{ type='str' } |
| 22 |
|
| 23 |
# Defined for the alias backwards compatibility, remove once aliases are removed |
| 24 |
url_username = @{ |
| 25 |
aliases = @("user", "username") |
| 26 |
deprecated_aliases = @( |
| 27 |
@{ name = "user"; version = "2.14" }, |
| 28 |
@{ name = "username"; version = "2.14" } |
| 29 |
) |
| 30 |
} |
| 31 |
url_password = @{ |
| 32 |
aliases = @("password") |
| 33 |
deprecated_aliases = @( |
| 34 |
@{ name = "password"; version = "2.14" } |
| 35 |
) |
| 36 |
} |
| 37 |
} |
| 38 |
mutually_exclusive = @( |
| 39 |
,@('checksum', 'checksum_url') |
| 40 |
) |
| 41 |
supports_check_mode = $true |
| 42 |
} |
| 43 |
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-AnsibleWebRequestSpec)) |
| 44 |
|
| 45 |
$url = $module.Params.url |
| 46 |
$dest = $module.Params.dest |
| 47 |
$force = $module.Params.force |
| 48 |
$checksum = $module.Params.checksum |
| 49 |
$checksum_algorithm = $module.Params.checksum_algorithm |
| 50 |
$checksum_url = $module.Params.checksum_url |
| 51 |
|
| 52 |
$module.Result.elapsed = 0 |
| 53 |
$module.Result.url = $url |
| 54 |
|
| 55 |
Function Get-ChecksumFromUri { |
| 56 |
param( |
| 57 |
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module, |
| 58 |
[Parameter(Mandatory=$true)][Uri]$Uri, |
| 59 |
[Uri]$SourceUri |
| 60 |
) |
| 61 |
|
| 62 |
$script = { |
| 63 |
param($Response, $Stream) |
| 64 |
|
| 65 |
$read_stream = New-Object -TypeName System.IO.StreamReader -ArgumentList $Stream |
| 66 |
$web_checksum = $read_stream.ReadToEnd() |
| 67 |
$basename = (Split-Path -Path $SourceUri.LocalPath -Leaf) |
| 68 |
$basename = [regex]::Escape($basename) |
| 69 |
$web_checksum_str = $web_checksum -split '\r?\n' | Select-String -Pattern $("\s+\.?\/?\\?" + $basename + "\s*$") |
| 70 |
if (-not $web_checksum_str) { |
| 71 |
$Module.FailJson("Checksum record not found for file name '$basename' in file from url: '$Uri'") |
| 72 |
} |
| 73 |
|
| 74 |
$web_checksum_str_splitted = $web_checksum_str[0].ToString().split(" ", 2) |
| 75 |
$hash_from_file = $web_checksum_str_splitted[0].Trim() |
| 76 |
# Remove any non-alphanumeric characters |
| 77 |
$hash_from_file = $hash_from_file -replace '\W+', '' |
| 78 |
|
| 79 |
Write-Output -InputObject $hash_from_file |
| 80 |
} |
| 81 |
$web_request = Get-AnsibleWebRequest -Uri $Uri -Module $Module |
| 82 |
|
| 83 |
try { |
| 84 |
Invoke-WithWebRequest -Module $Module -Request $web_request -Script $script |
| 85 |
} catch { |
| 86 |
$Module.FailJson("Error when getting the remote checksum from '$Uri'. $($_.Exception.Message)", $_) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
Function Compare-ModifiedFile { |
| 91 |
<# |
| 92 |
.SYNOPSIS |
| 93 |
Compares the remote URI resource against the local Dest resource. Will |
| 94 |
return true if the LastWriteTime/LastModificationDate of the remote is |
| 95 |
newer than the local resource date. |
| 96 |
#> |
| 97 |
param( |
| 98 |
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module, |
| 99 |
[Parameter(Mandatory=$true)][Uri]$Uri, |
| 100 |
[Parameter(Mandatory=$true)][String]$Dest |
| 101 |
) |
| 102 |
|
| 103 |
$dest_last_mod = (Get-AnsibleItem -Path $Dest).LastWriteTimeUtc |
| 104 |
|
| 105 |
# If the URI is a file we don't need to go through the whole WebRequest |
| 106 |
if ($Uri.IsFile) { |
| 107 |
$src_last_mod = (Get-AnsibleItem -Path $Uri.AbsolutePath).LastWriteTimeUtc |
| 108 |
} else { |
| 109 |
$web_request = Get-AnsibleWebRequest -Uri $Uri -Module $Module |
| 110 |
$web_request.Method = switch ($web_request.GetType().Name) { |
| 111 |
FtpWebRequest { [System.Net.WebRequestMethods+Ftp]::GetDateTimestamp } |
| 112 |
HttpWebRequest { [System.Net.WebRequestMethods+Http]::Head } |
| 113 |
} |
| 114 |
$script = { param($Response, $Stream); $Response.LastModified } |
| 115 |
|
| 116 |
try { |
| 117 |
$src_last_mod = Invoke-WithWebRequest -Module $Module -Request $web_request -Script $script |
| 118 |
} catch { |
| 119 |
$Module.FailJson("Error when requesting 'Last-Modified' date from '$Uri'. $($_.Exception.Message)", $_) |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
# Return $true if the Uri LastModification date is newer than the Dest LastModification date |
| 124 |
((Get-Date -Date $src_last_mod).ToUniversalTime() -gt $dest_last_mod) |
| 125 |
} |
| 126 |
|
| 127 |
Function Get-Checksum { |
| 128 |
param( |
| 129 |
[Parameter(Mandatory=$true)][String]$Path, |
| 130 |
[String]$Algorithm = "sha1" |
| 131 |
) |
| 132 |
|
| 133 |
switch ($Algorithm) { |
| 134 |
'md5' { $sp = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider } |
| 135 |
'sha1' { $sp = New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider } |
| 136 |
'sha256' { $sp = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider } |
| 137 |
'sha384' { $sp = New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider } |
| 138 |
'sha512' { $sp = New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider } |
| 139 |
} |
| 140 |
|
| 141 |
$fs = [System.IO.File]::Open($Path, [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read, |
| 142 |
[System.IO.FileShare]::ReadWrite) |
| 143 |
try { |
| 144 |
$hash = [System.BitConverter]::ToString($sp.ComputeHash($fs)).Replace("-", "").ToLower() |
| 145 |
} finally { |
| 146 |
$fs.Dispose() |
| 147 |
} |
| 148 |
return $hash |
| 149 |
} |
| 150 |
|
| 151 |
Function Invoke-DownloadFile { |
| 152 |
param( |
| 153 |
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module, |
| 154 |
[Parameter(Mandatory=$true)][Uri]$Uri, |
| 155 |
[Parameter(Mandatory=$true)][String]$Dest, |
| 156 |
[String]$Checksum, |
| 157 |
[String]$ChecksumAlgorithm |
| 158 |
) |
| 159 |
|
| 160 |
# Check $dest parent folder exists before attempting download, which avoids unhelpful generic error message. |
| 161 |
$dest_parent = Split-Path -LiteralPath $Dest |
| 162 |
if (-not (Test-Path -LiteralPath $dest_parent -PathType Container)) { |
| 163 |
$module.FailJson("The path '$dest_parent' does not exist for destination '$Dest', or is not visible to the current user. Ensure download destination folder exists (perhaps using win_file state=directory) before win_get_url runs.") |
| 164 |
} |
| 165 |
|
| 166 |
$download_script = { |
| 167 |
param($Response, $Stream) |
| 168 |
|
| 169 |
# Download the file to a temporary directory so we can compare it |
| 170 |
$tmp_dest = Join-Path -Path $Module.Tmpdir -ChildPath ([System.IO.Path]::GetRandomFileName()) |
| 171 |
$fs = [System.IO.File]::Create($tmp_dest) |
| 172 |
try { |
| 173 |
$Stream.CopyTo($fs) |
| 174 |
$fs.Flush() |
| 175 |
} finally { |
| 176 |
$fs.Dispose() |
| 177 |
} |
| 178 |
$tmp_checksum = Get-Checksum -Path $tmp_dest -Algorithm $ChecksumAlgorithm |
| 179 |
$Module.Result.checksum_src = $tmp_checksum |
| 180 |
|
| 181 |
# If the checksum has been set, verify the checksum of the remote against the input checksum. |
| 182 |
if ($Checksum -and $Checksum -ne $tmp_checksum) { |
| 183 |
$Module.FailJson(("The checksum for {0} did not match '{1}', it was '{2}'" -f $Uri, $Checksum, $tmp_checksum)) |
| 184 |
} |
| 185 |
|
| 186 |
$download = $true |
| 187 |
if (Test-Path -LiteralPath $Dest) { |
| 188 |
# Validate the remote checksum against the existing downloaded file |
| 189 |
$dest_checksum = Get-Checksum -Path $Dest -Algorithm $ChecksumAlgorithm |
| 190 |
|
| 191 |
# If we don't need to download anything, save the dest checksum so we don't waste time calculating it |
| 192 |
# again at the end of the script |
| 193 |
if ($dest_checksum -eq $tmp_checksum) { |
| 194 |
$download = $false |
| 195 |
$Module.Result.checksum_dest = $dest_checksum |
| 196 |
$Module.Result.size = (Get-AnsibleItem -Path $Dest).Length |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
if ($download) { |
| 201 |
Copy-Item -LiteralPath $tmp_dest -Destination $Dest -Force -WhatIf:$Module.CheckMode > $null |
| 202 |
$Module.Result.changed = $true |
| 203 |
} |
| 204 |
} |
| 205 |
$web_request = Get-AnsibleWebRequest -Uri $Uri -Module $Module |
| 206 |
|
| 207 |
try { |
| 208 |
Invoke-WithWebRequest -Module $Module -Request $web_request -Script $download_script |
| 209 |
} catch { |
| 210 |
$Module.FailJson("Error downloading '$Uri' to '$Dest': $($_.Exception.Message)", $_) |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
# Use last part of url for dest file name if a directory is supplied for $dest |
| 215 |
if (Test-Path -LiteralPath $dest -PathType Container) { |
| 216 |
$uri = [System.Uri]$url |
| 217 |
$basename = Split-Path -Path $uri.LocalPath -Leaf |
| 218 |
if ($uri.LocalPath -and $uri.LocalPath -ne '/' -and $basename) { |
| 219 |
$url_basename = Split-Path -Path $uri.LocalPath -Leaf |
| 220 |
$dest = Join-Path -Path $dest -ChildPath $url_basename |
| 221 |
} else { |
| 222 |
$dest = Join-Path -Path $dest -ChildPath $uri.Host |
| 223 |
} |
| 224 |
|
| 225 |
# Ensure we have a string instead of a PS object to avoid serialization issues |
| 226 |
$dest = $dest.ToString() |
| 227 |
} elseif (([System.IO.Path]::GetFileName($dest)) -eq '') { |
| 228 |
# We have a trailing path separator |
| 229 |
$module.FailJson("The destination path '$dest' does not exist, or is not visible to the current user. Ensure download destination folder exists (perhaps using win_file state=directory) before win_get_url runs.") |
| 230 |
} |
| 231 |
|
| 232 |
$module.Result.dest = $dest |
| 233 |
|
| 234 |
if ($checksum) { |
| 235 |
$checksum = $checksum.Trim().ToLower() |
| 236 |
} |
| 237 |
if ($checksum_algorithm) { |
| 238 |
$checksum_algorithm = $checksum_algorithm.Trim().ToLower() |
| 239 |
} |
| 240 |
if ($checksum_url) { |
| 241 |
$checksum_url = $checksum_url.Trim() |
| 242 |
} |
| 243 |
|
| 244 |
# Check for case $checksum variable contain url. If yes, get file data from url and replace original value in $checksum |
| 245 |
if ($checksum_url) { |
| 246 |
$checksum_uri = [System.Uri]$checksum_url |
| 247 |
if ($checksum_uri.Scheme -notin @("file", "ftp", "http", "https")) { |
| 248 |
$module.FailJson("Unsupported 'checksum_url' value for '$dest': '$checksum_url'") |
| 249 |
} |
| 250 |
|
| 251 |
$checksum = Get-ChecksumFromUri -Module $Module -Uri $checksum_uri -SourceUri $url |
| 252 |
} |
| 253 |
|
| 254 |
if ($force -or -not (Test-Path -LiteralPath $dest)) { |
| 255 |
# force=yes or dest does not exist, download the file |
| 256 |
# Note: Invoke-DownloadFile will compare the checksums internally if dest exists |
| 257 |
Invoke-DownloadFile -Module $module -Uri $url -Dest $dest -Checksum $checksum ` |
| 258 |
-ChecksumAlgorithm $checksum_algorithm |
| 259 |
} else { |
| 260 |
# force=no, we want to check the last modified dates and only download if they don't match |
| 261 |
$is_modified = Compare-ModifiedFile -Module $module -Uri $url -Dest $dest |
| 262 |
if ($is_modified) { |
| 263 |
Invoke-DownloadFile -Module $module -Uri $url -Dest $dest -Checksum $checksum ` |
| 264 |
-ChecksumAlgorithm $checksum_algorithm |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
if ((-not $module.Result.ContainsKey("checksum_dest")) -and (Test-Path -LiteralPath $dest)) { |
| 269 |
# Calculate the dest file checksum if it hasn't already been done |
| 270 |
$module.Result.checksum_dest = Get-Checksum -Path $dest -Algorithm $checksum_algorithm |
| 271 |
$module.Result.size = (Get-AnsibleItem -Path $dest).Length |
| 272 |
} |
| 273 |
|
| 274 |
$module.ExitJson() |