-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathAndroidMessageHandler.cs
1265 lines (1066 loc) · 53.3 KB
/
AndroidMessageHandler.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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
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.Text;
using System.Threading;
using System.Threading.Tasks;
using Android.OS;
using Android.Runtime;
using Java.IO;
using Java.Net;
using Java.Security;
using Java.Security.Cert;
using Javax.Net.Ssl;
namespace Xamarin.Android.Net
{
/// <summary>
/// A custom implementation of <see cref="System.Net.Http.HttpMessageHandler"/> which internally uses <see cref="Java.Net.HttpURLConnection"/>
/// (or its HTTPS incarnation) to send HTTP requests.
/// </summary>
/// <remarks>
/// <para>Instance of this class is used to configure <see cref="System.Net.Http.HttpClient"/> instance
/// in the following way:
///
/// <example>
/// var handler = new AndroidMessageHandler {
/// UseCookies = true,
/// AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
/// };
///
/// var httpClient = new HttpClient (handler);
/// var response = httpClient.GetAsync ("http://example.com")?.Result as AndroidHttpResponseMessage;
/// </example></para>
/// <para>
/// The class supports pre-authentication of requests albeit in a slightly "manual" way. Namely, whenever a request to a server requiring authentication
/// is made and no authentication credentials are provided in the <see cref="PreAuthenticationData"/> property (which is usually the case on the first
/// request), the <see cref="RequestNeedsAuthorization"/> property will return <c>true</c> and the <see cref="RequestedAuthentication"/> property will
/// contain all the authentication information gathered from the server. The application must then fill in the blanks (i.e. the credentials) and re-send
/// the request configured to perform pre-authentication. The reason for this manual process is that the underlying Java HTTP client API supports only a
/// single, VM-wide, authentication handler which cannot be configured to handle credentials for several requests. AndroidMessageHandler, therefore, implements
/// the authentication in managed .NET code. Message handler supports both Basic and Digest authentication. If an authentication scheme that's not supported
/// by AndroidMessageHandler is requested by the server, the application can provide its own authentication module (<see cref="AuthenticationData"/>,
/// <see cref="PreAuthenticationData"/>) to handle the protocol authorization.</para>
/// <para>AndroidMessageHandler also supports requests to servers with "invalid" (e.g. self-signed) SSL certificates. Since this process is a bit convoluted using
/// the Java APIs, AndroidMessageHandler defines two ways to handle the situation. First, easier, is to store the necessary certificates (either CA or server certificates)
/// in the <see cref="TrustedCerts"/> collection or, after deriving a custom class from AndroidMessageHandler, by overriding one or more methods provided for this purpose
/// (<see cref="ConfigureTrustManagerFactory"/>, <see cref="ConfigureKeyManagerFactory"/> and <see cref="ConfigureKeyStore"/>). The former method should be sufficient
/// for most use cases, the latter allows the application to provide fully customized key store, trust manager and key manager, if needed. Note that the instance of
/// AndroidMessageHandler configured to accept an "invalid" certificate from the particular server will most likely fail to validate certificates from other servers (even
/// if they use a certificate with a fully validated trust chain) unless you store the CA certificates from your Android system in <see cref="TrustedCerts"/> along with
/// the self-signed certificate(s).</para>
/// </remarks>
public class AndroidMessageHandler : HttpMessageHandler
{
sealed class RequestRedirectionState
{
public Uri? NewUrl;
public int RedirectCounter;
public HttpMethod? Method;
public bool MethodChanged;
}
/// <summary>
/// Some requests require modification to the set of headers returned from the native client.
/// However, the headers collection in it is immutable, so we need to perform the adjustments
/// in CopyHeaders. This class describes the necessary operations.
/// </summary>
sealed class ContentState
{
public bool? RemoveContentLengthHeader;
/// <summary>
/// If this is `true`, then `NewContentEncodingHeaderValue` is entirely ignored
/// </summary>
public bool? RemoveContentEncodingHeader;
/// <summary>
/// New 'Content-Encoding' header value. Ignored if not null and empty.
/// </summary>
public List<string>? NewContentEncodingHeaderValue;
/// <summary>
/// Reset the class to values that indicate there's no action to take. MUST be
/// called BEFORE any of the class members are assigned values and AFTER the state
/// modification is applied
/// </summary>
public void Reset ()
{
RemoveContentEncodingHeader = null;
RemoveContentLengthHeader = null;
NewContentEncodingHeaderValue = null;
}
}
internal const string LOG_APP = "monodroid-net";
const string GZIP_ENCODING = "gzip";
const string DEFLATE_ENCODING = "deflate";
const string BROTLI_ENCODING = "br";
const string IDENTITY_ENCODING = "identity";
const string ContentEncodingHeaderName = "Content-Encoding";
const string ContentLengthHeaderName = "Content-Length";
static readonly IDictionary<string, string> headerSeparators = new Dictionary<string, string> {
["User-Agent"] = " ",
};
static readonly HashSet <string> known_content_headers = new HashSet <string> (StringComparer.OrdinalIgnoreCase) {
"Allow",
"Content-Disposition",
ContentEncodingHeaderName,
"Content-Language",
ContentLengthHeaderName,
"Content-Location",
"Content-MD5",
"Content-Range",
"Content-Type",
"Expires",
"Last-Modified"
};
static readonly List <IAndroidAuthenticationModule> authModules = new List <IAndroidAuthenticationModule> {
new AuthModuleBasic (),
new AuthModuleDigest ()
};
CookieContainer? _cookieContainer;
DecompressionMethods _decompressionMethods;
bool disposed;
// Now all hail Java developers! Get this... HttpURLClient defaults to accepting AND
// uncompressing the gzip content encoding UNLESS you set the Accept-Encoding header to ANY
// value. So if we set it to 'gzip' below we WILL get gzipped stream but HttpURLClient will NOT
// uncompress it any longer, doh. And they don't support 'deflate' so we need to handle it ourselves.
bool decompress_here;
public bool SupportsAutomaticDecompression => true;
public bool SupportsProxy => true;
public bool SupportsRedirectConfiguration => true;
public DecompressionMethods AutomaticDecompression
{
get => _decompressionMethods;
set => _decompressionMethods = value;
}
public CookieContainer CookieContainer
{
get => _cookieContainer ?? (_cookieContainer = new CookieContainer ());
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_cookieContainer = value;
}
}
// NOTE: defaults here are based on:
// https://github.com/dotnet/runtime/blob/f3b77e64b87895aa7e697f321eb6d4151a4333df/src/libraries/Common/src/System/Net/Http/HttpHandlerDefaults.cs
public bool UseCookies { get; set; } = true;
public bool PreAuthenticate { get; set; } = false;
public bool UseProxy { get; set; } = true;
public IWebProxy? Proxy { get; set; }
public ICredentials? Credentials { get; set; }
public bool AllowAutoRedirect { get; set; } = true;
public ClientCertificateOption ClientCertificateOptions { get; set; }
public X509CertificateCollection? ClientCertificates { get; set; }
public ICredentials? DefaultProxyCredentials { get; set; }
public int MaxConnectionsPerServer { get; set; } = int.MaxValue;
public int MaxResponseHeadersLength { get; set; } = 64; // Units in K (1024) bytes.
public bool CheckCertificateRevocationList { get; set; } = false;
ServerCertificateCustomValidator? _serverCertificateCustomValidator = null;
public Func<HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool>? ServerCertificateCustomValidationCallback
{
get => _serverCertificateCustomValidator?.Callback;
set {
if (value is null) {
_serverCertificateCustomValidator = null;
} else if (_serverCertificateCustomValidator is null) {
_serverCertificateCustomValidator = new ServerCertificateCustomValidator (value);
} else {
_serverCertificateCustomValidator.Callback = value;
}
}
}
// See: https://developer.android.com/reference/javax/net/ssl/SSLSocket#protocols
public SslProtocols SslProtocols { get; set; } =
(int)Build.VERSION.SdkInt >= 29 ?
SslProtocols.Tls13 | SslProtocols.Tls12 : SslProtocols.Tls12;
public IDictionary<string, object?>? Properties { get; set; }
int maxAutomaticRedirections = 50;
public int MaxAutomaticRedirections
{
get => maxAutomaticRedirections;
set {
// https://github.com/dotnet/runtime/blob/913facdca8b04cc674163e31a7650ef6868a7d5b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs#L142-L145
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "The specified value must be greater than 0");
maxAutomaticRedirections = value;
}
}
/// <summary>
/// <para>
/// Gets or sets the pre authentication data for the request. This property must be set by the application
/// before the request is made. Generally the value can be taken from <see cref="RequestedAuthentication"/>
/// after the initial request, without any authentication data, receives the authorization request from the
/// server. The application must then store credentials in instance of <see cref="AuthenticationData"/> and
/// assign the instance to this property before retrying the request.
/// </para>
/// <para>
/// The property is never set by AndroidMessageHandler.
/// </para>
/// </summary>
/// <value>The pre authentication data.</value>
public AuthenticationData? PreAuthenticationData { get; set; }
/// <summary>
/// If the website requires authentication, this property will contain data about each scheme supported
/// by the server after the response. Note that unauthorized request will return a valid response - you
/// need to check the status code and and (re)configure AndroidMessageHandler instance accordingly by providing
/// both the credentials and the authentication scheme by setting the <see cref="PreAuthenticationData"/>
/// property. If AndroidMessageHandler is not able to detect the kind of authentication scheme it will store an
/// instance of <see cref="AuthenticationData"/> with its <see cref="AuthenticationData.Scheme"/> property
/// set to <c>AuthenticationScheme.Unsupported</c> and the application will be responsible for providing an
/// instance of <see cref="IAndroidAuthenticationModule"/> which handles this kind of authorization scheme
/// (<see cref="AuthenticationData.AuthModule"/>
/// </summary>
public IList <AuthenticationData>? RequestedAuthentication { get; private set; }
/// <summary>
/// Server authentication response indicates that the request to authorize comes from a proxy if this property is <c>true</c>.
/// All the instances of <see cref="AuthenticationData"/> stored in the <see cref="RequestedAuthentication"/> property will
/// have their <see cref="AuthenticationData.UseProxyAuthentication"/> preset to the same value as this property.
/// </summary>
public bool ProxyAuthenticationRequested { get; private set; }
/// <summary>
/// If <c>true</c> then the server requested authorization and the application must use information
/// found in <see cref="RequestedAuthentication"/> to set the value of <see cref="PreAuthenticationData"/>
/// </summary>
[MemberNotNullWhen(true, nameof(RequestedAuthentication))]
public bool RequestNeedsAuthorization {
get { return RequestedAuthentication?.Count > 0; }
}
/// <summary>
/// <para>
/// If the request is to the server protected with a self-signed (or otherwise untrusted) SSL certificate, the request will
/// fail security chain verification unless the application provides either the CA certificate of the entity which issued the
/// server's certificate or, alternatively, provides the server public key. Whichever the case, the certificate(s) must be stored
/// in this property in order for AndroidMessageHandler to configure the request to accept the server certificate.</para>
/// <para>AndroidMessageHandler uses a custom <see cref="KeyStore"/> and <see cref="TrustManagerFactory"/> to configure the connection.
/// If, however, the application requires finer control over the SSL configuration (e.g. it implements its own TrustManager) then
/// it should leave this property empty and instead derive a custom class from AndroidMessageHandler and override, as needed, the
/// <see cref="ConfigureTrustManagerFactory"/>, <see cref="ConfigureKeyManagerFactory"/> and <see cref="ConfigureKeyStore"/> methods
/// instead</para>
/// </summary>
/// <value>The trusted certs.</value>
public IList <Certificate>? TrustedCerts { get; set; }
/// <summary>
/// <para>
/// Specifies the connection read timeout.
/// </para>
/// <para>
/// Since there's no way for the handler to access <see cref="t:System.Net.Http.HttpClient.Timeout"/>
/// directly, this property should be set by the calling party to the same desired value. Value of this
/// property will be passed to the native Java HTTP client, unless it is set to <see
/// cref="t:System.TimeSpan.Zero"/>
/// </para>
/// <para>
/// The default value is <c>24</c> hours, much higher than the documented value of <see
/// cref="t:System.Net.Http.HttpClient.Timeout"/> and the same as the value of iOS-specific
/// NSUrlSessionHandler.
/// </para>
/// </summary>
public TimeSpan ReadTimeout { get; set; } = TimeSpan.FromHours (24);
/// <summary>
/// A feature switch that determines whether the message handler should attempt to authenticate the user
/// using the NTLM/Negotiate authentication method. Enable the feature by adding
/// <c><AndroidUseNegotiateAuthentication>true</AndroidUseNegotiateAuthentication></c> to your project file.
/// </summary>
static bool NegotiateAuthenticationIsEnabled =>
AppContext.TryGetSwitch ("Xamarin.Android.Net.UseNegotiateAuthentication", out bool isEnabled) && isEnabled;
/// <summary>
/// <para>
/// Specifies the connect timeout
/// </para>
/// <para>
/// The native Java client supports two separate timeouts - one for reading from the connection (<see
/// cref="ReadTimeout"/>) and another for establishing the connection. This property sets the value of
/// the latter timeout, unless it is set to <see cref="t:System.TimeSpan.Zero"/> in which case the
/// native Java client defaults are used.
/// </para>
/// <para>
/// The default value is <c>120</c> seconds.
/// </para>
/// </summary>
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromHours (24);
protected override void Dispose (bool disposing)
{
disposed = true;
base.Dispose (disposing);
}
protected void AssertSelf ()
{
if (!disposed)
return;
throw new ObjectDisposedException (nameof (AndroidMessageHandler));
}
string EncodeUrl (Uri url)
{
if (url == null)
return String.Empty;
// UriBuilder takes care of encoding everything properly
var bldr = new UriBuilder (url);
if (url.IsDefaultPort)
bldr.Port = -1; // Avoids adding :80 or :443 to the host name in the result
// bldr.Uri.ToString () would ruin the good job UriBuilder did
return bldr.ToString ();
}
/// <summary>
/// Returns a custom host name verifier for a HTTPS connection. By default it returns <c>null</c> and
/// thus the connection uses whatever host name verification mechanism the operating system defaults to.
/// Override in your class to define custom host name verification behavior. The overriding class should
/// not set the <see cref="m:HttpsURLConnection.HostnameVerifier"/> property directly on the passed
/// <paramref name="connection"/>
/// </summary>
/// <returns>Instance of IHostnameVerifier to be used for this HTTPS connection</returns>
/// <param name="connection">HTTPS connection object.</param>
protected virtual IHostnameVerifier? GetSSLHostnameVerifier (HttpsURLConnection connection)
{
return _serverCertificateCustomValidator?.HostnameVerifier;
}
internal IHostnameVerifier? GetSSLHostnameVerifierInternal (HttpsURLConnection connection)
=> GetSSLHostnameVerifier (connection);
/// <summary>
/// Creates, configures and processes an asynchronous request to the indicated resource.
/// </summary>
/// <returns>Task in which the request is executed</returns>
/// <param name="request">Request provided by <see cref="System.Net.Http.HttpClient"/></param>
/// <param name="cancellationToken">Cancellation token.</param>
protected override Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
if (NegotiateAuthenticationIsEnabled) {
return SendWithNegotiateAuthenticationAsync (request, cancellationToken);
}
return DoSendAsync (request, cancellationToken);
}
async Task <HttpResponseMessage> SendWithNegotiateAuthenticationAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await DoSendAsync (request, cancellationToken).ConfigureAwait (false);
if (RequestNeedsAuthorization && NegotiateAuthenticationHelper.RequestNeedsNegotiateAuthentication (this, request, out var requestedAuth)) {
var authenticatedResponse = await NegotiateAuthenticationHelper.SendWithAuthAsync (this, request, requestedAuth, cancellationToken).ConfigureAwait (false);
if (authenticatedResponse != null)
return authenticatedResponse;
}
return response;
}
internal async Task <HttpResponseMessage> DoSendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
{
AssertSelf ();
if (request == null)
throw new ArgumentNullException (nameof (request));
if (request.RequestUri is null || !request.RequestUri.IsAbsoluteUri)
throw new ArgumentException ("Must represent an absolute URI", "request");
var redirectState = new RequestRedirectionState {
NewUrl = request.RequestUri,
RedirectCounter = 0,
Method = request.Method
};
while (true) {
URL java_url = new URL (EncodeUrl (redirectState.NewUrl));
URLConnection? java_connection;
if (UseProxy) {
var javaProxy = await GetJavaProxy (redirectState.NewUrl, cancellationToken).ConfigureAwait (continueOnCapturedContext: false);
// When you use the parameter Java.Net.Proxy.NoProxy the system proxy is overriden. Leave the parameter out to respect the default settings.
java_connection = javaProxy == Java.Net.Proxy.NoProxy ? java_url.OpenConnection () : java_url.OpenConnection (javaProxy);
} else {
// In this case the consumer of this class has explicitly chosen to not use a proxy, so bypass the default proxy. The default value of UseProxy is true.
java_connection = java_url.OpenConnection (Java.Net.Proxy.NoProxy);
}
var httpsConnection = java_connection as HttpsURLConnection;
if (httpsConnection != null) {
IHostnameVerifier? hnv = GetSSLHostnameVerifier (httpsConnection);
if (hnv != null)
httpsConnection.HostnameVerifier = hnv;
}
if (ConnectTimeout != TimeSpan.Zero)
java_connection!.ConnectTimeout = checked ((int)ConnectTimeout.TotalMilliseconds);
if (ReadTimeout != TimeSpan.Zero)
java_connection!.ReadTimeout = checked ((int)ReadTimeout.TotalMilliseconds);
try {
HttpURLConnection httpConnection = await SetupRequestInternal (request, java_connection!).ConfigureAwait (continueOnCapturedContext: false);
HttpResponseMessage? response = await ProcessRequest (request, java_url, httpConnection, cancellationToken, redirectState).ConfigureAwait (continueOnCapturedContext: false);
if (response != null)
return response;
if (redirectState.NewUrl == null)
throw new InvalidOperationException ("Request redirected but no new URI specified");
request.Method = redirectState.Method;
request.RequestUri = redirectState.NewUrl;
} catch (Java.Net.SocketTimeoutException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new WebException (ex.Message, ex, WebExceptionStatus.Timeout, null);
} catch (Java.Net.UnknownServiceException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
} catch (Java.Lang.SecurityException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new WebException (ex.Message, ex, WebExceptionStatus.SecureChannelFailure, null);
} catch (Java.IO.IOException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new WebException (ex.Message, ex, WebExceptionStatus.UnknownError, null);
}
}
}
internal Task <HttpResponseMessage> SendAsyncInternal (HttpRequestMessage request, CancellationToken cancellationToken)
=> SendAsync (request, cancellationToken);
protected virtual async Task <Java.Net.Proxy?> GetJavaProxy (Uri destination, CancellationToken cancellationToken)
{
var proxy = Java.Net.Proxy.NoProxy;
if (destination == null || Proxy == null) {
return proxy;
}
Uri? puri = Proxy.GetProxy (destination);
if (puri == null) {
return proxy;
}
proxy = await Task <Java.Net.Proxy>.Run (() => {
// Let the Java code resolve the address, if necessary
var addr = new Java.Net.InetSocketAddress (puri.Host, puri.Port);
return new Java.Net.Proxy (Java.Net.Proxy.Type.Http, addr);
}, cancellationToken);
return proxy;
}
internal Task <Java.Net.Proxy?> GetJavaProxyInternal (Uri destination, CancellationToken cancellationToken)
=> GetJavaProxy (destination, cancellationToken);
Task <HttpResponseMessage?> ProcessRequest (HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState)
{
cancellationToken.ThrowIfCancellationRequested ();
httpConnection.InstanceFollowRedirects = false; // We handle it ourselves
RequestedAuthentication = null;
ProxyAuthenticationRequested = false;
return DoProcessRequest (request, javaUrl, httpConnection, cancellationToken, redirectState);
}
Task DisconnectAsync (HttpURLConnection httpConnection)
{
return Task.Run (() => httpConnection?.Disconnect ());
}
Task ConnectAsync (HttpURLConnection httpConnection, CancellationToken ct)
{
return Task.Run (() => {
try {
using (ct.Register(() => DisconnectAsync(httpConnection).ContinueWith(t => {
if (t.Exception != null) Logger.Log(LogLevel.Info, LOG_APP, $"Disconnection exception: {t.Exception}");
}, TaskScheduler.Default)))
httpConnection?.Connect ();
} catch (Exception ex) {
if (ct.IsCancellationRequested) {
Logger.Log (LogLevel.Info, LOG_APP, $"Exception caught while cancelling connection: {ex}");
ct.ThrowIfCancellationRequested ();
}
// All exceptions related to connectivity should be wrapped in HttpRequestException. In theory it is possible that the exception will be
// thrown for another reason above, but it's OK to wrap it in HttpRequestException anyway, since we're working in the context of
// `ConnectAsync` which, from the end user's point of view, is 100% related to connectivity.
throw new HttpRequestException ("Connection failure", ex);
}
}, ct);
}
protected virtual async Task WriteRequestContentToOutput (HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken)
{
if (request.Content is null)
return;
using (var stream = await request.Content.ReadAsStreamAsync ().ConfigureAwait (false)) {
await stream.CopyToAsync(httpConnection.OutputStream!, 4096, cancellationToken).ConfigureAwait(false);
//
// Rewind the stream to beginning in case the HttpContent implementation
// will be accessed again (e.g. after redirect) and it keeps its stream
// open behind the scenes instead of recreating it on the next call to
// ReadAsStreamAsync. If we don't rewind it, the ReadAsStreamAsync
// call above will throw an exception as we'd be attempting to read an
// already "closed" stream (that is one whose Position is set to its
// end).
//
// This is not a perfect solution since the HttpContent may do weird
// things in its implementation, but it's better than copying the
// content into a buffer since we have no way of knowing how the data is
// read or generated and also we don't want to keep potentially large
// amounts of data in memory (which would happen if we read the content
// into a byte[] buffer and kept it cached for re-use on redirect).
//
// See https://bugzilla.xamarin.com/show_bug.cgi?id=55477
//
if (stream.CanSeek)
stream.Seek (0, SeekOrigin.Begin);
}
}
internal Task WriteRequestContentToOutputInternal (HttpRequestMessage request, HttpURLConnection httpConnection, CancellationToken cancellationToken)
=> WriteRequestContentToOutput (request, httpConnection, cancellationToken);
async Task <HttpResponseMessage?> DoProcessRequest (HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState)
{
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"{this}.DoProcessRequest ()");
if (cancellationToken.IsCancellationRequested) {
if(Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, " cancelled");
cancellationToken.ThrowIfCancellationRequested ();
}
try {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $" connecting");
await ConnectAsync (httpConnection, cancellationToken).ConfigureAwait (continueOnCapturedContext: false);
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $" connected");
} catch (Java.Net.ConnectException ex) {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Connection exception {ex}");
// Wrap it nicely in a "standard" exception so that it's compatible with HttpClientHandler
throw new WebException (ex.Message, ex, WebExceptionStatus.ConnectFailure, null);
}
if (cancellationToken.IsCancellationRequested) {
if(Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, " cancelled");
await DisconnectAsync (httpConnection).ConfigureAwait (continueOnCapturedContext: false);
cancellationToken.ThrowIfCancellationRequested ();
}
CancellationTokenRegistration cancelRegistration = default (CancellationTokenRegistration);
HttpStatusCode statusCode = HttpStatusCode.OK;
Uri? connectionUri = null;
var contentState = new ContentState ();
try {
cancelRegistration = cancellationToken.Register (() => {
DisconnectAsync (httpConnection).ContinueWith (t => {
if (t.Exception != null)
Logger.Log (LogLevel.Info, LOG_APP, $"Disconnection exception: {t.Exception}");
}, TaskScheduler.Default);
}, useSynchronizationContext: false);
if (httpConnection.DoOutput)
await WriteRequestContentToOutput (request, httpConnection, cancellationToken);
statusCode = await Task.Run (() => (HttpStatusCode)httpConnection.ResponseCode, cancellationToken).ConfigureAwait (false);
connectionUri = new Uri (httpConnection.URL?.ToString ()!);
} finally {
cancelRegistration.Dispose ();
}
if (cancellationToken.IsCancellationRequested) {
await DisconnectAsync (httpConnection).ConfigureAwait (continueOnCapturedContext: false);
cancellationToken.ThrowIfCancellationRequested();
}
// If the request was redirected we need to put the new URL in the request
request.RequestUri = connectionUri;
var ret = new AndroidHttpResponseMessage (javaUrl, httpConnection) {
RequestMessage = request,
ReasonPhrase = httpConnection.ResponseMessage,
StatusCode = statusCode,
};
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Status code: {statusCode}");
if (!IsErrorStatusCode (statusCode)) {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Reading...");
ret.Content = GetContent (httpConnection, httpConnection.InputStream!, contentState);
} else {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Status code is {statusCode}, reading...");
// For 400 >= response code <= 599 the Java client throws the FileNotFound exception when attempting to read from the input stream.
// Instead we try to read the error stream and return an empty string if the error stream isn't readable.
ret.Content = GetErrorContent (httpConnection, new StringContent (String.Empty, Encoding.ASCII), contentState);
}
bool disposeRet;
if (HandleRedirect (statusCode, httpConnection, redirectState, out disposeRet)) {
if (redirectState.MethodChanged) {
// If a redirect uses GET but the original request used POST with content, then the redirected
// request will fail with an exception.
// There's also no way to send content using GET (except in the URL, of course), so discarding
// request.Content is what we should do.
//
// See https://github.com/xamarin/xamarin-android/issues/1282
if (redirectState.Method == HttpMethod.Get) {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Discarding content on redirect");
request.Content = null;
}
}
CopyHeaders (httpConnection, ret, contentState);
ParseCookies (ret, connectionUri);
if (disposeRet) {
ret.Dispose ();
ret = null!;
}
// We don't want to pass the authorization header onto the next location
request.Headers.Authorization = null;
return ret;
}
switch (statusCode) {
case HttpStatusCode.Unauthorized:
case HttpStatusCode.ProxyAuthenticationRequired:
// We don't resend the request since that would require new set of credentials if the
// ones provided in Credentials are invalid (or null) and that, in turn, may require asking the
// user which is not something that should be taken care of by us and in this
// context. The application should be responsible for this.
// HttpClientHandler throws an exception in this instance, but I think it's not a good
// idea. We'll return the response message with all the information required by the
// application to fill in the blanks and provide the requested credentials instead.
//
// We return the body of the response too, but the Java client will throw
// a FileNotFound exception if we attempt to access the input stream.
// Instead we try to read the error stream and return an default message if the error stream isn't readable.
ret.Content = GetErrorContent (httpConnection, new StringContent ("Unauthorized", Encoding.ASCII), contentState);
CopyHeaders (httpConnection, ret, contentState);
if (ret.Headers.WwwAuthenticate != null) {
ProxyAuthenticationRequested = false;
CollectAuthInfo (ret.Headers.WwwAuthenticate);
} else if (ret.Headers.ProxyAuthenticate != null) {
ProxyAuthenticationRequested = true;
CollectAuthInfo (ret.Headers.ProxyAuthenticate);
}
ret.RequestedAuthentication = RequestedAuthentication;
return ret;
}
CopyHeaders (httpConnection, ret, contentState);
ParseCookies (ret, connectionUri);
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Returning");
return ret;
}
HttpContent GetErrorContent (HttpURLConnection httpConnection, HttpContent fallbackContent, ContentState contentState)
{
var contentStream = httpConnection.ErrorStream;
if (contentStream != null) {
return GetContent (httpConnection, contentStream, contentState);
}
return fallbackContent;
}
Stream GetDecompressionWrapper (URLConnection httpConnection, Stream inputStream, ContentState contentState)
{
contentState.Reset ();
if (!decompress_here || String.IsNullOrEmpty (httpConnection.ContentEncoding)) {
return inputStream;
}
var encodings = new HashSet<string> (httpConnection.ContentEncoding.Split (','), StringComparer.OrdinalIgnoreCase);
Stream? ret = null;
string? supportedEncoding = null;
if (encodings.Contains (GZIP_ENCODING)) {
supportedEncoding = GZIP_ENCODING;
ret = new GZipStream (inputStream, CompressionMode.Decompress);
} else if (encodings.Contains (DEFLATE_ENCODING)) {
supportedEncoding = DEFLATE_ENCODING;
ret = new DeflateStream (inputStream, CompressionMode.Decompress);
} else if (encodings.Contains (BROTLI_ENCODING)) {
supportedEncoding = BROTLI_ENCODING;
ret = new BrotliStream (inputStream, CompressionMode.Decompress);
}
if (!String.IsNullOrEmpty (supportedEncoding)) {
contentState.RemoveContentLengthHeader = true;
encodings.Remove (supportedEncoding!);
if (encodings.Count == 0) {
contentState.RemoveContentEncodingHeader = true;
} else {
contentState.NewContentEncodingHeaderValue = new List<string> (encodings);
}
}
return ret ?? inputStream;
}
HttpContent GetContent (URLConnection httpConnection, Stream contentStream, ContentState contentState)
{
Stream inputStream = GetDecompressionWrapper (httpConnection, new BufferedStream (contentStream), contentState);
return new StreamContent (inputStream);
}
bool HandleRedirect (HttpStatusCode redirectCode, HttpURLConnection httpConnection, RequestRedirectionState redirectState, out bool disposeRet)
{
if (!AllowAutoRedirect) {
disposeRet = false;
return true; // We shouldn't follow and there's no data to fetch, just return
}
disposeRet = true;
redirectState.NewUrl = null;
redirectState.MethodChanged = false;
switch (redirectCode) {
case HttpStatusCode.MultipleChoices: // 300
break;
case HttpStatusCode.Moved: // 301
case HttpStatusCode.Redirect: // 302
case HttpStatusCode.SeeOther: // 303
redirectState.MethodChanged = redirectState.Method != HttpMethod.Get;
redirectState.Method = HttpMethod.Get;
break;
case HttpStatusCode.NotModified: // 304
disposeRet = false;
return true; // Not much happening here, just return and let the client decide
// what to do with the response
case HttpStatusCode.TemporaryRedirect: // 307
break;
default:
if ((int)redirectCode >= 300 && (int)redirectCode < 400)
throw new InvalidOperationException ($"HTTP Redirection status code {redirectCode} ({(int)redirectCode}) not supported");
return false;
}
var headers = httpConnection.HeaderFields;
IList <string>? locationHeader = null;
string? location = null;
if (headers?.TryGetValue ("Location", out locationHeader) == true && locationHeader != null && locationHeader.Count > 0) {
if (locationHeader.Count == 1) {
location = locationHeader [0]?.Trim ();
} else {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"More than one location header for HTTP {redirectCode} redirect. Will use the first non-empty one.");
foreach (string l in locationHeader) {
location = l?.Trim ();
if (!String.IsNullOrEmpty (location))
break;
}
}
}
if (String.IsNullOrEmpty (location)) {
// As per https://tools.ietf.org/html/rfc7231#section-6.4.1 the reponse isn't required to contain the Location header and the
// client should act accordingly. Since it is not documented what the action in this case should be, we're following what
// Xamarin.iOS does and simply return the content of the request as if it wasn't a redirect.
// It is not clear what to do if there is a Location header but its value is empty, so
// we assume the same action here.
disposeRet = false;
return true;
}
redirectState.RedirectCounter++;
if (redirectState.RedirectCounter >= MaxAutomaticRedirections)
throw new WebException ($"Maximum automatic redirections exceeded (allowed {MaxAutomaticRedirections}, redirected {redirectState.RedirectCounter} times)");
Uri redirectUrl;
try {
if (Logger.LogNet)
Logger.Log (LogLevel.Debug, LOG_APP, $"Raw redirect location: {location}");
var baseUrl = new Uri (httpConnection.URL?.ToString ()!);
if (location? [0] == '/') {
// Shortcut for the '/' and '//' cases, simplifies logic since URI won't treat
// such URLs as relative and we'd have to work around it in the `else` block
// below.
redirectUrl = new Uri (baseUrl, location);
} else {
// Special case (from https://tools.ietf.org/html/rfc3986#section-5.4.1) not
// handled by the Uri class: scheme:host
//
// This is a valid URI (should be treated as `scheme://host`) but URI throws an
// exception about DOS path being malformed IF the part before colon is just one
// character long... We could replace the scheme with the original request's one, but
// that would NOT be the right thing to do since it is not what the redirecting server
// meant. The fix doesn't belong here, but rather in the Uri class. So we'll throw...
redirectUrl = new Uri (location!, UriKind.RelativeOrAbsolute);
if (!redirectUrl.IsAbsoluteUri)
redirectUrl = new Uri (baseUrl, location);
}
if (Logger.LogNet)
Logger.Log (LogLevel.Debug, LOG_APP, $"Cooked redirect location: {redirectUrl}");
} catch (Exception ex) {
throw new WebException ($"Invalid redirect URI received: {location}", ex);
}
UriBuilder? builder = null;
if (!String.IsNullOrEmpty (httpConnection.URL?.Ref) && String.IsNullOrEmpty (redirectUrl.Fragment)) {
if (Logger.LogNet)
Logger.Log (LogLevel.Debug, LOG_APP, $"Appending fragment '{httpConnection.URL?.Ref}' to redirect URL '{redirectUrl}'");
builder = new UriBuilder (redirectUrl) {
Fragment = httpConnection.URL?.Ref
};
}
redirectState.NewUrl = builder == null ? redirectUrl : builder.Uri;
if (Logger.LogNet)
Logger.Log (LogLevel.Debug, LOG_APP, $"Request redirected to {redirectState.NewUrl}");
return true;
}
bool IsErrorStatusCode (HttpStatusCode statusCode)
{
return (int)statusCode >= 400 && (int)statusCode <= 599;
}
void CollectAuthInfo (HttpHeaderValueCollection <AuthenticationHeaderValue> headers)
{
var authData = new List <AuthenticationData> (headers.Count);
foreach (AuthenticationHeaderValue ahv in headers) {
var data = new AuthenticationData {
Scheme = GetAuthScheme (ahv.Scheme),
Challenge = $"{ahv.Scheme} {ahv.Parameter}",
UseProxyAuthentication = ProxyAuthenticationRequested
};
authData.Add (data);
}
RequestedAuthentication = authData.AsReadOnly ();
}
AuthenticationScheme GetAuthScheme (string scheme)
{
if (String.Compare ("basic", scheme, StringComparison.OrdinalIgnoreCase) == 0)
return AuthenticationScheme.Basic;
if (String.Compare ("digest", scheme, StringComparison.OrdinalIgnoreCase) == 0)
return AuthenticationScheme.Digest;
return AuthenticationScheme.Unsupported;
}
void ParseCookies (AndroidHttpResponseMessage ret, Uri connectionUri)
{
if (!UseCookies || CookieContainer == null || !ret.Headers.TryGetValues ("Set-Cookie", out var cookieHeaderValue) || cookieHeaderValue == null) {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"No cookies");
return;
}
try {
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Parsing cookies");
CookieContainer.SetCookies (connectionUri, String.Join (",", cookieHeaderValue));
} catch (Exception ex) {
// We don't want to terminate the response because of a bad cookie, hence just reporting
// the issue. We might consider adding a virtual method to let the user handle the
// issue, but not sure if it's really needed. Set-Cookie header will be part of the
// header collection so the user can always examine it if they spot an error.
if (Logger.LogNet)
Logger.Log (LogLevel.Info, LOG_APP, $"Failed to parse cookies in the server response. {ex.GetType ()}: {ex.Message}");
}
}
void CopyHeaders (HttpURLConnection httpConnection, HttpResponseMessage response, ContentState contentState)
{
var headers = httpConnection.HeaderFields;
bool removeContentLength = contentState.RemoveContentLengthHeader ?? false;
bool removeContentEncoding = contentState.RemoveContentEncodingHeader ?? false;
bool setNewContentEncodingValue = !removeContentEncoding && contentState.NewContentEncodingHeaderValue != null && contentState.NewContentEncodingHeaderValue.Count > 0;
foreach (var key in headers!.Keys) {
if (key == null) // First header entry has null key, it corresponds to the response message
continue;
HttpHeaders item_headers;
if (known_content_headers.Contains (key)) {
item_headers = response.Content.Headers;
} else {
item_headers = response.Headers;
}
IEnumerable<string> values = headers [key];
if (removeContentLength && String.Compare (ContentLengthHeaderName, key, StringComparison.OrdinalIgnoreCase) == 0) {
removeContentLength = false;
continue;
}
if ((removeContentEncoding || setNewContentEncodingValue) && String.Compare (ContentEncodingHeaderName, key, StringComparison.OrdinalIgnoreCase) == 0) {
if (removeContentEncoding) {
removeContentEncoding = false;
continue;
}
setNewContentEncodingValue = false;
values = contentState.NewContentEncodingHeaderValue!;
}
item_headers.TryAddWithoutValidation (key, values);
}
contentState.Reset ();
}
/// <summary>
/// Configure the <see cref="HttpURLConnection"/> before the request is sent. This method is meant to be overriden
/// by applications which need to perform some extra configuration steps on the connection. It is called with all
/// the request headers set, pre-authentication performed (if applicable) but before the request body is set
/// (e.g. for POST requests). The default implementation in AndroidMessageHandler does nothing.
/// </summary>
/// <param name="request">Request data</param>
/// <param name="conn">Pre-configured connection instance</param>
protected virtual Task SetupRequest (HttpRequestMessage request, HttpURLConnection conn)
{
AssertSelf ();
return Task.CompletedTask;
}
internal Task SetupRequestInternal (HttpRequestMessage request, HttpURLConnection conn)
=> SetupRequest (request, conn);
/// <summary>
/// Configures the key store. The <paramref name="keyStore"/> parameter is set to instance of <see cref="KeyStore"/>
/// created using the <see cref="KeyStore.DefaultType"/> type and with populated with certificates provided in the <see cref="TrustedCerts"/>