public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, AsyncCallback callback, object state)
 {
     ThreadTrace.Trace("BC:BeginWrite");
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.Flush(helper.RemainingTime());
     return base.BeginWrite(buffer, offset, size, immediate, helper.RemainingTime(), callback, state);
 }
 public static void DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection, Uri via, string contentType, ref TimeoutHelper timeoutHelper)
 {
     ValidateReadingFaultString(decoder);
     int offset = 0;
     byte[] buffer = DiagnosticUtility.Utility.AllocateByteArray(0x100);
     int size = connection.Read(buffer, offset, buffer.Length, timeoutHelper.RemainingTime());
     while (size > 0)
     {
         int num3 = decoder.Decode(buffer, offset, size);
         offset += num3;
         size -= num3;
         if (decoder.CurrentState == ClientFramingDecoderState.Fault)
         {
             ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime());
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType));
         }
         if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString)
         {
             throw Fx.AssertAndThrow("invalid framing client state machine");
         }
         if (size == 0)
         {
             offset = 0;
             size = connection.Read(buffer, offset, buffer.Length, timeoutHelper.RemainingTime());
         }
     }
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
 }
 public override void Reply(Message message, TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     Message message2 = message;
     if (message != null)
     {
         CorrelationCallbackMessageProperty property;
         this.contextProtocol.OnOutgoingMessage(message, this);
         if (CorrelationCallbackMessageProperty.TryGet(message, out property))
         {
             ContextExchangeCorrelationHelper.AddOutgoingCorrelationCallbackData(property, message, false);
             if (property.IsFullyDefined)
             {
                 message2 = property.FinalizeCorrelation(message, helper.RemainingTime());
                 message2.Properties.Remove(CorrelationCallbackMessageProperty.Name);
             }
         }
     }
     try
     {
         this.innerContext.Reply(message2, helper.RemainingTime());
     }
     finally
     {
         if ((message != null) && !object.ReferenceEquals(message, message2))
         {
             message2.Close();
         }
     }
 }
 protected override SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout)
 {
     SecurityProtocolFactory protocolFactoryForOutgoingMessages = this.ProtocolFactoryForOutgoingMessages;
     SecurityProtocolFactory protocolFactoryForIncomingMessages = this.ProtocolFactoryForIncomingMessages;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     SecurityProtocol outgoingProtocol = (protocolFactoryForOutgoingMessages == null) ? null : protocolFactoryForOutgoingMessages.CreateSecurityProtocol(target, via, listenerSecurityState, false, helper.RemainingTime());
     return new DuplexSecurityProtocol(outgoingProtocol, (protocolFactoryForIncomingMessages == null) ? null : protocolFactoryForIncomingMessages.CreateSecurityProtocol(null, null, listenerSecurityState, false, helper.RemainingTime()));
 }
 protected override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
     base.OnClose(timeoutHelper.RemainingTime());
     if (this.transportManagerContainer != null && !TransferTransportManagers())
     {
         this.transportManagerContainer.Close(timeoutHelper.RemainingTime());
     }
 }
 protected override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     base.Connection.Write(SingletonEncoder.EndBytes, 0, SingletonEncoder.EndBytes.Length, true, helper.RemainingTime());
     this.connectionDemuxer.ReuseConnection(this.rawConnection, helper.RemainingTime());
     if (this.channelBindingToken != null)
     {
         this.channelBindingToken.Dispose();
     }
 }
 public override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.forwardProtocolFactory != null)
     {
         this.forwardProtocolFactory.Close(false, helper.RemainingTime());
     }
     if (this.reverseProtocolFactory != null)
     {
         this.reverseProtocolFactory.Close(false, helper.RemainingTime());
     }
 }
 protected override Message OnRequest(Message request, TimeSpan timeout, bool last)
 {
     RequestContext context;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     base.Binder.Send(request, helper.RemainingTime(), MaskingMode.None);
     TimeSpan receiveTimeout = this.GetReceiveTimeout(helper.RemainingTime());
     base.Binder.TryReceive(receiveTimeout, out context, MaskingMode.None);
     if (context == null)
     {
         return null;
     }
     return context.RequestMessage;
 }
 public virtual void Abandon(Exception exception, TimeSpan timeout)
 {
     this.EnsureValidTimeout(timeout);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.WaitForStateLock(helper.RemainingTime());
     try
     {
         if (this.PreAbandon())
         {
             return;
         }
     }
     finally
     {
         this.ReleaseStateLock();
     }
     bool flag = false;
     try
     {
         if (exception == null)
         {
             this.OnAbandon(helper.RemainingTime());
         }
         else
         {
             if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
             {
                 TD.ReceiveContextAbandonWithException(base.GetType().ToString(), exception.GetType().ToString());
             }
             this.OnAbandon(exception, helper.RemainingTime());
         }
         lock (this.ThisLock)
         {
             this.ThrowIfFaulted();
             this.ThrowIfNotAbandoning();
             this.State = ReceiveContextState.Abandoned;
         }
         flag = true;
     }
     finally
     {
         if (!flag)
         {
             if (TD.ReceiveContextAbandonFailedIsEnabled())
             {
                 TD.ReceiveContextAbandonFailed(base.GetType().ToString());
             }
             this.Fault();
         }
     }
 }
 protected override IAsyncResult BeginSecureOutgoingMessageAtInitiatorCore(Message message, string actor, TimeSpan timeout, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     this.GetTokensForOutgoingMessages(out token, out token2, out parameters);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (!base.TryGetSupportingTokens(base.SecurityProtocolFactory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         return new SecureOutgoingMessageAsyncResult(actor, message, this, token, token2, parameters, helper.RemainingTime(), callback, state);
     }
     this.SetupDelayedSecurityExecution(actor, ref message, token, token2, parameters, list);
     return new CompletedAsyncResult<Message>(message, callback, state);
 }
        public void Open(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            if (this.securityProtocolFactory != null)
            {
                this.securityProtocolFactory.Open(false, timeoutHelper.RemainingTime());
            }
            if (this.sessionMode && this.sessionSettings != null)
            {
                this.sessionSettings.Open(timeoutHelper.RemainingTime());
            } 

            this.innerListener.Open(timeoutHelper.RemainingTime());

            this.SetBufferManager();        
        }
        public override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            base.OnOpen(timeoutHelper.RemainingTime());
            if (this.Factory.ActAsInitiator)
            {
                // 1. Create a token requirement for the provider
                InitiatorServiceModelSecurityTokenRequirement tokenProviderRequirement = CreateInitiatorTokenRequirement();

                // 2. Create a provider
                SecurityTokenProvider tokenProvider = this.Factory.SecurityTokenManager.CreateSecurityTokenProvider(tokenProviderRequirement);
                SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                if (this.Factory.SecurityTokenParameters.HasAsymmetricKey)
                {
                    this.initiatorAsymmetricTokenProvider = tokenProvider;
                }
                else
                {
                    this.initiatorSymmetricTokenProvider = tokenProvider;
                }

                // 3. Create a token requirement for authenticator
                InitiatorServiceModelSecurityTokenRequirement tokenAuthenticatorRequirement = CreateInitiatorTokenRequirement();

                // 4. Create authenticator (we dont support out of band resolvers on the client side
                SecurityTokenResolver outOfBandTokenResolver;
                this.initiatorTokenAuthenticator = this.Factory.SecurityTokenManager.CreateSecurityTokenAuthenticator(tokenAuthenticatorRequirement, out outOfBandTokenResolver);
                SecurityUtils.OpenTokenAuthenticatorIfRequired(this.initiatorTokenAuthenticator, timeoutHelper.RemainingTime());
            }
        }
        public OpenCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection)
            : base(otherCallback, state)
        {
            _timeoutHelper = new TimeoutHelper(timeout);
            _completedSynchronously = true;

            _count = collection.Count;
            if (_count == 0)
            {
                Complete(true);
                return;
            }

            for (int index = 0; index < collection.Count; index++)
            {
                // Throw exception if there was a failure calling EndOpen in the callback (skips remaining items)
                if (_exception != null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_exception);
                CallbackState callbackState = new CallbackState(this, collection[index]);
                IAsyncResult result = collection[index].BeginOpen(_timeoutHelper.RemainingTime(), s_nestedCallback, callbackState);
                if (result.CompletedSynchronously)
                {
                    collection[index].EndOpen(result);
                    Decrement(true);
                }
            }
        }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityToken token2;
     SecurityToken token3;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     this.GetTokensForOutgoingMessages(out token, out token2, out token3, out parameters);
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (base.TryGetSupportingTokens(this.Factory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         SecurityProtocolCorrelationState state2 = this.CreateCorrelationStateIfRequired();
         this.SetUpDelayedSecurityExecution(ref message, token, token2, token3, parameters, list, state2);
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     return new SecureOutgoingMessageAsyncResult(message, this, token, token2, token3, parameters, helper.RemainingTime(), callback, state);
 }
 public static bool InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, ref IConnection connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, ref TimeoutHelper timeoutHelper)
 {
     for (string str = upgradeInitiator.GetNextUpgrade(); str != null; str = upgradeInitiator.GetNextUpgrade())
     {
         EncodedUpgrade upgrade = new EncodedUpgrade(str);
         connection.Write(upgrade.EncodedBytes, 0, upgrade.EncodedBytes.Length, true, timeoutHelper.RemainingTime());
         byte[] buffer = new byte[1];
         int count = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime());
         if (!ValidateUpgradeResponse(buffer, count, decoder))
         {
             return false;
         }
         ConnectionStream stream = new ConnectionStream(connection, defaultTimeouts);
         Stream stream2 = upgradeInitiator.InitiateUpgrade(stream);
         connection = new StreamConnection(stream2, stream);
     }
     return true;
 }
 public override void OnOpen(TimeSpan timeout)
 {
     if ((this.ForwardProtocolFactory != null) && object.ReferenceEquals(this.ForwardProtocolFactory, this.ReverseProtocolFactory))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ReverseProtocolFactory", System.ServiceModel.SR.GetString("SameProtocolFactoryCannotBeSetForBothDuplexDirections"));
     }
     if (this.forwardProtocolFactory != null)
     {
         this.forwardProtocolFactory.ListenUri = base.ListenUri;
     }
     if (this.reverseProtocolFactory != null)
     {
         this.reverseProtocolFactory.ListenUri = base.ListenUri;
     }
     TimeoutHelper helper = new TimeoutHelper(timeout);
     this.Open(this.ForwardProtocolFactory, base.ActAsInitiator, "ForwardProtocolFactory", helper.RemainingTime());
     this.Open(this.ReverseProtocolFactory, !base.ActAsInitiator, "ReverseProtocolFactory", helper.RemainingTime());
 }
 public IConnection Connect(Uri uri, TimeSpan timeout)
 {
     if (DiagnosticUtility.ShouldTraceInformation)
     {
         TraceUtility.TraceEvent(TraceEventType.Information, 0x4002b, System.ServiceModel.SR.GetString("TraceCodeInitiatingTcpConnection"), new StringTraceRecord("Uri", uri.ToString()), this, null);
     }
     int port = uri.Port;
     IPAddress[] iPAddresses = GetIPAddresses(uri);
     Socket socket = null;
     SocketException innerException = null;
     if (port == -1)
     {
         port = 0x328;
     }
     int invalidAddressCount = 0;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     for (int i = 0; i < iPAddresses.Length; i++)
     {
         if (helper.RemainingTime() == TimeSpan.Zero)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateTimeoutException(uri, helper.OriginalTimeout, iPAddresses, invalidAddressCount, innerException));
         }
         AddressFamily addressFamily = iPAddresses[i].AddressFamily;
         if ((addressFamily == AddressFamily.InterNetworkV6) && !Socket.OSSupportsIPv6)
         {
             iPAddresses[i] = null;
         }
         else
         {
             DateTime utcNow = DateTime.UtcNow;
             try
             {
                 socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
                 socket.Connect(new IPEndPoint(iPAddresses[i], port));
                 innerException = null;
                 break;
             }
             catch (SocketException exception2)
             {
                 invalidAddressCount++;
                 TraceConnectFailure(socket, exception2, uri, (TimeSpan) (DateTime.UtcNow - utcNow));
                 innerException = exception2;
                 socket.Close();
             }
         }
     }
     if (socket == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(System.ServiceModel.SR.GetString("NoIPEndpointsFoundForHost", new object[] { uri.Host })));
     }
     if (innerException != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertConnectException(innerException, uri, helper.ElapsedTime(), innerException));
     }
     return this.CreateConnection(socket);
 }
 public override void OnClose(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.serverTokenProvider != null)
     {
         System.ServiceModel.Security.SecurityUtils.CloseTokenProviderIfRequired(this.serverTokenProvider, helper.RemainingTime());
         this.serverTokenProvider = null;
     }
     if (this.clientTokenAuthenticator != null)
     {
         System.ServiceModel.Security.SecurityUtils.CloseTokenAuthenticatorIfRequired(this.clientTokenAuthenticator, helper.RemainingTime());
         this.clientTokenAuthenticator = null;
     }
     if (this.serverToken != null)
     {
         this.serverToken = null;
     }
     base.OnClose(helper.RemainingTime());
 }
 protected override IAsyncResult BeginSecureOutgoingMessageCore(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState, AsyncCallback callback, object state)
 {
     SecurityToken token;
     SecurityTokenParameters parameters;
     IList<SupportingTokenSpecification> list;
     SecurityToken token2;
     SecurityProtocolCorrelationState state2;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (this.TryGetTokenSynchronouslyForOutgoingSecurity(message, correlationState, false, helper.RemainingTime(), out token, out parameters, out token2, out list, out state2))
     {
         this.SetUpDelayedSecurityExecution(ref message, token2, token, parameters, list, base.GetSignatureConfirmationCorrelationState(correlationState, state2));
         return new CompletedAsyncResult<Message, SecurityProtocolCorrelationState>(message, state2, callback, state);
     }
     if (!this.Factory.ActAsInitiator)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("ProtocolMustBeInitiator", new object[] { base.GetType().ToString() })));
     }
     return new SecureOutgoingMessageAsyncResult(message, this, this.GetTokenProvider(), this.Factory.ApplyConfidentiality, this.initiatorTokenAuthenticator, correlationState, helper.RemainingTime(), callback, state);
 }
        public virtual void Abandon(Exception exception, TimeSpan timeout)
        {
            EnsureValidTimeout(timeout);
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.WaitForStateLock(timeoutHelper.RemainingTime());

            try
            {
                if (PreAbandon())
                {
                    return;
                }
            }
            finally
            {
                // Abandon can never be reverted, release the state lock.
                this.ReleaseStateLock();
            }

            bool success = false;
            try
            {
                if (exception == null)
                {
                    OnAbandon(timeoutHelper.RemainingTime());
                }
                else
                {
                    if (TD.ReceiveContextAbandonWithExceptionIsEnabled())
                    {
                        TD.ReceiveContextAbandonWithException(this.eventTraceActivity, this.GetType().ToString(), exception.GetType().ToString());
                    }
                    OnAbandon(exception, timeoutHelper.RemainingTime());
                }
                lock (ThisLock)
                {
                    ThrowIfFaulted();
                    ThrowIfNotAbandoning();
                    this.State = ReceiveContextState.Abandoned;
                }
                success = true;
            }
            finally
            {
                if (!success)
                {
                    if (TD.ReceiveContextAbandonFailedIsEnabled())
                    {
                        TD.ReceiveContextAbandonFailed(this.eventTraceActivity, this.GetType().ToString());
                    }
                    Fault();
                }
            }

        }
 protected virtual IAsyncResult BeginSecureOutgoingMessageAtInitiatorCore(Message message, string actor, TimeSpan timeout, AsyncCallback callback, object state)
 {
     IList<SupportingTokenSpecification> list;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     if (base.TryGetSupportingTokens(base.SecurityProtocolFactory, base.Target, base.Via, message, helper.RemainingTime(), false, out list))
     {
         this.SetUpDelayedSecurityExecution(ref message, actor, list);
         return new CompletedAsyncResult<Message>(message, callback, state);
     }
     return new SecureOutgoingMessageAsyncResult(actor, message, this, timeout, callback, state);
 }
 public static void WriteMessage(Message message, IConnection connection, bool isRequest, IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper)
 {
     byte[] envelopeEndFramingEndBytes = null;
     if (message != null)
     {
         bool flag;
         MessageEncoder encoder = settings.MessageEncoderFactory.Encoder;
         byte[] envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;
         if (isRequest)
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndFramingEndBytes;
             flag = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
         }
         else
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndBytes;
             flag = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
         }
         if (flag)
         {
             connection.Write(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());
             Stream stream = new StreamingOutputConnectionStream(connection, settings);
             Stream stream2 = new TimeoutStream(stream, ref timeoutHelper);
             encoder.WriteMessage(message, stream2);
         }
         else
         {
             ArraySegment<byte> segment = SingletonEncoder.EncodeMessageFrame(encoder.WriteMessage(message, 0x7fffffff, settings.BufferManager, envelopeStartBytes.Length + 5));
             Buffer.BlockCopy(envelopeStartBytes, 0, segment.Array, segment.Offset - envelopeStartBytes.Length, envelopeStartBytes.Length);
             connection.Write(segment.Array, segment.Offset - envelopeStartBytes.Length, segment.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
         }
     }
     else if (isRequest)
     {
         envelopeEndFramingEndBytes = SingletonEncoder.EndBytes;
     }
     if (envelopeEndFramingEndBytes != null)
     {
         connection.Write(envelopeEndFramingEndBytes, 0, envelopeEndFramingEndBytes.Length, true, timeoutHelper.RemainingTime());
     }
 }
 public IConnection Connect(Uri remoteUri, TimeSpan timeout)
 {
     string str;
     BackoffTimeoutHelper helper;
     TimeoutHelper helper2 = new TimeoutHelper(timeout);
     this.PrepareConnect(remoteUri, helper2.RemainingTime(), out str, out helper);
     IConnection connection = null;
     while (connection == null)
     {
         connection = this.TryConnect(remoteUri, str, helper);
         if (connection == null)
         {
             helper.WaitAndBackoff();
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 TraceUtility.TraceEvent(TraceEventType.Information, 0x40031, System.ServiceModel.SR.GetString("TraceCodeFailedPipeConnect", new object[] { helper2.RemainingTime(), remoteUri }));
             }
         }
     }
     return connection;
 }
 private void CloseInitiate(TimeSpan timeout)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     foreach (InstanceContext context in this.ToArray())
     {
         try
         {
             if (context.State == CommunicationState.Opened)
             {
                 IAsyncResult result = context.BeginClose(helper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(InstanceContextManager.CloseInstanceContextCallback)), context);
                 if (result.CompletedSynchronously)
                 {
                     context.EndClose(result);
                 }
             }
             else
             {
                 context.Abort();
             }
         }
         catch (ObjectDisposedException exception)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
             }
         }
         catch (InvalidOperationException exception2)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information);
             }
         }
         catch (CommunicationException exception3)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information);
             }
         }
         catch (TimeoutException exception4)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Information);
             }
         }
     }
 }
 public void Close(TimeSpan timeout)
 {
     lock (this.ThisLock)
     {
         if (this.isClosed)
         {
             return;
         }
         this.isClosed = true;
     }
     TimeoutHelper helper = new TimeoutHelper(timeout);
     bool flag = false;
     try
     {
         if (this.inputStream != null)
         {
             byte[] buffer = DiagnosticUtility.Utility.AllocateByteArray(this.transportSettings.ConnectionBufferSize);
             while (!this.isAtEof)
             {
                 this.inputStream.ReadTimeout = TimeoutHelper.ToMilliseconds(helper.RemainingTime());
                 if (this.inputStream.Read(buffer, 0, buffer.Length) == 0)
                 {
                     this.isAtEof = true;
                 }
             }
         }
         this.OnClose(helper.RemainingTime());
         flag = true;
     }
     finally
     {
         if (!flag)
         {
             this.Abort();
         }
     }
 }
 protected override void VerifyIncomingMessageCore(ref Message message, TimeSpan timeout)
 {
     string actor = string.Empty;
     ReceiveSecurityHeader securityHeader = this.Factory.StandardsManager.CreateReceiveSecurityHeader(message, actor, this.Factory.IncomingAlgorithmSuite, MessageDirection.Input);
     securityHeader.RequireMessageProtection = false;
     securityHeader.ReaderQuotas = this.Factory.SecurityBindingElement.ReaderQuotas;
     IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = base.GetSupportingTokenAuthenticatorsAndSetExpectationFlags(this.Factory, message, securityHeader);
     ReadOnlyCollection<SecurityTokenResolver> outOfBandResolvers = base.MergeOutOfBandResolvers(supportingAuthenticators, this.sessionTokenResolverList);
     if ((supportingAuthenticators != null) && (supportingAuthenticators.Count > 0))
     {
         supportingAuthenticators = new List<SupportingTokenAuthenticatorSpecification>(supportingAuthenticators);
         supportingAuthenticators.Insert(0, this.sessionTokenAuthenticatorSpecificationList[0]);
     }
     else
     {
         supportingAuthenticators = this.sessionTokenAuthenticatorSpecificationList;
     }
     securityHeader.ConfigureTransportBindingServerReceiveHeader(supportingAuthenticators);
     securityHeader.ConfigureOutOfBandTokenResolver(outOfBandResolvers);
     securityHeader.ExpectEndorsingTokens = true;
     TimeoutHelper helper = new TimeoutHelper(timeout);
     securityHeader.SetTimeParameters(this.Factory.NonceCache, this.Factory.ReplayWindow, this.Factory.MaxClockSkew);
     securityHeader.EnforceDerivedKeyRequirement = message.Headers.Action != this.Factory.StandardsManager.SecureConversationDriver.CloseAction.Value;
     securityHeader.Process(helper.RemainingTime(), System.ServiceModel.Security.SecurityUtils.GetChannelBindingFromMessage(message), this.Factory.ExtendedProtectionPolicy);
     if (securityHeader.Timestamp == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString("RequiredTimestampMissingInSecurityHeader")));
     }
     bool flag = false;
     if (securityHeader.EndorsingSupportingTokens != null)
     {
         for (int i = 0; i < securityHeader.EndorsingSupportingTokens.Count; i++)
         {
             SecurityContextSecurityToken token = securityHeader.EndorsingSupportingTokens[i] as SecurityContextSecurityToken;
             if ((token != null) && (token.ContextId == this.sessionId))
             {
                 flag = true;
                 break;
             }
         }
     }
     if (!flag)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(System.ServiceModel.SR.GetString("NoSessionTokenPresentInMessage")));
     }
     message = securityHeader.ProcessedMessage;
     base.AttachRecipientSecurityProperty(message, securityHeader.BasicSupportingTokens, securityHeader.EndorsingSupportingTokens, securityHeader.SignedEndorsingSupportingTokens, securityHeader.SignedSupportingTokens, securityHeader.SecurityTokenAuthorizationPoliciesMapping);
     base.OnIncomingMessageVerified(message);
 }
        public override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            base.OnOpen(timeoutHelper.RemainingTime());
            if (this.Factory.ActAsInitiator)
            {
                if (this.Factory.ApplyIntegrity)
                {
                    InitiatorServiceModelSecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement();
                    this.Factory.CryptoTokenParameters.InitializeSecurityTokenRequirement(requirement);
                    requirement.KeyUsage = SecurityKeyUsage.Signature;
                    requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Output;
                    this.initiatorCryptoTokenProvider = this.Factory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
                    SecurityUtils.OpenTokenProviderIfRequired(this.initiatorCryptoTokenProvider, timeoutHelper.RemainingTime());
                }
                if (this.Factory.RequireIntegrity || this.Factory.ApplyConfidentiality)
                {
                    InitiatorServiceModelSecurityTokenRequirement providerRequirement = CreateInitiatorSecurityTokenRequirement();
                    this.Factory.AsymmetricTokenParameters.InitializeSecurityTokenRequirement(providerRequirement);
                    providerRequirement.KeyUsage = SecurityKeyUsage.Exchange;
                    providerRequirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = (this.Factory.ApplyConfidentiality) ? MessageDirection.Output : MessageDirection.Input;
                    this.initiatorAsymmetricTokenProvider = this.Factory.SecurityTokenManager.CreateSecurityTokenProvider(providerRequirement);
                    SecurityUtils.OpenTokenProviderIfRequired(this.initiatorAsymmetricTokenProvider, timeoutHelper.RemainingTime());

                    InitiatorServiceModelSecurityTokenRequirement authenticatorRequirement = CreateInitiatorSecurityTokenRequirement();
                    this.Factory.AsymmetricTokenParameters.InitializeSecurityTokenRequirement(authenticatorRequirement);
                    authenticatorRequirement.IsOutOfBandToken = !this.Factory.AllowSerializedSigningTokenOnReply;
                    authenticatorRequirement.KeyUsage = SecurityKeyUsage.Exchange;
                    authenticatorRequirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = (this.Factory.ApplyConfidentiality) ? MessageDirection.Output : MessageDirection.Input;
                    // Create authenticator (we dont support out of band resolvers on the client side
                    SecurityTokenResolver outOfBandTokenResolver;
                    this.initiatorAsymmetricTokenAuthenticator = this.Factory.SecurityTokenManager.CreateSecurityTokenAuthenticator(authenticatorRequirement, out outOfBandTokenResolver);
                    SecurityUtils.OpenTokenAuthenticatorIfRequired(this.initiatorAsymmetricTokenAuthenticator, timeoutHelper.RemainingTime());
                }
            }
        }
        public override ReceiveResult TryReceive(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode)
        {
            // ignore the transactionMode
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            MsmqQueueHandle handle = GetHandle();

            while (true)
            {
                int error = PeekLockCore(handle, (MsmqInputMessage)message, timeoutHelper.RemainingTime());

                if (error == 0)
                {
                    return ReceiveResult.MessageReceived;
                }

                if (IsReceiveErrorDueToInsufficientBuffer(error))
                {
                    message.GrowBuffers();
                    continue;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_IO_TIMEOUT)
                {
                    return ReceiveResult.Timeout;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_OPERATION_CANCELLED)
                {
                    return ReceiveResult.OperationCancelled;
                }
                else if (error == UnsafeNativeMethods.MQ_ERROR_INVALID_HANDLE)
                {
                    // should happen only if racing with Close
                    return ReceiveResult.OperationCancelled;
                }
                else if (IsErrorDueToStaleHandle(error))
                {
                    HandleIsStale(handle);
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error));
            }
        }
Esempio n. 29
0
        public CloseCollectionAsyncResult(TimeSpan timeout, AsyncCallback otherCallback, object state, IList<ICommunicationObject> collection)
            : base(otherCallback, state)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            _completedSynchronously = true;

            _count = collection.Count;
            if (_count == 0)
            {
                Complete(true);
                return;
            }

            for (int index = 0; index < collection.Count; index++)
            {
                CallbackState callbackState = new CallbackState(this, collection[index]);
                IAsyncResult result;
                try
                {
                    result = collection[index].BeginClose(timeoutHelper.RemainingTime(), s_nestedCallback, callbackState);
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    Decrement(true, e);
                    collection[index].Abort();
                    continue;
                }

                if (result.CompletedSynchronously)
                {
                    CompleteClose(collection[index], result);
                }
            }
        }
 public void Close(bool aborting, TimeSpan timeout)
 {
     if (!this.closed)
     {
         lock (this.tableLock)
         {
             if (!this.closed)
             {
                 this.closed = true;
                 TimeoutHelper helper = new TimeoutHelper(timeout);
                 TimeoutException innerException = null;
                 foreach (TransportManager manager in this.transportManagers)
                 {
                     try
                     {
                         if (!aborting && (innerException == null))
                         {
                             manager.Close(this.listener, helper.RemainingTime());
                         }
                         else
                         {
                             manager.Abort(this.listener);
                         }
                     }
                     catch (TimeoutException exception2)
                     {
                         innerException = exception2;
                         manager.Abort(this.listener);
                     }
                 }
                 this.transportManagers.Clear();
                 if (innerException != null)
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(System.ServiceModel.SR.GetString("TimeoutOnClose", new object[] { timeout }), innerException));
                 }
             }
         }
     }
 }