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
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace System.Net.Http
{
/// <summary>
/// Derived <see cref="HttpContent"/> class which can encapsulate an <see cref="HttpResponseMessage"/>
/// or an <see cref="HttpRequestMessage"/> as an entity with media type "application/http".
/// </summary>
public class HttpMessageContent : HttpContent
{
private const string SP = " ";
private const string CRLF = "\r\n";
private const string CommaSeparator = ", ";
private const int DefaultHeaderAllocation = 2 * 1024;
private const string DefaultMediaType = "application/http";
private const string MsgTypeParameter = "msgtype";
private const string DefaultRequestMsgType = "request";
private const string DefaultResponseMsgType = "response";
private const string DefaultRequestMediaType = DefaultMediaType + "; " + MsgTypeParameter + "=" + DefaultRequestMsgType;
private const string DefaultResponseMediaType = DefaultMediaType + "; " + MsgTypeParameter + "=" + DefaultResponseMsgType;
private static readonly Task<HttpContent> _nullContentTask = TaskHelpers.FromResult<HttpContent>(null);
private static readonly AsyncCallback _onWriteComplete = new AsyncCallback(OnWriteComplete);
/// <summary>
/// Set of header fields that only support single values such as Set-Cookie.
/// </summary>
private static readonly HashSet<string> _singleValueHeaderFields = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Set-Cookie",
"X-Powered-By",
};
private bool _contentConsumed;
private Lazy<Task<Stream>> _streamTask;
/// <summary>
/// Initializes a new instance of the <see cref="HttpMessageContent"/> class encapsulating an
/// <see cref="HttpRequestMessage"/>.
/// </summary>
/// <param name="httpRequest">The <see cref="HttpResponseMessage"/> instance to encapsulate.</param>
public HttpMessageContent(HttpRequestMessage httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
HttpRequestMessage = httpRequest;
Headers.ContentType = new MediaTypeHeaderValue(DefaultMediaType);
Headers.ContentType.Parameters.Add(new NameValueHeaderValue(MsgTypeParameter, DefaultRequestMsgType));
InitializeStreamTask();
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpMessageContent"/> class encapsulating an
/// <see cref="HttpResponseMessage"/>.
/// </summary>
/// <param name="httpResponse">The <see cref="HttpResponseMessage"/> instance to encapsulate.</param>
public HttpMessageContent(HttpResponseMessage httpResponse)
{
if (httpResponse == null)
{
throw new ArgumentNullException("httpResponse");
}
HttpResponseMessage = httpResponse;
Headers.ContentType = new MediaTypeHeaderValue(DefaultMediaType);
Headers.ContentType.Parameters.Add(new NameValueHeaderValue(MsgTypeParameter, DefaultResponseMsgType));
InitializeStreamTask();
}
private HttpContent Content
{
get { return HttpRequestMessage != null ? HttpRequestMessage.Content : HttpResponseMessage.Content; }
}
/// <summary>
/// Gets the HTTP request message.
/// </summary>
public HttpRequestMessage HttpRequestMessage { get; private set; }
/// <summary>
/// Gets the HTTP response message.
/// </summary>
public HttpResponseMessage HttpResponseMessage { get; private set; }
private void InitializeStreamTask()
{
_streamTask = new Lazy<Task<Stream>>(() => Content == null ? null : Content.ReadAsStreamAsync());
}
/// <summary>
/// Validates whether the content contains an HTTP Request or an HTTP Response.
/// </summary>
/// <param name="content">The content to validate.</param>
/// <param name="isRequest">if set to <c>true</c> if the content is either an HTTP Request or an HTTP Response.</param>
/// <param name="throwOnError">Indicates whether validation failure should result in an <see cref="Exception"/> or not.</param>
/// <returns><c>true</c> if content is either an HTTP Request or an HTTP Response</returns>
internal static bool ValidateHttpMessageContent(HttpContent content, bool isRequest, bool throwOnError)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
MediaTypeHeaderValue contentType = content.Headers.ContentType;
if (contentType != null)
{
if (!contentType.MediaType.Equals(DefaultMediaType, StringComparison.OrdinalIgnoreCase))
{
if (throwOnError)
{
throw new ArgumentException(
RS.Format(Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name,
isRequest ? DefaultRequestMediaType : DefaultResponseMediaType),
"content");
}
else
{
return false;
}
}
foreach (NameValueHeaderValue parameter in contentType.Parameters)
{
if (parameter.Name.Equals(MsgTypeParameter, StringComparison.OrdinalIgnoreCase))
{
string msgType = FormattingUtilities.UnquoteToken(parameter.Value);
if (!msgType.Equals(isRequest ? DefaultRequestMsgType : DefaultResponseMsgType, StringComparison.OrdinalIgnoreCase))
{
if (throwOnError)
{
throw new ArgumentException(
RS.Format(Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType),
"content");
}
else
{
return false;
}
}
return true;
}
}
}
if (throwOnError)
{
throw new ArgumentException(
RS.Format(Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType),
"content");
}
else
{
return false;
}
}
/// <summary>
/// Asynchronously serializes the object's content to the given <paramref name="stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to which to write.</param>
/// <param name="context">The associated <see cref="TransportContext"/>.</param>
/// <returns>A <see cref="Task"/> instance that is asynchronously serializing the object's content.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is propagated.")]
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Contract.Assert(stream != null);
// Serialize header
byte[] header = SerializeHeader();
TaskCompletionSource<object> writeTask = new TaskCompletionSource<object>();
try
{
// We don't use TaskFactory.FromAsync as it generates an FxCop CA908 error
Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>> state =
new Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>>(this, stream, writeTask);
IAsyncResult result = stream.BeginWrite(header, 0, header.Length, _onWriteComplete, state);
if (result.CompletedSynchronously)
{
WriteComplete(result, this, stream, writeTask);
}
}
catch (Exception e)
{
writeTask.TrySetException(e);
}
return writeTask.Task;
}
/// <summary>
/// Computes the length of the stream if possible.
/// </summary>
/// <param name="length">The computed length of the stream.</param>
/// <returns><c>true</c> if the length has been computed; otherwise <c>false</c>.</returns>
[SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1108:BlockStatementsMustNotContainEmbeddedComments",
Justification = "The code is more readable with such comments")]
protected override bool TryComputeLength(out long length)
{
// We have four states we could be in:
// 1. We have content, but the task is still running or finished without success
// 2. We have content, the task has finished successfully, and the stream came back as a null or non-seekable
// 3. We have content, the task has finished successfully, and the stream is seekable, so we know its length
// 4. We don't have content (streamTask.Value == null)
//
// For #1 and #2, we return false.
// For #3, we return true & the size of our headers + the content length
// For #4, we return true & the size of our headers
bool hasContent = _streamTask.Value != null;
length = 0;
// Cases #1, #2, #3
if (hasContent)
{
Stream readStream;
if (!_streamTask.Value.TryGetResult(out readStream) // Case #1
|| readStream == null || !readStream.CanSeek) // Case #2
{
length = -1;
return false;
}
length = readStream.Length; // Case #3
}
// We serialize header to a StringBuilder so that we can determine the length
// following the pattern for HttpContent to try and determine the message length.
// The perf overhead is no larger than for the other HttpContent implementations.
byte[] header = SerializeHeader();
length += header.Length;
return true;
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// If we ended up spinning up a task to get the content stream, make sure we observe any
// exceptions so that the task finalizer doesn't tear down our app domain.
if (_streamTask != null && _streamTask.IsValueCreated && _streamTask.Value != null)
{
_streamTask.Value.Catch(info => info.Handled());
_streamTask = null;
}
if (HttpRequestMessage != null)
{
HttpRequestMessage.Dispose();
HttpRequestMessage = null;
}
if (HttpResponseMessage != null)
{
HttpResponseMessage.Dispose();
HttpResponseMessage = null;
}
}
base.Dispose(disposing);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is propagated.")]
private static void OnWriteComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>> state =
(Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>>)result.AsyncState;
Contract.Assert(state != null, "state cannot be null");
try
{
WriteComplete(result, state.Item1, state.Item2, state.Item3);
}
catch (Exception e)
{
state.Item3.TrySetException(e);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is propagated.")]
private static void WriteComplete(IAsyncResult result, HttpMessageContent thisPtr, Stream stream, TaskCompletionSource<object> writeTask)
{
Contract.Assert(result != null, "result cannot be null");
Contract.Assert(thisPtr != null, "thisPtr cannot be null");
Contract.Assert(stream != null, "stream cannot be null");
Contract.Assert(writeTask != null, "writeTask cannot be null");
try
{
stream.EndWrite(result);
}
catch (Exception e)
{
writeTask.TrySetException(e);
}
thisPtr.PrepareContentAsync().Then(content =>
{
if (content != null)
{
content.CopyToAsync(stream)
.CopyResultToCompletionSource(writeTask, completionResult: null);
}
else
{
writeTask.TrySetResult(null);
}
});
}
/// <summary>
/// Serializes the HTTP request line.
/// </summary>
/// <param name="message">Where to write the request line.</param>
/// <param name="httpRequest">The HTTP request.</param>
private static void SerializeRequestLine(StringBuilder message, HttpRequestMessage httpRequest)
{
Contract.Assert(message != null, "message cannot be null");
message.Append(httpRequest.Method + SP);
message.Append(httpRequest.RequestUri.PathAndQuery + SP);
message.Append(FormattingUtilities.HttpVersionToken + "/" + (httpRequest.Version != null ? httpRequest.Version.ToString(2) : "1.1") + CRLF);
// Only insert host header if not already present.
if (httpRequest.Headers.Host == null)
{
message.Append(FormattingUtilities.HttpHostHeader + ":" + SP + httpRequest.RequestUri.Authority + CRLF);
}
}
/// <summary>
/// Serializes the HTTP status line.
/// </summary>
/// <param name="message">Where to write the status line.</param>
/// <param name="httpResponse">The HTTP response.</param>
private static void SerializeStatusLine(StringBuilder message, HttpResponseMessage httpResponse)
{
Contract.Assert(message != null, "message cannot be null");
message.Append(FormattingUtilities.HttpVersionToken + "/" + (httpResponse.Version != null ? httpResponse.Version.ToString(2) : "1.1") + SP);
message.Append((int)httpResponse.StatusCode + SP);
message.Append(httpResponse.ReasonPhrase + CRLF);
}
/// <summary>
/// Serializes the header fields.
/// </summary>
/// <param name="message">Where to write the status line.</param>
/// <param name="headers">The headers to write.</param>
private static void SerializeHeaderFields(StringBuilder message, HttpHeaders headers)
{
Contract.Assert(message != null, "message cannot be null");
if (headers != null)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
if (_singleValueHeaderFields.Contains(header.Key))
{
foreach (string value in header.Value)
{
message.Append(header.Key + ":" + SP + value + CRLF);
}
}
else
{
message.Append(header.Key + ":" + SP + String.Join(CommaSeparator, header.Value) + CRLF);
}
}
}
}
private Task<HttpContent> PrepareContentAsync()
{
if (Content == null)
{
return _nullContentTask;
}
return _streamTask.Value.Then(readStream =>
{
// If the content needs to be written to a target stream a 2nd time, then the stream must support
// seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target
// stream (e.g. a NetworkStream).
if (_contentConsumed)
{
if (readStream != null && readStream.CanRead)
{
readStream.Position = 0;
}
else
{
throw new InvalidOperationException(
RS.Format(Properties.Resources.HttpMessageContentAlreadyRead,
FormattingUtilities.HttpContentType.Name,
HttpRequestMessage != null
? FormattingUtilities.HttpRequestMessageType.Name
: FormattingUtilities.HttpResponseMessageType.Name));
}
_contentConsumed = true;
}
return Content;
});
}
private byte[] SerializeHeader()
{
StringBuilder message = new StringBuilder(DefaultHeaderAllocation);
HttpHeaders headers = null;
HttpContent content = null;
if (HttpRequestMessage != null)
{
SerializeRequestLine(message, HttpRequestMessage);
headers = HttpRequestMessage.Headers;
content = HttpRequestMessage.Content;
}
else
{
SerializeStatusLine(message, HttpResponseMessage);
headers = HttpResponseMessage.Headers;
content = HttpResponseMessage.Content;
}
SerializeHeaderFields(message, headers);
if (content != null)
{
SerializeHeaderFields(message, content.Headers);
}
message.Append(CRLF);
return Encoding.UTF8.GetBytes(message.ToString());
}
}
}
|