public override byte[] TakeBuffer(int bufferSize) { InternalBufferManager.PooledBufferManager.BufferPool bufferPool = this.FindPool(bufferSize); if (bufferPool == null) { if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace)) { TraceCore.BufferPoolAllocation(Fx.Trace, bufferSize); } return(Fx.AllocateByteArray(bufferSize)); } byte[] array = bufferPool.Take(); if (array != null) { bufferPool.DecrementCount(); return(array); } if (bufferPool.Peak == bufferPool.Limit) { bufferPool.Misses++; if (++this.totalMisses >= 8) { this.TuneQuotas(); } } if (TraceCore.BufferPoolAllocationIsEnabled(Fx.Trace)) { TraceCore.BufferPoolAllocation(Fx.Trace, bufferPool.BufferSize); } return(Fx.AllocateByteArray(bufferPool.BufferSize)); }
private ArraySegment <byte> CreatePreamble() { EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri); EncodedContentType encodedContentType = EncodedContentType.Create(this.MessageEncoder.ContentType); // calculate preamble length int startSize = ClientDuplexEncoder.ModeBytes.Length + SessionEncoder.CalcStartSize(encodedVia, encodedContentType); int preambleEndOffset = 0; if (_upgrade == null) { preambleEndOffset = startSize; startSize += ClientDuplexEncoder.PreambleEndBytes.Length; } byte[] startBytes = Fx.AllocateByteArray(startSize); Buffer.BlockCopy(ClientDuplexEncoder.ModeBytes, 0, startBytes, 0, ClientDuplexEncoder.ModeBytes.Length); SessionEncoder.EncodeStart(startBytes, ClientDuplexEncoder.ModeBytes.Length, encodedVia, encodedContentType); if (preambleEndOffset > 0) { Buffer.BlockCopy(ClientDuplexEncoder.PreambleEndBytes, 0, startBytes, preambleEndOffset, ClientDuplexEncoder.PreambleEndBytes.Length); } return(new ArraySegment <byte>(startBytes, 0, startSize)); }
public int Decode(byte[] buffer, int offset, int size) { DecoderHelper.ValidateSize(size); int bytesConsumed; switch (_currentState) { case State.ReadingSize: bytesConsumed = _sizeDecoder.Decode(buffer, offset, size); if (_sizeDecoder.IsValueDecoded) { _encodedSize = _sizeDecoder.Value; if (_encodedSize > _sizeQuota) { Exception quotaExceeded = OnSizeQuotaExceeded(_encodedSize); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(quotaExceeded); } if (_encodedBytes == null || _encodedBytes.Length < _encodedSize) { _encodedBytes = Fx.AllocateByteArray(_encodedSize); _value = null; } _currentState = State.ReadingBytes; _bytesNeeded = _encodedSize; } break; case State.ReadingBytes: if (_value != null && _valueLengthInBytes == _encodedSize && _bytesNeeded == _encodedSize && size >= _encodedSize && CompareBuffers(_encodedBytes, buffer, offset)) { bytesConsumed = _bytesNeeded; OnComplete(_value); } else { bytesConsumed = _bytesNeeded; if (size < _bytesNeeded) { bytesConsumed = size; } Buffer.BlockCopy(buffer, offset, _encodedBytes, _encodedSize - _bytesNeeded, bytesConsumed); _bytesNeeded -= bytesConsumed; if (_bytesNeeded == 0) { _value = Encoding.UTF8.GetString(_encodedBytes, 0, _encodedSize); _valueLengthInBytes = _encodedSize; OnComplete(_value); } } break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.InvalidDecoderStateMachine)); } return(bytesConsumed); }
public override byte[] TakeBuffer(int bufferSize) { InternalBufferManager.PooledBufferManager.BufferPool pool = this.FindPool(bufferSize); byte[] numArray1; if (pool != null) { byte[] numArray2 = pool.Take(); if (numArray2 != null) { pool.DecrementCount(); numArray1 = numArray2; } else { if (pool.Peak == pool.Limit) { ++pool.Misses; if (++this.totalMisses >= 8) { this.TuneQuotas(); } } numArray1 = Fx.AllocateByteArray(pool.BufferSize); } } else { numArray1 = Fx.AllocateByteArray(bufferSize); } return(numArray1); }
internal static byte[] SpliceBuffers(byte[] middle, byte[] wrapper, int wrapperLength, int wrappingDepth) { const byte openChar = (byte)'<'; int openCharsFound = 0; int openCharIndex; for (openCharIndex = wrapperLength - 1; openCharIndex >= 0; openCharIndex--) { if (wrapper[openCharIndex] == openChar) { openCharsFound++; if (openCharsFound == wrappingDepth) { break; } } } Fx.Assert(openCharIndex > 0, ""); byte[] splicedBuffer = Fx.AllocateByteArray(checked (middle.Length + wrapperLength - 1)); int offset = 0; int count = openCharIndex - 1; Buffer.BlockCopy(wrapper, 0, splicedBuffer, offset, count); offset += count; count = middle.Length; Buffer.BlockCopy(middle, 0, splicedBuffer, offset, count); offset += count; count = wrapperLength - openCharIndex; Buffer.BlockCopy(wrapper, openCharIndex, splicedBuffer, offset, count); return(splicedBuffer); }
internal static byte[] GenerateIVAndEncrypt(SymmetricAlgorithm algorithm, byte[] plainText, int offset, int count) { GenerateIVAndEncrypt(algorithm, new ArraySegment <byte>(plainText, offset, count), out byte[] iv, out byte[] cipherText); byte[] output = Fx.AllocateByteArray(checked (iv.Length + cipherText.Length)); Buffer.BlockCopy(iv, 0, output, 0, iv.Length); Buffer.BlockCopy(cipherText, 0, output, iv.Length, cipherText.Length); return(output); }
protected override SocketAsyncEventArgs Create() { SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs(); byte[] acceptBuffer = Fx.AllocateByteArray(acceptBufferSize); eventArgs.SetBuffer(acceptBuffer, 0, acceptBufferSize); return(eventArgs); }
public Message Receive(TimeSpan timeout) { Message message = GetPendingMessage(); if (message != null) { return(message); } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (; ;) { if (_isAtEOF) { return(null); } if (_size > 0) { message = DecodeMessage(timeoutHelper.RemainingTime()); if (message != null) { PrepareMessage(message); return(message); } else if (_isAtEOF) // could have read the END record under DecodeMessage { return(null); } } if (_size != 0) { throw new Exception("Receive: DecodeMessage() should consume the outstanding buffer or return a message."); } if (_buffer == null) { _buffer = Fx.AllocateByteArray(_connection.AsyncReadBufferSize); } int bytesRead; if (EnvelopeBuffer != null && (EnvelopeSize - EnvelopeOffset) >= _buffer.Length) { bytesRead = _connection.Read(EnvelopeBuffer, EnvelopeOffset, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, true); } else { bytesRead = _connection.Read(_buffer, 0, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, false); } } }
internal static byte[] CloneBuffer(byte[] buffer, int offset, int len) { DiagnosticUtility.DebugAssert(offset >= 0, "Negative offset passed to CloneBuffer."); DiagnosticUtility.DebugAssert(len >= 0, "Negative len passed to CloneBuffer."); DiagnosticUtility.DebugAssert(buffer.Length - offset >= len, "Invalid parameters to CloneBuffer."); byte[] copy = Fx.AllocateByteArray(len); Buffer.BlockCopy(buffer, offset, copy, 0, len); return(copy); }
public byte[] GetEntropy() { byte[] result = null; if (this.entropy != null) { result = Fx.AllocateByteArray(this.entropy.Length); Buffer.BlockCopy(this.entropy, 0, result, 0, this.entropy.Length); } return(result); }
protected override async Task OnCloseAsync(CancellationToken token) { lock (ThisLock) { if (isClosed) { return; } isClosed = true; } bool success = false; try { // first drain our stream if necessary if (_inputStream != null) { byte[] dummy = Fx.AllocateByteArray(_connection.ConnectionBufferSize); while (!_connection.EOF) { int bytesRead = await _inputStream.ReadAsync(dummy, 0, dummy.Length, token); if (bytesRead == 0) { _connection.EOF = true; } } } // send back EOF and then recycle the connection await _connection.Output.WriteAsync(SingletonEncoder.EndBytes, token); await _connection.Output.FlushAsync(token); // TODO: connection reuse //this.connectionDemuxer.ReuseConnection(this.rawConnection, timeoutHelper.RemainingTime()); // TODO: ChannelBinding //ChannelBindingUtility.Dispose(ref this.channelBindingToken); success = true; } finally { _tcs.TrySetResult(null); if (!success) { Abort(); } } }
private void WriteLater(byte[] buffer, int offset, int size, TimeSpan timeout) { lock (ThisLock) { bool setTimer = (_pendingWriteSize == 0); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); while (size > 0) { if (size >= _writeBufferSize && _pendingWriteSize == 0) { Connection.Write(buffer, offset, size, false, timeoutHelper.RemainingTime()); size = 0; } else { if (_writeBuffer == null) { _writeBuffer = Fx.AllocateByteArray(_writeBufferSize); } int remainingSize = _writeBufferSize - _pendingWriteSize; int copySize = size; if (copySize > remainingSize) { copySize = remainingSize; } Buffer.BlockCopy(buffer, offset, _writeBuffer, _pendingWriteSize, copySize); _pendingWriteSize += copySize; if (_pendingWriteSize == _writeBufferSize) { FlushCore(timeoutHelper.RemainingTime()); setTimer = true; } size -= copySize; offset += copySize; } } if (_pendingWriteSize > 0) { if (setTimer) { SetFlushTimer(); _pendingTimeout = TimeoutHelper.Add(_pendingTimeout, timeoutHelper.RemainingTime()); } } else { CancelFlushTimer(); } } }
internal void SetAuthenticator(byte[] authenticator) { if (authenticator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authenticator)); } if (this.IsReadOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ObjectIsReadOnly)); } this.authenticator = Fx.AllocateByteArray(authenticator.Length); Buffer.BlockCopy(authenticator, 0, this.authenticator, 0, authenticator.Length); }
internal EncodedFramingRecord(FramingRecordType recordType, string value) { int valueByteCount = Encoding.UTF8.GetByteCount(value); int sizeByteCount = IntEncoder.GetEncodedSize(valueByteCount); _encodedBytes = Fx.AllocateByteArray(checked (1 + sizeByteCount + valueByteCount)); _encodedBytes[0] = (byte)recordType; int offset = 1; offset += IntEncoder.Encode(valueByteCount, _encodedBytes, offset); Encoding.UTF8.GetBytes(value, 0, value.Length, _encodedBytes, offset); SetEncodedBytes(_encodedBytes); }
public DataProtectionSecurityStateEncoder(bool useCurrentUserProtectionScope, byte[] entropy) { this.useCurrentUserProtectionScope = useCurrentUserProtectionScope; if (entropy == null) { this.entropy = null; } else { this.entropy = Fx.AllocateByteArray(entropy.Length); Buffer.BlockCopy(entropy, 0, this.entropy, 0, entropy.Length); } }
internal byte[] GetAuthenticator() { if (this._isReceiver) { return(this._standardsManager.TrustDriver.GetAuthenticator(this)); } if (this._authenticator == null) { return((byte[])null); } byte[] numArray = Fx.AllocateByteArray(this._authenticator.Length); Buffer.BlockCopy((Array)this._authenticator, 0, (Array)numArray, 0, this._authenticator.Length); return(numArray); }
internal static string GetResponseStreamExcerptString(Stream responseStream, ref int bytesToRead) { long bufferSize = bytesToRead; if (bufferSize < 0 || bufferSize > ResponseStreamExcerptSize) { bufferSize = ResponseStreamExcerptSize; } byte[] responseBuffer = Fx.AllocateByteArray(checked ((int)bufferSize)); bytesToRead = responseStream.Read(responseBuffer, 0, (int)bufferSize); responseStream.Dispose(); return(Encoding.UTF8.GetString(responseBuffer, 0, bytesToRead)); }
// assume arguments are already validated public ManagedPsha1(byte[] secret, byte[] label, byte[] seed) { _secret = secret; _seed = Fx.AllocateByteArray(checked (label.Length + seed.Length)); label.CopyTo(_seed, 0); seed.CopyTo(_seed, label.Length); _aValue = _seed; _chunk = Array.Empty <byte>(); _index = 0; _position = 0; _hmac = CryptoHelper.NewHmacSha1KeyedHashAlgorithm(secret); _buffer = Fx.AllocateByteArray(checked (_hmac.HashSize / 8 + _seed.Length)); }
public void AddPreReadData(byte[] initialData, int initialOffset, int initialSize) { if (preReadCount > 0) { byte[] tempBuffer = preReadData ?? base.Connection.AsyncReadBuffer; preReadData = Fx.AllocateByteArray(initialSize + preReadCount); Buffer.BlockCopy(tempBuffer, preReadOffset, preReadData, 0, preReadCount); Buffer.BlockCopy(initialData, initialOffset, preReadData, preReadCount, initialSize); preReadOffset = 0; preReadCount += initialSize; } else { preReadData = initialData; preReadOffset = initialOffset; preReadCount = initialSize; } }
public void AddPreReadData(byte[] initialData, int initialOffset, int initialSize) { if (_preReadCount > 0) { byte[] tempBuffer = _preReadData; _preReadData = Fx.AllocateByteArray(initialSize + _preReadCount); Buffer.BlockCopy(tempBuffer, _preReadOffset, _preReadData, 0, _preReadCount); Buffer.BlockCopy(initialData, initialOffset, _preReadData, _preReadCount, initialSize); _preReadOffset = 0; _preReadCount += initialSize; } else { _preReadData = initialData; _preReadOffset = initialOffset; _preReadCount = initialSize; } }
public void Close(TimeSpan timeout) { lock (ThisLock) { if (_isClosed) { return; } _isClosed = true; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); bool success = false; try { // first drain our stream if necessary if (_inputStream != null) { byte[] dummy = Fx.AllocateByteArray(_transportSettings.ConnectionBufferSize); while (!_isAtEof) { _inputStream.ReadTimeout = TimeoutHelper.ToMilliseconds(timeoutHelper.RemainingTime()); int bytesRead = _inputStream.Read(dummy, 0, dummy.Length); if (bytesRead == 0) { _isAtEof = true; } } } OnClose(timeoutHelper.RemainingTime()); success = true; } finally { if (!success) { this.Abort(); } } }
public async Task CloseAsync(CancellationToken token) { lock (ThisLock) { if (isClosed) { return; } isClosed = true; } bool success = false; try { // first drain our stream if necessary if (inputStream != null) { byte[] dummy = Fx.AllocateByteArray(transportSettings.ConnectionBufferSize); while (!isAtEof) { int bytesRead = await inputStream.ReadAsync(dummy, 0, dummy.Length, token); if (bytesRead == 0) { isAtEof = true; } } } await OnCloseAsync(token); success = true; } finally { if (!success) { Abort(); } } }
internal byte[] GetAuthenticator() { if (IsReceiver) { return(_standardsManager.TrustDriver.GetAuthenticator(this)); } else { if (_authenticator == null) { return(null); } else { byte[] result = Fx.AllocateByteArray(_authenticator.Length); Buffer.BlockCopy(_authenticator, 0, result, 0, _authenticator.Length); return(result); } } }
public static async Task DecodeFramingFaultAsync(ClientFramingDecoder decoder, IConnection connection, Uri via, string contentType, TimeoutHelper timeoutHelper) { ValidateReadingFaultString(decoder); int offset = 0; byte[] faultBuffer = Fx.AllocateByteArray(FaultStringDecoder.FaultSizeQuota); int size = await connection.ReadAsync(0, Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize), timeoutHelper.RemainingTime()); while (size > 0) { int bytesDecoded = decoder.Decode(connection.AsyncReadBuffer, offset, size); offset += bytesDecoded; size -= bytesDecoded; if (decoder.CurrentState == ClientFramingDecoderState.Fault) { ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType)); } else { if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString) { throw Fx.AssertAndThrow("invalid framing client state machine"); } if (size == 0) { offset = 0; size = await connection.ReadAsync(0, Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize), timeoutHelper.RemainingTime()); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException()); }
public override AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action <object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size); if (preReadCount > 0) { int bytesToCopy = Math.Min(size, preReadCount); if (preReadData == null) { if (offset != preReadOffset) { preReadData = Fx.AllocateByteArray(preReadCount); Buffer.BlockCopy(base.Connection.AsyncReadBuffer, preReadOffset, preReadData, 0, preReadCount); preReadOffset = 0; Buffer.BlockCopy(preReadData, 0, base.Connection.AsyncReadBuffer, offset, bytesToCopy); preReadOffset += bytesToCopy; preReadCount -= bytesToCopy; asyncBytesRead = bytesToCopy; return(AsyncCompletionResult.Completed); } // Requested offset and preReadOffset are the same so no copy needed preReadOffset += bytesToCopy; preReadCount -= bytesToCopy; asyncBytesRead = bytesToCopy; return(AsyncCompletionResult.Completed); } Buffer.BlockCopy(preReadData, preReadOffset, AsyncReadBuffer, offset, bytesToCopy); preReadOffset += bytesToCopy; preReadCount -= bytesToCopy; asyncBytesRead = bytesToCopy; return(AsyncCompletionResult.Completed); } return(base.BeginRead(offset, size, timeout, callback, state)); }
protected override void OnOpened() { // setup our preamble which we'll use for all connections we establish EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri); EncodedContentType encodedContentType = EncodedContentType.Create(_settings.MessageEncoderFactory.Encoder.ContentType); int startSize = ClientSingletonEncoder.ModeBytes.Length + ClientSingletonEncoder.CalcStartSize(encodedVia, encodedContentType); int preambleEndOffset = 0; if (_upgrade == null) { preambleEndOffset = startSize; startSize += ClientDuplexEncoder.PreambleEndBytes.Length; } _startBytes = Fx.AllocateByteArray(startSize); Buffer.BlockCopy(ClientSingletonEncoder.ModeBytes, 0, _startBytes, 0, ClientSingletonEncoder.ModeBytes.Length); ClientSingletonEncoder.EncodeStart(_startBytes, ClientSingletonEncoder.ModeBytes.Length, encodedVia, encodedContentType); if (preambleEndOffset > 0) { Buffer.BlockCopy(ClientSingletonEncoder.PreambleEndBytes, 0, _startBytes, preambleEndOffset, ClientSingletonEncoder.PreambleEndBytes.Length); } // and then transition to the Opened state base.OnOpened(); }
internal byte[] AllocateByteArray(int size) { return(Fx.AllocateByteArray(size)); }
protected override async Task OnCloseAsync(CancellationToken token) { lock (ThisLock) { if (_isClosed) { return; } _isClosed = true; } bool success = false; try { // first drain our stream if necessary if (_inputStream != null) { byte[] dummy = Fx.AllocateByteArray(_connection.ConnectionBufferSize); while (!_connection.EOF) { int bytesRead = await _inputStream.ReadAsync(dummy, 0, dummy.Length, token); if (bytesRead == 0) { _connection.EOF = true; } } } // send back EOF and then recycle the connection _connection.RawStream?.StartUnwrapRead(); try { await _connection.Output.WriteAsync(SingletonEncoder.EndBytes, token); await _connection.Output.FlushAsync(token); } finally { if (_connection.RawStream != null) { await _connection.RawStream.FinishUnwrapReadAsync(); _connection.RawStream = null; _connection.Output.Complete(); _connection.Input.Complete(); } } // TODO: ChannelBinding //ChannelBindingUtility.Dispose(ref this.channelBindingToken); success = true; } finally { _tcs.TrySetResult(null); if (!success) { Abort(); } } }
internal static byte[] CloneBuffer(byte[] buffer) { byte[] copy = Fx.AllocateByteArray(buffer.Length); Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length); return(copy); }
public override byte[] TakeBuffer(int bufferSize) { return(Fx.AllocateByteArray(bufferSize)); }