-
Notifications
You must be signed in to change notification settings - Fork 514
/
NSUrlSessionHandler.cs
1552 lines (1327 loc) · 56.6 KB
/
NSUrlSessionHandler.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
//
// 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;
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.Runtime.InteropServices;
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 Foundation;
using Security;
#if !MONOMAC
using UIKit;
#endif
#nullable enable
#if !MONOMAC
namespace System.Net.Http {
#else
namespace Foundation {
#endif
#if !NET
public delegate bool NSUrlSessionHandlerTrustOverrideCallback (NSUrlSessionHandler sender, SecTrust trust);
#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);
}
if (cookie.Properties.ContainsKey (NSHttpCookie.KeyMaximumAge)) {
var timeStampString = (NSString) cookie.Properties [NSHttpCookie.KeyMaximumAge];
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 ();
}
}
public partial class NSUrlSessionHandler : HttpMessageHandler {
private const string SetCookie = "Set-Cookie";
private const string Cookie = "Cookie";
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 && !__WATCHOS__
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
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;
}
public NSUrlSessionHandler () : this (CreateConfig ())
{
}
[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;
var sp = ServicePointManager.SecurityProtocol;
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) 12288) != 0) // Tls13 value not yet in monno
configuration.TLSMinimumSupportedProtocol = SslProtocol.Tls_1_3;
session = NSUrlSession.FromConfiguration (configuration, (INSUrlSessionDelegate) new NSUrlSessionHandlerDelegate (this), null);
inflightRequests = new Dictionary<NSUrlSessionTask, InflightData> ();
}
#if !MONOMAC && !__WATCHOS__ && !NET8_0
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
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 ();
data.Dispose ();
inflightRequests.Remove (task);
}
#if !MONOMAC && !__WATCHOS__ && !NET8_0
// 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 ();
}
protected override void Dispose (bool disposing)
{
lock (inflightRequestsLock) {
#if !MONOMAC && !__WATCHOS__ && !NET8_0
// remove the notification if present, method checks against null
RemoveNotification ();
#endif
foreach (var pair in inflightRequests) {
pair.Key?.Cancel ();
pair.Key?.Dispose ();
pair.Value?.Dispose ();
}
inflightRequests.Clear ();
}
base.Dispose (disposing);
}
bool disableCaching;
public bool DisableCaching {
get {
return disableCaching;
}
set {
EnsureModifiability ();
disableCaching = value;
}
}
bool allowAutoRedirect;
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;
public ICredentials? Credentials {
get {
return credentials;
}
set {
EnsureModifiability ();
credentials = value;
}
}
#if !NET
NSUrlSessionHandlerTrustOverrideCallback? trustOverride;
[Obsolete ("Use the 'TrustOverrideForUrl' property instead.")]
public NSUrlSessionHandlerTrustOverrideCallback? TrustOverride {
get {
return trustOverride;
}
set {
EnsureModifiability ();
trustOverride = value;
}
}
#endif
NSUrlSessionHandlerTrustOverrideForUrlCallback? trustOverrideForUrl;
public NSUrlSessionHandlerTrustOverrideForUrlCallback? TrustOverrideForUrl {
get {
return trustOverrideForUrl;
}
set {
EnsureModifiability ();
trustOverrideForUrl = value;
}
}
#if !NET8_0
// 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
[Obsolete ("This property is ignored.")]
#else
[Obsolete ("This property will be ignored in .NET 8.")]
#endif
public bool BypassBackgroundSessionCheck {
get {
#if NET8_0
return true;
#else
return bypassBackgroundCheck;
#endif
}
set {
#if !NET8_0
EnsureModifiability ();
bypassBackgroundCheck = value;
#endif
}
}
#endif // !XAMCORE_5_0
public CookieContainer? CookieContainer {
get {
return cookieContainer;
}
set {
EnsureModifiability ();
cookieContainer = value;
}
}
public bool UseCookies {
get {
return session.Configuration.HttpCookieStorage is not null;
}
set {
EnsureModifiability ();
if (sessionType == NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral)
throw new InvalidOperationException ("Cannot set the use of cookies in Ephemeral sessions.");
// we have to consider the following table of cases:
// 1. Value is set to true and cookie storage is not null -> we do nothing
// 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
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 -> no allowed. apple does not provide a way to access to the private implementation of the storage class :/
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 __WATCHOS__
if (error.Domain == NSError.NSUrlErrorDomain) {
#else
if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain)) {
#endif
// 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:
#if !__WATCHOS__
case (NSUrlError) NSNetServicesStatus.CancelledError:
#endif
// 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) {
// 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;
}
#if (SYSTEM_NET_HTTP || MONOMAC) && !NET
internal
#endif
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 && !__WATCHOS__ && !NET8_0
// 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);
}
#if NET
// 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 { }
}
// 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#L158
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public bool CheckCertificateRevocationList { get; set; } = false;
// 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#L150
// Note: we can't return null (like Xamarin.Android does), because the return type isn't nullable.
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
public X509CertificateCollection ClientCertificates { get { return new X509CertificateCollection (); } }
// 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#L148
[UnsupportedOSPlatform ("ios")]
[UnsupportedOSPlatform ("maccatalyst")]
[UnsupportedOSPlatform ("tvos")]
[UnsupportedOSPlatform ("macos")]
[EditorBrowsable (EditorBrowsableState.Never)]
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 => 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);
}
}
}
// 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
{
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> Callback { get; private set; }
public ServerCertificateCustomValidationCallbackHelper (Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> callback)
{
Callback = callback;
}
public bool Invoke (HttpRequestMessage request, SecTrust secTrust)
{
X509Certificate2[] certificates = ConvertCertificates (secTrust);
X509Certificate2? 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 (IsSecTrustGetCertificateChainSupported) {
var originalChain = secTrust.GetCertificateChain ();
for (int i = 0; i < originalChain.Length; i++)
certificates [i] = originalChain [i].ToX509Certificate2 ();
} else {
for (int i = 0; i < secTrust.Count; i++)
certificates [i] = secTrust [i].ToX509Certificate2 ();
}
return certificates;
}
static bool? isSecTrustGetCertificateChainSupported = null;
static bool IsSecTrustGetCertificateChainSupported {
get {
if (!isSecTrustGetCertificateChainSupported.HasValue) {
#if MONOMAC
isSecTrustGetCertificateChainSupported = ObjCRuntime.SystemVersion.CheckmacOS (12, 0);
#elif WATCH
isSecTrustGetCertificateChainSupported = ObjCRuntime.SystemVersion.CheckWatchOS (8, 0);
#elif IOS || TVOS || MACCATALYST
isSecTrustGetCertificateChainSupported = ObjCRuntime.SystemVersion.CheckiOS (15, 0);
#else
#error Unknown platform
#endif
}
return isSecTrustGetCertificateChainSupported.Value;
}
}
X509Chain CreateChain (X509Certificate2[] certificates)
{
// inspired by https://github.com/dotnet/runtime/blob/99d21b9276ebe8f7bea7fb3ba74dca9fca625fe2/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs#L691-L696
var chain = new X509Chain ();
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
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 (ArgumentException) {
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.");;
}
}
#endif // NET
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)
{
var inflight = GetInflightData (dataTask);
if (inflight is null)
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
};
httpResponse.RequestMessage.RequestUri = absoluteUri;
foreach (var v in urlResponse.AllHeaderFields) {
// NB: Cocoa trolling us so hard by giving us back dummy dictionary entries
if (v.Key is null || v.Value is null) continue;
// NSUrlSession tries to be smart with cookies, we will not use the raw value but the ones provided by the cookie storage
if (v.Key.ToString () == SetCookie) continue;
httpResponse.Headers.TryAddWithoutValidation (v.Key.ToString (), v.Value.ToString ());
httpResponse.Content.Headers.TryAddWithoutValidation (v.Key.ToString (), v.Value.ToString ());
}
// it might be confusing that we are not using the managed CookieStore here, this is ONLY for those cookies that have been retrieved from
// the server via a Set-Cookie header, the managed container does not know a thing about this and apple is storing them in the native
// cookie container. Once we have the cookies from the response, we need to update the managed cookie container
if (session.Configuration.HttpCookieStorage is not null) {
var cookies = session.Configuration.HttpCookieStorage.CookiesForUrl (response.Url);
UpdateManagedCookieContainer (absoluteUri, cookies);
for (var index = 0; index < cookies.Length; index++) {
httpResponse.Headers.TryAddWithoutValidation (SetCookie, cookies [index].GetHeaderValue ());
}
}
inflight.Response = httpResponse;
// We don't want to send the response back to the task just yet. Because we want to mimic .NET behavior
// as much as possible. When the response is sent back in .NET, the content stream is ready to read or the
// request has completed, because of this we want to send back the response in DidReceiveData or DidCompleteWithError
if (dataTask.State == NSUrlSessionTaskState.Suspended)
dataTask.Resume ();
} catch (Exception ex) {
inflight.CompletionSource.TrySetException (ex);
inflight.Stream.TrySetException (ex);
sessionHandler.RemoveInflightData (dataTask);
}
completionHandler (NSUrlSessionResponseDisposition.Allow);
}
[Preserve (Conditional = true)]
public override void DidReceiveData (NSUrlSession session, NSUrlSessionDataTask dataTask, NSData data)
{
var inflight = GetInflightData (dataTask);
if (inflight is null)
return;
inflight.Stream.Add (data);
SetResponse (inflight);
}
[Preserve (Conditional = true)]
public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError? error)
{
var inflight = GetInflightData (task);
var serverError = task.Error;
// this can happen if the HTTP request times out and it is removed as part of the cancellation process
if (inflight is not null) {
// send the error or send the response back
if (error is not null || serverError is not null) {
// got an error, cancel the stream operatios before we do anything
inflight.CancellationTokenSource.Cancel ();
inflight.Errored = true;
var exc = inflight.Exception ?? createExceptionForNSError (error ?? serverError!); // client errors wont happen if we get server errors
inflight.CompletionSource.TrySetException (exc);
inflight.Stream.TrySetException (exc);
} else {
// set the stream as finished
inflight.Stream.TrySetReceivedAllData ();
inflight.Completed = true;
SetResponse (inflight);
}
sessionHandler.RemoveInflightData (task, cancel: false);
}
}
void SetResponse (InflightData inflight)
{
lock (inflight.Lock) {
if (inflight.ResponseSent)
return;
if (inflight.CancellationTokenSource.Token.IsCancellationRequested)
return;
if (inflight.CompletionSource.Task.IsCompleted)
return;
var httpResponse = inflight.Response;
inflight.ResponseSent = true;
// EVIL HACK: having TrySetResult inline was blocking the request from completing
Task.Run (() => inflight.CompletionSource.TrySetResult (httpResponse!));
}
}
[Preserve (Conditional = true)]
public override void WillCacheResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSCachedUrlResponse proposedResponse, Action<NSCachedUrlResponse> completionHandler)
{
var inflight = GetInflightData (dataTask);
if (inflight is null)
return;
// apple caches post request with a body, which should not happen. https://github.com/xamarin/maccore/issues/2571
var disableCache = sessionHandler.DisableCaching || (inflight.Request.Method == HttpMethod.Post && inflight.Request.Content is not null);
completionHandler (disableCache ? null! : proposedResponse);
}
[Preserve (Conditional = true)]
public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
{
completionHandler (sessionHandler.AllowAutoRedirect ? newRequest : null!);
}
[Preserve (Conditional = true)]
public override void DidReceiveChallenge (NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{