File: helpers.ps1.erb

package info (click to toggle)
ruby-mixlib-install 3.12.16-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 193,056 kB
  • sloc: ruby: 3,843; sh: 664; makefile: 4
file content (195 lines) | stat: -rw-r--r-- 5,751 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
[Console]::OutputEncoding = New-Object -typename System.Text.ASCIIEncoding
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12'

function Get-PlatformVersion {
  switch -regex ((Get-Win32OS).version) {
    '10\.0\.\d+'   {$platform_version = '2016'}
    '10\.0\.17\d+' {$platform_version = '2019'}
    '6\.3\.\d+'    {$platform_version = '2012r2'}
    '6\.2\.\d+'    {$platform_version = '2012'}
    '6\.1\.\d+'    {$platform_version = '2008r2'}
    '6\.0\.\d+'    {$platform_version = '2008'}
  }

  if(Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels') {
    $levels = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels'
    if($levels.NanoServer -eq 1) { $platform_version += 'nano' }
  }

  return $platform_version
}

function Get-PlatformArchitecture {
  if ((Get-Win32OS).osarchitecture -like '64-bit') {
    $architecture = 'x86_64'
  } else {
    $architecture = 'i386'
  }
  return $architecture
}

function Get-Win32OS {
  if(!$global:win32OS)
  {
    $global:win32OS = Get-WMIQuery win32_operatingsystem
  }
  $global:win32OS
}

function New-Uri {
  param ($baseuri, $newuri)

  try {
    $base = new-object System.Uri $baseuri
    new-object System.Uri $base, $newuri
  }
  catch [System.Management.Automation.MethodInvocationException]{
    Write-Error "$($_.exception.message)"
    throw $_.exception
  }
}

function Get-WebContent {
  param ($uri, $filepath)

  try {
    if($PSVersionTable.PSEdition -eq 'Core') {
      Get-WebContentOnCore $uri $filepath
    }
    else {
      Get-WebContentOnFullNet $uri $filepath
    }
  }
  catch {
    $exception = $_.Exception
    Write-Host "There was an error: "
    do {
      Write-Host "`t$($exception.message)"
      $exception = $exception.innerexception
    } while ($exception)
    throw "Failed to download from $uri."
  }
}

function Get-WebContentOnFullNet {
  param ($uri, $filepath)

  $proxy = New-Object -TypeName System.Net.WebProxy
  $wc = new-object System.Net.WebClient
  $wc.Headers.Add("user-agent", "<%= user_agent_string %>")
  $proxy.Address = $env:http_proxy
  $bypassList = $env:no_proxy


  if($bypassList -ne $null){

	 $bypassList = $bypassList.split(",")
	 $proxy.BypassList = $byPassList
  }

  $wc.Proxy = $proxy

  if ([string]::IsNullOrEmpty($filepath)) {
    $wc.downloadstring($uri)
  }
  else {
    $wc.downloadfile($uri, $filepath)
  }
}

function Get-WebContentOnCore {
  param ($uri, $filepath)

  $handler = New-Object System.Net.Http.HttpClientHandler
  $client = New-Object System.Net.Http.HttpClient($handler)
  $client.DefaultRequestHeaders.UserAgent.ParseAdd("<%= user_agent_string %>")
  $client.Timeout = New-Object System.TimeSpan(0, 30, 0)
  $cancelTokenSource = [System.Threading.CancellationTokenSource]::new()
  $responseMsg = $client.GetAsync([System.Uri]::new($uri), $cancelTokenSource.Token)
  $responseMsg.Wait()
  if (!$responseMsg.IsCanceled) {
    $response = $responseMsg.Result
    if ($response.IsSuccessStatusCode) {
      if ([string]::IsNullOrEmpty($filepath)) {
        $response.Content.ReadAsStringAsync().Result
      }
      else {
        $downloadedFileStream = [System.IO.FileStream]::new($filepath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
        $copyStreamOp = $response.Content.CopyToAsync($downloadedFileStream)
        $copyStreamOp.Wait()
        $downloadedFileStream.Close()
        if ($copyStreamOp.Exception -ne $null) {
          throw $copyStreamOp.Exception
        }
      }
    }
  }
}

function Test-ProjectPackage {
  [cmdletbinding()]
  param ($Path, $Algorithm = 'SHA256', $Hash)
  if (!$env:Valid_ProjectPackage){
    Write-Verbose "Testing the $Algorithm hash for $path."
    $ActualHash = (Custom-GetFileHash -Algorithm $Algorithm -Path $Path).Hash.ToLower()

    Write-Verbose "`tDesired Hash - '$Hash'"
    Write-Verbose "`tActual Hash  - '$ActualHash'"
    $env:Valid_ProjectPackage = $ActualHash -eq $Hash
    if (-not $env:Valid_ProjectPackage) {
      Write-Error "Failed to validate the downloaded installer.  The expected $Algorithm hash was '$Hash' and the actual hash was '$ActualHash' for $path"
    }
  }
  return $env:Valid_ProjectPackage
}

function Custom-GetFileHash ($Path, $Algorithm) {
  function disposable($o){($o -is [IDisposable]) -and (($o | get-member | foreach-object {$_.name}) -contains 'Dispose')}
  function use($obj, [scriptblock]$sb){try {& $sb} catch [exception]{throw $_} finally {if (disposable $obj) {$obj.Dispose()}} }
  $Path = (resolve-path $Path).providerpath
  $hash = @{Algorithm = $Algorithm; Path = $Path}
  use ($c = Get-SHA256Converter) {
    use ($in = (gi $Path).OpenRead()) {
      $hash.Hash = ([BitConverter]::ToString($c.ComputeHash($in))).Replace("-", "").ToUpper()
    }
  }
  return $hash
}

function Get-SHA256Converter {
  if ($(Is-FIPS) -ge 1) {
    New-Object -TypeName Security.Cryptography.SHA256Cng
  } else {
    if($PSVersionTable.PSEdition -eq 'Core') {
      [System.Security.Cryptography.SHA256]::Create()
    }
    else {
      New-Object -TypeName Security.Cryptography.SHA256Managed
    }
  }
}

function Is-FIPS {
  if (!$env:fips){
    $env:fips = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy).Enabled
  }
  return $env:fips
}

function Get-WMIQuery {
  param ($class)

  if(Get-Command -Name Get-CimInstance -ErrorAction SilentlyContinue) {
    try{
      $classObject = Get-CimInstance $class
      # If the Get-CimInstance command exists but fails due to security settings, try Get-WmiObject.
    }
    catch {
      $classObject = Get-WmiObject $class
    }
  }
  else {
    $classObject = Get-WmiObject $class
  }
  return $classObject
}