Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MonoWebRequestHandler.cs « System.Net.Http « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 023343f01f4468a1e736166b459fc931e8454905 (plain)
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
//
// MonoWebRequestHandler.cs
//
// Authors:
//	Marek Safar  <marek.safar@gmail.com>
//      Martin Baulig  <mabaul@microsoft.com>
//
// Copyright (C) 2011-2018 Xamarin Inc (http://www.xamarin.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.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Net.Http.Headers;
using System.Net.Cache;
using System.Net.Security;
using System.Linq;

namespace System.Net.Http
{
	class MonoWebRequestHandler : IMonoHttpClientHandler
	{
		static long groupCounter;

		bool allowAutoRedirect;
		DecompressionMethods automaticDecompression;
		CookieContainer cookieContainer;
		ICredentials credentials;
		int maxAutomaticRedirections;
		long maxRequestContentBufferSize;
		bool preAuthenticate;
		IWebProxy proxy;
		bool useCookies;
		bool useProxy;
		SslClientAuthenticationOptions sslOptions;
		bool allowPipelining;
		RequestCachePolicy cachePolicy;
		AuthenticationLevel authenticationLevel;
		TimeSpan continueTimeout;
		TokenImpersonationLevel impersonationLevel;
		int maxResponseHeadersLength;
		int readWriteTimeout;
		RemoteCertificateValidationCallback serverCertificateValidationCallback;
		bool unsafeAuthenticatedConnectionSharing;
		bool sentRequest;
		string connectionGroupName;
		TimeSpan? timeout;
		bool disposed;

		internal MonoWebRequestHandler ()
		{
			allowAutoRedirect = true;
			maxAutomaticRedirections = 50;
			maxRequestContentBufferSize = int.MaxValue;
			useCookies = true;
			useProxy = true;
			allowPipelining = true;
			authenticationLevel = AuthenticationLevel.MutualAuthRequested;
			cachePolicy = System.Net.WebRequest.DefaultCachePolicy;
			continueTimeout = TimeSpan.FromMilliseconds (350);
			impersonationLevel = TokenImpersonationLevel.Delegation;
			maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
			readWriteTimeout = 300000;
			serverCertificateValidationCallback = null;
			unsafeAuthenticatedConnectionSharing = false;
			connectionGroupName = "HttpClientHandler" + Interlocked.Increment (ref groupCounter);
		}

		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.");
		}

		public bool AllowAutoRedirect {
			get {
				return allowAutoRedirect;
			}
			set {
				EnsureModifiability ();
				allowAutoRedirect = value;
			}
		}

		public DecompressionMethods AutomaticDecompression {
			get {
				return automaticDecompression;
			}
			set {
				EnsureModifiability ();
				automaticDecompression = value;
			}
		}

		public CookieContainer CookieContainer {
			get {
				return cookieContainer ?? (cookieContainer = new CookieContainer ());
			}
			set {
				EnsureModifiability ();
				cookieContainer = value;
			}
		}

		public ICredentials Credentials {
			get {
				return credentials;
			}
			set {
				EnsureModifiability ();
				credentials = value;
			}
		}

		public int MaxAutomaticRedirections {
			get {
				return maxAutomaticRedirections;
			}
			set {
				EnsureModifiability ();
				if (value <= 0)
					throw new ArgumentOutOfRangeException ();

				maxAutomaticRedirections = value;
			}
		}

		public long MaxRequestContentBufferSize {
			get {
				return maxRequestContentBufferSize;
			}
			set {
				EnsureModifiability ();
				if (value < 0)
					throw new ArgumentOutOfRangeException ();

				maxRequestContentBufferSize = value;
			}
		}

		public bool PreAuthenticate {
			get {
				return preAuthenticate;
			}
			set {
				EnsureModifiability ();
				preAuthenticate = value;
			}
		}

		public IWebProxy Proxy {
			get {
				return proxy;
			}
			set {
				EnsureModifiability ();
				if (!UseProxy)
					throw new InvalidOperationException ();

				proxy = value;
			}
		}

		public virtual bool SupportsAutomaticDecompression {
			get {
				return true;
			}
		}

		public virtual bool SupportsProxy {
			get {
				return true;
			}
		}

		public virtual bool SupportsRedirectConfiguration {
			get {
				return true;
			}
		}

		public bool UseCookies {
			get {
				return useCookies;
			}
			set {
				EnsureModifiability ();
				useCookies = value;
			}
		}

		public bool UseProxy {
			get {
				return useProxy;
			}
			set {
				EnsureModifiability ();
				useProxy = value;
			}
		}

		public bool AllowPipelining {
			get { return allowPipelining; }
			set {
				EnsureModifiability ();
				allowPipelining = value;
			}
		}

		public RequestCachePolicy CachePolicy {
			get { return cachePolicy; }
			set {
				EnsureModifiability ();
				cachePolicy = value;
			}
		}

		public AuthenticationLevel AuthenticationLevel {
			get { return authenticationLevel; }
			set {
				EnsureModifiability ();
				authenticationLevel = value;
			}
		}

		[MonoTODO]
		public TimeSpan ContinueTimeout {
			get { return continueTimeout; }
			set {
				EnsureModifiability ();
				continueTimeout = value;
			}
		}

		public TokenImpersonationLevel ImpersonationLevel {
			get { return impersonationLevel; }
			set {
				EnsureModifiability ();
				impersonationLevel = value;
			}
		}

		public int MaxResponseHeadersLength {
			get { return maxResponseHeadersLength; }
			set {
				EnsureModifiability ();
				maxResponseHeadersLength = value;
			}
		}

		public int ReadWriteTimeout {
			get { return readWriteTimeout; }
			set {
				EnsureModifiability ();
				readWriteTimeout = value;
			}
		}

		public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
			get { return serverCertificateValidationCallback; }
			set {
				EnsureModifiability ();
				serverCertificateValidationCallback = value;
			}
		}

		public bool UnsafeAuthenticatedConnectionSharing {
			get { return unsafeAuthenticatedConnectionSharing; }
			set {
				EnsureModifiability ();
				unsafeAuthenticatedConnectionSharing = value;
			}
		}

		public SslClientAuthenticationOptions SslOptions {
			get => sslOptions ?? (sslOptions = new SslClientAuthenticationOptions ());
			set {
				EnsureModifiability ();
				sslOptions = value;
			}
		}

		public void Dispose ()
		{
			Dispose (true);
		}

		protected virtual void Dispose (bool disposing)
		{
			if (disposing && !disposed) {
				Volatile.Write (ref disposed, true);
				ServicePointManager.CloseConnectionGroup (connectionGroupName);
			}
		}

		bool GetConnectionKeepAlive (HttpRequestHeaders headers)
		{
			return headers.Connection.Any (l => string.Equals (l, "Keep-Alive", StringComparison.OrdinalIgnoreCase));
		}

		internal virtual HttpWebRequest CreateWebRequest (HttpRequestMessage request)
		{
			var wr = new HttpWebRequest (request.RequestUri);
			wr.ThrowOnError = false;
			wr.AllowWriteStreamBuffering = false;

			if (request.Version == HttpVersion.Version20)
				wr.ProtocolVersion = HttpVersion.Version11;
			else
				wr.ProtocolVersion = request.Version;

			wr.ConnectionGroupName = connectionGroupName;
			wr.Method = request.Method.Method;

			if (wr.ProtocolVersion == HttpVersion.Version10) {
				wr.KeepAlive = GetConnectionKeepAlive (request.Headers);
			} else {
				wr.KeepAlive = request.Headers.ConnectionClose != true;
			}

			if (allowAutoRedirect) {
				wr.AllowAutoRedirect = true;
				wr.MaximumAutomaticRedirections = maxAutomaticRedirections;
			} else {
				wr.AllowAutoRedirect = false;
			}

			wr.AutomaticDecompression = automaticDecompression;
			wr.PreAuthenticate = preAuthenticate;

			if (useCookies) {
				// It cannot be null or allowAutoRedirect won't work
				wr.CookieContainer = CookieContainer;
			}

			wr.Credentials = credentials;

			if (useProxy) {
				wr.Proxy = proxy;
			} else {
				// Disables default WebRequest.DefaultWebProxy value
				wr.Proxy = null;
			}

			wr.ServicePoint.Expect100Continue = request.Headers.ExpectContinue == true;

			if (timeout != null)
				wr.Timeout = (int)timeout.Value.TotalMilliseconds;

			// Add request headers
			var headers = wr.Headers;
			foreach (var header in request.Headers) {
				var values = header.Value;
				if (header.Key == "Host") {
					//
					// Host must be explicitly set for HttpWebRequest
					//
					wr.Host = request.Headers.Host;
					continue;
				}

				if (header.Key == "Transfer-Encoding") {
					//
					// Chunked Transfer-Encoding is set for HttpWebRequest later when Content length is checked
					//
					values = values.Where (l => l != "chunked");
				}

				var values_formated = PlatformHelper.GetSingleHeaderString (header.Key, values);
				if (values_formated == null)
					continue;

				headers.AddInternal (header.Key, values_formated);
			}

			return wr;
		}

		HttpResponseMessage CreateResponseMessage (HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
		{
			var response = new HttpResponseMessage (wr.StatusCode);
			response.RequestMessage = requestMessage;
			response.ReasonPhrase = wr.StatusDescription;
			response.Content = PlatformHelper.CreateStreamContent (wr.GetResponseStream (), cancellationToken);

			var headers = wr.Headers;
			for (int i = 0; i < headers.Count; ++i) {
				var key = headers.GetKey (i);
				var value = headers.GetValues (i);

				HttpHeaders item_headers;
				if (PlatformHelper.IsContentHeader (key))
					item_headers = response.Content.Headers;
				else
					item_headers = response.Headers;

				item_headers.TryAddWithoutValidation (key, value);
			}

			requestMessage.RequestUri = wr.ResponseUri;

			return response;
		}

		static bool MethodHasBody (HttpMethod method)
		{
			switch (method.Method) {
			case "HEAD":
			case "GET":
			case "MKCOL":
			case "CONNECT":
			case "TRACE":
				return false;
			default:
				return true;
			}
		}

		public async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (disposed)
				throw new ObjectDisposedException (GetType ().ToString ());

			Volatile.Write (ref sentRequest, true);
			var wrequest = CreateWebRequest (request);
			HttpWebResponse wresponse = null;

			try {
				using (cancellationToken.Register (l => ((HttpWebRequest)l).Abort (), wrequest)) {
					var content = request.Content;
					if (content != null) {
						var headers = wrequest.Headers;

						foreach (var header in content.Headers) {
							foreach (var value in header.Value) {
								headers.AddInternal (header.Key, value);
							}
						}

						if (request.Headers.TransferEncodingChunked == true) {
							wrequest.SendChunked = true;
						} else {
							//
							// Content length has to be set because HttpWebRequest is running without buffering
							//
							var contentLength = content.Headers.ContentLength;
							if (contentLength != null) {
								wrequest.ContentLength = contentLength.Value;
							} else {
								if (MaxRequestContentBufferSize == 0)
									throw new InvalidOperationException ("The content length of the request content can't be determined. Either set TransferEncodingChunked to true, load content into buffer, or set MaxRequestContentBufferSize.");

								await content.LoadIntoBufferAsync (MaxRequestContentBufferSize).ConfigureAwait (false);
								wrequest.ContentLength = content.Headers.ContentLength.Value;
							}
						}

						wrequest.ResendContentFactory = content.CopyToAsync;

						using (var stream = await wrequest.GetRequestStreamAsync ().ConfigureAwait (false)) {
							await request.Content.CopyToAsync (stream).ConfigureAwait (false);
						}
					} else if (MethodHasBody (request.Method)) {
						// Explicitly set this to make sure we're sending a "Content-Length: 0" header.
						// This fixes the issue that's been reported on the forums:
						// http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release
						wrequest.ContentLength = 0;
					}

					wresponse = (HttpWebResponse)await wrequest.GetResponseAsync ().ConfigureAwait (false);
				}
			} catch (WebException we) {
				if (we.Status != WebExceptionStatus.RequestCanceled)
					throw new HttpRequestException ("An error occurred while sending the request", we);
			} catch (System.IO.IOException ex) {
				throw new HttpRequestException ("An error occurred while sending the request", ex);
			}

			if (cancellationToken.IsCancellationRequested) {
				var cancelled = new TaskCompletionSource<HttpResponseMessage> ();
				cancelled.SetCanceled ();
				return await cancelled.Task;
			}

			return CreateResponseMessage (wresponse, request, cancellationToken);
		}

		public ICredentials DefaultProxyCredentials {
			get {
				throw new NotImplementedException ();
			}
			set {
				throw new NotImplementedException ();
			}
		}

		public int MaxConnectionsPerServer {
			get {
				throw new NotImplementedException ();
			}
			set {
				throw new NotImplementedException ();
			}
		}

		public IDictionary<string, object> Properties {
			get {
				throw new NotImplementedException ();
			}
		}

		void IMonoHttpClientHandler.SetWebRequestTimeout (TimeSpan timeout)
		{
			this.timeout = timeout;
		}
	}
}