-
Notifications
You must be signed in to change notification settings - Fork 559
Expand file tree
/
Copy pathNSUrlSessionHandler.cs
More file actions
1778 lines (1527 loc) · 69.9 KB
/
NSUrlSessionHandler.cs
File metadata and controls
1778 lines (1527 loc) · 69.9 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
//
// NSUrlSessionHandler.cs:
//
// Authors:
// Ani Betts <anais@anaisbetts.org>
// Nick Berardi <nick@nickberardi.com>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using CoreFoundation;
using Security;
#if !MONOMAC
using UIKit;
#endif
#nullable enable
#if !MONOMAC && !XAMCORE_5_0
namespace System.Net.Http {
#else
namespace Foundation {
#endif
public delegate bool NSUrlSessionHandlerTrustOverrideForUrlCallback (NSUrlSessionHandler sender, string url, SecTrust trust);
// useful extensions for the class in order to set it in a header
static class NSHttpCookieExtensions {
static void AppendSegment (StringBuilder builder, string name, string? value)
{
if (builder.Length > 0)
builder.Append ("; ");
builder.Append (name);
if (value is not null)
builder.Append ("=").Append (value);
}
// returns the header for a cookie
public static string GetHeaderValue (this NSHttpCookie cookie)
{
var header = new StringBuilder ();
AppendSegment (header, cookie.Name, cookie.Value);
AppendSegment (header, NSHttpCookie.KeyPath.ToString (), cookie.Path.ToString ());
AppendSegment (header, NSHttpCookie.KeyDomain.ToString (), cookie.Domain.ToString ());
AppendSegment (header, NSHttpCookie.KeyVersion.ToString (), cookie.Version.ToString ());
if (cookie.Comment is not null)
AppendSegment (header, NSHttpCookie.KeyComment.ToString (), cookie.Comment.ToString ());
if (cookie.CommentUrl is not null)
AppendSegment (header, NSHttpCookie.KeyCommentUrl.ToString (), cookie.CommentUrl.ToString ());
if (cookie.Properties.ContainsKey (NSHttpCookie.KeyDiscard))
AppendSegment (header, NSHttpCookie.KeyDiscard.ToString (), null);
if (cookie.ExpiresDate is not null) {
// Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo)
var dateStr = ((DateTime) cookie.ExpiresDate).ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture);
AppendSegment (header, NSHttpCookie.KeyExpires.ToString (), dateStr);
}
var timeStampStringValue = cookie.Properties [NSHttpCookie.KeyMaximumAge];
if (timeStampStringValue is NSString timeStampString)
AppendSegment (header, NSHttpCookie.KeyMaximumAge.ToString (), timeStampString);
if (cookie.IsSecure)
AppendSegment (header, NSHttpCookie.KeySecure.ToString (), null);
if (cookie.IsHttpOnly)
AppendSegment (header, "httponly", null); // Apple does not show the key for the httponly
return header.ToString ();
}
}
/// <summary>To be added.</summary>
/// <remarks>To be added.</remarks>
public partial class NSUrlSessionHandler : HttpMessageHandler {
private const string SetCookie = "Set-Cookie";
private const string Cookie = "Cookie";
private const string ContentEncodingHeaderName = "Content-Encoding";
private const string ContentLengthHeaderName = "Content-Length";
private CookieContainer? cookieContainer;
readonly Dictionary<string, string> headerSeparators = new Dictionary<string, string> {
["User-Agent"] = " ",
["Server"] = " ",
};
NSUrlSession session;
readonly Dictionary<NSUrlSessionTask, InflightData> inflightRequests;
readonly object inflightRequestsLock = new object ();
readonly NSUrlSessionConfiguration.SessionConfigurationType sessionType;
#if !MONOMAC && !NET8_0 && !NET10_0_OR_GREATER
NSObject? notificationToken; // needed to make sure we do not hang if not using a background session
readonly object notificationTokenLock = new object (); // need to make sure that threads do no step on each other with a dispose and a remove inflight data
#endif
X509ChainPolicy? policy;
static NSUrlSessionConfiguration CreateConfig ()
{
// modifying the configuration does not affect future calls
var config = NSUrlSessionConfiguration.DefaultSessionConfiguration;
// but we want, by default, the timeout from HttpClient to have precedence over the one from NSUrlSession
// Double.MaxValue does not work, so default to 24 hours
config.TimeoutIntervalForRequest = 24 * 60 * 60;
config.TimeoutIntervalForResource = 24 * 60 * 60;
return config;
}
/// <summary>To be added.</summary>
/// <remarks>To be added.</remarks>
public NSUrlSessionHandler () : this (CreateConfig ())
{
}
/// <param name="configuration">To be added.</param>
/// <summary>To be added.</summary>
/// <remarks>To be added.</remarks>
[CLSCompliant (false)]
public NSUrlSessionHandler (NSUrlSessionConfiguration configuration)
{
if (configuration is null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (configuration));
// HACK: we need to store the following because session.Configuration gets a copy of the object and the value gets lost
sessionType = configuration.SessionType;
allowsCellularAccess = configuration.AllowsCellularAccess;
AllowAutoRedirect = true;
#if !NET10_0_OR_GREATER
#pragma warning disable SYSLIB0014
// SYSLIB0014: 'ServicePointManager' is obsolete: 'WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead. Settings on ServicePointManager no longer affect SslStream or HttpClient.' (https://aka.ms/dotnet-warnings/SYSLIB0014)
// https://github.com/dotnet/macios/issues/20764
var sp = ServicePointManager.SecurityProtocol;
#pragma warning restore SYSLIB0014
// The analyzer has a bug where SupportedOSPlatformGuard attributes don't work correctly (https://github.com/dotnet/roslyn-analyzers/issues/7665#issuecomment-2898275765), so ignore CA1416/CA1422 here
// warning CA1422: This call site is reachable on: 'ios' 12.2 and later, 'maccatalyst' 12.2 and later, 'macOS/OSX' 12.0 and later, 'tvos' 12.2 and later. 'NSUrlSessionConfiguration.[...]' is obsoleted on: 'ios' 13.0 and later (Use '...' instead.), 'maccatalyst' 13.0 and later (Use '...' instead.), 'macOS/OSX' 10.15 and later (Use '...' instead.).
// warning CA1416: This call site is reachable on: 'ios' 12.2 and later, 'maccatalyst' 12.2 and later, 'macOS/OSX' 10.15 and later, 'tvos' 12.2 and later. 'NSUrlSessionConfiguration.[...]' is only supported on: 'ios' 13.0 and later, 'tvos' 13.0 and later
#pragma warning disable CA1416
#pragma warning disable CA1422
if (SystemVersion.IsAtLeastXcode11) {
if ((sp & SecurityProtocolType.Ssl3) != 0) {
// no equivalent
} else if ((sp & SecurityProtocolType.Tls) != 0) {
configuration.TlsMinimumSupportedProtocolVersion = TlsProtocolVersion.Tls10;
} else if ((sp & SecurityProtocolType.Tls11) != 0) {
configuration.TlsMinimumSupportedProtocolVersion = TlsProtocolVersion.Tls11;
} else if ((sp & SecurityProtocolType.Tls12) != 0) {
configuration.TlsMinimumSupportedProtocolVersion = TlsProtocolVersion.Tls12;
} else if ((sp & SecurityProtocolType.Tls13) != 0) {
configuration.TlsMinimumSupportedProtocolVersion = TlsProtocolVersion.Tls13;
}
} else {
if ((sp & SecurityProtocolType.Ssl3) != 0)
configuration.TLSMinimumSupportedProtocol = SslProtocol.Ssl_3_0;
else if ((sp & SecurityProtocolType.Tls) != 0)
configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_0;
else if ((sp & SecurityProtocolType.Tls11) != 0)
configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_1;
else if ((sp & SecurityProtocolType.Tls12) != 0)
configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_2;
else if ((sp & SecurityProtocolType.Tls13) != 0)
configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_3;
}
#pragma warning restore CA1422
#pragma warning restore CA1416
#endif // NET10_0_OR_GREATER
session = NSUrlSession.FromConfiguration (configuration, (INSUrlSessionDelegate) new NSUrlSessionHandlerDelegate (this), null);
inflightRequests = new Dictionary<NSUrlSessionTask, InflightData> ();
}
#if !MONOMAC && !NET8_0 && !NET10_0_OR_GREATER
void AddNotification ()
{
lock (notificationTokenLock) {
if (!bypassBackgroundCheck && sessionType != NSUrlSessionConfiguration.SessionConfigurationType.Background && notificationToken is null)
notificationToken = NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillResignActiveNotification, BackgroundNotificationCb);
} // lock
}
void RemoveNotification ()
{
NSObject? localNotificationToken;
lock (notificationTokenLock) {
localNotificationToken = notificationToken;
notificationToken = null;
}
if (localNotificationToken is not null)
NSNotificationCenter.DefaultCenter.RemoveObserver (localNotificationToken);
}
void BackgroundNotificationCb (NSNotification obj)
{
// the cancelation task of each of the sources will clean the different resources. Each removal is done
// inside a lock, but of course, the .Values collection will not like that because it is modified during the
// iteration. We split the operation in two, get all the diff cancelation sources, then try to cancel each of them
// which will do the correct lock dance. Note that we could be tempted to do a RemoveAll, that will yield the same
// runtime issue, this is dull but safe.
List<TaskCompletionSource<HttpResponseMessage>> sources;
lock (inflightRequestsLock) { // just lock when we iterate
sources = new List<TaskCompletionSource<HttpResponseMessage>> (inflightRequests.Count);
foreach (var r in inflightRequests.Values) {
sources.Add (r.CompletionSource);
}
}
sources.ForEach (source => { source.TrySetCanceled (); });
}
#endif
/// <summary>The maximum amount of content to load into memory when sending content with a request.</summary>
/// <value>The maximum size of content to load into memory.</value>
/// <remarks>
/// <para>When sending content with a request, the content can be provided either in memory, or in a streaming manner.</para>
/// <para>If the content is provided in memory, the underlying NSURLSession will set the Content-Length header to the size of the content.</para>
/// <para>If the content is provided in a streaming manner, the underlying NSURLSession will send the content using a chunked encoding, and the Content-Length header will not be set.</para>
/// <para>This means that if a chunked encoding is not desirable, or a Content-Length header is required, then the content must be provided in memory.</para>
/// <para>On the other hand, if upload progress is needed, it's required to provide the content in a streaming manner, and this can be forced by setting this property to 0.</para>
/// <para>If the content to upload doesn't have a pre-determined length, then it will always be sent in a streaming manner.</para>
/// </remarks>
public long MaxInputInMemory { get; set; } = long.MaxValue;
void RemoveInflightData (NSUrlSessionTask task, bool cancel = true)
{
lock (inflightRequestsLock) {
if (inflightRequests.TryGetValue (task, out var data)) {
if (cancel)
data.CancellationTokenSource.Cancel ();
inflightRequests.Remove (task);
}
#if !MONOMAC && !NET8_0 && !NET10_0_OR_GREATER
// do we need to be notified? If we have not inflightData, we do not
if (inflightRequests.Count == 0)
RemoveNotification ();
#endif
}
if (cancel)
task?.Cancel ();
task?.Dispose ();
}
/// <param name="disposing">To be added.</param>
/// <summary>To be added.</summary>
/// <remarks>To be added.</remarks>
protected override void Dispose (bool disposing)
{
lock (inflightRequestsLock) {
#if !MONOMAC && !NET8_0 && !NET10_0_OR_GREATER
// remove the notification if present, method checks against null
RemoveNotification ();
#endif
foreach (var pair in inflightRequests) {
pair.Key?.Cancel ();
pair.Key?.Dispose ();
}
inflightRequests.Clear ();
}
session.InvalidateAndCancel ();
base.Dispose (disposing);
}
bool disableCaching;
/// <summary>To be added.</summary>
/// <value>To be added.</value>
/// <remarks>To be added.</remarks>
public bool DisableCaching {
get {
return disableCaching;
}
set {
EnsureModifiability ();
disableCaching = value;
}
}
bool allowAutoRedirect;
/// <summary>To be added.</summary>
/// <value>To be added.</value>
/// <remarks>To be added.</remarks>
public bool AllowAutoRedirect {
get {
return allowAutoRedirect;
}
set {
EnsureModifiability ();
allowAutoRedirect = value;
}
}
bool allowsCellularAccess = true;
public bool AllowsCellularAccess {
get {
return allowsCellularAccess;
}
set {
EnsureModifiability ();
allowsCellularAccess = value;
}
}
ICredentials? credentials;
/// <summary>To be added.</summary>
/// <value>To be added.</value>
/// <remarks>To be added.</remarks>
public ICredentials? Credentials {
get {
return credentials;
}
set {
EnsureModifiability ();
credentials = value;
}
}
NSUrlSessionHandlerTrustOverrideForUrlCallback? trustOverrideForUrl;
public NSUrlSessionHandlerTrustOverrideForUrlCallback? TrustOverrideForUrl {
get {
return trustOverrideForUrl;
}
set {
EnsureModifiability ();
trustOverrideForUrl = value;
}
}
#if !NET8_0 && !NET10_0_OR_GREATER
// we do check if a user does a request and the application goes to the background, but
// in certain cases the user does that on purpose (BeingBackgroundTask) and wants to be able
// to use the network. In those cases, which are few, we want the developer to explicitly
// bypass the check when there are not request in flight
bool bypassBackgroundCheck = true;
#endif
#if !XAMCORE_5_0
[EditorBrowsable (EditorBrowsableState.Never)]
#if NET8_0 || NET10_0_OR_GREATER
[Obsolete ("This property is ignored.")]
#else
[Obsolete ("This property will be ignored in .NET 10+.")]
#endif
public bool BypassBackgroundSessionCheck {
get {
#if NET8_0 || NET10_0_OR_GREATER
return true;
#else
return bypassBackgroundCheck;
#endif
}
set {
#if !NET8_0 && !NET10_0_OR_GREATER
EnsureModifiability ();
bypassBackgroundCheck = value;
#endif
}
}
#endif // !XAMCORE_5_0
public CookieContainer? CookieContainer {
get {
return cookieContainer;
}
set {
EnsureModifiability ();
cookieContainer = value;
}
}
/// <summary>Enable or disable the use of cookies.</summary>
/// <remarks>
/// <para>
/// For default and background sessions, the shared cookie storage (<see cref="NSHttpCookieStorage.SharedStorage" /> will be used.
/// This shared cookie storage will persist beyond app restarts; to clear the cookies call <c>NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast)</c>.
/// To use a custom cookie storage, use a custom <see cref="NSUrlSessionConfiguration" />, set the <see cref="NSUrlSessionConfiguration.HttpCookieStorage" /> property, and then pass in the custom session configuration when creating the <see cref="NSUrlSessionHandler(NSUrlSessionConfiguration)" />.
/// </para>
/// <para>Ephemeral sessions have by default a private cookie storage area. This private cookie storage area can't be recreated, which means that if the use of cookies is disabled, then it can't be re-enabled.</para>
/// </remarks>
public bool UseCookies {
get {
return session.Configuration.HttpCookieStorage is not null;
}
set {
EnsureModifiability ();
// first check if anything changed
if (value == UseCookies)
return;
// we have to consider the following table of cases:
// 1. Value is set to true and cookie storage is not null -> we do nothing (already handled above)
// 2. Value is set to true and cookie storage is null -> we create/set the storage.
// 3. Value is false and cookie container is not null -> we clear the cookie storage
// 4. Value is false and cookie container is null -> we do nothing (already handled above)
var oldSession = session;
var configuration = session.Configuration;
if (value && configuration.HttpCookieStorage is null) {
// create storage because the user wants to use it. Things are not that easy, we have to
// consider the following:
// 1. Default Session -> uses sharedHTTPCookieStorage
// 2. Background Session -> uses sharedHTTPCookieStorage
// 3. Ephemeral Session -> we can't create an instance of a private cookie storage. Note that ephemeral sessions have a private cookie storage by default, so this can only happen if the developer disables cookies, and then re-enables them.
if (sessionType == NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral)
throw new InvalidOperationException ("Can't re-enable the use of cookies in Ephemeral sessions.");
configuration.HttpCookieStorage = NSHttpCookieStorage.SharedStorage;
}
if (!value && configuration.HttpCookieStorage is not null) {
// remove storage so that it is not used in any of the requests
configuration.HttpCookieStorage = null;
}
session = NSUrlSession.FromConfiguration (configuration, (INSUrlSessionDelegate) new NSUrlSessionHandlerDelegate (this), null);
oldSession.Dispose ();
}
}
bool sentRequest;
internal void EnsureModifiability ()
{
if (sentRequest)
throw new InvalidOperationException (
"This instance has already started one or more requests. " +
"Properties can only be modified before sending the first request.");
}
static Exception createExceptionForNSError (NSError error)
{
var innerException = new NSErrorException (error);
// errors that exists in both share the same error code, so we can use a single switch/case
// this also ease watchOS integration as if does not expose CFNetwork but (I would not be
// surprised if it)could return some of it's error codes
if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain)) {
// Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
// .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
switch ((NSUrlError) (long) error.Code) {
case NSUrlError.Cancelled:
case NSUrlError.UserCancelledAuthentication:
case (NSUrlError) NSNetServicesStatus.CancelledError:
// No more processing is required so just return.
return new OperationCanceledException (error.LocalizedDescription, innerException);
}
}
return new HttpRequestException (error.LocalizedDescription, innerException);
}
string GetHeaderSeparator (string name)
{
if (!headerSeparators.TryGetValue (name, out var value))
value = ",";
return value;
}
void AddManagedHeaders (NSMutableDictionary nativeHeaders, IEnumerable<KeyValuePair<string, IEnumerable<string>>> managedHeaders)
{
foreach (var keyValuePair in managedHeaders) {
var keyPtr = NSString.CreateNative (keyValuePair.Key);
var valuePtr = NSString.CreateNative (string.Join (GetHeaderSeparator (keyValuePair.Key), keyValuePair.Value));
nativeHeaders.LowlevelSetObject (valuePtr, keyPtr);
NSString.ReleaseNative (keyPtr);
NSString.ReleaseNative (valuePtr);
}
}
async Task<NSUrlRequest> CreateRequest (HttpRequestMessage request)
{
var stream = Stream.Null;
var nativeHeaders = new NSMutableDictionary ();
// set header cookies if needed from the managed cookie container if we do use Cookies
if (session.Configuration.HttpCookieStorage is not null) {
var cookies = cookieContainer?.GetCookieHeader (request.RequestUri!); // as per docs: An HTTP cookie header, with strings representing Cookie instances delimited by semicolons.
if (!string.IsNullOrEmpty (cookies)) {
var cookiePtr = NSString.CreateNative (Cookie);
var cookiesPtr = NSString.CreateNative (cookies);
nativeHeaders.LowlevelSetObject (cookiesPtr, cookiePtr);
NSString.ReleaseNative (cookiePtr);
NSString.ReleaseNative (cookiesPtr);
}
}
AddManagedHeaders (nativeHeaders, request.Headers);
if (request.Content is not null) {
stream = await request.Content.ReadAsStreamAsync ().ConfigureAwait (false);
AddManagedHeaders (nativeHeaders, request.Content.Headers);
}
var nsrequest = new NSMutableUrlRequest {
AllowsCellularAccess = allowsCellularAccess,
CachePolicy = DisableCaching ? NSUrlRequestCachePolicy.ReloadIgnoringCacheData : NSUrlRequestCachePolicy.UseProtocolCachePolicy,
HttpMethod = request.Method.ToString ().ToUpperInvariant (),
Url = NSUrl.FromString (request.RequestUri?.AbsoluteUri),
Headers = nativeHeaders,
};
if (stream != Stream.Null) {
// Rewind the stream to the beginning in case the HttpContent implementation
// will be accessed again (e.g. for retry/redirect) and it keeps its stream open behind the scenes.
if (stream.CanSeek)
stream.Seek (0, SeekOrigin.Begin);
// HttpContent.TryComputeLength is `protected internal` :-( but it's indirectly called by headers
var length = request.Content?.Headers?.ContentLength;
if (length.HasValue && (length <= MaxInputInMemory))
nsrequest.Body = NSData.FromStream (stream);
else
nsrequest.BodyStream = new WrappedNSInputStream (stream);
}
return nsrequest;
}
/// <param name="request">To be added.</param>
/// <param name="cancellationToken">To be added.</param>
/// <summary>To be added.</summary>
/// <returns>To be added.</returns>
/// <remarks>To be added.</remarks>
protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
Volatile.Write (ref sentRequest, true);
var nsrequest = await CreateRequest (request).ConfigureAwait (false);
var dataTask = session.CreateDataTask (nsrequest);
var inflightData = new InflightData (request.RequestUri?.AbsoluteUri!, cancellationToken, request);
lock (inflightRequestsLock) {
#if !MONOMAC && !NET8_0 && !NET10_0_OR_GREATER
// Add the notification whenever needed
AddNotification ();
#endif
inflightRequests.Add (dataTask, inflightData);
}
if (dataTask.State == NSUrlSessionTaskState.Suspended)
dataTask.Resume ();
// as per documentation:
// If this token is already in the canceled state, the
// delegate will be run immediately and synchronously.
// Any exception the delegate generates will be
// propagated out of this method call.
//
// The execution of the register ensures that if we
// receive a already cancelled token or it is cancelled
// just before this call, we will cancel the task.
// Other approaches are harder, since querying the state
// of the token does not guarantee that in the next
// execution a threads cancels it.
cancellationToken.Register (() => {
RemoveInflightData (dataTask);
inflightData.CompletionSource.TrySetCanceled ();
});
return await inflightData.CompletionSource.Task.ConfigureAwait (false);
}
// Properties that will be called by the default HttpClientHandler
// NSUrlSession handler automatically handles decompression, and there doesn't seem to be a way to turn it off.
// The available decompression algorithms depend on the OS version we're running on, and maybe the target OS version as well,
// so just say we're doing them all, and not do anything in the setter (it doesn't seem to be configurable in NSUrlSession anyways).
public DecompressionMethods AutomaticDecompression {
get => DecompressionMethods.All;
set { }
}
/// <summary>Gets or sets a value that indicates whether the certificate is checked against the certificate authority revocation list.</summary>
/// <remarks>
/// <para>This is the same as setting CertificateChainPolicy.RevocationMode = X509RevocationMode.Online (if enabling the check) or X509RevocationMode.NoCheck (if disabling the check).</para>
/// <para>This only has an effect if a custom server certificate validation callback is being used ('ServerCertificateCustomValidationCallback' is set).</para>
/// </remarks>
[EditorBrowsable (EditorBrowsableState.Never)]
public bool CheckCertificateRevocationList {
// This implementation was mostly copied from https://github.com/dotnet/runtime/blob/0e3562e97c6db531f26a2ffe3e8084cf67ba8a93/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs#L326-L335
get => CertificateChainPolicy!.RevocationMode == X509RevocationMode.Online;
set {
EnsureModifiability ();
CertificateChainPolicy!.RevocationMode = value ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
}
}
/// <summary>Gets or sets the custom chain policy to use when validating certificate chains.</summary>
/// <remarks>
/// <para>The getter will never return a <see langword="null" /> policy, it will return a policy configured with the default behavior.</para>
/// <para>To select the default policy, call the setter with <see langword="null" /> value.</para>
/// <para>This only has an effect if a custom server certificate validation callback is being used ('ServerCertificateCustomValidationCallback' is set).</para>
/// </remarks>
public X509ChainPolicy? CertificateChainPolicy {
get {
if (policy is null) {
policy = new X509ChainPolicy () {
RevocationMode = X509RevocationMode.Online,
RevocationFlag = X509RevocationFlag.ExcludeRoot,
// Ignore unknown revocation status, because Apple has a bug where revocation checks fail if the certificate(s)
// in question don't support revocation checking via OCSP.
// References:
// * https://learn.microsoft.com/en-us/dotnet/core/compatibility/networking/10.0/ssl-certificate-revocation-check-default
// * https://github.com/dotnet/macios/issues/23764#issuecomment-3264999234
// * https://github.com/dotnet/runtime/issues/117195
VerificationFlags = X509VerificationFlags.IgnoreEndRevocationUnknown,
};
}
return policy;
}
set => policy = value;
}
X509CertificateCollection? _clientCertificates;
/// <summary>Gets the collection of security certificates that are associated with requests to the server.</summary>
/// <remarks>Client certificates are only supported when ClientCertificateOptions is set to ClientCertificateOptions.Manual.</remarks>
public X509CertificateCollection ClientCertificates {
get {
if (ClientCertificateOptions != ClientCertificateOption.Manual) {
throw new InvalidOperationException ($"Enable manual options first on {nameof (ClientCertificateOptions)}");
}
return _clientCertificates ?? (_clientCertificates = new X509CertificateCollection ());
}
}
public ClientCertificateOption ClientCertificateOptions { get; set; }
// We're ignoring this property, just like Xamarin.Android does:
// https://github.com/xamarin/xamarin-android/blob/09e8cb5c07ea6c39383185a3f90e53186749b802/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs#L152
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public ICredentials? DefaultProxyCredentials { get; set; }
public int MaxAutomaticRedirections {
get => int.MaxValue;
set {
// I believe it's possible to implement support for MaxAutomaticRedirections (it just has to be done)
if (value != int.MaxValue)
ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to lower the max number of automatic redirections."); ;
}
}
// We're ignoring this property, just like Xamarin.Android does:
// https://github.com/xamarin/xamarin-android/blob/09e8cb5c07ea6c39383185a3f90e53186749b802/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs#L154
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public int MaxConnectionsPerServer { get; set; } = int.MaxValue;
// We're ignoring this property, just like Xamarin.Android does:
// https://github.com/xamarin/xamarin-android/blob/09e8cb5c07ea6c39383185a3f90e53186749b802/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs#L156
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public int MaxResponseHeadersLength { get; set; } = 64; // Units in K (1024) bytes.
// We don't support PreAuthenticate, so always return false, and ignore any attempts to change it.
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public bool PreAuthenticate {
get => false;
set { }
}
// We're ignoring this property, just like Xamarin.Android does:
// https://github.com/xamarin/xamarin-android/blob/09e8cb5c07ea6c39383185a3f90e53186749b802/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs#L167
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public IDictionary<string, object>? Properties { get { return null; } }
// We dont support any custom proxies, and don't let anybody wonder why their proxy isn't
// being used if they try to assign one (in any case we also return false from 'SupportsProxy').
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public IWebProxy? Proxy {
get => null;
set {
if (value is not null)
throw new PlatformNotSupportedException ();
}
}
// There doesn't seem to be a trivial way to specify the protocols to accept (or not)
// It might be possible to reject some protocols in code during the challenge phase,
// but accepting earlier (unsafe) protocols requires adding entires to the Info.plist,
// which means it's not trivial to detect/accept/reject from code here.
// Currently the default for Apple platforms is to accept TLS v1.2 and v1.3, so default
// to that value, and ignore any changes to it.
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;
private ServerCertificateCustomValidationCallbackHelper? _serverCertificateCustomValidationCallbackHelper;
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>? ServerCertificateCustomValidationCallback {
get => _serverCertificateCustomValidationCallbackHelper?.Callback;
set {
if (value is null) {
_serverCertificateCustomValidationCallbackHelper = null;
} else {
_serverCertificateCustomValidationCallbackHelper = new ServerCertificateCustomValidationCallbackHelper (value, CertificateChainPolicy!);
}
}
}
// returns false if there's no callback
internal bool TryInvokeServerCertificateCustomValidationCallback (HttpRequestMessage request, SecTrust secTrust, out bool trusted)
{
trusted = false;
var helper = _serverCertificateCustomValidationCallbackHelper;
if (helper is null)
return false;
trusted = helper.Invoke (request, secTrust);
return true;
}
sealed class ServerCertificateCustomValidationCallbackHelper {
X509ChainPolicy policy;
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> Callback { get; private set; }
public ServerCertificateCustomValidationCallbackHelper (Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> callback, X509ChainPolicy policy)
{
Callback = callback;
this.policy = policy;
}
public bool Invoke (HttpRequestMessage request, SecTrust secTrust)
{
var certificates = ConvertCertificates (secTrust);
var certificate = certificates.Length > 0 ? certificates [0] : null;
using X509Chain chain = CreateChain (certificates);
SslPolicyErrors sslPolicyErrors = EvaluateSslPolicyErrors (certificate, chain, secTrust);
return Callback (request, certificate, chain, sslPolicyErrors);
}
X509Certificate2 [] ConvertCertificates (SecTrust secTrust)
{
var certificates = new X509Certificate2 [secTrust.Count];
if (SystemVersion.IsAtLeastXcode13) {
var originalChain = secTrust.GetCertificateChain ();
if (originalChain is null)
return Array.Empty<X509Certificate2> ();
for (int i = 0; i < originalChain.Length; i++)
certificates [i] = originalChain [i].ToX509Certificate2 ();
} else {
for (int i = 0; i < secTrust.Count; i++) {
// The analyzer has a bug where SupportedOSPlatformGuard attributes don't work correctly (https://github.com/dotnet/roslyn-analyzers/issues/7665#issuecomment-2898275765), so ignore CA1422 here
#pragma warning disable CA1422 // This call site is reachable on: 'ios' 12.2 and later, 'maccatalyst' 12.2 and later, 'macOS/OSX' 12.0 and later, 'tvos' 12.2 and later. 'SecTrust.this[nint]' is obsoleted on: 'ios' 15.0 and later
certificates [i] = secTrust [i].ToX509Certificate2 ();
#pragma warning restore CA1422
}
}
return certificates;
}
X509Chain CreateChain (X509Certificate2 [] certificates)
{
// See https://github.com/dotnet/macios/issues/23764 for more information.
var chain = new X509Chain ();
chain.ChainPolicy = policy.Clone ();
chain.ChainPolicy.ExtraStore.AddRange (certificates);
return chain;
}
SslPolicyErrors EvaluateSslPolicyErrors (X509Certificate2? certificate, X509Chain chain, SecTrust secTrust)
{
var sslPolicyErrors = SslPolicyErrors.None;
try {
if (certificate is null) {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
} else if (!chain.Build (certificate)) {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
} catch {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
if (!secTrust.Evaluate (out _)) {
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
return sslPolicyErrors;
}
}
// There's no way to turn off automatic decompression, so yes, we support it
public bool SupportsAutomaticDecompression {
get => true;
}
// We don't support using custom proxies, but NSUrlSession will automatically use any proxies configured in the OS.
public bool SupportsProxy {
get => false;
}
// We support the AllowAutoRedirect property, but we don't support changing the MaxAutomaticRedirections value,
// so be safe here and say we don't support redirect configuration.
public bool SupportsRedirectConfiguration {
get => false;
}
// NSUrlSession will automatically use any proxies configured in the OS (so always return true in the getter).
// There doesn't seem to be a way to turn this off, so throw if someone attempts to disable this.
public bool UseProxy {
get => true;
set {
if (!value)
ObjCRuntime.ThrowHelper.ThrowArgumentOutOfRangeException (nameof (value), value, "It's not possible to disable the use of system proxies."); ;
}
}
static bool HasCompressedEncoding (string headerValue)
{
foreach (var encoding in headerValue.Split (',')) {
if (IsCompressedEncoding (encoding.Trim ()))
return true;
}
return false;
}
static bool IsCompressedEncoding (string encoding)
{
return string.Equals (encoding, "gzip", StringComparison.OrdinalIgnoreCase)
|| string.Equals (encoding, "deflate", StringComparison.OrdinalIgnoreCase)
|| string.Equals (encoding, "br", StringComparison.OrdinalIgnoreCase)
|| string.Equals (encoding, "compress", StringComparison.OrdinalIgnoreCase)
|| string.Equals (encoding, "zstd", StringComparison.OrdinalIgnoreCase);
}
partial class NSUrlSessionHandlerDelegate : NSUrlSessionDataDelegate {
readonly NSUrlSessionHandler sessionHandler;
public NSUrlSessionHandlerDelegate (NSUrlSessionHandler handler)
{
sessionHandler = handler;
}
InflightData? GetInflightData (NSUrlSessionTask task)
{
var inflight = default (InflightData);
lock (sessionHandler.inflightRequestsLock)
if (sessionHandler.inflightRequests.TryGetValue (task, out inflight)) {
// ensure that we did not cancel the request, if we did, do cancel the task, if we
// cancel the task it means that we are not interested in any of the delegate methods:
//
// DidReceiveResponse We might have received a response, but either the user cancelled or a
// timeout did, if that is the case, we do not care about the response.
// DidReceiveData Of buffer has a partial response ergo garbage and there is not real
// reason we would like to add more data.
// DidCompleteWithError - We are not changing a behaviour compared to the case in which
// we did not find the data.
if (inflight.CancellationToken.IsCancellationRequested) {
task?.Cancel ();
// return null so that we break out of any delegate method.
return null;
}
return inflight;
}
// if we did not manage to get the inflight data, we either got an error or have been canceled, lets cancel the task, that will execute DidCompleteWithError
task?.Cancel ();
return null;
}
void UpdateManagedCookieContainer (Uri absoluteUri, NSHttpCookie [] cookies)
{
if (sessionHandler.cookieContainer is not null && cookies.Length > 0)
lock (sessionHandler.inflightRequestsLock) { // ensure we lock when writing to the collection
var cookiesContents = Array.ConvertAll (cookies, static cookie => cookie.GetHeaderValue ());
sessionHandler.cookieContainer.SetCookies (absoluteUri, string.Join (',', cookiesContents)); // as per docs: The contents of an HTTP set-cookie header as returned by a HTTP server, with Cookie instances delimited by commas.
}
}
[Preserve (Conditional = true)]
public override void DidReceiveResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler)
{
try {
DidReceiveResponseImpl (session, dataTask, response, completionHandler);
} catch {
completionHandler (NSUrlSessionResponseDisposition.Cancel);
throw;
}
}
void DidReceiveResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler)
{
var inflight = GetInflightData (dataTask);
if (inflight is null) {
completionHandler (NSUrlSessionResponseDisposition.Cancel);
return;
}
try {
var urlResponse = (NSHttpUrlResponse) response;
var status = (int) urlResponse.StatusCode;
var absoluteUri = new Uri (urlResponse.Url.AbsoluteString!);
var content = new NSUrlSessionDataTaskStreamContent (inflight.Stream, () => {
if (!inflight.Completed) {
dataTask.Cancel ();
}
inflight.Disposed = true;
inflight.Stream.TrySetException (new ObjectDisposedException ("The content stream was disposed."));
sessionHandler.RemoveInflightData (dataTask);
}, inflight.CancellationTokenSource.Token);
// NB: The double cast is because of a Xamarin compiler bug
var httpResponse = new HttpResponseMessage ((HttpStatusCode) status) {
Content = content,
RequestMessage = inflight.Request,
};
var wasRedirected = dataTask.CurrentRequest?.Url?.AbsoluteString != dataTask.OriginalRequest?.Url?.AbsoluteString;
if (wasRedirected)
httpResponse.RequestMessage.RequestUri = absoluteUri;
// NSURLSession automatically decompresses content for all supported
// encodings (gzip, deflate, br, zstd, etc.), and there's no way to
// turn it off. After decompression, Content-Encoding and Content-Length
// are stale (Content-Length refers to compressed size), so we need to
// remove them to match the behavior of other HTTP handlers:
// - SocketsHttpHandler: https://github.com/dotnet/runtime/blob/b2974279efd059efaa17f359ed4b266b1c705721/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/DecompressionHandler.cs#L122-L123
// - AndroidMessageHandler: https://github.com/dotnet/android/pull/7785
// Ref: https://github.com/dotnet/macios/issues/23958
// This behavior can be opted out of by setting the
// Foundation.NSUrlSessionHandler.KeepHeadersAfterDecompression switch.
var keepHeaders = AppContext.TryGetSwitch ("Foundation.NSUrlSessionHandler.KeepHeadersAfterDecompression", out var keepHeadersEnabled) && keepHeadersEnabled;
string? contentEncodingValue = null;
string? contentLengthValue = null;
foreach (var v in urlResponse.AllHeaderFields) {
var key = v.Key?.ToString ();
var value = v.Value?.ToString ();
// NB: Cocoa trolling us so hard by giving us back dummy dictionary entries