forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpListener.psm1
More file actions
377 lines (346 loc) · 16.2 KB
/
HttpListener.psm1
File metadata and controls
377 lines (346 loc) · 16.2 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Function Stop-HTTPListener {
<#
.Synopsis
Stop HTTP Listener used for PowerShell tests rather than rely on 3rd party websites
.Description
Sends `exit` command to HTTP Listener causing it to exit.
.Parameter Port
Port to use, default is 8080
.Example
Stop-HTTPListener -Port 8080
#>
Param (
[Parameter()]
[Int] $Port = 8080
)
Invoke-WebRequest -Uri "http://localhost:$port/PowerShell?test=exit"
}
Function Start-HTTPListener {
<#
.Synopsis
Creates a new HTTP Listener to be used for PowerShell tests rather than rely on 3rd party websites
.Description
Creates a new HTTP Listener supporting several test cases intended to be used only by PowerShell tests.
Use Ctrl-C to stop the listener. You'll need to send another web request to allow the listener to stop since
it will be blocked waiting for a request.
.Parameter Port
Port to listen, default is 8080
.Example
Start-HTTPListener -Port 8080
Invoke-WebRequest -Uri "http://localhost:8080/PowerShell/?test=linkheader&maxlinks=5"
#>
Param (
[Parameter()]
[Int] $Port = 8080,
[Parameter()]
[switch] $Foreground
)
Process {
$ErrorActionPreference = "Stop"
[scriptblock]$script = {
param ($Port)
$script:supportedRedirects = @{
[System.Net.HttpStatusCode]::Ok = 1; # No redirect
[System.Net.HttpStatusCode]::Found = 1;
[System.Net.HttpStatusCode]::MultipleChoices = 1;
[System.Net.HttpStatusCode]::Moved = 1;
[System.Net.HttpStatusCode]::SeeOther = 1;
[System.Net.HttpStatusCode]::TemporaryRedirect = 1;
}
# HttpListener.QueryString is not being populated, need to follow-up with CoreFx, workaround is to parse it ourselves
Function ParseQueryString([string]$url)
{
Write-Verbose "Parsing: $url"
$uri = [uri]$url
$queryItems = @{}
if ($null -ne $uri.Query)
{
foreach ($segment in $uri.Query.Split("&"))
{
if ($segment -match "\??(?<name>\w*)(=(?<value>.*?))?$")
{
$name = $Matches["name"]
$value = $Matches["value"]
if ($null -ne $value)
{
$value = [System.Web.HttpUtility]::UrlDecode($value)
}
$queryItems.Add($name, $value)
Write-Verbose "Found: $name = $value"
}
}
}
return $queryItems
}
$listener = [System.Net.HttpListener]::New()
$urlPrefix = "/PowerShell"
$url = "http://localhost:$Port$urlPrefix"
$listener.Prefixes.Add($url + "/") # trailing slash required for registration
$listener.AuthenticationSchemes = [System.Net.AuthenticationSchemes]::Anonymous
try {
Write-Warning "Note that thread is blocked waiting for a request. After using Ctrl-C to stop listening, you need to send a valid HTTP request to stop the listener cleanly."
Write-Warning "Use Stop-HttpListener or Invoke-WebRequest -Uri '${Url}?test=exit' to stop the listener."
Write-Verbose "Listening on $Url..."
$listener.Start()
$exit = $false
while ($exit -eq $false) {
$context = $listener.GetContext()
$request = $context.Request
$queryItems = ParseQueryString($request.Url)
$test = $queryItems["test"]
Write-Verbose "Testing: $test"
foreach ($key in $request.Headers.Keys)
{
Write-Verbose -Message "Found Header: $key, $($request.Headers[$key])"
}
# the status code to return for the response
$statusCode = [System.Net.HttpStatusCode]::OK
# this is the body of the response, return json/xml as appropriate
$output = ""
# this is hashtable of headers in the response
$outputHeader = @{}
# this is the contenttype, example 'application/json'
$contentType = $null
switch ($test)
{
$null
{
$statusCode = [System.Net.HttpStatusCode]::BadRequest
$output = "Test not specified"
}
"exit"
{
Write-Verbose "Received command to exit listener"
$output = "Exit command received"
$exit = $true
}
"response"
{
$statusCode = $queryItems["statuscode"]
$contentType = $queryItems["contenttype"]
$output = $queryItems["output"]
# Pass a JSON collection to the 'headers' field
# /PowerShell?test=response&headers={"Pragma":"no-cache","X-Fake-Header":["testvalue01","testvalue02"]}
# In PowerShell:
# $headers = @{Pragma='no-cache';'X-Fake-Header'='testvalue01','testvalue02'} | ConvertTo-Json -Compress
# $uri = "http://localhost:8080/PowerShell?test=response&headers=$headers"
if ($queryItems['headers'])
{
$headerCollection = $queryItems['headers'] | ConvertFrom-Json
foreach ($header in $headerCollection.psobject.Properties.name)
{
$outputHeader.add($header,$headerCollection.$header)
}
}
}
# Echo the request as the output.
"echo"
{
Write-Verbose -Message "Echo request"
$output = $request | ConvertTo-Json -Depth 6
}
<#
This test provides support for multiple redirection types as well as a custom
multi-hop redirection to handle Authorization stripping logic.
The following redirection types are supported:
MultipleChoices (300), Moved (301), Found (302), SeeOther (303), TemporaryRedirect (307)
The original URL should indicate the type of redirection.
For example: The following indicates that a 302 redirection (found) should be used.
?test=redirectex&type=Found
WebRequest cmdlet tests also use a special option called multiredirect. This produces two redirects
where the second
Example: test=redirectex&type=Moved&multiredirect=true
See also https://docs.microsoft.com/dotnet/api/system.net.httpstatuscode
#>
"redirect"
{
$redirectedUrl = [string]::Empty
$redirectType = $queryItems["type"]
$multiredirect = $queryItems["multiredirect"]
if ($null -eq $redirectType)
{
# End of redirection
$redirectType = 'Ok'
}
[System.Net.HttpStatusCode] $type = [System.Net.HttpStatusCode]::Found
[bool] $isValid = [System.Enum]::TryParse($redirectType, $true, [ref] $type)
if ($isValid -eq $false -or $script:supportedRedirects.ContainsKey($type) -eq $false)
{
Write-Verbose -Message "Invalid request type: $type"
$statusCode = [System.Net.HttpStatusCode]::BadRequest
$output = "Invalid Redirect Type: $type"
}
elseif ($type -eq [System.Net.HttpStatusCode]::Ok)
{
# no redirection
Write-Verbose -Message "No redirection"
$output = $request | ConvertTo-Json -Depth 6
}
elseif ($null -eq $multiredirect)
{
Write-Verbose -Message "Standard redirection"
$redirectedUrl = "${Url}?test=redirect&type=Ok"
}
elseif ($multiredirect -eq $true)
{
Write-Verbose -Message "Redirect 1 of 2"
$redirectedUrl = "${Url}?test=redirect&type=$type&multiredirect=false"
}
elseif ($multiredirect -eq $false)
{
Write-Verbose -Message "Redirect 2 of 2"
$redirectedUrl = "${Url}?test=redirect&type=$type"
}
if ($isValid)
{
$statusCode = $type
if (-not [string]::IsNullOrEmpty($redirectedUrl))
{
$outputHeader.Add("Location",$redirectedUrl)
Write-Verbose -Message "Redirecting to $($outputHeader.Location)"
}
}
}
"linkheader"
{
$maxLinks = $queryItems["maxlinks"]
if ($null -eq $maxlinks)
{
$maxLinks = 3
}
$linkNumber = [int]$queryItems["linknumber"]
$prev = ""
if ($linkNumber -eq 0)
{
$linkNumber = 1
}
else
{
# use $urlPrefix to ensure output is resolved to absolute uri
$prev = ", <$($urlPrefix)?test=linkheader&maxlinks=$maxlinks&linknumber=$($linkNumber-1); rel=`"prev`""
}
$links = ""
if ($linkNumber -lt $maxLinks)
{
switch ($queryItems["type"])
{
"noUrl"
{
$links = "<>; rel=`"next`","
}
"malformed"
{
$links = "{url}; foo,"
}
"noRel"
{
$links = "<url>; foo=`"bar`","
}
default
{
$links = "<$($urlPrefix)?test=linkheader&maxlinks=$maxlinks&linknumber=$($linkNumber+1)>; rel=`"next`", "
}
}
}
$links = "$links<$($urlPrefix)?test=linkheader&maxlinks=$maxlinks&linknumber=$maxlinks>; rel=`"last`"$prev"
$outputHeader.Add("Link", $links)
$output = "{ `"output`": `"$linkNumber`"}"
}
default
{
$statusCode = [System.Net.HttpStatusCode]::NotFound
$output = "Unknown Test: $Test"
}
}
$response = $context.Response
if ($outputHeader.ContainsKey('Content-Type') -eq $false)
{
if ([string]::IsNullOrEmpty($contentType))
{
$contentType = 'application/json'
}
$outputHeader.Add('Content-Type', $contentType)
$response.ContentType = $contentType
Write-Verbose -Message "Setting ContentType to $contentType"
}
if ($null -ne $statusCode)
{
$response.StatusCode = $statusCode
}
$response.Headers.Clear()
foreach ($header in $outputHeader.Keys)
{
foreach ($headerValue in $outputHeader.$header)
{
$response.Headers.Add($header, $headerValue)
}
}
if ($null -ne $output)
{
$buffer = [System.Text.Encoding]::UTF8.GetBytes($output)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
$output.Write($buffer,0,$buffer.Length)
$output.Close()
}
$response.Close()
}
}
catch
{
$errormsg = $_ | ConvertTo-Json
Write-Error $errormsg
}
finally
{
$listener.Stop()
Write-Information "Listener is stopped" -InformationAction Continue
}
}
if ($Foreground)
{
& $script -Port $Port
}
else
{
$ps = [powershell]::Create()
$null = $ps.AddScript($script)
$null = $ps.AddParameter("port",$port)
$AsyncResponse = $ps.BeginInvoke()
# check that it's up and running
$out = $null
$startTime = Get-Date
$succeeded = $false
while (!$succeeded -and (((Get-Date) - $startTime)).Seconds -lt 10)
{
try
{
$out = Invoke-WebRequest "http://localhost:${Port}/PowerShell?test=response"
if ($out.StatusCode -eq 200)
{
$succeeded = $true
}
}
catch
{
# ignore if listener is not ready
}
Start-Sleep -Milliseconds 100
}
if (!$succeeded)
{
throw "HttpListener failed to respond"
}
# include the AsyncResponse in the return object
# it can be used to determine whether execution
# is still underway, and may be useful in debugging
# if something goes amiss
[pscustomobject]@{
PowerShell = $ps
AsyncResponse = $AsyncResponse
}
}
}
}