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
|
//
// WebRequestStream.cs
//
// Author:
// Martin Baulig <mabaul@microsoft.com>
//
// Copyright (c) 2017 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.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.ExceptionServices;
using System.Net.Sockets;
namespace System.Net
{
class WebRequestStream : WebConnectionStream
{
static byte[] crlf = new byte[] { 13, 10 };
MemoryStream writeBuffer;
bool requestWritten;
bool allowBuffering;
bool sendChunked;
WebCompletionSource pendingWrite;
long totalWritten;
byte[] headers;
bool headersSent;
int completeRequestWritten;
int chunkTrailerWritten;
internal readonly string ME;
public WebRequestStream (WebConnection connection, WebOperation operation,
Stream stream, WebConnectionTunnel tunnel)
: base (connection, operation)
{
InnerStream = stream;
allowBuffering = operation.Request.InternalAllowBuffering;
sendChunked = operation.Request.SendChunked && operation.WriteBuffer == null;
if (!sendChunked && allowBuffering && operation.WriteBuffer == null)
writeBuffer = new MemoryStream ();
KeepAlive = Request.KeepAlive;
if (tunnel?.ProxyVersion != null && tunnel?.ProxyVersion != HttpVersion.Version11)
KeepAlive = false;
#if MONO_WEB_DEBUG
ME = $"WRQ(Cnc={Connection.ID}, Op={Operation.ID})";
#endif
}
internal Stream InnerStream {
get;
}
public bool KeepAlive {
get;
}
public override bool CanRead => false;
public override bool CanWrite => true;
internal bool SendChunked {
get { return sendChunked; }
set { sendChunked = value; }
}
internal bool HasWriteBuffer {
get {
return Operation.WriteBuffer != null || writeBuffer != null;
}
}
internal int WriteBufferLength {
get {
if (Operation.WriteBuffer != null)
return Operation.WriteBuffer.Size;
if (writeBuffer != null)
return (int)writeBuffer.Length;
return -1;
}
}
internal BufferOffsetSize GetWriteBuffer ()
{
if (Operation.WriteBuffer != null)
return Operation.WriteBuffer;
if (writeBuffer == null || writeBuffer.Length == 0)
return null;
var buffer = writeBuffer.GetBuffer ();
return new BufferOffsetSize (buffer, 0, (int)writeBuffer.Length, false);
}
async Task FinishWriting (CancellationToken cancellationToken)
{
if (Interlocked.CompareExchange (ref completeRequestWritten, 1, 0) != 0)
return;
WebConnection.Debug ($"{ME} FINISH WRITING: {sendChunked}");
try {
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (sendChunked)
await WriteChunkTrailer_inner (cancellationToken).ConfigureAwait (false);
} catch (Exception ex) {
Operation.CompleteRequestWritten (this, ex);
throw;
} finally {
WebConnection.Debug ($"{ME} FINISH WRITING DONE");
}
Operation.CompleteRequestWritten (this);
}
public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException (nameof (buffer));
int length = buffer.Length;
if (offset < 0 || length < offset)
throw new ArgumentOutOfRangeException (nameof (offset));
if (count < 0 || (length - offset) < count)
throw new ArgumentOutOfRangeException (nameof (count));
WebConnection.Debug ($"{ME} WRITE ASYNC: {buffer.Length}/{offset}/{count}");
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled (cancellationToken);
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (Operation.WriteBuffer != null)
throw new InvalidOperationException ();
var completion = new WebCompletionSource ();
if (Interlocked.CompareExchange (ref pendingWrite, completion, null) != null)
throw new InvalidOperationException (SR.GetString (SR.net_repcall));
return WriteAsyncInner (buffer, offset, count, completion, cancellationToken);
}
async Task WriteAsyncInner (byte[] buffer, int offset, int size,
WebCompletionSource completion,
CancellationToken cancellationToken)
{
try {
await ProcessWrite (buffer, offset, size, cancellationToken).ConfigureAwait (false);
WebConnection.Debug ($"{ME} WRITE ASYNC #1: {allowBuffering} {sendChunked} {Request.ContentLength} {totalWritten}");
if (Request.ContentLength > 0 && totalWritten == Request.ContentLength)
await FinishWriting (cancellationToken);
pendingWrite = null;
completion.TrySetCompleted ();
} catch (Exception ex) {
KillBuffer ();
closed = true;
WebConnection.Debug ($"{ME} WRITE ASYNC EX: {ex.Message}");
var oldError = Operation.CheckDisposed (cancellationToken);
if (oldError != null)
ex = oldError.SourceException;
else if (ex is SocketException)
ex = new IOException ("Error writing request", ex);
Operation.CompleteRequestWritten (this, ex);
pendingWrite = null;
completion.TrySetException (ex);
if (oldError != null)
oldError.Throw ();
throw;
}
}
async Task ProcessWrite (byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (sendChunked) {
requestWritten = true;
string cSize = String.Format ("{0:X}\r\n", size);
byte[] head = Encoding.ASCII.GetBytes (cSize);
int chunkSize = 2 + size + head.Length;
byte[] newBuffer = new byte[chunkSize];
Buffer.BlockCopy (head, 0, newBuffer, 0, head.Length);
Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
if (allowBuffering) {
if (writeBuffer == null)
writeBuffer = new MemoryStream ();
writeBuffer.Write (buffer, offset, size);
}
totalWritten += size;
buffer = newBuffer;
offset = 0;
size = chunkSize;
} else {
CheckWriteOverflow (Request.ContentLength, totalWritten, size);
if (allowBuffering) {
if (writeBuffer == null)
writeBuffer = new MemoryStream ();
writeBuffer.Write (buffer, offset, size);
totalWritten += size;
if (Request.ContentLength <= 0 || totalWritten < Request.ContentLength)
return;
requestWritten = true;
buffer = writeBuffer.GetBuffer ();
offset = 0;
size = (int)totalWritten;
} else {
totalWritten += size;
}
}
await InnerStream.WriteAsync (buffer, offset, size, cancellationToken).ConfigureAwait (false);
}
void CheckWriteOverflow (long contentLength, long totalWritten, long size)
{
if (contentLength == -1)
return;
long avail = contentLength - totalWritten;
if (size > avail) {
KillBuffer ();
closed = true;
var throwMe = new ProtocolViolationException (
"The number of bytes to be written is greater than " +
"the specified ContentLength.");
Operation.CompleteRequestWritten (this, throwMe);
throw throwMe;
}
}
internal async Task Initialize (CancellationToken cancellationToken)
{
Operation.ThrowIfClosedOrDisposed (cancellationToken);
WebConnection.Debug ($"{ME} INIT: {Operation.WriteBuffer != null}");
if (Operation.WriteBuffer != null) {
if (Operation.IsNtlmChallenge)
Request.InternalContentLength = 0;
else
Request.InternalContentLength = Operation.WriteBuffer.Size;
}
await SetHeadersAsync (false, cancellationToken).ConfigureAwait (false);
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (Operation.WriteBuffer != null && !Operation.IsNtlmChallenge) {
await WriteRequestAsync (cancellationToken);
Close ();
}
}
async Task SetHeadersAsync (bool setInternalLength, CancellationToken cancellationToken)
{
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (headersSent)
return;
string method = Request.Method;
bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE");
bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
method == "COPY" || method == "MOVE" || method == "LOCK" ||
method == "UNLOCK");
if (Operation.IsNtlmChallenge)
no_writestream = true;
if (setInternalLength && !no_writestream && HasWriteBuffer)
Request.InternalContentLength = WriteBufferLength;
bool has_content = !no_writestream && (!HasWriteBuffer || Request.ContentLength > -1);
if (!(sendChunked || has_content || no_writestream || webdav))
return;
headersSent = true;
headers = Request.GetRequestHeaders ();
WebConnection.Debug ($"{ME} SET HEADERS: {Request.ContentLength}");
try {
await InnerStream.WriteAsync (headers, 0, headers.Length, cancellationToken).ConfigureAwait (false);
var cl = Request.ContentLength;
if (!sendChunked && cl == 0)
requestWritten = true;
} catch (Exception e) {
if (e is WebException || e is OperationCanceledException)
throw;
throw new WebException ("Error writing headers", WebExceptionStatus.SendFailure, WebExceptionInternalStatus.RequestFatal, e);
}
}
internal async Task WriteRequestAsync (CancellationToken cancellationToken)
{
Operation.ThrowIfClosedOrDisposed (cancellationToken);
WebConnection.Debug ($"{ME} WRITE REQUEST: {requestWritten} {sendChunked} {allowBuffering} {HasWriteBuffer}");
if (requestWritten)
return;
requestWritten = true;
if (sendChunked || !HasWriteBuffer)
return;
BufferOffsetSize buffer = GetWriteBuffer ();
if (buffer != null && !Operation.IsNtlmChallenge && Request.ContentLength != -1 && Request.ContentLength < buffer.Size) {
closed = true;
var throwMe = new WebException ("Specified Content-Length is less than the number of bytes to write", null,
WebExceptionStatus.ServerProtocolViolation, null);
Operation.CompleteRequestWritten (this, throwMe);
throw throwMe;
}
await SetHeadersAsync (true, cancellationToken).ConfigureAwait (false);
WebConnection.Debug ($"{ME} WRITE REQUEST #1: {buffer != null}");
Operation.ThrowIfClosedOrDisposed (cancellationToken);
if (buffer != null && buffer.Size > 0)
await InnerStream.WriteAsync (buffer.Buffer, 0, buffer.Size, cancellationToken);
await FinishWriting (cancellationToken);
}
async Task WriteChunkTrailer_inner (CancellationToken cancellationToken)
{
if (Interlocked.CompareExchange (ref chunkTrailerWritten, 1, 0) != 0)
return;
Operation.ThrowIfClosedOrDisposed (cancellationToken);
byte[] chunk = Encoding.ASCII.GetBytes ("0\r\n\r\n");
await InnerStream.WriteAsync (chunk, 0, chunk.Length, cancellationToken).ConfigureAwait (false);
}
async Task WriteChunkTrailer ()
{
var cts = new CancellationTokenSource ();
try {
cts.CancelAfter (WriteTimeout);
var timeoutTask = Task.Delay (WriteTimeout, cts.Token);
while (true) {
var completion = new WebCompletionSource ();
var oldCompletion = Interlocked.CompareExchange (ref pendingWrite, completion, null);
if (oldCompletion == null)
break;
var oldWriteTask = oldCompletion.WaitForCompletion ();
var ret = await Task.WhenAny (timeoutTask, oldWriteTask).ConfigureAwait (false);
if (ret == timeoutTask)
throw new WebException ("The operation has timed out.", WebExceptionStatus.Timeout);
}
await WriteChunkTrailer_inner (cts.Token).ConfigureAwait (false);
} catch {
// Intentionally eating exceptions.
} finally {
pendingWrite = null;
cts.Cancel ();
cts.Dispose ();
}
}
internal void KillBuffer ()
{
writeBuffer = null;
}
public override Task<int> ReadAsync (byte[] buffer, int offset, int size, CancellationToken cancellationToken)
{
return Task.FromException<int> (new NotSupportedException (SR.net_writeonlystream));
}
protected override bool TryReadFromBufferedContent (byte[] buffer, int offset, int count, out int result) => throw new InvalidOperationException ();
protected override void Close_internal (ref bool disposed)
{
WebConnection.Debug ($"{ME} CLOSE: {disposed} {requestWritten} {allowBuffering}");
if (disposed)
return;
disposed = true;
if (sendChunked) {
// Don't use FinishWriting() here, we need to block on 'pendingWrite' to ensure that
// any pending WriteAsync() has been completed.
//
// FIXME: I belive .NET simply aborts if you call Close() or Dispose() while writing,
// need to check this. 2017/07/17 Martin.
WriteChunkTrailer ().Wait ();
return;
}
if (!allowBuffering || requestWritten) {
Operation.CompleteRequestWritten (this);
return;
}
long length = Request.ContentLength;
if (!sendChunked && !Operation.IsNtlmChallenge && length != -1 && totalWritten != length) {
IOException io = new IOException ("Cannot close the stream until all bytes are written");
closed = true;
disposed = true;
var throwMe = new WebException ("Request was cancelled.", WebExceptionStatus.RequestCanceled, WebExceptionInternalStatus.RequestFatal, io);
Operation.CompleteRequestWritten (this, throwMe);
throw throwMe;
}
// Commented out the next line to fix xamarin bug #1512
//WriteRequest ();
disposed = true;
Operation.CompleteRequestWritten (this);
}
}
}
|