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
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime;
using System.ServiceModel;
using System.Threading;
using System.ServiceModel.Diagnostics.Application;
// Low level abstraction for a socket/pipe
interface IConnection
{
byte[] AsyncReadBuffer { get; }
int AsyncReadBufferSize { get; }
TraceEventType ExceptionEventType { get; set; }
IPEndPoint RemoteIPEndPoint { get; }
void Abort();
void Close(TimeSpan timeout, bool asyncAndLinger);
void Shutdown(TimeSpan timeout);
AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
WaitCallback callback, object state);
void EndWrite();
void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout);
void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager);
int Read(byte[] buffer, int offset, int size, TimeSpan timeout);
AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, WaitCallback callback, object state);
int EndRead();
// very ugly listener stuff
object DuplicateAndClose(int targetProcessId);
object GetCoreTransport();
IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state);
bool EndValidate(IAsyncResult result);
}
// Low level abstraction for connecting a socket/pipe
interface IConnectionInitiator
{
IConnection Connect(Uri uri, TimeSpan timeout);
IAsyncResult BeginConnect(Uri uri, TimeSpan timeout, AsyncCallback callback, object state);
IConnection EndConnect(IAsyncResult result);
}
// Low level abstraction for listening for sockets/pipes
interface IConnectionListener : IDisposable
{
void Listen();
IAsyncResult BeginAccept(AsyncCallback callback, object state);
IConnection EndAccept(IAsyncResult result);
}
abstract class DelegatingConnection : IConnection
{
IConnection connection;
protected DelegatingConnection(IConnection connection)
{
this.connection = connection;
}
public virtual byte[] AsyncReadBuffer
{
get { return connection.AsyncReadBuffer; }
}
public virtual int AsyncReadBufferSize
{
get { return connection.AsyncReadBufferSize; }
}
public TraceEventType ExceptionEventType
{
get { return connection.ExceptionEventType; }
set { connection.ExceptionEventType = value; }
}
protected IConnection Connection
{
get { return connection; }
}
public IPEndPoint RemoteIPEndPoint
{
get { return connection.RemoteIPEndPoint; }
}
public virtual void Abort()
{
connection.Abort();
}
public virtual void Close(TimeSpan timeout, bool asyncAndLinger)
{
connection.Close(timeout, asyncAndLinger);
}
public virtual void Shutdown(TimeSpan timeout)
{
connection.Shutdown(timeout);
}
public virtual object DuplicateAndClose(int targetProcessId)
{
return connection.DuplicateAndClose(targetProcessId);
}
public virtual object GetCoreTransport()
{
return connection.GetCoreTransport();
}
public virtual IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state)
{
return connection.BeginValidate(uri, callback, state);
}
public virtual bool EndValidate(IAsyncResult result)
{
return connection.EndValidate(result);
}
public virtual AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
WaitCallback callback, object state)
{
return connection.BeginWrite(buffer, offset, size, immediate, timeout, callback, state);
}
public virtual void EndWrite()
{
connection.EndWrite();
}
public virtual void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
{
connection.Write(buffer, offset, size, immediate, timeout);
}
public virtual void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
{
connection.Write(buffer, offset, size, immediate, timeout, bufferManager);
}
public virtual int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
return connection.Read(buffer, offset, size, timeout);
}
public virtual AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout,
WaitCallback callback, object state)
{
return connection.BeginRead(offset, size, timeout, callback, state);
}
public virtual int EndRead()
{
return connection.EndRead();
}
}
class PreReadConnection : DelegatingConnection
{
int asyncBytesRead;
byte[] preReadData;
int preReadOffset;
int preReadCount;
public PreReadConnection(IConnection innerConnection, byte[] initialData)
: this(innerConnection, initialData, 0, initialData.Length)
{
}
public PreReadConnection(IConnection innerConnection, byte[] initialData, int initialOffset, int initialSize)
: base(innerConnection)
{
this.preReadData = initialData;
this.preReadOffset = initialOffset;
this.preReadCount = initialSize;
}
public void AddPreReadData(byte[] initialData, int initialOffset, int initialSize)
{
if (this.preReadCount > 0)
{
byte[] tempBuffer = this.preReadData;
this.preReadData = DiagnosticUtility.Utility.AllocateByteArray(initialSize + this.preReadCount);
Buffer.BlockCopy(tempBuffer, this.preReadOffset, this.preReadData, 0, this.preReadCount);
Buffer.BlockCopy(initialData, initialOffset, this.preReadData, this.preReadCount, initialSize);
this.preReadOffset = 0;
this.preReadCount += initialSize;
}
else
{
this.preReadData = initialData;
this.preReadOffset = initialOffset;
this.preReadCount = initialSize;
}
}
public override int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);
if (this.preReadCount > 0)
{
int bytesToCopy = Math.Min(size, this.preReadCount);
Buffer.BlockCopy(this.preReadData, this.preReadOffset, buffer, offset, bytesToCopy);
this.preReadOffset += bytesToCopy;
this.preReadCount -= bytesToCopy;
return bytesToCopy;
}
return base.Read(buffer, offset, size, timeout);
}
public override AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, WaitCallback callback, object state)
{
ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size);
if (this.preReadCount > 0)
{
int bytesToCopy = Math.Min(size, this.preReadCount);
Buffer.BlockCopy(this.preReadData, this.preReadOffset, AsyncReadBuffer, offset, bytesToCopy);
this.preReadOffset += bytesToCopy;
this.preReadCount -= bytesToCopy;
this.asyncBytesRead = bytesToCopy;
return AsyncCompletionResult.Completed;
}
return base.BeginRead(offset, size, timeout, callback, state);
}
public override int EndRead()
{
if (this.asyncBytesRead > 0)
{
int retValue = this.asyncBytesRead;
this.asyncBytesRead = 0;
return retValue;
}
return base.EndRead();
}
}
class ConnectionStream : Stream
{
TimeSpan closeTimeout;
int readTimeout;
int writeTimeout;
IConnection connection;
bool immediate;
public ConnectionStream(IConnection connection, IDefaultCommunicationTimeouts defaultTimeouts)
{
this.connection = connection;
this.closeTimeout = defaultTimeouts.CloseTimeout;
this.ReadTimeout = TimeoutHelper.ToMilliseconds(defaultTimeouts.ReceiveTimeout);
this.WriteTimeout = TimeoutHelper.ToMilliseconds(defaultTimeouts.SendTimeout);
immediate = true;
}
public IConnection Connection
{
get { return connection; }
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public TimeSpan CloseTimeout
{
get { return closeTimeout; }
set { this.closeTimeout = value; }
}
public override int ReadTimeout
{
get { return this.readTimeout; }
set
{
if (value < -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeInRange, -1, int.MaxValue)));
}
this.readTimeout = value;
}
}
public override int WriteTimeout
{
get { return this.writeTimeout; }
set
{
if (value < -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeInRange, -1, int.MaxValue)));
}
this.writeTimeout = value;
}
}
public bool Immediate
{
get { return immediate; }
set { immediate = value; }
}
public override long Length
{
get
{
#pragma warning suppress 56503 // [....], required by the Stream.Length contract
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
}
public override long Position
{
get
{
#pragma warning suppress 56503 // [....], required by the Stream.Position contract
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
set
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
}
public TraceEventType ExceptionEventType
{
get { return connection.ExceptionEventType; }
set { connection.ExceptionEventType = value; }
}
public void Abort()
{
connection.Abort();
}
public override void Close()
{
connection.Close(this.CloseTimeout, false);
}
public override void Flush()
{
// NOP
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return new WriteAsyncResult(this.connection, buffer, offset, count, this.Immediate, TimeoutHelper.FromMilliseconds(this.WriteTimeout), callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
WriteAsyncResult.End(asyncResult);
}
public override void Write(byte[] buffer, int offset, int count)
{
connection.Write(buffer, offset, count, this.Immediate, TimeoutHelper.FromMilliseconds(this.WriteTimeout));
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return new ReadAsyncResult(connection, buffer, offset, count, TimeoutHelper.FromMilliseconds(this.ReadTimeout), callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
return ReadAsyncResult.End(asyncResult);
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.Read(buffer, offset, count, TimeoutHelper.FromMilliseconds(this.ReadTimeout));
}
protected int Read(byte[] buffer, int offset, int count, TimeSpan timeout)
{
return connection.Read(buffer, offset, count, timeout);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
public override void SetLength(long value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
public void Shutdown(TimeSpan timeout)
{
connection.Shutdown(timeout);
}
public IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state)
{
return this.connection.BeginValidate(uri, callback, state);
}
public bool EndValidate(IAsyncResult result)
{
return this.connection.EndValidate(result);
}
abstract class IOAsyncResult : AsyncResult
{
static WaitCallback onAsyncIOComplete;
IConnection connection;
protected IOAsyncResult(IConnection connection, AsyncCallback callback, object state)
: base(callback, state)
{
this.connection = connection;
}
protected WaitCallback GetWaitCompletion()
{
if (onAsyncIOComplete == null)
{
onAsyncIOComplete = new WaitCallback(OnAsyncIOComplete);
}
return onAsyncIOComplete;
}
protected abstract void HandleIO(IConnection connection);
static void OnAsyncIOComplete(object state)
{
IOAsyncResult thisPtr = (IOAsyncResult)state;
Exception completionException = null;
try
{
thisPtr.HandleIO(thisPtr.connection);
}
#pragma warning suppress 56500 // [....], transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completionException = e;
}
thisPtr.Complete(false, completionException);
}
}
sealed class ReadAsyncResult : IOAsyncResult
{
int bytesRead;
byte[] buffer;
int offset;
public ReadAsyncResult(IConnection connection, byte[] buffer, int offset, int count, TimeSpan timeout,
AsyncCallback callback, object state)
: base(connection, callback, state)
{
this.buffer = buffer;
this.offset = offset;
AsyncCompletionResult readResult = connection.BeginRead(0, Math.Min(count, connection.AsyncReadBufferSize),
timeout, GetWaitCompletion(), this);
if (readResult == AsyncCompletionResult.Completed)
{
HandleIO(connection);
base.Complete(true);
}
}
protected override void HandleIO(IConnection connection)
{
bytesRead = connection.EndRead();
Buffer.BlockCopy(connection.AsyncReadBuffer, 0, buffer, offset, bytesRead);
}
public static int End(IAsyncResult result)
{
ReadAsyncResult thisPtr = AsyncResult.End<ReadAsyncResult>(result);
return thisPtr.bytesRead;
}
}
sealed class WriteAsyncResult : IOAsyncResult
{
public WriteAsyncResult(IConnection connection, byte[] buffer, int offset, int count, bool immediate, TimeSpan timeout, AsyncCallback callback, object state)
: base(connection, callback, state)
{
AsyncCompletionResult writeResult = connection.BeginWrite(buffer, offset, count, immediate, timeout, GetWaitCompletion(), this);
if (writeResult == AsyncCompletionResult.Completed)
{
HandleIO(connection);
base.Complete(true);
}
}
protected override void HandleIO(IConnection connection)
{
connection.EndWrite();
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteAsyncResult>(result);
}
}
}
class StreamConnection : IConnection
{
byte[] asyncReadBuffer;
int bytesRead;
ConnectionStream innerStream;
AsyncCallback onRead;
AsyncCallback onWrite;
IAsyncResult readResult;
IAsyncResult writeResult;
WaitCallback readCallback;
WaitCallback writeCallback;
Stream stream;
public StreamConnection(Stream stream, ConnectionStream innerStream)
{
Fx.Assert(stream != null, "StreamConnection: Stream cannot be null.");
Fx.Assert(innerStream != null, "StreamConnection: Inner stream cannot be null.");
this.stream = stream;
this.innerStream = innerStream;
onRead = Fx.ThunkCallback(new AsyncCallback(OnRead));
onWrite = Fx.ThunkCallback(new AsyncCallback(OnWrite));
}
public byte[] AsyncReadBuffer
{
get
{
if (this.asyncReadBuffer == null)
{
lock (ThisLock)
{
if (this.asyncReadBuffer == null)
{
this.asyncReadBuffer = DiagnosticUtility.Utility.AllocateByteArray(innerStream.Connection.AsyncReadBufferSize);
}
}
}
return this.asyncReadBuffer;
}
}
public int AsyncReadBufferSize
{
get { return innerStream.Connection.AsyncReadBufferSize; }
}
public Stream Stream
{
get { return this.stream; }
}
public object ThisLock
{
get { return this; }
}
public TraceEventType ExceptionEventType
{
get { return innerStream.ExceptionEventType; }
set { innerStream.ExceptionEventType = value; }
}
public IPEndPoint RemoteIPEndPoint
{
get
{
#pragma warning suppress 56503 // Not publicly accessible and this should never be called.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
public void Abort()
{
innerStream.Abort();
}
Exception ConvertIOException(IOException ioException)
{
if (ioException.InnerException is TimeoutException)
{
return new TimeoutException(ioException.InnerException.Message, ioException);
}
else if (ioException.InnerException is CommunicationObjectAbortedException)
{
return new CommunicationObjectAbortedException(ioException.InnerException.Message, ioException);
}
else if (ioException.InnerException is CommunicationException)
{
return new CommunicationException(ioException.InnerException.Message, ioException);
}
else
{
return new CommunicationException(SR.GetString(SR.StreamError), ioException);
}
}
public void Close(TimeSpan timeout, bool asyncAndLinger)
{
innerStream.CloseTimeout = timeout;
try
{
stream.Close();
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public void Shutdown(TimeSpan timeout)
{
innerStream.Shutdown(timeout);
}
public object DuplicateAndClose(int targetProcessId)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public virtual object GetCoreTransport()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state)
{
return this.innerStream.BeginValidate(uri, callback, state);
}
public bool EndValidate(IAsyncResult result)
{
return this.innerStream.EndValidate(result);
}
public AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout,
WaitCallback callback, object state)
{
if (callback == null)
{
Fx.AssertAndThrow("Cannot call BeginWrite without a callback");
}
if (this.writeCallback != null)
{
Fx.AssertAndThrow("BeginWrite cannot be called twice");
}
this.writeCallback = callback;
bool throwing = true;
try
{
innerStream.Immediate = immediate;
SetWriteTimeout(timeout);
IAsyncResult localResult = stream.BeginWrite(buffer, offset, size, this.onWrite, state);
if (!localResult.CompletedSynchronously)
{
throwing = false;
return AsyncCompletionResult.Queued;
}
throwing = false;
stream.EndWrite(localResult);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
finally
{
if (throwing)
{
this.writeCallback = null;
}
}
return AsyncCompletionResult.Completed;
}
public void EndWrite()
{
IAsyncResult localResult = this.writeResult;
this.writeResult = null;
this.writeCallback = null;
if (localResult != null)
{
try
{
stream.EndWrite(localResult);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
}
void OnWrite(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
if (this.writeResult != null)
{
throw Fx.AssertAndThrow("StreamConnection: OnWrite called twice.");
}
this.writeResult = result;
this.writeCallback(result.AsyncState);
}
public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
{
try
{
innerStream.Immediate = immediate;
SetWriteTimeout(timeout);
stream.Write(buffer, offset, size);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager)
{
Write(buffer, offset, size, immediate, timeout);
bufferManager.ReturnBuffer(buffer);
}
void SetReadTimeout(TimeSpan timeout)
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
if (stream.CanTimeout)
{
stream.ReadTimeout = timeoutInMilliseconds;
}
innerStream.ReadTimeout = timeoutInMilliseconds;
}
void SetWriteTimeout(TimeSpan timeout)
{
int timeoutInMilliseconds = TimeoutHelper.ToMilliseconds(timeout);
if (stream.CanTimeout)
{
stream.WriteTimeout = timeoutInMilliseconds;
}
innerStream.WriteTimeout = timeoutInMilliseconds;
}
public int Read(byte[] buffer, int offset, int size, TimeSpan timeout)
{
try
{
SetReadTimeout(timeout);
return stream.Read(buffer, offset, size);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
public AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, WaitCallback callback, object state)
{
ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size);
readCallback = callback;
try
{
SetReadTimeout(timeout);
IAsyncResult localResult = stream.BeginRead(AsyncReadBuffer, offset, size, onRead, state);
if (!localResult.CompletedSynchronously)
{
return AsyncCompletionResult.Queued;
}
bytesRead = stream.EndRead(localResult);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
return AsyncCompletionResult.Completed;
}
public int EndRead()
{
IAsyncResult localResult = this.readResult;
this.readResult = null;
if (localResult != null)
{
try
{
bytesRead = stream.EndRead(localResult);
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertIOException(ioException));
}
}
return bytesRead;
}
void OnRead(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
if (this.readResult != null)
{
throw Fx.AssertAndThrow("StreamConnection: OnRead called twice.");
}
this.readResult = result;
readCallback(result.AsyncState);
}
}
class ConnectionMessageProperty
{
IConnection connection;
public ConnectionMessageProperty(IConnection connection)
{
this.connection = connection;
}
public static string Name
{
get { return "iconnection"; }
}
public IConnection Connection
{
get { return this.connection; }
}
}
static class ConnectionUtilities
{
internal static void CloseNoThrow(IConnection connection, TimeSpan timeout)
{
bool success = false;
try
{
connection.Close(timeout, false);
success = true;
}
catch (TimeoutException e)
{
if (TD.CloseTimeoutIsEnabled())
{
TD.CloseTimeout(e.Message);
}
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
catch (CommunicationException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
finally
{
if (!success)
{
connection.Abort();
}
}
}
internal static void ValidateBufferBounds(ArraySegment<byte> buffer)
{
ValidateBufferBounds(buffer.Array, buffer.Offset, buffer.Count);
}
internal static void ValidateBufferBounds(byte[] buffer, int offset, int size)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
}
ValidateBufferBounds(buffer.Length, offset, size);
}
internal static void ValidateBufferBounds(int bufferSize, int offset, int size)
{
if (offset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.GetString(
SR.ValueMustBeNonNegative)));
}
if (offset > bufferSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset, SR.GetString(
SR.OffsetExceedsBufferSize, bufferSize)));
}
if (size <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.GetString(
SR.ValueMustBePositive)));
}
int remainingBufferSpace = bufferSize - offset;
if (size > remainingBufferSpace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size, SR.GetString(
SR.SizeExceedsRemainingBufferSpace, remainingBufferSpace)));
}
}
}
}
|