-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Expand file tree
/
Copy pathWebRequestPSCmdlet.Common.cs
More file actions
1985 lines (1706 loc) · 79 KB
/
WebRequestPSCmdlet.Common.cs
File metadata and controls
1985 lines (1706 loc) · 79 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
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.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
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 = 0,
/// <summary>
/// Specifies the TLS 1.0 security protocol. The TLS protocol is defined in IETF RFC 2246.
/// </summary>
Tls = SslProtocols.Tls,
/// <summary>
/// Specifies the TLS 1.1 security protocol. The TLS protocol is defined in IETF RFC 4346.
/// </summary>
Tls11 = SslProtocols.Tls11,
/// <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 partial class WebRequestPSCmdlet : PSCmdlet
{
#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
#region HTTP Version
/// <summary>
/// Gets or sets the HTTP Version property.
/// </summary>
[Parameter]
[ArgumentToVersionTransformation]
[HttpVersionCompletions]
public virtual Version HttpVersion { get; set; }
#endregion
#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
#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
#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 TimeOut property.
/// </summary>
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int TimeoutSec { 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; }
#endregion
#region Redirect
/// <summary>
/// Gets or sets the RedirectMax property.
/// </summary>
[Parameter]
[ValidateRange(0, int.MaxValue)]
public virtual int MaximumRedirection
{
get { return _maximumRedirection; }
set { _maximumRedirection = value; }
}
private int _maximumRedirection = -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 RetryIntervalSec property, which determines the number seconds between retries.
/// </summary>
[Parameter]
[ValidateRange(1, int.MaxValue)]
public virtual int RetryIntervalSec { get; set; } = 5;
#endregion
#region Method
/// <summary>
/// Gets or sets the Method property.
/// </summary>
[Parameter(ParameterSetName = "StandardMethod")]
[Parameter(ParameterSetName = "StandardMethodNoProxy")]
public virtual WebRequestMethod Method
{
get { return _method; }
set { _method = value; }
}
private WebRequestMethod _method = 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 { return _customMethod; }
set { _customMethod = value; }
}
private string _customMethod;
#endregion
#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
#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
#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]
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
#region Output
/// <summary>
/// Gets or sets the OutFile property.
/// </summary>
[Parameter]
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
#endregion Virtual Properties
#region Virtual Methods
internal virtual void ValidateParameters()
{
// sessions
if ((WebSession != null) && (SessionVariable != 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 != null) && (Credential != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict,
"WebCmdletAuthenticationTokenConflictException");
ThrowTerminatingError(error);
}
if ((Authentication == WebAuthenticationType.Basic) && (Credential == null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied,
"WebCmdletAuthenticationCredentialNotSuppliedException");
ThrowTerminatingError(error);
}
if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied,
"WebCmdletAuthenticationTokenNotSuppliedException");
ThrowTerminatingError(error);
}
if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https"))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired,
"WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
}
if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https"))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired,
"WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
}
// credentials
if (UseDefaultCredentials && (Credential != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict,
"WebCmdletCredentialConflictException");
ThrowTerminatingError(error);
}
// Proxy server
if (ProxyUseDefaultCredentials && (ProxyCredential != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict,
"WebCmdletProxyCredentialConflictException");
ThrowTerminatingError(error);
}
else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied,
"WebCmdletProxyUriNotSuppliedException");
ThrowTerminatingError(error);
}
// request body content
if ((Body != null) && (InFile != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict,
"WebCmdletBodyConflictException");
ThrowTerminatingError(error);
}
if ((Body != null) && (Form != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict,
"WebCmdletBodyFormConflictException");
ThrowTerminatingError(error);
}
if ((InFile != null) && (Form != null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict,
"WebCmdletFormInFileConflictException");
ThrowTerminatingError(error);
}
// validate InFile path
if (InFile != null)
{
ProviderInfo provider = null;
ErrorRecord errorRecord = null;
try
{
Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out 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 != null)
{
ThrowTerminatingError(errorRecord);
}
}
// output ??
if (PassThru && (OutFile == null))
{
ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing,
"WebCmdletOutFileMissingException", nameof(PassThru));
ThrowTerminatingError(error);
}
// Resume requires OutFile.
if (Resume.IsPresent && OutFile == null)
{
ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing,
"WebCmdletOutFileMissingException", nameof(Resume));
ThrowTerminatingError(error);
}
}
internal virtual void PrepareSession()
{
// make sure we have a valid WebRequestSession object to work with
if (WebSession == null)
{
WebSession = new WebRequestSession();
}
if (SessionVariable != null)
{
// save the session back to the PS environment if requested
PSVariableIntrinsics vi = SessionState.PSVariable;
vi.Set(SessionVariable, WebSession);
}
//
// handle credentials
//
if (Credential != 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 != null || Token != null) && Authentication != WebAuthenticationType.None)
{
ProcessAuthentication();
}
else if (UseDefaultCredentials)
{
WebSession.UseDefaultCredentials = true;
}
if (CertificateThumbprint != null)
{
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)
{
CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound);
throw ex;
}
foreach (X509Certificate2 tbCert in tbCollection)
{
X509Certificate certificate = (X509Certificate)tbCert;
WebSession.AddCertificate(certificate);
}
}
if (Certificate != null)
{
WebSession.AddCertificate(Certificate);
}
//
// handle the user agent
//
if (UserAgent != null)
{
// store the UserAgent string
WebSession.UserAgent = UserAgent;
}
if (Proxy != null)
{
WebProxy webProxy = new(Proxy);
webProxy.BypassProxyOnLocal = false;
if (ProxyCredential != null)
{
webProxy.Credentials = ProxyCredential.GetNetworkCredential();
}
else if (ProxyUseDefaultCredentials)
{
// If both ProxyCredential and ProxyUseDefaultCredentials are passed,
// UseDefaultCredentials will overwrite the supplied credentials.
webProxy.UseDefaultCredentials = true;
}
WebSession.Proxy = webProxy;
}
if (MaximumRedirection > -1)
{
WebSession.MaximumRedirection = MaximumRedirection;
}
// store the other supplied headers
if (Headers != null)
{
foreach (string key in Headers.Keys)
{
var value = Headers[key];
// null is not valid value for header.
// We silently ignore header if value is null.
if (value is not null)
{
// add the header value (or overwrite it if already present)
WebSession.Headers[key] = value.ToString();
}
}
}
if (MaximumRetryCount > 0)
{
WebSession.MaximumRetryCount = MaximumRetryCount;
// only set retry interval if retry count is set.
WebSession.RetryIntervalInSeconds = RetryIntervalSec;
}
}
#endregion Virtual Methods
#region Helper Properties
internal string QualifiedOutFile
{
get { return (QualifyFilePath(OutFile)); }
}
internal bool ShouldSaveToOutFile
{
get { return (!string.IsNullOrEmpty(OutFile)); }
}
internal bool ShouldWriteToPipeline
{
get { return (!ShouldSaveToOutFile || PassThru); }
}
internal bool ShouldCheckHttpStatus
{
get { return !SkipHttpErrorCheck; }
}
/// <summary>
/// Determines whether writing to a file should Resume and append rather than overwrite.
/// </summary>
internal bool ShouldResume
{
get { return (Resume.IsPresent && _resumeSuccess); }
}
#endregion Helper Properties
#region Helper Methods
private Uri PrepareUri(Uri uri)
{
uri = CheckProtocol(uri);
// before creating the web request,
// preprocess Body if content is a dictionary and method is GET (set as query)
IDictionary bodyAsDictionary;
LanguagePrimitives.TryConvertTo<IDictionary>(Body, out bodyAsDictionary);
if ((bodyAsDictionary != null)
&& ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get))
|| (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET")))
{
UriBuilder uriBuilder = new(uri);
if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
{
uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary));
}
else
{
uriBuilder.Query = FormatDictionary(bodyAsDictionary);
}
uri = uriBuilder.Uri;
// set body to null to prevent later FillRequestStream
Body = null;
}
return uri;
}
private static Uri CheckProtocol(Uri uri)
{
if (uri == null) { throw new ArgumentNullException(nameof(uri)); }
if (!uri.IsAbsoluteUri)
{
uri = new Uri("http://" + uri.OriginalString);
}
return (uri);
}
private string QualifyFilePath(string path)
{
string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true);
return resolvedFilePath;
}
private static string FormatDictionary(IDictionary content)
{
if (content == null)
throw new ArgumentNullException(nameof(content));
StringBuilder bodyBuilder = new();
foreach (string key in content.Keys)
{
if (bodyBuilder.Length > 0)
{
bodyBuilder.Append('&');
}
object value = content[key];
// URLEncode the key and value
string encodedKey = WebUtility.UrlEncode(key);
string encodedValue = string.Empty;
if (value != null)
{
encodedValue = WebUtility.UrlEncode(value.ToString());
}
bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue);
}
return bodyBuilder.ToString();
}
private ErrorRecord GetValidationError(string msg, string errorId)
{
var ex = new ValidationMetadataException(msg);
var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
return (error);
}
private ErrorRecord GetValidationError(string msg, string errorId, params object[] args)
{
msg = string.Format(CultureInfo.InvariantCulture, msg, args);
var ex = new ValidationMetadataException(msg);
var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
return (error);
}
private bool IsStandardMethodSet()
{
return (ParameterSetName == "StandardMethod" || ParameterSetName == "StandardMethodNoProxy");
}
private bool IsCustomMethodSet()
{
return (ParameterSetName == "CustomMethod" || ParameterSetName == "CustomMethodNoProxy");
}
private string GetBasicAuthorizationHeader()
{
var password = new NetworkCredential(null, Credential.Password).Password;
string unencoded = string.Format("{0}:{1}", Credential.UserName, password);
byte[] bytes = Encoding.UTF8.GetBytes(unencoded);
return string.Format("Basic {0}", Convert.ToBase64String(bytes));
}
private string GetBearerAuthorizationHeader()
{
return string.Format("Bearer {0}", new NetworkCredential(string.Empty, Token).Password);
}
private void ProcessAuthentication()
{
if (Authentication == WebAuthenticationType.Basic)
{
WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader();
}
else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth)
{
WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader();
}
else
{
Diagnostics.Assert(false, string.Format("Unrecognized Authentication value: {0}", Authentication));
}
}
#endregion Helper Methods
}
// TODO: Merge Partials
/// <summary>
/// Exception class for webcmdlets to enable returning HTTP error response.
/// </summary>
public sealed class HttpResponseException : HttpRequestException
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpResponseException"/> class.
/// </summary>
/// <param name="message">Message for the exception.</param>
/// <param name="response">Response from the HTTP server.</param>
public HttpResponseException(string message, HttpResponseMessage response) : base(message)
{
Response = response;
}
/// <summary>
/// HTTP error response.
/// </summary>
public HttpResponseMessage Response { get; }
}
/// <summary>
/// Base class for Invoke-RestMethod and Invoke-WebRequest commands.
/// </summary>
public abstract partial class WebRequestPSCmdlet : PSCmdlet
{
/// <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 SkipHeaderValidation property.
/// </summary>
/// <remarks>
/// This property adds headers to the request's header collection without validation.
/// </remarks>
[Parameter]
public virtual SwitchParameter SkipHeaderValidation { get; set; }
#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
/// <summary>
/// Cancellation token source.
/// </summary>
internal CancellationTokenSource _cancelToken = null;
/// <summary>
/// Parse Rel Links.
/// </summary>
internal bool _parseRelLink = false;
/// <summary>
/// Automatically follow Rel Links.
/// </summary>
internal bool _followRelLink = false;
/// <summary>
/// Automatically follow Rel Links.
/// </summary>
internal Dictionary<string, string> _relationLink = null;
/// <summary>
/// Maximum number of Rel Links to follow.
/// </summary>
internal int _maximumFollowRelLink = int.MaxValue;
/// <summary>
/// The remote endpoint returned a 206 status code indicating successful resume.
/// </summary>
private bool _resumeSuccess = false;
/// <summary>
/// The current size of the local file being resumed.
/// </summary>
private long _resumeFileSize = 0;
private HttpMethod GetHttpMethod(WebRequestMethod method)
{
switch (Method)
{
case WebRequestMethod.Default:
case WebRequestMethod.Get:
return HttpMethod.Get;
case WebRequestMethod.Head:
return HttpMethod.Head;
case WebRequestMethod.Post:
return HttpMethod.Post;
case WebRequestMethod.Put:
return HttpMethod.Put;
case WebRequestMethod.Delete:
return HttpMethod.Delete;
case WebRequestMethod.Trace:
return HttpMethod.Trace;
case WebRequestMethod.Options:
return HttpMethod.Options;
default:
// Merge and Patch
return new HttpMethod(Method.ToString().ToUpperInvariant());
}
}
#region Virtual Methods
// NOTE: Only pass true for handleRedirect if the original request has an authorization header
// and PreserveAuthorizationOnRedirect is NOT set.
internal virtual HttpClient GetHttpClient(bool handleRedirect)
{
// By default the HttpClientHandler will automatically decompress GZip and Deflate content
HttpClientHandler handler = new();
handler.CookieContainer = WebSession.Cookies;