-
Notifications
You must be signed in to change notification settings - Fork 7.2k
/
WebRequestPSCmdlet.Common.cs
1931 lines (1635 loc) · 79.3 KB
/
WebRequestPSCmdlet.Common.cs
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The valid values for the -Authentication parameter for Invoke-RestMethod and Invoke-WebRequest.
/// </summary>
public enum WebAuthenticationType
{
/// <summary>
/// No authentication. Default.
/// </summary>
None,
/// <summary>
/// RFC-7617 Basic Authentication. Requires -Credential.
/// </summary>
Basic,
/// <summary>
/// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token.
/// </summary>
Bearer,
/// <summary>
/// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token.
/// </summary>
OAuth,
}
// WebSslProtocol is used because not all SslProtocols are supported by HttpClientHandler.
// Also SslProtocols.Default is not the "default" for HttpClientHandler as SslProtocols.Ssl3 is not supported.
/// <summary>
/// The valid values for the -SslProtocol parameter for Invoke-RestMethod and Invoke-WebRequest.
/// </summary>
[Flags]
public enum WebSslProtocol
{
/// <summary>
/// No SSL protocol will be set and the system defaults will be used.
/// </summary>
Default = SslProtocols.None,
/// <summary>
/// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2.
/// </summary>
Tls = SslProtocols.Tls12,
/// <summary>
/// Specifies the TLS 1.1 is obsolete. Using this value now defaults to TLS 1.2.
/// </summary>
Tls11 = SslProtocols.Tls12,
/// <summary>
/// Specifies the TLS 1.2 security protocol. The TLS protocol is defined in IETF RFC 5246.
/// </summary>
Tls12 = SslProtocols.Tls12,
/// <summary>
/// Specifies the TLS 1.3 security protocol. The TLS protocol is defined in IETF RFC 8446.
/// </summary>
Tls13 = SslProtocols.Tls13
}
/// <summary>
/// Base class for Invoke-RestMethod and Invoke-WebRequest commands.
/// </summary>
public abstract class WebRequestPSCmdlet : PSCmdlet, IDisposable
{
#region Fields
/// <summary>
/// Cancellation token source.
/// </summary>
internal CancellationTokenSource _cancelToken = null;
/// <summary>
/// Automatically follow Rel Links.
/// </summary>
internal bool _followRelLink = false;
/// <summary>
/// Maximum number of Rel Links to follow.
/// </summary>
internal int _maximumFollowRelLink = int.MaxValue;
/// <summary>
/// Maximum number of Redirects to follow.
/// </summary>
internal int _maximumRedirection;
/// <summary>
/// Parse Rel Links.
/// </summary>
internal bool _parseRelLink = false;
/// <summary>
/// Automatically follow Rel Links.
/// </summary>
internal Dictionary<string, string> _relationLink = null;
/// <summary>
/// The current size of the local file being resumed.
/// </summary>
private long _resumeFileSize = 0;
/// <summary>
/// The remote endpoint returned a 206 status code indicating successful resume.
/// </summary>
private bool _resumeSuccess = false;
/// <summary>
/// True if the Dispose() method has already been called to cleanup Disposable fields.
/// </summary>
private bool _disposed = false;
#endregion Fields
#region Virtual Properties
#region URI
/// <summary>
/// Deprecated. Gets or sets UseBasicParsing. This has no affect on the operation of the Cmdlet.
/// </summary>
[Parameter(DontShow = true)]
public virtual SwitchParameter UseBasicParsing { get; set; } = true;
/// <summary>
/// Gets or sets the Uri property.
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
public virtual Uri Uri { get; set; }
#endregion URI
#region HTTP Version
/// <summary>
/// Gets or sets the HTTP Version property.
/// </summary>
[Parameter]
[ArgumentToVersionTransformation]
[HttpVersionCompletions]
public virtual Version HttpVersion { get; set; }
#endregion HTTP Version
#region Session
/// <summary>
/// Gets or sets the Session property.
/// </summary>
[Parameter]
public virtual WebRequestSession WebSession { get; set; }
/// <summary>
/// Gets or sets the SessionVariable property.
/// </summary>
[Parameter]
[Alias("SV")]
public virtual string SessionVariable { get; set; }
#endregion Session
#region Authorization and Credentials
/// <summary>
/// Gets or sets the AllowUnencryptedAuthentication property.
/// </summary>
[Parameter]
public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; }
/// <summary>
/// Gets or sets the Authentication property used to determine the Authentication method for the web session.
/// Authentication does not work with UseDefaultCredentials.
/// Authentication over unencrypted sessions requires AllowUnencryptedAuthentication.
/// Basic: Requires Credential.
/// OAuth/Bearer: Requires Token.
/// </summary>
[Parameter]
public virtual WebAuthenticationType Authentication { get; set; } = WebAuthenticationType.None;
/// <summary>
/// Gets or sets the Credential property.
/// </summary>
[Parameter]
[Credential]
public virtual PSCredential Credential { get; set; }
/// <summary>
/// Gets or sets the UseDefaultCredentials property.
/// </summary>
[Parameter]
public virtual SwitchParameter UseDefaultCredentials { get; set; }
/// <summary>
/// Gets or sets the CertificateThumbprint property.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual string CertificateThumbprint { get; set; }
/// <summary>
/// Gets or sets the Certificate property.
/// </summary>
[Parameter]
[ValidateNotNull]
public virtual X509Certificate Certificate { get; set; }
/// <summary>
/// Gets or sets the SkipCertificateCheck property.
/// </summary>
[Parameter]
public virtual SwitchParameter SkipCertificateCheck { get; set; }
/// <summary>
/// Gets or sets the TLS/SSL protocol used by the Web Cmdlet.
/// </summary>
[Parameter]
public virtual WebSslProtocol SslProtocol { get; set; } = WebSslProtocol.Default;
/// <summary>
/// Gets or sets the Token property. Token is required by Authentication OAuth and Bearer.
/// </summary>
[Parameter]
public virtual SecureString Token { get; set; }
#endregion Authorization and Credentials
#region Headers
/// <summary>
/// Gets or sets the UserAgent property.
/// </summary>
[Parameter]
public virtual string UserAgent { get; set; }
/// <summary>
/// Gets or sets the DisableKeepAlive property.
/// </summary>
[Parameter]
public virtual SwitchParameter DisableKeepAlive { get; set; }
/// <summary>
/// Gets or sets the ConnectionTimeoutSeconds property.
/// </summary>
/// <remarks>
/// This property applies to sending the request and receiving the response headers only.
/// </remarks>
[Alias("TimeoutSec")]
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int ConnectionTimeoutSeconds { get; set; }
/// <summary>
/// Gets or sets the OperationTimeoutSeconds property.
/// </summary>
/// <remarks>
/// This property applies to each read operation when receiving the response body.
/// </remarks>
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int OperationTimeoutSeconds { get; set; }
/// <summary>
/// Gets or sets the Headers property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[Parameter]
public virtual IDictionary Headers { get; set; }
/// <summary>
/// Gets or sets the SkipHeaderValidation property.
/// </summary>
/// <remarks>
/// This property adds headers to the request's header collection without validation.
/// </remarks>
[Parameter]
public virtual SwitchParameter SkipHeaderValidation { get; set; }
#endregion Headers
#region Redirect
/// <summary>
/// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS.
/// </summary>
[Parameter]
public virtual SwitchParameter AllowInsecureRedirect { get; set; }
/// <summary>
/// Gets or sets the RedirectMax property.
/// </summary>
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int MaximumRedirection { get; set; } = -1;
/// <summary>
/// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request.
/// </summary>
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int MaximumRetryCount { get; set; }
/// <summary>
/// Gets or sets the PreserveAuthorizationOnRedirect property.
/// </summary>
/// <remarks>
/// This property overrides compatibility with web requests on Windows.
/// On FullCLR (WebRequest), authorization headers are stripped during redirect.
/// CoreCLR (HTTPClient) does not have this behavior so web requests that work on
/// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility,
/// we'll detect requests with an Authorization header and automatically strip
/// the header when the first redirect occurs. This switch turns off this logic for
/// edge cases where the authorization header needs to be preserved across redirects.
/// </remarks>
[Parameter]
public virtual SwitchParameter PreserveAuthorizationOnRedirect { get; set; }
/// <summary>
/// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries.
/// </summary>
[Parameter]
[ValidateRange(1, int.MaxValue)]
public virtual int RetryIntervalSec { get; set; } = 5;
#endregion Redirect
#region Method
/// <summary>
/// Gets or sets the Method property.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "StandardMethodNoProxy")]
public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default;
/// <summary>
/// Gets or sets the CustomMethod property.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "CustomMethod")]
[Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
[Alias("CM")]
[ValidateNotNullOrEmpty]
public virtual string CustomMethod { get => _customMethod; set => _customMethod = value.ToUpperInvariant(); }
private string _customMethod;
/// <summary>
/// Gets or sets the PreserveHttpMethodOnRedirect property.
/// </summary>
[Parameter]
public virtual SwitchParameter PreserveHttpMethodOnRedirect { get; set; }
/// <summary>
/// Gets or sets the UnixSocket property.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual UnixDomainSocketEndPoint UnixSocket { get; set; }
#endregion Method
#region NoProxy
/// <summary>
/// Gets or sets the NoProxy property.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
[Parameter(Mandatory = true, ParameterSetName = "StandardMethodNoProxy")]
public virtual SwitchParameter NoProxy { get; set; }
#endregion NoProxy
#region Proxy
/// <summary>
/// Gets or sets the Proxy property.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
public virtual Uri Proxy { get; set; }
/// <summary>
/// Gets or sets the ProxyCredential property.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
[Credential]
public virtual PSCredential ProxyCredential { get; set; }
/// <summary>
/// Gets or sets the ProxyUseDefaultCredentials property.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "CustomMethod")]
public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; }
#endregion Proxy
#region Input
/// <summary>
/// Gets or sets the Body property.
/// </summary>
[Parameter(ValueFromPipeline = true)]
public virtual object Body { get; set; }
/// <summary>
/// Dictionary for use with RFC-7578 multipart/form-data submissions.
/// Keys are form fields and their respective values are form values.
/// A value may be a collection of form values or single form value.
/// </summary>
[Parameter]
public virtual IDictionary Form { get; set; }
/// <summary>
/// Gets or sets the ContentType property.
/// </summary>
[Parameter]
public virtual string ContentType { get; set; }
/// <summary>
/// Gets or sets the TransferEncoding property.
/// </summary>
[Parameter]
[ValidateSet("chunked", "compress", "deflate", "gzip", "identity", IgnoreCase = true)]
public virtual string TransferEncoding { get; set; }
/// <summary>
/// Gets or sets the InFile property.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual string InFile { get; set; }
/// <summary>
/// Keep the original file path after the resolved provider path is assigned to InFile.
/// </summary>
private string _originalFilePath;
#endregion Input
#region Output
/// <summary>
/// Gets or sets the OutFile property.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public virtual string OutFile { get; set; }
/// <summary>
/// Gets or sets the PassThrough property.
/// </summary>
[Parameter]
public virtual SwitchParameter PassThru { get; set; }
/// <summary>
/// Resumes downloading a partial or incomplete file. OutFile is required.
/// </summary>
[Parameter]
public virtual SwitchParameter Resume { get; set; }
/// <summary>
/// Gets or sets whether to skip checking HTTP status for error codes.
/// </summary>
[Parameter]
public virtual SwitchParameter SkipHttpErrorCheck { get; set; }
#endregion Output
#endregion Virtual Properties
#region Helper Properties
internal string QualifiedOutFile => QualifyFilePath(OutFile);
internal string _qualifiedOutFile;
internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck;
/// <summary>
/// Determines whether writing to a file should Resume and append rather than overwrite.
/// </summary>
internal bool ShouldResume => Resume.IsPresent && _resumeSuccess;
internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile);
internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru;
#endregion Helper Properties
#region Abstract Methods
/// <summary>
/// Read the supplied WebResponse object and push the resulting output into the pipeline.
/// </summary>
/// <param name="response">Instance of a WebResponse object to be processed.</param>
internal abstract void ProcessResponse(HttpResponseMessage response);
#endregion Abstract Methods
#region Overrides
/// <summary>
/// The main execution method for cmdlets derived from WebRequestPSCmdlet.
/// </summary>
protected override void ProcessRecord()
{
try
{
// Set cmdlet context for write progress
ValidateParameters();
PrepareSession();
// If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set,
// it needs to be stripped on the first redirect.
bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent
&& WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization);
bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect;
HttpClient client = GetHttpClient(handleRedirect);
int followedRelLink = 0;
Uri uri = Uri;
do
{
if (followedRelLink > 0)
{
string linkVerboseMsg = string.Format(
CultureInfo.CurrentCulture,
WebCmdletStrings.FollowingRelLinkVerboseMsg,
uri.AbsoluteUri);
WriteVerbose(linkVerboseMsg);
}
using (HttpRequestMessage request = GetRequest(uri))
{
FillRequestStream(request);
try
{
long requestContentLength = request.Content is null ? 0 : request.Content.Headers.ContentLength.Value;
string reqVerboseMsg = string.Format(
CultureInfo.CurrentCulture,
WebCmdletStrings.WebMethodInvocationVerboseMsg,
request.Version,
request.Method,
requestContentLength);
WriteVerbose(reqVerboseMsg);
_maximumRedirection = WebSession.MaximumRedirection;
using HttpResponseMessage response = GetResponse(client, request, handleRedirect);
string contentType = ContentHelper.GetContentType(response);
long? contentLength = response.Content.Headers.ContentLength;
string respVerboseMsg = contentLength is null
? string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseNoSizeVerboseMsg, response.Version, contentType)
: string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.WebResponseVerboseMsg, response.Version, contentLength, contentType);
WriteVerbose(respVerboseMsg);
bool _isSuccess = response.IsSuccessStatusCode;
// Check if the Resume range was not satisfiable because the file already completed downloading.
// This happens when the local file is the same size as the remote file.
if (Resume.IsPresent
&& response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable
&& response.Content.Headers.ContentRange.HasLength
&& response.Content.Headers.ContentRange.Length == _resumeFileSize)
{
_isSuccess = true;
WriteVerbose(string.Format(
CultureInfo.CurrentCulture,
WebCmdletStrings.OutFileWritingSkipped,
OutFile));
// Disable writing to the OutFile.
OutFile = null;
}
// Detect insecure redirection.
if (!AllowInsecureRedirect)
{
// We will skip detection if either of the URIs is relative, because the 'Scheme' property is not supported on a relative URI.
// If we have to skip the check, an error may be thrown later if it's actually an insecure https-to-http redirect.
bool originIsHttps = response.RequestMessage.RequestUri.IsAbsoluteUri && response.RequestMessage.RequestUri.Scheme == "https";
bool destinationIsHttp = response.Headers.Location is not null && response.Headers.Location.IsAbsoluteUri && response.Headers.Location.Scheme == "http";
if (originIsHttps && destinationIsHttp)
{
ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request);
er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection);
ThrowTerminatingError(er);
}
}
if (ShouldCheckHttpStatus && !_isSuccess)
{
string message = string.Format(
CultureInfo.CurrentCulture,
WebCmdletStrings.ResponseStatusCodeFailure,
(int)response.StatusCode,
response.ReasonPhrase);
HttpResponseException httpEx = new(message, response);
ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request);
string detailMsg = string.Empty;
try
{
// We can't use ReadAsStringAsync because it doesn't have per read timeouts
TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds);
string characterSet = WebResponseHelper.GetCharacterSet(response);
var responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token);
int initialCapacity = (int)Math.Min(contentLength ?? StreamHelper.DefaultReadBuffer, StreamHelper.DefaultReadBuffer);
var bufferedStream = new WebResponseContentMemoryStream(responseStream, initialCapacity, this, contentLength, perReadTimeout, _cancelToken.Token);
string error = StreamHelper.DecodeStream(bufferedStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token);
detailMsg = FormatErrorMessage(error, contentType);
}
catch (Exception ex)
{
// Catch all
er.ErrorDetails = new ErrorDetails(ex.ToString());
}
if (!string.IsNullOrEmpty(detailMsg))
{
er.ErrorDetails = new ErrorDetails(detailMsg);
}
ThrowTerminatingError(er);
}
if (_parseRelLink || _followRelLink)
{
ParseLinkHeader(response);
}
ProcessResponse(response);
UpdateSession(response);
// If we hit our maximum redirection count, generate an error.
// Errors with redirection counts of greater than 0 are handled automatically by .NET, but are
// impossible to detect programmatically when we hit this limit. By handling this ourselves
// (and still writing out the result), users can debug actual HTTP redirect problems.
if (_maximumRedirection == 0 && IsRedirectCode(response.StatusCode))
{
ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request);
er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded);
WriteError(er);
}
}
catch (TimeoutException ex)
{
ErrorRecord er = new(ex, "OperationTimeoutReached", ErrorCategory.OperationTimeout, null);
ThrowTerminatingError(er);
}
catch (HttpRequestException ex)
{
ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request);
if (ex.InnerException is not null)
{
er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
}
ThrowTerminatingError(er);
}
finally
{
_cancelToken?.Dispose();
_cancelToken = null;
}
if (_followRelLink)
{
if (!_relationLink.ContainsKey("next"))
{
return;
}
uri = new Uri(_relationLink["next"]);
followedRelLink++;
}
}
}
while (_followRelLink && (followedRelLink < _maximumFollowRelLink));
}
catch (CryptographicException ex)
{
ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null);
ThrowTerminatingError(er);
}
catch (NotSupportedException ex)
{
ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null);
ThrowTerminatingError(er);
}
}
/// <summary>
/// To implement ^C.
/// </summary>
protected override void StopProcessing() => _cancelToken?.Cancel();
/// <summary>
/// Disposes the associated WebSession if it is not being used as part of a persistent session.
/// </summary>
/// <param name="disposing">True when called from Dispose() and false when called from finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing && !IsPersistentSession())
{
WebSession?.Dispose();
WebSession = null;
}
_disposed = true;
}
}
/// <summary>
/// Disposes the associated WebSession if it is not being used as part of a persistent session.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion Overrides
#region Virtual Methods
internal virtual void ValidateParameters()
{
// Sessions
if (WebSession is not null && SessionVariable is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException");
ThrowTerminatingError(error);
}
// Authentication
if (UseDefaultCredentials && Authentication != WebAuthenticationType.None)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException");
ThrowTerminatingError(error);
}
if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException");
ThrowTerminatingError(error);
}
if (Authentication == WebAuthenticationType.Basic && Credential is null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException");
ThrowTerminatingError(error);
}
if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException");
ThrowTerminatingError(error);
}
if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https")
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
}
// Credentials
if (UseDefaultCredentials && Credential is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException");
ThrowTerminatingError(error);
}
// Proxy server
if (ProxyUseDefaultCredentials && ProxyCredential is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException");
ThrowTerminatingError(error);
}
else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException");
ThrowTerminatingError(error);
}
// Request body content
if (Body is not null && InFile is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException");
ThrowTerminatingError(error);
}
if (Body is not null && Form is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException");
ThrowTerminatingError(error);
}
if (InFile is not null && Form is not null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException");
ThrowTerminatingError(error);
}
// Validate InFile path
if (InFile is not null)
{
ErrorRecord errorRecord = null;
try
{
Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider);
if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
{
errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile);
}
else
{
if (providerPaths.Count > 1)
{
errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile);
}
else if (providerPaths.Count == 0)
{
errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile);
}
else
{
if (Directory.Exists(providerPaths[0]))
{
errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile);
}
_originalFilePath = InFile;
InFile = providerPaths[0];
}
}
}
catch (ItemNotFoundException pathNotFound)
{
errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound);
}
catch (ProviderNotFoundException providerNotFound)
{
errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound);
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound);
}
if (errorRecord is not null)
{
ThrowTerminatingError(errorRecord);
}
}
// Output ??
if (PassThru.IsPresent && OutFile is null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru));
ThrowTerminatingError(error);
}
// Resume requires OutFile.
if (Resume.IsPresent && OutFile is null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume));
ThrowTerminatingError(error);
}
_qualifiedOutFile = ShouldSaveToOutFile ? QualifiedOutFile : null;
// OutFile must not be a directory to use Resume.
if (Resume.IsPresent && Directory.Exists(_qualifiedOutFile))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ResumeNotFilePath, "WebCmdletResumeNotFilePathException", _qualifiedOutFile);
ThrowTerminatingError(error);
}
}
internal virtual void PrepareSession()
{
// Make sure we have a valid WebRequestSession object to work with
WebSession ??= new WebRequestSession();
if (SessionVariable is not null)
{
// Save the session back to the PS environment if requested
PSVariableIntrinsics vi = SessionState.PSVariable;
vi.Set(SessionVariable, WebSession);
}
// Handle credentials
if (Credential is not null && Authentication == WebAuthenticationType.None)
{
// Get the relevant NetworkCredential
NetworkCredential netCred = Credential.GetNetworkCredential();
WebSession.Credentials = netCred;
// Supplying a credential overrides the UseDefaultCredentials setting
WebSession.UseDefaultCredentials = false;
}
else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None)
{
ProcessAuthentication();
}
else if (UseDefaultCredentials)
{
WebSession.UseDefaultCredentials = true;
}
if (CertificateThumbprint is not null)
{
using X509Store store = new(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
if (tbCollection.Count == 0)
{
throw new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
}
foreach (X509Certificate2 tbCert in tbCollection)
{
X509Certificate certificate = (X509Certificate)tbCert;
WebSession.AddCertificate(certificate);
}
}
if (Certificate is not null)
{
WebSession.AddCertificate(Certificate);
}
// Handle the user agent
if (UserAgent is not null)
{
// Store the UserAgent string
WebSession.UserAgent = UserAgent;
}
// Proxy and NoProxy parameters are mutually exclusive.
// If NoProxy is provided, WebSession will turn off the proxy
// and if Proxy is provided NoProxy will be turned off.
if (NoProxy.IsPresent)
{
WebSession.NoProxy = true;
}
else
{
if (Proxy is not null)
{
WebProxy webProxy = new(Proxy);
webProxy.BypassProxyOnLocal = false;
if (ProxyCredential is not null)
{
webProxy.Credentials = ProxyCredential.GetNetworkCredential();
}
else