Example #1
0
        public Task SendAsync(Message message, TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            message = SecurityProtocol.SecureOutgoingMessage(message, timeoutHelper.GetCancellationToken());
            return(InnerDuplexChannel.SendAsync(message, timeoutHelper.GetCancellationToken()));
        }
Example #2
0
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            // Supporting a passed in cancellationToken as well as honoring the timeout token in this class would require
            // creating a linked token source on every call which is extra allocation and needs disposal. As this is an
            // internal classs, it's okay to add this extra constraint to usage of this method.
            Fx.Assert(!cancellationToken.CanBeCanceled, "cancellationToken shouldn't be cancellable");
            var cancelToken = _timeoutHelper.GetCancellationToken();

            return(await base.ReadAsync(buffer, offset, count, cancelToken));
        }
Example #3
0
        internal SecurityTokenContainer GetCertificateSecurityToken(SecurityTokenProvider certificateProvider,
                                                                    EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, ref TimeoutHelper timeoutHelper)
        {
            SecurityToken          token          = null;
            SecurityTokenContainer tokenContainer = null;
            SecurityTokenProvider  requestCertificateProvider;

            if (ManualAddressing && RequireClientCertificate)
            {
                requestCertificateProvider = CreateAndOpenCertificateTokenProvider(to, via, channelParameters, timeoutHelper.RemainingTime());
            }
            else
            {
                requestCertificateProvider = certificateProvider;
            }

            if (requestCertificateProvider != null)
            {
                token = requestCertificateProvider.GetTokenAsync(timeoutHelper.GetCancellationToken()).GetAwaiter().GetResult();
            }

            if (ManualAddressing && RequireClientCertificate)
            {
                SecurityUtils.AbortTokenProviderIfRequired(requestCertificateProvider);
            }

            if (token != null)
            {
                tokenContainer = new SecurityTokenContainer(token);
            }

            return(tokenContainer);
        }
Example #4
0
        internal async Task <IList <SupportingTokenSpecification> > TryGetSupportingTokensAsync(SecurityProtocolFactory factory, EndpointAddress target, Uri via, Message message, TimeSpan timeout)
        {
            IList <SupportingTokenSpecification> supportingTokens = null;

            if (!factory.ActAsInitiator)
            {
                return(null);
            }

            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
            }

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            IList <SupportingTokenProviderSpecification> supportingTokenProviders = GetSupportingTokenProviders(message.Headers.Action);

            if (supportingTokenProviders != null && supportingTokenProviders.Count > 0)
            {
                supportingTokens = new Collection <SupportingTokenSpecification>();
                for (int i = 0; i < supportingTokenProviders.Count; ++i)
                {
                    SupportingTokenProviderSpecification spec = supportingTokenProviders[i];
                    SecurityToken supportingToken;
                    supportingToken = await spec.TokenProvider.GetTokenAsync(timeoutHelper.GetCancellationToken());

                    supportingTokens.Add(new SupportingTokenSpecification(supportingToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, spec.SecurityTokenAttachmentMode, spec.TokenParameters));
                }
            }

            // add any runtime supporting tokens
            AddMessageSupportingTokens(message, ref supportingTokens);
            return(supportingTokens);
        }
Example #5
0
        public void CloseAfterFault(TimeSpan timeout)
        {
            var helper = new TimeoutHelper(timeout);

            _channel.CloseAsync(helper.GetCancellationToken());
            AbortRequests();
        }
Example #6
0
        internal async Task EnsureInstanceContextAsync(MessageRpc rpc)
        {
            if (rpc.InstanceContext == null)
            {
                rpc.InstanceContext = new InstanceContext(rpc.Host, false);
                rpc.InstanceContext.ServiceThrottle       = rpc.channelHandler.InstanceContextServiceThrottle;
                rpc.MessageRpcOwnsInstanceContextThrottle = false;
            }

            rpc.OperationContext.SetInstanceContext(rpc.InstanceContext);
            rpc.InstanceContext.Behavior = this;

            if (rpc.InstanceContext.State == CommunicationState.Created)
            {
                Task openTask = null;
                lock (rpc.InstanceContext.ThisLock)
                {
                    if (rpc.InstanceContext.State == CommunicationState.Created)
                    {
                        var helper = new TimeoutHelper(rpc.Channel.CloseTimeout);
                        // awaiting the task outside the lock is safe as OpenAsync will transition the state away from Created before
                        // it returns an uncompleted Task.
                        openTask = rpc.InstanceContext.OpenAsync(helper.GetCancellationToken());
                        Fx.Assert(rpc.InstanceContext.State != CommunicationState.Created, "InstanceContext.OpenAsync should transition away from Created before returning a Task");
                    }
                }

                await openTask;
            }

            rpc.InstanceContext.BindRpc(rpc);
        }
        private void SendFaultIfRequired(Exception e, RequestContext innerContext, TimeSpan timeout)
        {
            if (!_sendUnsecuredFaults)
            {
                return;
            }
            MessageFault fault = SecurityUtils.CreateSecurityMessageFault(e, SecurityProtocol.SecurityProtocolFactory.StandardsManager);

            if (fault == null)
            {
                return;
            }
            Message requestMessage = innerContext.RequestMessage;
            Message faultMessage   = Message.CreateMessage(requestMessage.Version, fault, requestMessage.Version.Addressing.DefaultFaultAction);

            try
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                innerContext.ReplyAsync(faultMessage);
                innerContext.CloseAsync(timeoutHelper.GetCancellationToken());
            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }
            }
            finally
            {
                faultMessage.Close();
                innerContext.Abort();
            }
        }
Example #8
0
                public async Task <Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
                {
                    try
                    {
                        _timeoutHelper = timeoutHelper;
                        var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
                        var replyMessage   = await responseHelper.ParseIncomingResponse();

                        TryCompleteHttpRequest(_httpRequestMessage);
                        return(replyMessage);
                    }
                    catch (OperationCanceledException)
                    {
                        var cancelToken = _timeoutHelper.GetCancellationToken();
                        if (cancelToken.IsCancellationRequested)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
                                                                                                               SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
                        }
                        else
                        {
                            // Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
                            throw;
                        }
                    }
                }
 protected override void ShutdownCore(TimeSpan timeout)
 {
     try
     {
         // All the steps of a socket shutdown are not possible with StreamSocket. As part of a socket shutdown
         // any pending data to write is given the chance to be sent so we'll attempt that.
         var toh = new TimeoutHelper(timeout);
         _outputStream.FlushAsync(toh.GetCancellationToken()).GetAwaiter().GetResult();
     }
     catch (ObjectDisposedException objectDisposedException)
     {
         Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Undefined);
         if (object.ReferenceEquals(exceptionToThrow, objectDisposedException))
         {
             throw;
         }
         else
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow);
         }
     }
     catch (Exception exception)
     {
         if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
         {
             SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                       ConvertSendException(socketException, TimeSpan.MaxValue));
         }
         throw;
     }
 }
            private async Task <Message> PrepareMessageAsync(WebSocketReceiveResult result, byte[] buffer, int count)
            {
                if (result.MessageType != WebSocketMessageType.Close)
                {
                    Message message;
                    if (_useStreaming)
                    {
                        TimeoutHelper readTimeoutHelper = new TimeoutHelper(_defaultTimeouts.ReceiveTimeout);
                        message = await _encoder.ReadMessageAsync(
                            new MaxMessageSizeStream(
                                new TimeoutStream(
                                    new WebSocketStream(
                                        this,
                                        new ArraySegment <byte>(buffer, 0, count),
                                        _webSocket,
                                        result.EndOfMessage,
                                        _bufferManager,
                                        new TimeoutHelper(_defaultTimeouts.CloseTimeout).GetCancellationToken()),
                                    readTimeoutHelper.GetCancellationToken()),
                                _maxReceivedMessageSize),
                            _maxBufferSize);
                    }
                    else
                    {
                        ArraySegment <byte> bytes = new ArraySegment <byte>(buffer, 0, count);
                        message = _encoder.ReadMessage(bytes, _bufferManager);
                    }

                    if (message.Version.Addressing != AddressingVersion.None || !_localAddress.IsAnonymous)
                    {
                        _localAddress.ApplyTo(message);
                    }

                    if (message.Version.Addressing == AddressingVersion.None && message.Headers.Action == null)
                    {
                        if (result.MessageType == WebSocketMessageType.Binary)
                        {
                            message.Headers.Action = WebSocketTransportSettings.BinaryMessageReceivedAction;
                        }
                        else
                        {
                            // WebSocketMesssageType should always be binary or text at this moment. The layer below us will help protect this.
                            Fx.Assert(result.MessageType == WebSocketMessageType.Text, "result.MessageType must be WebSocketMessageType.Text.");
                            message.Headers.Action = WebSocketTransportSettings.TextMessageReceivedAction;
                        }
                    }

                    if (message != null)
                    {
                        AddMessageProperties(message.Properties, result.MessageType);
                    }

                    return(message);
                }

                return(null);
            }
        protected override void WriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
        {
            // as per http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b201213
            // we shouldn't write more than 64K synchronously to a socket
            const int maxSocketWrite = 64 * 1024;

            ConnectionUtilities.ValidateBufferBounds(buffer, offset, size);

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                int bytesToWrite = size;

                using (timeoutHelper.GetCancellationToken().Register(OnSendTimeout, this))
                {
                    while (bytesToWrite > 0)
                    {
                        size = Math.Min(bytesToWrite, maxSocketWrite);
                        _outputStream.Write(buffer, offset, size);
                        if (immediate)
                        {
                            _outputStream.Flush();
                        }

                        bytesToWrite -= size;
                        offset       += size;
                    }
                }
            }
            catch (ObjectDisposedException objectDisposedException)
            {
                Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write);
                if (object.ReferenceEquals(exceptionToThrow, objectDisposedException))
                {
                    throw;
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow);
                }
            }
            catch (Exception exception)
            {
                if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
                {
                    SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              ConvertSendException(socketException, timeoutHelper.RemainingTime()));
                }
                throw;
            }
        }
Example #12
0
 internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenAuthenticator authenticator, TimeSpan timeout)
 {
     if (authenticator != null)
     {
         TimeoutHelper helper = new TimeoutHelper(timeout);
         SecurityUtils.OpenTokenAuthenticatorIfRequiredAsync(authenticator, helper.GetCancellationToken());
     }
     else
     {
         OnPropertySettingsError(propertyName, requiredForForwardDirection);
     }
 }
Example #13
0
        // TODO: Make async
        internal void CloseChannel()
        {
            if ((Channel != null) && Channel.HasSession)
            {
                try
                {
                    var helper = new TimeoutHelper(ChannelHandler.CloseAfterFaultTimeout);
                    Channel.CloseAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    channelHandler.HandleError(e);
                }
            }
        }
            internal override async Task OpenAsync(TimeSpan timeout)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

                base.Open(timeoutHelper.RemainingTime());

                OutWrapper <TokenImpersonationLevel> impersonationLevelWrapper = new OutWrapper <TokenImpersonationLevel>();
                OutWrapper <bool> allowNtlmWrapper = new OutWrapper <bool>();

                SecurityUtils.OpenTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime());
                _credential = await TransportSecurityHelpers.GetSspiCredentialAsync(
                    _clientTokenProvider,
                    impersonationLevelWrapper,
                    allowNtlmWrapper,
                    timeoutHelper.GetCancellationToken());

                _impersonationLevel = impersonationLevelWrapper.Value;
                _allowNtlm          = allowNtlmWrapper;

                return;
            }
 public Task <Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
 {
     try
     {
         _connectionReader = new ClientSingletonConnectionReader(_connection, _connectionPoolHelper, _channel._settings);
         return(_connectionReader.ReceiveAsync(timeoutHelper));
     }
     catch (OperationCanceledException)
     {
         var cancelToken = _timeoutHelper.GetCancellationToken();
         if (cancelToken.IsCancellationRequested)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
                                                                                                SR.RequestChannelWaitForReplyTimedOut, timeoutHelper.OriginalTimeout)));
         }
         else
         {
             // Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
             throw;
         }
     }
 }
Example #16
0
        internal void EnsureInstanceContext(ref MessageRpc rpc)
        {
            if (rpc.InstanceContext == null)
            {
                rpc.InstanceContext = new InstanceContext(rpc.Host, false);
            }

            rpc.OperationContext.SetInstanceContext(rpc.InstanceContext);
            rpc.InstanceContext.Behavior = this;

            if (rpc.InstanceContext.State == CommunicationState.Created)
            {
                lock (rpc.InstanceContext.ThisLock)
                {
                    if (rpc.InstanceContext.State == CommunicationState.Created)
                    {
                        var helper = new TimeoutHelper(rpc.Channel.CloseTimeout);
                        rpc.InstanceContext.OpenAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
                    }
                }
            }
            rpc.InstanceContext.BindRpc(ref rpc);
        }
        protected override int ReadCore(byte[] buffer, int offset, int size, TimeSpan timeout, bool closing)
        {
            int           bytesRead     = 0;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                using (timeoutHelper.GetCancellationToken().Register(OnReceiveTimeout, this))
                {
                    bytesRead = _inputStream.Read(buffer, offset, size);
                }
            }
            catch (ObjectDisposedException objectDisposedException)
            {
                Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read);
                if (object.ReferenceEquals(exceptionToThrow, objectDisposedException))
                {
                    throw;
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow);
                }
            }
            catch (Exception exception)
            {
                if (RTSocketError.GetStatus(exception.HResult) != SocketErrorStatus.Unknown)
                {
                    SocketException socketException = new SocketException(exception.HResult & 0x0000FFFF);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              ConvertReceiveException(socketException, timeoutHelper.RemainingTime()));
                }
                throw;
            }

            return(bytesRead);
        }
        public virtual void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (!ActAsInitiator)
            {
                foreach (SupportingTokenAuthenticatorSpecification spec in ChannelSupportingTokenAuthenticatorSpecification)
                {
                    SecurityUtils.CloseTokenAuthenticatorIfRequiredAsync(spec.TokenAuthenticator, timeoutHelper.GetCancellationToken());
                }
                foreach (string action in ScopedSupportingTokenAuthenticatorSpecification.Keys)
                {
                    ICollection <SupportingTokenAuthenticatorSpecification> supportingAuthenticators = ScopedSupportingTokenAuthenticatorSpecification[action];
                    foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators)
                    {
                        SecurityUtils.CloseTokenAuthenticatorIfRequiredAsync(spec.TokenAuthenticator, timeoutHelper.GetCancellationToken());
                    }
                }
            }
        }
Example #19
0
        // used by server WindowsStream security (from Open)
        public static NetworkCredential GetSspiCredential(SecurityTokenManager credentialProvider,
                                                          SecurityTokenRequirement sspiTokenRequirement, TimeSpan timeout,
                                                          out bool extractGroupsForWindowsAccounts)
        {
            extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            NetworkCredential result = null;

            if (credentialProvider != null)
            {
                SecurityTokenProvider tokenProvider = credentialProvider.CreateSecurityTokenProvider(sspiTokenRequirement);
                if (tokenProvider != null)
                {
                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                    SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                    bool success = false;
                    try
                    {
                        OutWrapper <TokenImpersonationLevel> dummyImpersonationLevelWrapper = new OutWrapper <TokenImpersonationLevel>();
                        OutWrapper <bool> dummyAllowNtlmWrapper = new OutWrapper <bool>();
                        OutWrapper <bool> extractGroupsForWindowsAccountsWrapper = new OutWrapper <bool>();
                        result = GetSspiCredentialAsync((SspiSecurityTokenProvider)tokenProvider, extractGroupsForWindowsAccountsWrapper,
                                                        dummyImpersonationLevelWrapper, dummyAllowNtlmWrapper, timeoutHelper.GetCancellationToken()).GetAwaiter().GetResult();

                        success = true;
                    }
                    finally
                    {
                        if (!success)
                        {
                            SecurityUtils.AbortTokenProviderIfRequired(tokenProvider);
                        }
                    }
                    SecurityUtils.CloseTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                }
            }

            return(result);
        }
Example #20
0
        private async Task MergeSupportingTokenProvidersAsync(TimeSpan timeout)
        {
            if (ScopedSupportingTokenProviderSpecification.Count == 0)
            {
                _mergedSupportingTokenProvidersMap = null;
            }
            else
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                SecurityProtocolFactory.ExpectSupportingTokens = true;
                _mergedSupportingTokenProvidersMap             = new Dictionary <string, Collection <SupportingTokenProviderSpecification> >();
                foreach (string action in ScopedSupportingTokenProviderSpecification.Keys)
                {
                    ICollection <SupportingTokenProviderSpecification> scopedProviders = ScopedSupportingTokenProviderSpecification[action];
                    if (scopedProviders == null || scopedProviders.Count == 0)
                    {
                        continue;
                    }
                    Collection <SupportingTokenProviderSpecification> mergedProviders = new Collection <SupportingTokenProviderSpecification>();
                    foreach (SupportingTokenProviderSpecification spec in ChannelSupportingTokenProviderSpecification)
                    {
                        mergedProviders.Add(spec);
                    }
                    foreach (SupportingTokenProviderSpecification spec in scopedProviders)
                    {
                        await SecurityUtils.OpenTokenProviderIfRequiredAsync(spec.TokenProvider, timeoutHelper.GetCancellationToken());

                        if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
                        {
                            if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey)
                            {
                                SecurityProtocolFactory.ExpectKeyDerivation = true;
                            }
                        }
                        mergedProviders.Add(spec);
                    }
                    _mergedSupportingTokenProvidersMap.Add(action, mergedProviders);
                }
            }
        }
Example #21
0
        public override Task ReplyAsync(Message message)
        {
            var helper = new TimeoutHelper(defaultSendTimeout);

            return(ReplyAsync(message, helper.GetCancellationToken()));
        }
Example #22
0
            public Task CloseOutputSessionAsync()
            {
                var timeoutHelper = new TimeoutHelper(Channel.DefaultCloseTimeout);

                return(CloseOutputSessionAsync(timeoutHelper.GetCancellationToken()));
            }
Example #23
0
        public virtual async Task OnOpenAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (SecurityProtocolFactory.ActAsInitiator)
            {
                ChannelSupportingTokenProviderSpecification = new Collection <SupportingTokenProviderSpecification>();
                ScopedSupportingTokenProviderSpecification  = new Dictionary <string, ICollection <SupportingTokenProviderSpecification> >();

                AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.EndpointSupportingTokenParameters, false, (IList <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalEndpointSupportingTokenParameters, true, (IList <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters.Keys)
                {
                    Collection <SupportingTokenProviderSpecification> providerSpecList = new Collection <SupportingTokenProviderSpecification>();
                    AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters[action], false, providerSpecList);
                    ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
                }

                foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters.Keys)
                {
                    Collection <SupportingTokenProviderSpecification>  providerSpecList;
                    ICollection <SupportingTokenProviderSpecification> existingList;
                    if (ScopedSupportingTokenProviderSpecification.TryGetValue(action, out existingList))
                    {
                        providerSpecList = ((Collection <SupportingTokenProviderSpecification>)existingList);
                    }
                    else
                    {
                        providerSpecList = new Collection <SupportingTokenProviderSpecification>();
                        ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
                    }

                    AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters[action], true, providerSpecList);
                }

                if (!ChannelSupportingTokenProviderSpecification.IsReadOnly)
                {
                    if (ChannelSupportingTokenProviderSpecification.Count == 0)
                    {
                        ChannelSupportingTokenProviderSpecification = EmptyTokenProviders;
                    }
                    else
                    {
                        SecurityProtocolFactory.ExpectSupportingTokens = true;
                        foreach (SupportingTokenProviderSpecification tokenProviderSpec in ChannelSupportingTokenProviderSpecification)
                        {
                            SecurityUtils.OpenTokenProviderIfRequiredAsync(tokenProviderSpec.TokenProvider, timeoutHelper.GetCancellationToken());
                            if (tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
                            {
                                if (tokenProviderSpec.TokenParameters.RequireDerivedKeys && !tokenProviderSpec.TokenParameters.HasAsymmetricKey)
                                {
                                    SecurityProtocolFactory.ExpectKeyDerivation = true;
                                }
                            }
                        }
                        ChannelSupportingTokenProviderSpecification =
                            new ReadOnlyCollection <SupportingTokenProviderSpecification>((Collection <SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
                    }
                }
                // create a merged map of the per operation supporting tokens
                await MergeSupportingTokenProvidersAsync(timeoutHelper.RemainingTime());
            }
        }
Example #24
0
            public object Invoke(object instance, object[] inputs, out object[] outputs)
            {
                outputs = EmptyArray <object> .Allocate(0);

                Message message = inputs[0] as Message;

                if (message == null)
                {
                    return(null);
                }

                string action = message.Headers.Action;

                //if (DiagnosticUtility.ShouldTraceInformation)
                //{
                //    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.UnhandledAction,
                //        SR.TraceCodeUnhandledAction,
                //        new StringTraceRecord("Action", action),
                //        this, null, message);
                //}

                FaultCode code = FaultCode.CreateSenderFaultCode(AddressingStrings.ActionNotSupported,
                                                                 message.Version.Addressing.Namespace);
                string      reasonText = SR.Format(SR.SFxNoEndpointMatchingContract, action);
                FaultReason reason     = new FaultReason(reasonText);

                FaultException exception = new FaultException(reason, code);

                ErrorBehavior.ThrowAndCatch(exception);

                ServiceChannel serviceChannel = OperationContext.Current.InternalServiceChannel;

                OperationContext.Current.OperationCompleted +=
                    delegate(object sender, EventArgs e)
                {
                    ChannelDispatcher channelDispatcher = dispatchRuntime.ChannelDispatcher;
                    if (!channelDispatcher.HandleError(exception) && serviceChannel.HasSession)
                    {
                        try
                        {
                            var helper = new TimeoutHelper(ChannelHandler.CloseAfterFaultTimeout);
                            serviceChannel.CloseAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
                        }
                        catch (Exception ex)
                        {
                            if (Fx.IsFatal(ex))
                            {
                                throw;
                            }
                            channelDispatcher.HandleError(ex);
                        }
                    }
                };

                if (dispatchRuntime.shared.EnableFaults)
                {
                    MessageFault fault = MessageFault.CreateFault(code, reason, action);
                    return(Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultFaultAction));
                }
                else
                {
                    OperationContext.Current.RequestContext.CloseAsync().GetAwaiter().GetResult();
                    OperationContext.Current.RequestContext = null;
                    return(null);
                }
            }
Example #25
0
        public Task SendAsync(Message message)
        {
            var helper = new TimeoutHelper(DefaultSendTimeout);

            return(SendAsync(message, helper.GetCancellationToken()));
        }
Example #26
0
            public Task <Message> ReceiveAsync()
            {
                var helper = new TimeoutHelper(DefaultReceiveTimeout);

                return(ReceiveAsync(helper.GetCancellationToken()));
            }
Example #27
0
        public async Task SendFaultAsync(string faultString, TimeSpan sendTimeout, int maxRead)
        {
            //if (TD.ConnectionReaderSendFaultIsEnabled())
            //{
            //    TD.ConnectionReaderSendFault(faultString);
            //}
            var encodedFault  = new EncodedFault(faultString);
            var timeoutHelper = new TimeoutHelper(sendTimeout);
            var ct            = timeoutHelper.GetCancellationToken();

            try
            {
                await Output.WriteAsync(encodedFault.EncodedBytes, ct);

                await Output.FlushAsync();

                // Connection will be closed on completion of Task returned from NetMessageFramingConnectionHandler.OnConnectedAsync
            }
            catch (CommunicationException e) // TODO: Consider exception filters to remvoe duplicate code
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                Abort(e);
                return;
            }
            catch (OperationCanceledException e)
            {
                //if (TD.SendTimeoutIsEnabled())
                //{
                //    TD.SendTimeout(e.Message);
                //}
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                Abort(e);
                return;
            }
            catch (TimeoutException e)
            {
                //if (TD.SendTimeoutIsEnabled())
                //{
                //    TD.SendTimeout(e.Message);
                //}
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                Abort(e);
                return;
            }

            // make sure we read until EOF or a quota is hit
            ReadResult readResult;
            long       readTotal = 0;

            for (; ;)
            {
                try
                {
                    readResult = await Input.ReadAsync(ct);
                }
                catch (CommunicationException e) // TODO: Exception filters?
                {
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    Abort(e);
                    return;
                }
                // TODO: Standardize handling of OperationCanceledException/TimeoutException
                catch (OperationCanceledException e)
                {
                    //if (TD.SendTimeoutIsEnabled())
                    //{
                    //    TD.SendTimeout(e.Message);
                    //}
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    Abort(e);
                    return;
                }
                catch (TimeoutException e)
                {
                    //if (TD.SendTimeoutIsEnabled())
                    //{
                    //    TD.SendTimeout(e.Message);
                    //}
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    Abort(e);
                    return;
                }

                if (readResult.IsCompleted)
                {
                    break;
                }

                readTotal += readResult.Buffer.Length;
                Input.AdvanceTo(readResult.Buffer.End);
                if (readTotal > maxRead || timeoutHelper.RemainingTime() <= TimeSpan.Zero)
                {
                    Abort();
                    return;
                }
            }
        }
Example #28
0
        public void CloseAfterFault(TimeSpan timeout)
        {
            var helper = new TimeoutHelper(timeout);

            channel.CloseAsync(helper.GetCancellationToken()).GetAwaiter().GetResult();
        }
Example #29
0
        public async Task OnConnectedAsync(FramingConnection connection)
        {
            var  receiveTimeout = connection.ServiceDispatcher.Binding.ReceiveTimeout;
            var  timeoutHelper  = new TimeoutHelper(receiveTimeout);
            bool success        = false;

            try
            {
                var decoder = connection.FramingDecoder as ServerSingletonDecoder;
                Fx.Assert(decoder != null, "FramingDecoder must be non-null and an instance of ServerSessionDecoder");

                // first validate our content type
                //ValidateContentType(connection, decoder);
                UpgradeState upgradeState = UpgradeState.None;
                // next read any potential upgrades and finish consuming the preamble
                ReadOnlySequence <byte> buffer = ReadOnlySequence <byte> .Empty;
                while (true)
                {
                    if (buffer.Length == 0 && CanReadAndDecode(upgradeState))
                    {
                        var readResult = await connection.Input.ReadAsync();

                        buffer = readResult.Buffer;
                        if (readResult.IsCompleted)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
                        }
                    }

                    while (true)
                    {
                        if (CanReadAndDecode(upgradeState))
                        {
                            Fx.Assert(buffer.Length > 0, "There must be something in the buffer to decode");
                            int bytesDecoded = decoder.Decode(buffer);
                            if (bytesDecoded > 0)
                            {
                                buffer = buffer.Slice(bytesDecoded);
                                if (buffer.Length == 0)
                                {
                                    connection.Input.AdvanceTo(buffer.Start);
                                }
                            }
                        }

                        switch (decoder.CurrentState)
                        {
                        case ServerSingletonDecoder.State.UpgradeRequest:
                            switch (upgradeState)
                            {
                            case UpgradeState.None:
                                //change the state so that we don't read/decode until it is safe
                                ChangeUpgradeState(ref upgradeState, UpgradeState.VerifyingUpgradeRequest);
                                break;

                            case UpgradeState.VerifyingUpgradeRequest:
                                if (connection.StreamUpgradeAcceptor == null)
                                {
                                    await connection.SendFaultAsync(FramingEncodingString.UpgradeInvalidFault, timeoutHelper.RemainingTime(), TransportDefaults.MaxDrainSize);

                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                              new ProtocolException(SR.Format(SR.UpgradeRequestToNonupgradableService, decoder.Upgrade)));
                                }

                                if (!connection.StreamUpgradeAcceptor.CanUpgrade(decoder.Upgrade))
                                {
                                    await connection.SendFaultAsync(FramingEncodingString.UpgradeInvalidFault, timeoutHelper.RemainingTime(), TransportDefaults.MaxDrainSize);

                                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.UpgradeProtocolNotSupported, decoder.Upgrade)));
                                }

                                ChangeUpgradeState(ref upgradeState, UpgradeState.WritingUpgradeAck);
                                // accept upgrade
                                await connection.Output.WriteAsync(ServerSingletonEncoder.UpgradeResponseBytes, timeoutHelper.GetCancellationToken());

                                await connection.Output.FlushAsync(timeoutHelper.GetCancellationToken());

                                ChangeUpgradeState(ref upgradeState, UpgradeState.UpgradeAckSent);
                                break;

                            case UpgradeState.UpgradeAckSent:
                                // This state was used to capture any extra read bytes into PreReadConnection but we don't need to do that when using pipes.
                                // This extra state transition has been left here to maintain the same state transitions as on .NET Framework to make comparison easier.
                                ChangeUpgradeState(ref upgradeState, UpgradeState.BeginUpgrade);
                                break;

                            case UpgradeState.BeginUpgrade:
                                // Set input pipe so that the next read will return all the unconsumed bytes.
                                // If all bytes have already been consumed so the buffer has 0 length, AdvanceTo would throw
                                // as it's already been called.
                                if (buffer.Length > 0)
                                {
                                    connection.Input.AdvanceTo(buffer.Start);
                                }

                                buffer = ReadOnlySequence <byte> .Empty;
                                try
                                {
                                    await UpgradeConnectionAsync(connection);

                                    ChangeUpgradeState(ref upgradeState, UpgradeState.EndUpgrade);
                                }
                                catch (Exception exception)
                                {
                                    if (Fx.IsFatal(exception))
                                    {
                                        throw;
                                    }

                                    throw;
                                }
                                break;

                            case UpgradeState.EndUpgrade:
                                //Must be a different state here than UpgradeComplete so that we don't try to read from the connection
                                ChangeUpgradeState(ref upgradeState, UpgradeState.UpgradeComplete);
                                break;

                            case UpgradeState.UpgradeComplete:
                                //Client is doing more than one upgrade, reset the state
                                ChangeUpgradeState(ref upgradeState, UpgradeState.VerifyingUpgradeRequest);
                                break;
                            }
                            break;

                        case ServerSingletonDecoder.State.Start:
                            SetupSecurityIfNecessary(connection);
                            if (upgradeState == UpgradeState.UpgradeComplete ||  //We have done at least one upgrade, but we are now done.
                                upgradeState == UpgradeState.None)       //no upgrade, just send the preample end bytes
                            {
                                ChangeUpgradeState(ref upgradeState, UpgradeState.WritingPreambleEnd);
                                // we've finished the preamble. Ack and return.
                                await connection.Output.WriteAsync(ServerSessionEncoder.AckResponseBytes);

                                await connection.Output.FlushAsync();

                                //terminal state
                                ChangeUpgradeState(ref upgradeState, UpgradeState.PreambleEndSent);
                            }
                            // If all bytes have already been consumed so the buffer has 0 length, AdvanceTo would throw
                            // as it's already been called.
                            if (buffer.Length > 0)
                            {
                                connection.Input.AdvanceTo(buffer.Start);
                            }

                            success = true;
                            await _next(connection);

                            return;
                        }

                        if (buffer.Length == 0)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                if (!success)
                {
                    connection.Abort();
                }
            }
        }
Example #30
0
            public Task CloseAsync()
            {
                var helper = new TimeoutHelper(DefaultCloseTimeout);

                return(CloseAsync(helper.GetCancellationToken()));
            }