< Summary - CoreWCF Coverage — PR #1766

Information
Class: CoreWCF.Security.SecuritySessionServerSettings
Assembly: CoreWCF.Primitives
File(s): /home/runner/work/CoreWCF/CoreWCF/src/CoreWCF.Primitives/src/CoreWCF/Security/SecuritySessionServerSettings.cs
Line coverage
54%
Covered lines: 605
Uncovered lines: 512
Coverable lines: 1117
Total lines: 2708
Line coverage: 54.1%
Branch coverage
42%
Covered branches: 177
Total branches: 416
Branch coverage: 42.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.cctor()100%11100%
.ctor()100%11100%
OnFaulted()100%110%
OnOpened()100%110%
OnOpening()100%110%
OnAbort()100%110%
Abort()100%110%
OnCloseCore(...)0%660%
OnAbortCore()0%660%
SetupSessionTokenAuthenticatorAsync()50%8883.33%
StopAcceptingNewWork()100%110%
GetPendingSessionCount()100%11100%
AbortPendingChannels(...)100%110%
ClosePendingChannels()0%440%
ConfigureSessionSecurityProtocolFactory()50%2280%
OnTokenRenewed(...)0%880%
CreateSessionMessageServiceDispatcher(...)75%4490.9%
OnTokenIssued(...)50%6671.42%
GetSecurityContextSecurityToken(...)0%880%
OnTimer(...)66.66%121271.42%
AddPendingSession(...)50%6677.77%
ClearPendingSessions()33.33%6620%
RemovePendingSession(...)25%4450%
FindSessionChannel(...)100%110%
AddSessionChannel(...)100%11100%
RemoveSessionChannel(...)100%11100%
RemoveSessionChannel(...)100%11100%
RemoveServiceDispatcher(...)75%4480%
CloseAsync(...)100%110%
OnCloseAsync(...)100%110%
OpenAsync(...)100%11100%
OnOpenAsync(...)55.55%181875.75%
OnClosed()100%110%
OnClosing()100%110%
.ctor(...)100%11100%
CreateServiceChannelDispatcherAsync()80%101073.91%
.ctor(...)50%2294.44%
OpenAsync(...)66.66%6687.5%
AbortCore()0%660%
CloseCoreAsync()75%8877.77%
RenewSessionToken(...)0%660%
GetSessionToken(...)50%161680%
CheckIncomingToken(...)30%202032.14%
ReceiveRequestAsync(...)100%11100%
ReceiveRequestAsync()50%2285.71%
TryReceiveRequestAsync()75%161672%
ThrowIfFaulted()100%11100%
SendFaultIfRequired(...)0%440%
ShouldWrapException(...)0%220%
ProcessRequestContextAsync()36.36%222259.09%
CheckOutgoingToken()50%2280%
SecureApplicationMessage(...)100%11100%
ThrowIfClosedOrNotOpen()100%11100%
VerifyIncomingMessageAsync()100%11100%
PrepareReply(...)66.66%6671.42%
InitializeFaultCodesIfRequired()0%440%
SendRenewFault(...)0%220%
ProcessCloseRequest(...)66.66%121289.28%
CreateCloseResponse(...)100%11100%
TraceSessionClosedResponseSuccess()100%11100%
TraceSessionClosedResponseFailure(...)100%110%
TraceSessionClosedSuccess()100%110%
TraceSessionClosedFailure(...)100%110%
SendCloseResponseAsync()100%1150%
CreateCloseMessage(...)0%660%
SendCloseAsync()100%110%
SendMessageAsync()100%22100%
OnFaulted(...)100%110%
.ctor(...)100%22100%
WriteSessionTokenIdentifier(...)100%110%
TryReadSessionTokenIdentifier(...)0%440%
.ctor(...)100%11100%
CleanupPendingCloseState()0%440%
AbortCore()100%110%
CloseCoreAsync()100%11100%
CloseAsync(...)100%11100%
OnCloseAsync()50%2280%
ShouldSendCloseResponseOnClose(...)50%6673.33%
SendCloseResponseOnCloseIfRequiredAsync()40%101052.63%
OnCloseResponseMessageReceived(...)100%110%
Fault(...)100%110%
OnCloseMessageReceived(...)50%2275%
SendCloseResponseOnCloseReceivedIfRequiredAsync()60%101072%
.ctor(...)100%11100%
Abort()100%110%
CloseAsync()100%110%
CloseAsync(...)100%11100%
DispatchAsync()100%11100%
DispatchAsync(...)100%110%
GetProperty()100%22100%
OpenAsync()100%11100%
OpenAsync()100%11100%
OpenAsync(...)100%110%
.ctor(...)100%11100%
AbortCore()100%110%
CleanupPendingCloseState()0%440%
Abort()100%110%
CloseAsync()100%110%
CloseAsync()50%101070.58%
CloseDuplexSessionChannelAsync()33.33%181848.27%
DetermineCloseOutputSessionMessage(...)83.33%6689.47%
CloseOutputSessionAsync()50%101065%
OnCloseMessageReceived(...)75%121284%
OnCloseResponseMessageReceived(...)0%10100%
WaitForOutputSessionCloseAsync()0%2240%
WaitForInputSessionCloseAsync()41.66%121250%
.ctor(...)100%11100%
CloseOutputSessionAsync()100%110%
CloseOutputSessionAsync(...)100%110%
CloseOutputSessionAsync()0%660%
.ctor(...)100%11100%
DispatchAsync(...)100%110%
DispatchAsync()100%22100%
GetProperty()100%22100%
OpenAsync()100%11100%
OpenAsync()100%11100%
OpenAsync(...)100%110%
SendAsync(...)100%110%
SendAsync(...)100%11100%
ReceiveAsync(...)100%110%
TryReceiveAsync(...)100%110%
CheckOutputOpen()50%2280%
OnFaulted(...)100%110%
OnAbort()100%110%
OnCloseAsync(...)100%110%
OnOpenAsync(...)100%110%
.ctor(...)100%11100%
OnAbort()100%110%
OnCloseAsync(...)100%11100%
OnReplyAsync()100%22100%
.ctor(...)100%11100%
OnAbort()100%110%
OnCloseAsync(...)100%11100%
OnReplyAsync(...)50%2275%
.ctor(...)50%22100%
HandleDemuxFailure(...)0%220%
CreateSessionDemuxFaultMessage(...)0%220%
HandleDemuxFailureAsync(...)100%110%
HandleDemuxFailureAsync()0%220%

File(s)

/home/runner/work/CoreWCF/CoreWCF/src/CoreWCF.Primitives/src/CoreWCF/Security/SecuritySessionServerSettings.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System;
 5using System.Collections.Generic;
 6using System.Diagnostics;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using System.Xml;
 10using CoreWCF.Channels;
 11using CoreWCF.Configuration;
 12using CoreWCF.Description;
 13using CoreWCF.Diagnostics;
 14using CoreWCF.Dispatcher;
 15using CoreWCF.IdentityModel;
 16using CoreWCF.IdentityModel.Claims;
 17using CoreWCF.IdentityModel.Selectors;
 18using CoreWCF.IdentityModel.Tokens;
 19using CoreWCF.Runtime;
 20using CoreWCF.Security.Tokens;
 21using Microsoft.Extensions.DependencyInjection;
 22
 23namespace CoreWCF.Security
 24{
 25    internal sealed class SecuritySessionServerSettings : IServiceDispatcherSecureConversationSessionSettings, ISecurity
 26    {
 427        internal static readonly TimeSpan s_defaultKeyRenewalInterval = TimeSpan.FromHours(15);
 428        internal static readonly TimeSpan s_defaultKeyRolloverInterval = TimeSpan.FromMinutes(5);
 29        internal const bool DefaultTolerateTransportFailures = true;
 30        internal const int DefaultMaximumPendingSessions = 128;
 431        internal static readonly TimeSpan s_defaultInactivityTimeout = TimeSpan.FromMinutes(2);
 32        private int _maximumPendingSessions;
 33        private Dictionary<UniqueId, SecurityContextSecurityToken> _pendingSessions1;
 34        private Dictionary<UniqueId, SecurityContextSecurityToken> _pendingSessions2;
 35        private Dictionary<UniqueId, MessageFilter> _sessionFilters;
 36        private IOThreadTimer _inactivityTimer;
 37        private TimeSpan _inactivityTimeout;
 38        private bool _tolerateTransportFailures;
 39        private TimeSpan _maximumKeyRenewalInterval;
 40        private TimeSpan _keyRolloverInterval;
 41        private int _maximumPendingKeysPerSession;
 42        private SecurityProtocolFactory _sessionProtocolFactory;
 43        private readonly Dictionary<UniqueId, IServerSecuritySessionChannel> _activeSessions;
 44        private SecurityServiceDispatcher _securityServiceDispatcher;
 45        private ChannelBuilder _channelBuilder;
 46        private SecurityStandardsManager _standardsManager;
 47        private SecurityTokenParameters _issuedTokenParameters;
 48        private SecurityTokenResolver _sessionTokenResolver;
 49        private bool _acceptNewWork;
 50        private Uri _listenUri;
 51        private SecurityListenerSettingsLifetimeManager _settingsLifetimeManager;
 52
 2253        public SecuritySessionServerSettings()
 54        {
 2255            _activeSessions = new Dictionary<UniqueId, IServerSecuritySessionChannel>();
 2256            _maximumKeyRenewalInterval = s_defaultKeyRenewalInterval;
 2257            _maximumPendingKeysPerSession = 5;
 2258            _keyRolloverInterval = s_defaultKeyRolloverInterval;
 2259            _inactivityTimeout = s_defaultInactivityTimeout;
 2260            _tolerateTransportFailures = DefaultTolerateTransportFailures;
 2261            _maximumPendingSessions = DefaultMaximumPendingSessions;
 2262            WrapperCommunicationObj = new WrapperSecurityCommunicationObject(this);
 2263        }
 64
 65        internal ChannelBuilder ChannelBuilder
 66        {
 67            get
 68            {
 2069                return _channelBuilder;
 70            }
 71            set
 72            {
 2273                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 2274                _channelBuilder = value;
 2275            }
 76        }
 77
 62678        internal WrapperSecurityCommunicationObject WrapperCommunicationObj { get; }
 79
 80        internal SecurityListenerSettingsLifetimeManager SettingsLifetimeManager
 81        {
 82            get
 83            {
 1084                return _settingsLifetimeManager;
 85            }
 86            set
 87            {
 2288                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 2289                _settingsLifetimeManager = value;
 2290            }
 91        }
 92
 93        internal SecurityServiceDispatcher SecurityServiceDispatcher
 94        {
 95            get
 96            {
 3297                return _securityServiceDispatcher;
 98            }
 99            set
 100            {
 44101                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 44102                _securityServiceDispatcher = value;
 44103            }
 104        }
 105
 106        /// <summary>
 107        /// AcceptorChannelType will help determine if it's a duplex or simple reply channel
 108        /// </summary>
 64109        internal Type AcceptorChannelType { get; set; }
 110
 111        // TODO: Used by security tracing
 112        //private Uri Uri
 113        //{
 114        //    get
 115        //    {
 116        //        WrapperCommunicationObj.ThrowIfNotOpened();
 117        //        return _listenUri;
 118        //    }
 119        //}
 120
 116121        internal object ThisGlobalLock { get; } = new object();
 122
 142123        public SecurityTokenAuthenticator SessionTokenAuthenticator { get; private set; }
 124
 32125        public ISecurityContextSecurityTokenCache SessionTokenCache { get; private set; }
 126
 10127        public SecurityTokenResolver SessionTokenResolver => _sessionTokenResolver;
 128
 129        public SecurityTokenParameters IssuedSecurityTokenParameters
 130        {
 131            get
 132            {
 54133                return _issuedTokenParameters;
 134            }
 135            set
 136            {
 22137                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22138                _issuedTokenParameters = value;
 22139            }
 140        }
 141
 142        internal SecurityStandardsManager SecurityStandardsManager
 143        {
 144            get
 145            {
 104146                return _standardsManager;
 147            }
 148            set
 149            {
 22150                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22151                _standardsManager = value;
 22152            }
 153        }
 154
 155        public bool TolerateTransportFailures
 156        {
 157            get
 158            {
 0159                return _tolerateTransportFailures;
 160            }
 161            set
 162            {
 22163                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22164                _tolerateTransportFailures = value;
 22165            }
 166        }
 167
 44168        public bool CanRenewSession { get; set; } = true;
 169
 170        public int MaximumPendingSessions
 171        {
 172            get
 173            {
 10174                return _maximumPendingSessions;
 175            }
 176            set
 177            {
 22178                if (value <= 0)
 179                {
 0180                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(val
 181                }
 182
 22183                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22184                _maximumPendingSessions = value;
 22185            }
 186        }
 187
 188        public TimeSpan InactivityTimeout
 189        {
 190            get
 191            {
 0192                return _inactivityTimeout;
 193            }
 194            set
 195            {
 22196                if (value <= TimeSpan.Zero)
 197                {
 0198                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(val
 199                }
 200
 22201                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22202                _inactivityTimeout = value;
 22203            }
 204        }
 205
 206        public TimeSpan MaximumKeyRenewalInterval
 207        {
 208            get
 209            {
 0210                return _maximumKeyRenewalInterval;
 211            }
 212            set
 213            {
 22214                if (value <= TimeSpan.Zero)
 215                {
 0216                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(val
 217                }
 22218                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22219                _maximumKeyRenewalInterval = value;
 22220            }
 221        }
 222
 223        public TimeSpan KeyRolloverInterval
 224        {
 225            get
 226            {
 0227                return _keyRolloverInterval;
 228            }
 229            set
 230            {
 22231                if (value <= TimeSpan.Zero)
 232                {
 0233                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(val
 234                }
 22235                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22236                _keyRolloverInterval = value;
 22237            }
 238        }
 239
 240        public int MaximumPendingKeysPerSession
 241        {
 242            get
 243            {
 0244                return _maximumPendingKeysPerSession;
 245            }
 246            set
 247            {
 0248                if (value <= 0)
 249                {
 0250                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(val
 251                }
 0252                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 0253                _maximumPendingKeysPerSession = value;
 0254            }
 255        }
 256
 257        public SecurityProtocolFactory SessionProtocolFactory
 258        {
 259            get
 260            {
 42261                return _sessionProtocolFactory;
 262            }
 263            set
 264            {
 22265                WrapperCommunicationObj.ThrowIfDisposedOrImmutable();
 22266                _sessionProtocolFactory = value;
 22267            }
 268        }
 269
 32270        public MessageVersion MessageVersion { get; private set; }
 271
 272        // ISecurityCommunicationObject members
 44273        public TimeSpan DefaultOpenTimeout => ServiceDefaults.OpenTimeout;
 274
 0275        public TimeSpan DefaultCloseTimeout => ServiceDefaults.CloseTimeout;
 276
 277        public void OnFaulted()
 278        {
 0279        }
 280
 281        public void OnOpened()
 282        {
 0283        }
 284
 285        public void OnOpening()
 286        {
 0287        }
 288
 289        public void OnAbort()
 290        {
 0291            TimeoutHelper timeoutHelper = new TimeoutHelper(ServiceDefaults.ServiceHostCloseTimeout);
 0292            AbortPendingChannels(timeoutHelper.GetCancellationToken());
 0293            OnAbortCore();
 0294        }
 295
 296        internal void Abort()
 297        {
 0298            WrapperCommunicationObj.Abort();
 0299        }
 300
 301        private void OnCloseCore(TimeSpan timeout)
 302        {
 0303            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 0304            ClearPendingSessions();
 0305            ClosePendingChannels(timeoutHelper.GetCancellationToken());
 0306            if (_inactivityTimer != null)
 307            {
 0308                _inactivityTimer.Cancel();
 309            }
 0310            if (_sessionProtocolFactory != null)
 311            {
 0312                _sessionProtocolFactory.OnCloseAsync(timeoutHelper.RemainingTime());
 313            }
 0314            if (SessionTokenAuthenticator != null)
 315            {
 0316                SecurityUtils.CloseTokenAuthenticatorIfRequiredAsync(SessionTokenAuthenticator, timeoutHelper.GetCancell
 317            }
 0318        }
 319
 320        private void OnAbortCore()
 321        {
 0322            if (_inactivityTimer != null)
 323            {
 0324                _inactivityTimer.Cancel();
 325            }
 0326            if (_sessionProtocolFactory != null)
 327            {
 0328                _sessionProtocolFactory.OnCloseAsync(TimeSpan.Zero);
 329            }
 0330            if (SessionTokenAuthenticator != null)
 331            {
 0332                SecurityUtils.AbortTokenAuthenticatorIfRequired(SessionTokenAuthenticator);
 333            }
 0334        }
 335
 336        private Task SetupSessionTokenAuthenticatorAsync()
 337        {
 22338            RecipientServiceModelSecurityTokenRequirement requirement = new RecipientServiceModelSecurityTokenRequiremen
 22339            _issuedTokenParameters.InitializeSecurityTokenRequirement(requirement);
 22340            requirement.KeyUsage = SecurityKeyUsage.Signature;
 22341            requirement.ListenUri = _listenUri;
 22342            requirement.SecurityBindingElement = _sessionProtocolFactory.SecurityBindingElement;
 22343            requirement.SecurityAlgorithmSuite = _sessionProtocolFactory.IncomingAlgorithmSuite;
 22344            requirement.SupportSecurityContextCancellation = true;
 22345            requirement.MessageSecurityVersion = _sessionProtocolFactory.MessageSecurityVersion.SecurityTokenVersion;
 346            // requirement.AuditLogLocation = sessionProtocolFactory.AuditLogLocation;
 347            // requirement.SuppressAuditFailure = sessionProtocolFactory.SuppressAuditFailure;
 348            // requirement.MessageAuthenticationAuditLevel = sessionProtocolFactory.MessageAuthenticationAuditLevel;
 22349            requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Inp
 22350            if (_sessionProtocolFactory.EndpointFilterTable != null)
 351            {
 0352                requirement.Properties[ServiceModelSecurityTokenRequirement.EndpointFilterTableProperty] = _sessionProto
 353            }
 22354            SessionTokenAuthenticator = _sessionProtocolFactory.SecurityTokenManager.CreateSecurityTokenAuthenticator(re
 22355            if (!(SessionTokenAuthenticator is IIssuanceSecurityTokenAuthenticator))
 356            {
 0357                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Sec
 358            }
 22359            if (_sessionTokenResolver == null || (!(_sessionTokenResolver is ISecurityContextSecurityTokenCache)))
 360            {
 0361                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Sec
 362            }
 22363            SessionTokenCache = (ISecurityContextSecurityTokenCache)_sessionTokenResolver;
 22364            return Task.CompletedTask;
 365        }
 366
 367        public void StopAcceptingNewWork()
 368        {
 0369            _acceptNewWork = false;
 0370        }
 371
 372        private int GetPendingSessionCount()
 373        {
 10374            return _pendingSessions1.Count + _pendingSessions2.Count;
 375        }
 376
 377        private void AbortPendingChannels(CancellationToken token)
 378        {
 0379            ClosePendingChannels(token);
 0380        }
 381
 382        private async void ClosePendingChannels(CancellationToken token)
 383        {
 0384            var tasks = new Task[_activeSessions.Count];
 0385            lock (ThisGlobalLock)
 386            {
 0387                int index = 0;
 0388                if (typeof(IReplyChannel).Equals(AcceptorChannelType))
 389                {
 0390                    foreach (ServerSecuritySimplexSessionChannel securitySessionSimplexChannel in _activeSessions.Values
 391                    {
 0392                        tasks[index] = securitySessionSimplexChannel.CloseAsync(token);
 0393                        index++;
 394                    }
 395                }
 0396            }
 0397            await Task.WhenAll(tasks);
 0398        }
 399
 400        private void ConfigureSessionSecurityProtocolFactory()
 401        {
 402            //TODO while implementing message security
 403
 404            //if (this.sessionProtocolFactory is SessionSymmetricMessageSecurityProtocolFactory)
 405            //{
 406            //    AddressingVersion addressing = MessageVersion.Default.Addressing;
 407            //    if (this.channelBuilder != null)
 408            //    {
 409            //        MessageEncodingBindingElement encoding = this.channelBuilder.Binding.Elements.Find<MessageEncoding
 410            //        if (encoding != null)
 411            //        {
 412            //            addressing = encoding.MessageVersion.Addressing;
 413            //        }
 414            //    }
 415
 416            //    if (addressing != AddressingVersion.WSAddressing10 && addressing != AddressingVersion.WSAddressingAugu
 417            //    {
 418            //        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
 419            //            new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, addressing)));
 420            //    }
 421
 422            //    SessionSymmetricMessageSecurityProtocolFactory messagePf = (SessionSymmetricMessageSecurityProtocolFac
 423            //    if (!messagePf.ApplyIntegrity || !messagePf.RequireIntegrity)
 424            //    {
 425            //        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
 426            //    }
 427            //    MessagePartSpecification bodyPart = new MessagePartSpecification(true);
 428            //    messagePf.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManag
 429            //    messagePf.ProtectionRequirements.IncomingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManag
 430            //    messagePf.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManag
 431            //    messagePf.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, this.SecurityStandardsManag
 432            //    messagePf.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, addressing.FaultAction);
 433            //    messagePf.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, addressing.DefaultFaultActi
 434            //    messagePf.ProtectionRequirements.OutgoingSignatureParts.AddParts(bodyPart, DotNetSecurityStrings.Secur
 435            //    if (messagePf.ApplyConfidentiality)
 436            //    {
 437            //        messagePf.ProtectionRequirements.OutgoingEncryptionParts.AddParts(MessagePartSpecification.NoParts
 438            //        messagePf.ProtectionRequirements.OutgoingEncryptionParts.AddParts(MessagePartSpecification.NoParts
 439            //        messagePf.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, addressing.FaultAction
 440            //        messagePf.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, addressing.DefaultFaul
 441            //        messagePf.ProtectionRequirements.OutgoingEncryptionParts.AddParts(bodyPart, DotNetSecurityStrings.
 442            //    }
 443            //    if (messagePf.RequireConfidentiality)
 444            //    {
 445            //        messagePf.ProtectionRequirements.IncomingEncryptionParts.AddParts(MessagePartSpecification.NoParts
 446            //        messagePf.ProtectionRequirements.IncomingEncryptionParts.AddParts(MessagePartSpecification.NoParts
 447            //    }
 448            //    messagePf.SecurityTokenParameters = this.IssuedSecurityTokenParameters;
 449            //}
 450            //else
 22451            if (_sessionProtocolFactory is SessionSymmetricTransportSecurityProtocolFactory sessionSymmetricProtocolFact
 452            {
 22453                sessionSymmetricProtocolFactory.AddTimestamp = true;
 22454                sessionSymmetricProtocolFactory.SecurityTokenParameters = IssuedSecurityTokenParameters;
 22455                sessionSymmetricProtocolFactory.SecurityTokenParameters.RequireDerivedKeys = false;
 456            }
 457            else
 458            {
 0459                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
 460            }
 461        }
 462
 463        private void OnTokenRenewed(SecurityToken newToken, SecurityToken oldToken)
 464        {
 0465            WrapperCommunicationObj.ThrowIfClosed();
 0466            if (!_acceptNewWork)
 467            {
 0468                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.SecurityListe
 469            }
 0470            if (!(newToken is SecurityContextSecurityToken newSecurityContextToken))
 471            {
 0472                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SessionToke
 473            }
 0474            if (!(oldToken is SecurityContextSecurityToken oldSecurityContextToken))
 475            {
 0476                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SessionToke
 477            }
 0478            IServerSecuritySessionChannel sessionChannel = FindSessionChannel(newSecurityContextToken.ContextId);
 0479            if (sessionChannel == null)
 480            {
 0481                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.Ca
 482            }
 0483            sessionChannel.RenewSessionToken(newSecurityContextToken, oldSecurityContextToken);
 0484        }
 485
 486        /// <summary>
 487        /// This method creates SessionInitiationMessageServiceDispatcher which would act as
 488        /// holder for SecurityReplySessionServiceChannelDispatcher (for Duplex we can implement simillar to ServerSecur
 489        /// Even though the Dispatcher is being added to demuxer, the ServiceChannelDispatcher is lazily initialized(bas
 490        /// When close received, the ServiceChannelDispatcher is cleared as well as the Dispatcher from Demuxer.
 491        /// </summary>
 492        /// <param name="sessionToken"></param>
 493        private void CreateSessionMessageServiceDispatcher(SecurityContextSecurityToken sessionToken, EndpointAddress re
 494        {
 10495            lock (ThisGlobalLock)
 496            {
 10497                MessageFilter sctFilter = new SecuritySessionFilter(sessionToken.ContextId, _sessionProtocolFactory.Stan
 10498                SessionInitiationMessageServiceDispatcher sessionServiceDispatcher
 10499                 = new SessionInitiationMessageServiceDispatcher(this, sessionToken, sctFilter, remoteAddress);
 500                //logic to separate for Duplex
 10501                if (typeof(IReplyChannel).Equals(AcceptorChannelType))
 502                {
 8503                    ChannelBuilder.AddServiceDispatcher<IReplyChannel>(sessionServiceDispatcher, new ChannelDemuxerFilte
 504                }
 2505                else if (typeof(IDuplexSessionChannel).Equals(AcceptorChannelType))
 506                {
 2507                    ChannelBuilder.AddServiceDispatcher<IDuplexSessionChannel>(sessionServiceDispatcher, new ChannelDemu
 508                }
 509
 10510                AddPendingSession(sessionToken.ContextId, sessionToken, sctFilter);
 10511            }
 10512        }
 513
 514        private void OnTokenIssued(SecurityToken issuedToken, EndpointAddress tokenRequestor)
 515        {
 10516            WrapperCommunicationObj.ThrowIfClosed(); //TODO mark open
 10517            if (!_acceptNewWork)
 518            {
 0519                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.SecurityListe
 520            }
 10521            if (!(issuedToken is SecurityContextSecurityToken issuedSecurityContextToken))
 522            {
 0523                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SessionToke
 524            }
 10525            CreateSessionMessageServiceDispatcher(issuedSecurityContextToken, tokenRequestor ?? EndpointAddress.Anonymou
 10526        }
 527
 528        internal SecurityContextSecurityToken GetSecurityContextSecurityToken(UniqueId sessionId)
 529        {
 0530            if (_pendingSessions1 != null && _pendingSessions1.ContainsKey(sessionId))
 531            {
 0532                return _pendingSessions1[sessionId];
 533            }
 534
 0535            if (_pendingSessions2 != null && _pendingSessions2.ContainsKey(sessionId))
 536            {
 0537                return _pendingSessions2[sessionId];
 538            }
 539
 0540            return null;
 541        }
 542
 543        private void OnTimer(object state)
 544        {
 44545            if (WrapperCommunicationObj.State == CommunicationState.Closed
 44546                || WrapperCommunicationObj.State == CommunicationState.Faulted)
 547            {
 0548                return;
 549            }
 550            try
 551            {
 44552                ClearPendingSessions();
 44553            }
 554            catch (Exception e)
 555            {
 0556                if (Fx.IsFatal(e))
 557                {
 0558                    throw;
 559                }
 0560            }
 561            finally
 562            {
 44563                if (WrapperCommunicationObj.State != CommunicationState.Closed
 44564                    && WrapperCommunicationObj.State != CommunicationState.Closing
 44565                    && WrapperCommunicationObj.State != CommunicationState.Faulted)
 566                {
 44567                    _inactivityTimer.Set(_inactivityTimeout);
 568                }
 44569            }
 44570        }
 571
 572        private void AddPendingSession(UniqueId sessionId, SecurityContextSecurityToken securityToken, MessageFilter fil
 573        {
 10574            lock (ThisGlobalLock)
 575            {
 10576                if ((GetPendingSessionCount() + 1) > MaximumPendingSessions)
 577                {
 0578                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(SR.SecuritySess
 579                }
 10580                if (_pendingSessions1.ContainsKey(sessionId) || _pendingSessions2.ContainsKey(sessionId))
 581                {
 0582                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(S
 583                }
 10584                _pendingSessions1.Add(sessionId, securityToken);
 10585                _sessionFilters.Add(sessionId, filter);
 10586            }
 587            //SecurityTraceRecordHelper.TracePendingSessionAdded(sessionId, this.Uri);
 588            //if (TD.SecuritySessionRatioIsEnabled())
 589            //{
 590            //    TD.SecuritySessionRatio(GetPendingSessionCount(), this.MaximumPendingSessions);
 591            //}
 10592        }
 593
 594        private void ClearPendingSessions()
 595        {
 44596            lock (ThisGlobalLock)
 597            {
 44598                if (_pendingSessions1.Count == 0 && _pendingSessions2.Count == 0)
 599                {
 44600                    return;
 601                }
 0602                foreach (UniqueId sessionId in _pendingSessions2.Keys)
 603                {
 0604                    SecurityContextSecurityToken token = _pendingSessions2[sessionId];
 605                    try
 606                    {
 607                        //TryCloseBinder(channelBinder, this.CloseTimeout); // Replacing this line with below (being pro
 0608                        RemoveServiceDispatcher(sessionId);
 0609                        SessionTokenCache.RemoveAllContexts(sessionId);
 0610                    }
 611                    catch (CommunicationException e)
 612                    {
 0613                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
 0614                    }
 615                    catch (TimeoutException e)
 616                    {
 617                        //if (TD.CloseTimeoutIsEnabled())
 618                        //{
 619                        //    TD.CloseTimeout(e.Message);
 620                        //}
 0621                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
 0622                    }
 623                    catch (ObjectDisposedException e)
 624                    {
 0625                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
 0626                    }
 627                    // SecurityTraceRecordHelper.TracePendingSessionClosed(sessionId, this.Uri);
 628                }
 0629                _pendingSessions2.Clear();
 0630                Dictionary<UniqueId, SecurityContextSecurityToken> temp = _pendingSessions2;
 0631                _pendingSessions2 = _pendingSessions1;
 0632                _pendingSessions1 = temp;
 0633            }
 44634        }
 635
 636        internal bool RemovePendingSession(UniqueId sessionId)
 637        {
 638            bool result;
 10639            lock (ThisGlobalLock)
 640            {
 10641                if (_pendingSessions1.ContainsKey(sessionId))
 642                {
 10643                    _pendingSessions1.Remove(sessionId);
 10644                    result = true;
 645                }
 0646                else if (_pendingSessions2.ContainsKey(sessionId))
 647                {
 0648                    _pendingSessions2.Remove(sessionId);
 0649                    result = true;
 650                }
 651                else
 652                {
 0653                    result = false;
 654                }
 0655            }
 656            /* if (result)
 657             {
 658                 SecurityTraceRecordHelper.TracePendingSessionActivated(sessionId, this.Uri);
 659                 if (TD.SecuritySessionRatioIsEnabled())
 660                 {
 661                     TD.SecuritySessionRatio(GetPendingSessionCount(), this.MaximumPendingSessions);
 662                 }
 663             }*/
 10664            return result;
 665        }
 666
 667        private IServerSecuritySessionChannel FindSessionChannel(UniqueId sessionId)
 668        {
 669            IServerSecuritySessionChannel result;
 0670            lock (ThisGlobalLock)
 671            {
 0672                _activeSessions.TryGetValue(sessionId, out result);
 0673            }
 0674            return result;
 675        }
 676
 677        private void AddSessionChannel(UniqueId sessionId, IServerSecuritySessionChannel channel, MessageFilter filter)
 678        {
 10679            lock (ThisGlobalLock)
 680            {
 10681                _activeSessions.Add(sessionId, channel);
 10682            }
 10683        }
 684
 685        internal void RemoveSessionChannel(string sessionId)
 686        {
 10687            RemoveSessionChannel(new UniqueId(sessionId));
 10688        }
 689
 690        private void RemoveSessionChannel(UniqueId sessionId)
 691        {
 10692            lock (ThisGlobalLock)
 693            {
 10694                RemoveServiceDispatcher(sessionId);
 10695                _activeSessions.Remove(sessionId);
 10696                _sessionFilters.Remove(sessionId);
 10697            }
 698            //SecurityTraceRecordHelper.TraceActiveSessionRemoved(sessionId, this.Uri);
 10699        }
 700
 701        private void RemoveServiceDispatcher(UniqueId sessionId)
 702        {
 10703            if (AcceptorChannelType == typeof(IReplyChannel))
 704            {
 8705                ChannelBuilder.RemoveServiceDispatcher<IReplyChannel>(_sessionFilters[sessionId]);
 706            }
 2707            else if (AcceptorChannelType == typeof(IDuplexSessionChannel))
 708            {
 2709                ChannelBuilder.RemoveServiceDispatcher<IDuplexSessionChannel>(_sessionFilters[sessionId]);
 710            }
 2711        }
 712
 713        public Task CloseAsync(TimeSpan timeout)
 714        {
 0715            return WrapperCommunicationObj.CloseAsync();
 716        }
 717        public Task OnCloseAsync(TimeSpan timeout)
 718        {
 0719            OnCloseCore(timeout);
 0720            return Task.CompletedTask;
 721        }
 722
 723        public Task OpenAsync(TimeSpan timeout)
 724        {
 22725            return WrapperCommunicationObj.OpenAsync();
 726        }
 727        public Task OnOpenAsync(TimeSpan timeout)
 728        {
 22729            if (_sessionProtocolFactory == null)
 730            {
 0731                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SecuritySessi
 732            }
 22733            if (_standardsManager == null)
 734            {
 0735                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Sec
 736            }
 22737            if (_issuedTokenParameters == null)
 738            {
 0739                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Iss
 740            }
 22741            if (_maximumKeyRenewalInterval < _keyRolloverInterval)
 742            {
 0743                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.KeyRolloverGr
 744            }
 22745            if (_securityServiceDispatcher == null)
 746            {
 0747                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Sec
 748            }
 22749            if (_settingsLifetimeManager == null)
 750            {
 0751                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.Sec
 752            }
 22753            MessageVersion = _channelBuilder.Binding.MessageVersion;
 22754            _listenUri = _securityServiceDispatcher.BaseAddress;
 22755            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 22756            _pendingSessions1 = new Dictionary<UniqueId, SecurityContextSecurityToken>();
 22757            _pendingSessions2 = new Dictionary<UniqueId, SecurityContextSecurityToken>();
 22758            _sessionFilters = new Dictionary<UniqueId, MessageFilter>();
 22759            if (_inactivityTimeout < TimeSpan.MaxValue)
 760            {
 22761                _inactivityTimer = new IOThreadTimer(new Action<object>(OnTimer), this, false);
 22762                _inactivityTimer.Set(_inactivityTimeout);
 763            }
 22764            ConfigureSessionSecurityProtocolFactory();
 22765            _sessionProtocolFactory.OpenAsync(timeoutHelper.RemainingTime());
 22766            SetupSessionTokenAuthenticatorAsync();
 22767            ((IIssuanceSecurityTokenAuthenticator)SessionTokenAuthenticator).IssuedSecurityTokenHandler = OnTokenIssued;
 22768            ((IIssuanceSecurityTokenAuthenticator)SessionTokenAuthenticator).RenewedSecurityTokenHandler = OnTokenRenewe
 22769            if (SessionTokenAuthenticator is SecuritySessionSecurityTokenAuthenticator securitySessionTokenAuthenticator
 770            {
 22771                securitySessionTokenAuthenticator.SecurityServiceDispatcher = SecurityServiceDispatcher;
 0772            }else if(SessionTokenAuthenticator is WrappedSessionSecurityTokenAuthenticator wrappedSessionSecurityTokenAu
 773            {
 0774                wrappedSessionSecurityTokenAuthenticator.SetSecureServiceDispatcher(SecurityServiceDispatcher);
 775            }
 22776            _acceptNewWork = true;
 22777            SecurityUtils.OpenTokenAuthenticatorIfRequiredAsync(SessionTokenAuthenticator, timeoutHelper.GetCancellation
 22778            return Task.CompletedTask;
 779        }
 780
 781        public void OnClosed()
 782        {
 0783            throw new NotImplementedException();
 784        }
 785
 786        public void OnClosing()
 787        {
 0788            throw new NotImplementedException();
 789        }
 790
 791        //Renaming SessionInitiationMessageHandler to SessionInitiationMessageServiceDispatcher
 792        //
 793        internal class SessionInitiationMessageServiceDispatcher : IServiceDispatcher
 794        {
 795            private readonly SecuritySessionServerSettings _settings;
 796            private readonly SecurityContextSecurityToken _sessionToken;
 797            private volatile IServiceChannelDispatcher _sessionChannelDispatcher;
 798            private readonly MessageFilter _messageFilter;
 799            private readonly EndpointAddress _remoteAddress;
 800
 10801            public SessionInitiationMessageServiceDispatcher(/*IServerReliableChannelBinder channelBinder,*/ SecuritySes
 802            {
 10803                _settings = settings;
 10804                _sessionToken = sessionToken;
 10805                _messageFilter = filter;
 10806                _remoteAddress = address;
 10807            }
 808
 0809            public Uri BaseAddress => throw new NotImplementedException();
 810
 0811            public Binding Binding => throw new NotImplementedException();
 812
 0813            public ServiceHostBase Host => throw new NotImplementedException();
 814
 20815            public AsyncLock AsyncLock { get; } = new AsyncLock();
 816
 0817            public IList<Type> SupportedChannelTypes => throw new NotImplementedException();
 818
 819            /// <summary>
 820            /// ProcessMessage equivalent in WCF
 821            /// </summary>
 822            /// <returns></returns>
 823            public async Task<IServiceChannelDispatcher> CreateServiceChannelDispatcherAsync(IChannel channel)
 824            {
 20825                if (_sessionChannelDispatcher == null)
 826                {
 10827                    await using (await AsyncLock.TakeLockAsync())
 828                    {
 10829                        if (_sessionChannelDispatcher == null)
 830                        {
 10831                            if (!_settings.RemovePendingSession(_sessionToken.ContextId))
 832                            {
 0833                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(
 0834                                    new CommunicationException(SR.Format(SR.SecuritySessionNotPending,
 0835                                        _sessionToken.ContextId)));
 836                            }
 837
 10838                            ServerSecuritySessionChannel _replySessionChannelDispatcher = null;
 10839                            if (_settings.AcceptorChannelType == typeof(IDuplexSessionChannel))
 840                            {
 2841                                _replySessionChannelDispatcher = new ServerSecurityDuplexSessionChannel.
 2842                                    ServerSecurityDuplexSessionChannelDispatcher(_settings, _sessionToken,
 2843                                        null, _settings.SettingsLifetimeManager, channel, _remoteAddress);
 844
 845                            }
 8846                            else if (_settings.AcceptorChannelType == typeof(IReplyChannel))
 847                            {
 8848                                _replySessionChannelDispatcher = new ServerSecuritySimplexSessionChannel.
 8849                                    SecurityReplySessionServiceChannelDispatcher(_settings, _sessionToken,
 8850                                        null, _settings.SettingsLifetimeManager, channel, _remoteAddress);
 851                            }
 852
 10853                            await _replySessionChannelDispatcher.OpenAsync(ServiceDefaults.OpenTimeout);
 10854                            _sessionChannelDispatcher = (IServiceChannelDispatcher)_replySessionChannelDispatcher;
 10855                            _settings.AddSessionChannel(_sessionToken.ContextId, _replySessionChannelDispatcher,
 10856                                _messageFilter);
 10857                        }
 858                    }
 859                }
 20860                return _sessionChannelDispatcher;
 20861            }
 862        }
 863
 864        private interface IServerSecuritySessionChannel
 865        {
 866            void RenewSessionToken(SecurityContextSecurityToken newToken, SecurityContextSecurityToken supportingToken);
 867        }
 868
 869        private abstract class ServerSecuritySessionChannel : /*ChannelBase,*/ IServerSecuritySessionChannel
 870        {
 871            private FaultCode _renewFaultCode;
 872            private FaultReason _renewFaultReason;
 873            private FaultCode _sessionAbortedFaultCode;
 874            private FaultReason _sessionAbortedFaultReason;
 875
 876            // Double-checked locking pattern requires volatile for read/write synchronization
 877            private bool _areFaultCodesInitialized;
 878            //private readonly IServerReliableChannelBinder _channelBinder;
 879            private readonly SecurityProtocol _securityProtocol;
 880
 881            // This is used to sign outgoing messages
 882            private SecurityContextSecurityToken _currentSessionToken;
 883            private readonly UniqueId _sessionId;
 884
 885            // These are renewed tokens that have not been used as yet
 886            private readonly List<SecurityContextSecurityToken> _futureSessionTokens;
 887            private RequestContext _initialRequestContext;
 888            private bool _isInputClosed;
 889            private readonly MessageVersion _messageVersion;
 890            private readonly SecurityListenerSettingsLifetimeManager _settingsLifetimeManager;
 891            private bool _hasSecurityStateReference;
 892
 10893            protected ServerSecuritySessionChannel(SecuritySessionServerSettings settings,
 10894                SecurityContextSecurityToken sessionToken,
 10895                object listenerSecurityProtocolState,
 10896                SecurityListenerSettingsLifetimeManager settingsLifetimeManager, EndpointAddress address)
 897            {
 10898                Settings = settings;
 10899                _messageVersion = settings.MessageVersion;
 900                // See issue #285
 901                // channelBinder.Faulted += this.OnInnerFaulted;
 10902                _securityProtocol = Settings.SessionProtocolFactory.CreateSecurityProtocol(null, null, true, TimeSpan.Ze
 10903                if (!(_securityProtocol is IAcceptorSecuritySessionProtocol))
 904                {
 905                    Fx.Assert("Security protocol must be IAcceptorSecuritySessionProtocol.");
 0906                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR
 907                }
 10908                _currentSessionToken = sessionToken;
 10909                _sessionId = sessionToken.ContextId;
 10910                _futureSessionTokens = new List<SecurityContextSecurityToken>(1);
 10911                ((IAcceptorSecuritySessionProtocol)_securityProtocol).SetOutgoingSessionToken(sessionToken);
 10912                ((IAcceptorSecuritySessionProtocol)_securityProtocol).SetSessionTokenAuthenticator(_sessionId, Settings.
 10913                _settingsLifetimeManager = settingsLifetimeManager;
 10914                LocalAddress = address;
 10915                LocalLock = new object();
 10916            }
 917
 254918            protected SecuritySessionServerSettings Settings { get; }
 919
 2920            protected virtual bool CanDoSecurityCorrelation => false;
 921
 0922            internal TimeSpan InternalSendTimeout => ServiceDefaults.SendTimeout;
 923
 2924            public EndpointAddress LocalAddress { get; }
 925
 64926            public object LocalLock { get; }
 927
 66928            public CommunicationState State => Settings.WrapperCommunicationObj.State;
 929
 78930            internal SecurityProtocol SecurityProtocol => _securityProtocol;
 931
 932            public virtual Task OpenAsync(TimeSpan timeout)
 933            {
 10934                SecurityProtocol.OpenAsync(timeout);
 10935                if (CanDoSecurityCorrelation)
 936                {
 8937                    ((IAcceptorSecuritySessionProtocol)SecurityProtocol).ReturnCorrelationState = true;
 938                } // if an abort happened concurrently with the open, then return
 10939                if (State == CommunicationState.Closed || State == CommunicationState.Closing)
 940                {
 0941                    return Task.CompletedTask;
 942                }
 10943                _settingsLifetimeManager.AddReference();
 10944                _hasSecurityStateReference = true;
 10945                return Task.CompletedTask;
 946            }
 947
 948            protected virtual void AbortCore()
 949            {
 0950                if (SecurityProtocol != null)
 951                {
 0952                    TimeoutHelper timeout = new TimeoutHelper(ServiceDefaults.CloseTimeout);
 0953                    SecurityProtocol.CloseAsync(true, timeout.RemainingTime());
 954                }
 0955                Settings.SessionTokenCache.RemoveAllContexts(_currentSessionToken.ContextId);
 0956                bool abortLifetimeManager = false;
 0957                lock (LocalLock)
 958                {
 0959                    if (_hasSecurityStateReference)
 960                    {
 0961                        abortLifetimeManager = true;
 0962                        _hasSecurityStateReference = false;
 963                    }
 0964                }
 0965                if (abortLifetimeManager)
 966                {
 0967                    _settingsLifetimeManager.Abort();
 968                }
 0969            }
 970
 971            protected virtual async Task CloseCoreAsync(CancellationToken token)
 972            {
 973                try
 974                {
 10975                    TimeoutHelper helper = new TimeoutHelper(ServiceDefaults.CloseTimeout);
 10976                    if (SecurityProtocol != null)
 977                    {
 10978                        await SecurityProtocol.CloseAsync(false, helper.RemainingTime());
 979                    }
 10980                    bool closeLifetimeManager = false;
 10981                    lock (LocalLock)
 982                    {
 10983                        if (_hasSecurityStateReference)
 984                        {
 10985                            closeLifetimeManager = true;
 10986                            _hasSecurityStateReference = false;
 987                        }
 10988                    }
 10989                    if (closeLifetimeManager)
 990                    {
 10991                        await _settingsLifetimeManager.CloseAsync(helper.RemainingTime());
 992                    }
 10993                }
 0994                catch (CommunicationObjectAbortedException)
 995                {
 0996                    if (State != CommunicationState.Closed)
 997                    {
 0998                        throw;
 999                    }
 1000                    // a parallel thread aborted the channel. Ignore the exception
 01001                }
 101002                Settings.SessionTokenCache.RemoveAllContexts(_currentSessionToken.ContextId);
 101003            }
 1004
 1005            protected abstract void OnCloseMessageReceived(RequestContext requestContext, Message message, SecurityProto
 1006
 1007            protected abstract void OnCloseResponseMessageReceived(RequestContext requestContext, Message message, Secur
 1008
 1009            public void RenewSessionToken(SecurityContextSecurityToken newToken, SecurityContextSecurityToken supporting
 1010            {
 01011                ThrowIfClosedOrNotOpen();
 1012                // enforce that the token being renewed is the current session token
 01013                lock (LocalLock)
 1014                {
 01015                    if (supportingToken.ContextId != _currentSessionToken.ContextId || supportingToken.KeyGeneration != 
 1016                    {
 01017                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Form
 1018                    }
 01019                    if (_futureSessionTokens.Count == Settings.MaximumPendingKeysPerSession)
 1020                    {
 01021                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.TooM
 1022                    }
 01023                    _futureSessionTokens.Add(newToken);
 01024                }
 1025                // SecurityTraceRecordHelper.TraceNewServerSessionKeyIssued(newToken, supportingToken, GetLocalUri());
 01026            }
 1027
 1028            //protected Uri GetLocalUri()
 1029            //{
 1030            //    if (_channelBinder.LocalAddress == null)
 1031            //    {
 1032            //        return null;
 1033            //    }
 1034            //    else
 1035            //    {
 1036            //        return _channelBinder.LocalAddress.Uri;
 1037            //    }
 1038            //}
 1039
 1040            // TODO: Wire up the channel binder faults to call this.
 1041            //private void OnInnerFaulted(IReliableChannelBinder sender, Exception exception)
 1042            //{
 1043            //    OnFaulted(exception);
 1044            //}
 1045
 1046            private SecurityContextSecurityToken GetSessionToken(SecurityMessageProperty securityProperty)
 1047            {
 201048                SecurityContextSecurityToken sct = (securityProperty.ProtectionToken != null) ? securityProperty.Protect
 201049                if (sct != null && sct.ContextId == _sessionId)
 1050                {
 01051                    return sct;
 1052                }
 201053                if (securityProperty.HasIncomingSupportingTokens)
 1054                {
 401055                    for (int i = 0; i < securityProperty.IncomingSupportingTokens.Count; ++i)
 1056                    {
 201057                        if (securityProperty.IncomingSupportingTokens[i].SecurityTokenAttachmentMode == SecurityTokenAtt
 1058                        {
 201059                            sct = (securityProperty.IncomingSupportingTokens[i].SecurityToken as SecurityContextSecurity
 201060                            if (sct != null && sct.ContextId == _sessionId)
 1061                            {
 201062                                return sct;
 1063                            }
 1064                        }
 1065                    }
 1066                }
 01067                return null;
 1068            }
 1069
 1070            private bool CheckIncomingToken(RequestContext requestContext, Message message, SecurityProtocolCorrelationS
 1071            {
 201072                SecurityMessageProperty securityProperty = message.Properties.Security;
 1073                // this is guaranteed to be non-null and matches the session ID since the binding checked it
 201074                SecurityContextSecurityToken incomingToken = GetSessionToken(securityProperty);
 201075                if (incomingToken == null)
 1076                {
 01077                    throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.NoSessionTokenPresentInMessage
 1078                }
 1079                // the incoming token's key should have been issued within keyRenewalPeriod time in the past
 1080                // if not, send back a renewal fault. However if this is a session close message then its ok to not requ
 1081                // to renew the key in order to send the close.
 201082                if (incomingToken.KeyExpirationTime < DateTime.UtcNow &&
 201083                    message.Headers.Action != Settings.SecurityStandardsManager.SecureConversationDriver.CloseAction.Val
 1084                {
 01085                    if (Settings.CanRenewSession)
 1086                    {
 01087                        SendRenewFault(requestContext, correlationState, timeout);
 01088                        return false;
 1089                    }
 1090                    else
 1091                    {
 01092                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new Exception(SR.Format(SR.SecurityC
 1093                    }
 1094                }
 1095                // this is a valid token. If it corresponds to a newly issued session token, make it the current
 1096                // session token.
 201097                lock (LocalLock)
 1098                {
 201099                    if (_futureSessionTokens.Count > 0 && incomingToken.KeyGeneration != _currentSessionToken.KeyGenerat
 1100                    {
 01101                        bool changedCurrentSessionToken = false;
 01102                        for (int i = 0; i < _futureSessionTokens.Count; ++i)
 1103                        {
 01104                            if (_futureSessionTokens[i].KeyGeneration == incomingToken.KeyGeneration)
 1105                            {
 1106                                // let the current token expire after KeyRollover time interval
 01107                                DateTime keyRolloverTime = TimeoutHelper.Add(DateTime.UtcNow, Settings.KeyRolloverInterv
 01108                                Settings.SessionTokenCache.UpdateContextCachingTime(_currentSessionToken, keyRolloverTim
 01109                                _currentSessionToken = _futureSessionTokens[i];
 01110                                _futureSessionTokens.RemoveAt(i);
 01111                                ((IAcceptorSecuritySessionProtocol)SecurityProtocol).SetOutgoingSessionToken(_currentSes
 01112                                changedCurrentSessionToken = true;
 01113                                break;
 1114                            }
 1115                        }
 01116                        if (changedCurrentSessionToken)
 1117                        {
 1118                            // SecurityTraceRecordHelper.TraceServerSessionKeyUpdated(this.currentSessionToken, GetLocal
 1119                            // remove all renewed tokens that will never be used.
 01120                            for (int i = 0; i < _futureSessionTokens.Count; ++i)
 1121                            {
 01122                                Settings.SessionTokenCache.RemoveContext(_futureSessionTokens[i].ContextId, _futureSessi
 1123                            }
 01124                            _futureSessionTokens.Clear();
 1125                        }
 1126                    }
 201127                }
 1128
 201129                return true;
 1130            }
 1131
 1132            public ValueTask<RequestContext> ReceiveRequestAsync(RequestContext initialRequestContext)
 1133            {
 201134                return ReceiveRequestAsync(ServiceDefaults.ReceiveTimeout, initialRequestContext);
 1135            }
 1136
 1137            public async ValueTask<RequestContext> ReceiveRequestAsync(TimeSpan timeout, RequestContext initialRequestCo
 1138            {
 201139                _initialRequestContext = initialRequestContext;
 201140                (bool success, RequestContext requestContext) receiveRequestTry = await TryReceiveRequestAsync(timeout);
 201141                RequestContext requestContext = receiveRequestTry.requestContext;
 1142
 201143                if (receiveRequestTry.success)
 1144                {
 201145                    return requestContext;
 1146                }
 1147                else
 1148                {
 01149                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException());
 1150                }
 201151            }
 1152
 1153            public async ValueTask<(bool, RequestContext)> TryReceiveRequestAsync(TimeSpan timeout)
 1154            {
 221155                ThrowIfFaulted();
 221156                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 101157                while (true)
 1158                {
 321159                    if (_isInputClosed || State == CommunicationState.Faulted)
 1160                    {
 1161                        break;
 1162                    }
 201163                    if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
 1164                    {
 01165                        return (false, null);
 1166                    }
 1167
 1168                    RequestContext innerRequestContext;
 201169                    if (_initialRequestContext != null)
 1170                    {
 201171                        innerRequestContext = _initialRequestContext;
 201172                        _initialRequestContext = null;
 1173                    }
 1174                    else
 1175                    {
 01176                        return (false, null);
 1177                    }
 201178                    if (innerRequestContext == null)
 1179                    {
 1180                        // the channel could have been aborted or closed
 1181                        break;
 1182                    }
 201183                    if (_isInputClosed && innerRequestContext.RequestMessage != null)
 1184                    {
 01185                        Message message = innerRequestContext.RequestMessage;
 1186                        try
 1187                        {
 01188                            ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
 01189                            throw TraceUtility.ThrowHelperWarning(error, message);
 1190                        }
 1191                        finally
 1192                        {
 01193                            message.Close();
 01194                            innerRequestContext.Abort();
 1195                        }
 1196                    }
 1197
 201198                    (Message message, SecurityProtocolCorrelationState correlationState, bool _) processedRequestContext
 201199                    if (processedRequestContext.message != null)
 1200                    {
 101201                        RequestContext requestContext = new SecuritySessionRequestContext(innerRequestContext, processed
 101202                        return (true, requestContext);
 1203                    }
 101204                }
 121205                ThrowIfFaulted();
 1206
 121207                return (true, null);
 221208            }
 1209
 1210            private void ThrowIfFaulted()
 1211            {
 441212                Settings.WrapperCommunicationObj.ThrowIfFaulted();
 441213            }
 1214
 1215            //public override T GetProperty<T>()
 1216            //{
 1217            //    if (typeof(T) == typeof(FaultConverter) && (this.channelBinder != null))
 1218            //    {
 1219            //        return new SecurityChannelFaultConverter(this.channelBinder.Channel) as T;
 1220            //    }
 1221
 1222            //    T result = base.GetProperty<T>();
 1223            //    if ((result == null) && (channelBinder != null) && (channelBinder.Channel != null))
 1224            //    {
 1225            //        result = channelBinder.Channel.GetProperty<T>();
 1226            //    }
 1227
 1228            //    return result;
 1229            //}
 1230
 1231            private void SendFaultIfRequired(Exception e, Message unverifiedMessage, RequestContext requestContext, Time
 1232            {
 1233                try
 1234                {
 01235                    MessageFault fault = SecurityUtils.CreateSecurityMessageFault(e, SecurityProtocol.SecurityProtocolFa
 01236                    if (fault == null)
 1237                    {
 01238                        return;
 1239                    }
 01240                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 1241                    try
 1242                    {
 01243                        using (Message faultMessage = Message.CreateMessage(unverifiedMessage.Version, fault, unverified
 1244                        {
 01245                            if (unverifiedMessage.Headers.MessageId != null)
 1246                            {
 01247                                faultMessage.InitializeReply(unverifiedMessage);
 1248                            }
 1249
 01250                            requestContext.ReplyAsync(faultMessage, timeoutHelper.GetCancellationToken());
 01251                            requestContext.CloseAsync(timeoutHelper.GetCancellationToken());
 01252                        }
 01253                    }
 1254                    catch (CommunicationException ex)
 1255                    {
 01256                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
 01257                    }
 1258                    catch (TimeoutException ex)
 1259                    {
 1260                        //if (TD.CloseTimeoutIsEnabled())
 1261                        //{
 1262                        //    TD.CloseTimeout(e.Message);
 1263                        //}
 01264                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
 01265                    }
 1266                }
 1267                finally
 1268                {
 01269                    unverifiedMessage.Close();
 01270                    requestContext.Abort();
 01271                }
 01272            }
 1273
 1274            private bool ShouldWrapException(Exception e)
 1275            {
 01276                return ((e is FormatException) || (e is XmlException));
 1277            }
 1278
 1279            private async ValueTask<(Message, SecurityProtocolCorrelationState, bool)> ProcessRequestContextAsync(Reques
 1280            {
 201281                SecurityProtocolCorrelationState correlationState = null;
 201282                bool isSecurityProcessingFailure = false;
 201283                if (requestContext == null)
 1284                {
 01285                    return (null, correlationState, isSecurityProcessingFailure);
 1286                }
 1287
 201288                Message result = null;
 201289                Message message = requestContext.RequestMessage;
 201290                bool cleanupContextState = true;
 1291                try
 1292                {
 201293                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 201294                    Message unverifiedMessage = message;
 201295                    Exception securityException = null;
 1296                    try
 1297                    {
 201298                        (Message message, SecurityProtocolCorrelationState correlationState) verifiedIncomingMessage = a
 201299                        message = verifiedIncomingMessage.message;
 201300                        correlationState = verifiedIncomingMessage.correlationState;
 1301                        // message.Properties.Security
 201302                    }
 01303                    catch (MessageSecurityException e)
 1304                    {
 01305                        isSecurityProcessingFailure = true;
 01306                        securityException = e;
 01307                        throw;
 1308                    }
 201309                    if (securityException != null)
 1310                    {
 1311                        // SendFaultIfRequired closes the unverified message and context
 01312                        SendFaultIfRequired(securityException, unverifiedMessage, requestContext, timeoutHelper.Remainin
 01313                        cleanupContextState = false;
 01314                        return (null, correlationState, isSecurityProcessingFailure);
 1315                    }
 201316                    else if (CheckIncomingToken(requestContext, message, correlationState, timeoutHelper.RemainingTime()
 1317                    {
 201318                        if (message.Headers.Action == Settings.SecurityStandardsManager.SecureConversationDriver.CloseAc
 1319                        {
 1320                            //  SecurityTraceRecordHelper.TraceServerSessionCloseReceived(this.currentSessionToken, GetL
 101321                            _isInputClosed = true;
 1322                            // OnCloseMessageReceived is responsible for closing the message and requestContext if requi
 101323                            OnCloseMessageReceived(requestContext, message, correlationState, timeoutHelper.GetCancellat
 101324                            correlationState = null;
 1325                        }
 101326                        else if (message.Headers.Action == Settings.SecurityStandardsManager.SecureConversationDriver.Cl
 1327                        {
 1328                            // SecurityTraceRecordHelper.TraceServerSessionCloseResponseReceived(this.currentSessionToke
 01329                            _isInputClosed = true;
 1330                            // OnCloseResponseMessageReceived is responsible for closing the message and requestContext 
 01331                            OnCloseResponseMessageReceived(requestContext, message, correlationState, timeoutHelper.Rema
 01332                            correlationState = null;
 1333                        }
 1334                        else
 1335                        {
 101336                            result = message;
 1337                        }
 201338                        cleanupContextState = false;
 1339                    }
 201340                }
 01341                catch (Exception e)
 1342                {
 01343                    if ((e is CommunicationException) || (e is TimeoutException) || (Fx.IsFatal(e)) || !ShouldWrapExcept
 1344                    {
 01345                        throw;
 1346                    }
 01347                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.MessageS
 1348                }
 1349                finally
 1350                {
 201351                    if (cleanupContextState)
 1352                    {
 01353                        if (requestContext.RequestMessage != null)
 1354                        {
 01355                            requestContext.RequestMessage.Close();
 1356                        }
 01357                        requestContext.Abort();
 1358                    }
 1359                }
 1360
 201361                return (result, correlationState, isSecurityProcessingFailure);
 201362            }
 1363
 1364            internal void CheckOutgoingToken()
 1365            {
 101366                lock (LocalLock)
 1367                {
 101368                    if (_currentSessionToken.KeyExpirationTime < DateTime.UtcNow)
 1369                    {
 01370                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Exception(SR.SecuritySessionKeyIsS
 1371                    }
 101372                }
 101373            }
 1374
 1375            internal void SecureApplicationMessage(ref Message message, SecurityProtocolCorrelationState correlationStat
 1376            {
 101377                ThrowIfFaulted();
 101378                ThrowIfClosedOrNotOpen();
 101379                CheckOutgoingToken();
 101380                message = SecurityProtocol.SecureOutgoingMessage(message, token);
 101381            }
 1382
 1383            private void ThrowIfClosedOrNotOpen()
 1384            {
 1385                //throw new NotImplementedException();
 101386            }
 1387
 1388            internal async ValueTask<(Message, SecurityProtocolCorrelationState)> VerifyIncomingMessageAsync(Message mes
 1389            {
 201390                return await SecurityProtocol.VerifyIncomingMessageAsync(message, timeout, null);
 201391            }
 1392
 1393            private void PrepareReply(Message request, Message reply)
 1394            {
 101395                if (request.Headers.ReplyTo != null)
 1396                {
 101397                    request.Headers.ReplyTo.ApplyTo(reply);
 1398                }
 01399                else if (request.Headers.From != null)
 1400                {
 01401                    request.Headers.From.ApplyTo(reply);
 1402                }
 101403                if (request.Headers.MessageId != null)
 1404                {
 101405                    reply.Headers.RelatesTo = request.Headers.MessageId;
 1406                }
 1407                //TraceUtility.CopyActivity(request, reply);
 1408                //if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
 1409                //{
 1410                //    TraceUtility.AddActivityHeader(reply);
 1411                //}
 101412            }
 1413
 1414            protected void InitializeFaultCodesIfRequired()
 1415            {
 01416                if (!_areFaultCodesInitialized)
 1417                {
 01418                    lock (LocalLock)
 1419                    {
 01420                        if (!_areFaultCodesInitialized)
 1421                        {
 01422                            SecurityStandardsManager standardsManager = SecurityProtocol.SecurityProtocolFactory.Standar
 01423                            SecureConversationDriver scDriver = standardsManager.SecureConversationDriver;
 01424                            _renewFaultCode = FaultCode.CreateSenderFaultCode(scDriver.RenewNeededFaultCode.Value, scDri
 01425                            _renewFaultReason = new FaultReason(SR.SecurityRenewFaultReason, System.Globalization.Cultur
 01426                            _sessionAbortedFaultCode = FaultCode.CreateSenderFaultCode(DotNetSecurityStrings.SecuritySes
 01427                            _sessionAbortedFaultReason = new FaultReason(SR.SecuritySessionAbortedFaultReason, System.Gl
 01428                            _areFaultCodesInitialized = true;
 1429                        }
 01430                    }
 1431                }
 01432            }
 1433
 1434            [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Ju
 1435            private void SendRenewFault(RequestContext requestContext, SecurityProtocolCorrelationState correlationState
 1436            {
 01437                Message message = requestContext.RequestMessage;
 1438                try
 1439                {
 01440                    InitializeFaultCodesIfRequired();
 01441                    MessageFault renewFault = MessageFault.CreateFault(_renewFaultCode, _renewFaultReason);
 1442                    Message response;
 01443                    if (message.Headers.MessageId != null)
 1444                    {
 01445                        response = Message.CreateMessage(message.Version, renewFault, DotNetSecurityStrings.SecuritySess
 01446                        response.InitializeReply(message);
 1447                    }
 1448                    else
 1449                    {
 01450                        response = Message.CreateMessage(message.Version, renewFault, DotNetSecurityStrings.SecuritySess
 1451                    }
 1452                    try
 1453                    {
 01454                        PrepareReply(message, response);
 01455                        TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 01456                        response = SecurityProtocol.SecureOutgoingMessage(response, timeoutHelper.GetCancellationToken()
 01457                        response.Properties.AllowOutputBatching = false;
 01458                        var messageTask = SendMessageAsync(requestContext, response, timeoutHelper.GetCancellationToken(
 01459                        messageTask.GetAwaiter().GetResult();
 01460                    }
 1461                    finally
 1462                    {
 01463                        response.Close();
 01464                    }
 1465                    //  SecurityTraceRecordHelper.TraceSessionRenewalFaultSent(this.currentSessionToken, GetLocalUri(), 
 01466                }
 01467                catch (CommunicationException/* e*/)
 1468                {
 1469                    //SecurityTraceRecordHelper.TraceRenewFaultSendFailure(this.currentSessionToken, GetLocalUri(), e);
 01470                }
 01471                catch (TimeoutException/* e*/)
 1472                {
 1473                    // SecurityTraceRecordHelper.TraceRenewFaultSendFailure(this.currentSessionToken, GetLocalUri(), e);
 01474                }
 01475            }
 1476
 1477            private Message ProcessCloseRequest(Message request)
 1478            {
 1479                RequestSecurityToken rst;
 101480                XmlDictionaryReader bodyReader = request.GetReaderAtBodyContents();
 101481                using (bodyReader)
 1482                {
 101483                    rst = Settings.SecurityStandardsManager.TrustDriver.CreateRequestSecurityToken(bodyReader);
 101484                    request.ReadFromBodyContentsToEnd(bodyReader);
 101485                }
 101486                if (rst.RequestType != null && rst.RequestType != Settings.SecurityStandardsManager.TrustDriver.RequestT
 1487                {
 01488                    throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.InvalidRstRequestTyp
 1489                }
 101490                if (rst.CloseTarget == null)
 1491                {
 01492                    throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.NoCloseTargetSpecified), reque
 1493                }
 101494                if (!(rst.CloseTarget is SecurityContextKeyIdentifierClause sctSkiClause) || !SecuritySessionSecurityTok
 1495                {
 01496                    throw TraceUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.BadCloseTarget, rst.
 1497                }
 101498                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(Settings.SecurityStandardsManager)
 101499                {
 101500                    Context = rst.Context,
 101501                    IsRequestedTokenClosed = true
 101502                };
 101503                rstr.MakeReadOnly();
 101504                BodyWriter bodyWriter = rstr;
 101505                if (Settings.SecurityStandardsManager.MessageSecurityVersion.TrustVersion == TrustVersion.WSTrust13)
 1506                {
 41507                    List<RequestSecurityTokenResponse> rstrList = new List<RequestSecurityTokenResponse>(1)
 41508                    {
 41509                        rstr
 41510                    };
 41511                    RequestSecurityTokenResponseCollection rstrc = new RequestSecurityTokenResponseCollection(rstrList, 
 41512                    bodyWriter = rstrc;
 1513                }
 101514                Message response = Message.CreateMessage(request.Version, ActionHeader.Create(Settings.SecurityStandards
 101515                PrepareReply(request, response);
 101516                return response;
 1517            }
 1518
 1519            internal Message CreateCloseResponse(Message message, SecurityProtocolCorrelationState correlationState, Can
 1520            {
 101521                using (message)
 1522                {
 101523                    Message response = ProcessCloseRequest(message);
 101524                    response = SecurityProtocol.SecureOutgoingMessage(response, token);
 101525                    response.Properties.AllowOutputBatching = false;
 101526                    return response;
 1527                }
 101528            }
 1529
 1530            internal void TraceSessionClosedResponseSuccess()
 1531            {
 1532                // SecurityTraceRecordHelper.TraceSessionClosedResponseSent(this.currentSessionToken, GetLocalUri());
 101533            }
 1534
 1535            internal void TraceSessionClosedResponseFailure(Exception e)
 1536            {
 1537                // SecurityTraceRecordHelper.TraceSessionClosedResponseSendFailure(this.currentSessionToken, GetLocalUri
 01538            }
 1539
 1540            internal void TraceSessionClosedSuccess()
 1541            {
 1542                //  SecurityTraceRecordHelper.TraceSessionClosedSent(this.currentSessionToken, GetLocalUri());
 01543            }
 1544
 1545            internal void TraceSessionClosedFailure(Exception e)
 1546            {
 1547                //  SecurityTraceRecordHelper.TraceSessionCloseSendFailure(this.currentSessionToken, GetLocalUri(), e);
 01548            }
 1549
 1550            // SendCloseResponse closes the message and underlying context if the operation completes successfully
 1551            protected async Task SendCloseResponseAsync(RequestContext requestContext, Message closeResponse, Cancellati
 1552            {
 1553                try
 1554                {
 101555                    using (closeResponse)
 1556                    {
 101557                        await SendMessageAsync(requestContext, closeResponse, token);
 101558                    }
 1559
 101560                    TraceSessionClosedResponseSuccess();
 101561                }
 01562                catch (CommunicationException e)
 1563                {
 01564                    TraceSessionClosedResponseFailure(e);
 01565                }
 01566                catch (TimeoutException e)
 1567                {
 01568                    TraceSessionClosedResponseFailure(e);
 01569                }
 101570            }
 1571
 1572            internal Message CreateCloseMessage(CancellationToken token)
 1573            {
 01574                RequestSecurityToken rst = new RequestSecurityToken(Settings.SecurityStandardsManager)
 01575                {
 01576                    RequestType = Settings.SecurityStandardsManager.TrustDriver.RequestTypeClose,
 01577                    CloseTarget = Settings.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(_currentSessionToken,
 01578                };
 01579                rst.MakeReadOnly();
 01580                Message closeMessage = Message.CreateMessage(_messageVersion, ActionHeader.Create(Settings.SecurityStand
 01581                RequestReplyCorrelator.PrepareRequest(closeMessage);
 01582                if (LocalAddress != null)
 1583                {
 01584                    closeMessage.Headers.ReplyTo = LocalAddress;
 1585                }
 1586                else
 1587                {
 01588                    if (closeMessage.Version.Addressing == AddressingVersion.WSAddressing10)
 1589                    {
 01590                        closeMessage.Headers.ReplyTo = null;
 1591                    }
 01592                    else if (closeMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
 1593                    {
 01594                        closeMessage.Headers.ReplyTo = EndpointAddress.AnonymousAddress;
 1595                    }
 1596                    else
 1597                    {
 01598                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
 01599                            new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, closeMessage.Version.Addre
 1600                    }
 1601                }
 01602                SecurityProtocol.SecureOutgoingMessage(closeMessage, token);
 01603                closeMessage.Properties.AllowOutputBatching = false;
 01604                return closeMessage;
 1605            }
 1606
 1607            protected async Task SendCloseAsync(CancellationToken token)
 1608            {
 1609                try
 1610                {
 01611                    using (Message closeMessage = CreateCloseMessage(token))
 1612                    {
 01613                        await SendMessageAsync(null, closeMessage, token);
 01614                    }
 01615                    TraceSessionClosedSuccess();
 01616                }
 01617                catch (CommunicationException e)
 1618                {
 01619                    TraceSessionClosedFailure(e);
 01620                }
 01621                catch (TimeoutException e)
 1622                {
 01623                    TraceSessionClosedFailure(e);
 01624                }
 01625            }
 1626
 1627            protected async Task SendMessageAsync(RequestContext requestContext, Message message, CancellationToken toke
 1628            {
 101629                if (requestContext != null)
 1630                {
 101631                    await requestContext.ReplyAsync(message, token);
 101632                    await requestContext.CloseAsync(token);
 1633                }
 101634            }
 1635
 1636            internal virtual void OnFaulted(Exception ex)
 1637            {
 01638                Settings.WrapperCommunicationObj.Fault(ex);
 01639            }
 1640
 1641            protected class SoapSecurityInputSession : ISecureConversationSession, IInputSession
 1642            {
 1643                private readonly ServerSecuritySessionChannel _channel;
 1644                private readonly UniqueId _securityContextTokenId;
 1645                private readonly SecurityKeyIdentifierClause _sessionTokenIdentifier;
 1646                private readonly SecurityStandardsManager _standardsManager;
 1647
 101648                public SoapSecurityInputSession(SecurityContextSecurityToken sessionToken,
 101649                    SecuritySessionServerSettings settings, ServerSecuritySessionChannel channel)
 1650                {
 101651                    _channel = channel;
 101652                    _securityContextTokenId = sessionToken.ContextId;
 101653                    Claim identityClaim = SecurityUtils.GetPrimaryIdentityClaim(sessionToken.AuthorizationPolicies);
 101654                    if (identityClaim != null)
 1655                    {
 101656                        RemoteIdentity = EndpointIdentity.CreateIdentity(identityClaim);
 1657                    }
 1658
 101659                    _sessionTokenIdentifier = settings.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(sessionTo
 101660                    _standardsManager = settings.SessionProtocolFactory.StandardsManager;
 101661                }
 1662
 101663                public string Id => _securityContextTokenId.ToString();
 1664
 01665                public EndpointIdentity RemoteIdentity { get; }
 1666
 1667                public void WriteSessionTokenIdentifier(XmlDictionaryWriter writer)
 1668                {
 01669                    _standardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, _sessionTokenIdentifier);
 01670                }
 1671
 1672                public bool TryReadSessionTokenIdentifier(XmlReader reader)
 1673                {
 01674                    if (!_standardsManager.SecurityTokenSerializer.CanReadKeyIdentifierClause(reader))
 1675                    {
 01676                        return false;
 1677                    }
 1678
 01679                    return _standardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(reader) is SecurityContextK
 1680                }
 1681            }
 1682        }
 1683
 1684        private abstract class ServerSecuritySimplexSessionChannel : ServerSecuritySessionChannel
 1685        {
 1686            private readonly SoapSecurityInputSession _session;
 1687            private bool _receivedClose;
 1688            private bool _canSendCloseResponse;
 1689            private bool _sentCloseResponse;
 1690            private RequestContext _closeRequestContext;
 1691            private Message _closeResponse;
 1692
 1693            public ServerSecuritySimplexSessionChannel(
 1694                SecuritySessionServerSettings settings,
 1695                SecurityContextSecurityToken sessionToken,
 1696                object listenerSecurityState, SecurityListenerSettingsLifetimeManager settingsLifetimeManager, EndpointA
 81697                : base(settings, sessionToken, listenerSecurityState, settingsLifetimeManager, address)
 1698            {
 81699                _session = new SoapSecurityInputSession(sessionToken, settings, this);
 81700            }
 1701
 01702            public IInputSession Session => _session;
 1703
 1704            private void CleanupPendingCloseState()
 1705            {
 01706                lock (LocalLock)
 1707                {
 01708                    if (_closeResponse != null)
 1709                    {
 01710                        _closeResponse.Close();
 01711                        _closeResponse = null;
 1712                    }
 01713                    if (_closeRequestContext != null)
 1714                    {
 01715                        _closeRequestContext.Abort();
 01716                        _closeRequestContext = null;
 1717                    }
 01718                }
 01719            }
 1720
 1721            protected override void AbortCore()
 1722            {
 01723                base.AbortCore();
 01724                Settings.RemoveSessionChannel(_session.Id);
 01725                CleanupPendingCloseState();
 01726            }
 1727
 1728            protected override async Task CloseCoreAsync(CancellationToken token)
 1729            {
 81730                await base.CloseCoreAsync(token);
 81731                Settings.RemoveSessionChannel(_session.Id);
 81732            }
 1733
 1734            public virtual Task CloseAsync(CancellationToken token)
 1735            {
 81736                return OnCloseAsync(token);
 1737            }
 1738            protected async Task OnCloseAsync(CancellationToken token)
 1739            {
 1740                // send a close response if one was not sent yet
 81741                bool wasAborted = await SendCloseResponseOnCloseIfRequiredAsync(token);
 81742                if (wasAborted)
 1743                {
 01744                    return;
 1745                }
 81746                await CloseCoreAsync(token);
 81747            }
 1748
 1749            private bool ShouldSendCloseResponseOnClose(out RequestContext pendingCloseRequestContext, out Message pendi
 1750            {
 81751                bool sendCloseResponse = false;
 81752                lock (LocalLock)
 1753                {
 81754                    _canSendCloseResponse = true;
 81755                    if (!_sentCloseResponse && _receivedClose && _closeResponse != null)
 1756                    {
 81757                        _sentCloseResponse = true;
 81758                        sendCloseResponse = true;
 81759                        pendingCloseRequestContext = _closeRequestContext;
 81760                        pendingCloseResponse = _closeResponse;
 81761                        _closeResponse = null;
 81762                        _closeRequestContext = null;
 1763                    }
 1764                    else
 1765                    {
 01766                        _canSendCloseResponse = false;
 01767                        pendingCloseRequestContext = null;
 01768                        pendingCloseResponse = null;
 1769                    }
 01770                }
 81771                return sendCloseResponse;
 1772            }
 1773
 1774            private async Task<bool> SendCloseResponseOnCloseIfRequiredAsync(CancellationToken token)
 1775            {
 81776                bool aborted = false;
 81777                bool sendCloseResponse = ShouldSendCloseResponseOnClose(out RequestContext pendingCloseRequestContext, o
 81778                bool cleanupCloseState = true;
 81779                if (sendCloseResponse)
 1780                {
 1781                    try
 1782                    {
 81783                        await SendCloseResponseAsync(pendingCloseRequestContext, pendingCloseResponse, token);
 1784                        // this.inputSessionClosedHandle.Set();
 81785                        cleanupCloseState = false;
 81786                    }
 01787                    catch (CommunicationObjectAbortedException)
 1788                    {
 01789                        if (State != CommunicationState.Closed)
 1790                        {
 01791                            throw;
 1792                        }
 01793                        aborted = true;
 01794                    }
 1795                    finally
 1796                    {
 81797                        if (cleanupCloseState)
 1798                        {
 01799                            if (pendingCloseResponse != null)
 1800                            {
 01801                                pendingCloseResponse.Close();
 1802                            }
 01803                            if (pendingCloseRequestContext != null)
 1804                            {
 01805                                pendingCloseRequestContext.Abort();
 1806                            }
 1807                        }
 1808                    }
 1809                }
 1810
 81811                return aborted;
 81812            }
 1813
 1814            protected override void OnCloseResponseMessageReceived(RequestContext requestContext, Message message, Secur
 1815            {
 1816                // we dont expect a close-response for non-duplex security session
 01817                message.Close();
 01818                requestContext.Abort();
 01819                Fault(new ProtocolException(SR.UnexpectedSecuritySessionCloseResponse));
 01820            }
 1821
 1822            private void Fault(ProtocolException protocolException)
 1823            {
 01824                AbortCore();
 01825                OnFaulted(protocolException);
 01826            }
 1827
 1828            protected override void OnCloseMessageReceived(RequestContext requestContext, Message message, SecurityProto
 1829            {
 81830                if (State == CommunicationState.Created)
 1831                {
 1832                    Fx.Assert("ServerSecuritySimplexSessionChannel.OnCloseMessageReceived (this.State == Created)");
 01833                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR
 1834                }
 81835                if (SendCloseResponseOnCloseReceivedIfRequiredAsync(requestContext, message, correlationState, token).Re
 1836                {
 1837                    // inputSessionClosedHandle.Set();
 1838                }
 81839            }
 1840
 1841            private async Task<bool> SendCloseResponseOnCloseReceivedIfRequiredAsync(RequestContext requestContext, Mess
 1842            {
 81843                bool sendCloseResponse = false;
 1844                //  ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? TraceUtility.ExtractActivity(m
 81845                bool cleanupContext = true;
 1846                try
 1847                {
 81848                    Message localCloseResponse = null;
 81849                    lock (LocalLock)
 1850                    {
 81851                        if (!_receivedClose)
 1852                        {
 81853                            _receivedClose = true;
 81854                            localCloseResponse = CreateCloseResponse(message, correlationState, token);
 81855                            if (_canSendCloseResponse)
 1856                            {
 01857                                _sentCloseResponse = true;
 01858                                sendCloseResponse = true;
 1859                            }
 1860                            else
 1861                            {
 1862                                // save the close requestContext to reply later
 81863                                _closeRequestContext = requestContext;
 81864                                _closeResponse = localCloseResponse;
 81865                                cleanupContext = false;
 1866                            }
 1867                        }
 81868                    }
 81869                    if (sendCloseResponse)
 1870                    {
 01871                        await SendCloseResponseAsync(requestContext, localCloseResponse, token);
 01872                        cleanupContext = false;
 1873                    }
 81874                    else if (cleanupContext)
 1875                    {
 01876                        await requestContext.CloseAsync(token);
 01877                        cleanupContext = false;
 1878                    }
 81879                    return sendCloseResponse;
 1880                }
 1881                finally
 1882                {
 81883                    message.Close();
 81884                    if (cleanupContext)
 1885                    {
 01886                        requestContext.Abort();
 1887                    }
 1888                    //if (DiagnosticUtility.ShouldUseActivity && (activity != null))
 1889                    //{
 1890                    //    activity.Stop();
 1891                    //}
 1892                }
 81893            }
 1894
 1895            //Renamed SecurityReplySessionChannel => SecurityReplySessionServiceChannelDispatcher (implementd IServiceCh
 1896            public class SecurityReplySessionServiceChannelDispatcher : ServerSecuritySimplexSessionChannel, IServiceCha
 1897            {
 1898                private readonly IServiceProvider _serviceProvider;
 1899                private volatile IServiceChannelDispatcher _channelDispatcher;
 1900                public SecurityReplySessionServiceChannelDispatcher(
 1901                    SecuritySessionServerSettings settings,
 1902                    SecurityContextSecurityToken sessionToken,
 1903                    object listenerSecurityState, SecurityListenerSettingsLifetimeManager settingsLifetimeManager
 1904                    , IChannel channel, EndpointAddress address)
 81905                    : base(settings,
 81906                          sessionToken, listenerSecurityState, settingsLifetimeManager, address)
 1907                {
 81908                    IncomingChannel = (IReplyChannel)channel;
 81909                    _serviceProvider = IncomingChannel.GetProperty<IServiceScopeFactory>().CreateScope().ServiceProvider
 81910                }
 1911
 321912                public IReplyChannel IncomingChannel { get; set; }
 1913
 01914                public IServiceChannelDispatcher ChannelDispatcher { get => throw new NotImplementedException(); set => 
 1915
 81916                protected override bool CanDoSecurityCorrelation => true;
 1917
 1918#pragma warning disable CS0067 // The event is never used - see issue #287
 1919                public event EventHandler Closed;
 1920                public event EventHandler Closing;
 1921                public event EventHandler Faulted;
 1922                public event EventHandler Opened;
 1923                public event EventHandler Opening;
 1924#pragma warning restore CS0067 // The event is never used
 1925
 1926                public void Abort()
 1927                {
 01928                    base.AbortCore();
 01929                }
 1930
 1931                public Task CloseAsync()
 1932                {
 01933                    TimeoutHelper helper = new TimeoutHelper(ServiceDefaults.CloseTimeout);
 01934                    return CloseAsync(helper.GetCancellationToken());
 1935                }
 1936
 1937                public override Task CloseAsync(CancellationToken token)
 1938                {
 81939                    base.CloseAsync(token);
 81940                    return Task.CompletedTask;
 1941                }
 1942
 1943                public async Task DispatchAsync(RequestContext context)
 1944                {
 161945                    RequestContext securityRequestContext = await ReceiveRequestAsync(context);
 161946                    await _channelDispatcher.DispatchAsync(securityRequestContext);
 161947                }
 1948
 1949                public Task DispatchAsync(Message message)
 1950                {
 01951                    throw new NotImplementedException();
 1952                }
 1953
 1954                public T GetProperty<T>() where T : class
 1955                {
 321956                    T tObj = _serviceProvider.GetService<T>();
 321957                    if (tObj == null)
 1958                    {
 161959                        return IncomingChannel.GetProperty<T>();
 1960                    }
 1961                    else
 1962                    {
 161963                        return tObj;
 1964                    }
 1965                }
 1966
 1967                public Task OpenAsync()
 1968                {
 81969                    return Task.CompletedTask;
 1970                }
 1971
 1972                public override async Task OpenAsync(TimeSpan timeout)
 1973                {
 81974                    await base.OpenAsync(timeout);
 81975                    _channelDispatcher = await Settings.SecurityServiceDispatcher.
 81976                        GetInnerServiceChannelDispatcher(this);
 81977                }
 1978
 1979                public Task OpenAsync(CancellationToken token)
 1980                {
 01981                    return Task.CompletedTask;
 1982                }
 1983            }
 1984        }
 1985
 1986        private class ServerSecurityDuplexSessionChannel : ServerSecuritySessionChannel //, IDuplexSessionChannel
 1987        {
 1988            private SoapSecurityServerDuplexSession _session;
 1989            private bool _isInputClosed;
 1990            private bool _isOutputClosed;
 1991            private bool _sentClose;
 1992            private bool _receivedClose;
 1993            private RequestContext _closeRequestContext;
 1994            private Message _closeResponseMessage;
 21995            private InterruptibleWaitObject _outputSessionCloseHandle = new InterruptibleWaitObject(true);
 21996            private InterruptibleWaitObject _inputSessionCloseHandle = new InterruptibleWaitObject(false);
 1997            private DuplexCommunication _duplexCommObj;
 1998            private IDuplexSessionChannel _duplexSessionChannel;
 1999
 2000            public ServerSecurityDuplexSessionChannel(
 2001                SecuritySessionServerSettings settings,
 2002                SecurityContextSecurityToken sessionToken,
 2003                object listenerSecurityState, SecurityListenerSettingsLifetimeManager settingsLifetimeManager, EndpointA
 22004                : base(settings,
 22005                      sessionToken, listenerSecurityState, settingsLifetimeManager, address)
 2006            {
 22007                _session = new SoapSecurityServerDuplexSession(sessionToken, settings, this);
 22008                _duplexCommObj = new DuplexCommunication();
 22009                _duplexSessionChannel = (IDuplexSessionChannel)channel;
 22010            }
 2011
 2012            public EndpointAddress RemoteAddress
 2013            {
 2014                get
 2015                {
 22016                    return LocalAddress;
 2017                }
 2018            }
 2019
 2020            public Uri Via
 2021            {
 2022                get
 2023                {
 02024                    return RemoteAddress.Uri;
 2025                }
 2026            }
 2027
 2028            public IDuplexSession Session
 2029            {
 2030                get
 2031                {
 02032                    return _session;
 2033                }
 2034            }
 2035
 2036            protected override void AbortCore()
 2037            {
 02038                _duplexSessionChannel.Abort();
 02039                base.AbortCore();
 02040                Settings.RemoveSessionChannel(_session.Id);
 02041                CleanupPendingCloseState();
 02042                _inputSessionCloseHandle.Abort(_duplexCommObj);
 02043                _outputSessionCloseHandle.Abort(_duplexCommObj);
 02044            }
 2045
 2046            private void CleanupPendingCloseState()
 2047            {
 02048                lock (LocalLock)
 2049                {
 02050                    if (_closeResponseMessage != null)
 2051                    {
 02052                        _closeResponseMessage.Close();
 02053                        _closeResponseMessage = null;
 2054                    }
 02055                    if (_closeRequestContext != null)
 2056                    {
 02057                        _closeRequestContext.Abort();
 02058                        _closeRequestContext = null;
 2059                    }
 02060                }
 02061            }
 2062
 2063            public void Abort()
 2064            {
 02065                AbortCore();
 02066            }
 2067
 2068            public Task CloseAsync()
 2069            {
 02070                return CloseAsync(new TimeoutHelper(ServiceDefaults.CloseTimeout).GetCancellationToken());
 2071            }
 2072
 2073            public async Task CloseAsync(CancellationToken token)
 2074            {
 2075                // step 1: close output session
 22076                await CloseOutputSessionAsync(token);
 2077
 2078                // if the channel was aborted while closing the output session, return
 22079                if (State == CommunicationState.Closed)
 2080                {
 02081                    return;
 2082                }
 2083                // step 2: wait for input session to be closed
 2084
 2085                bool wasAborted;
 2086                bool didInputSessionClose;
 22087                (didInputSessionClose, wasAborted) = await WaitForInputSessionCloseAsync(ServiceDefaults.CloseTimeout);
 22088                if (wasAborted)
 2089                {
 02090                    return;
 2091                }
 2092
 22093                if (!didInputSessionClose)
 2094                {
 02095                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.Format(SR.Servic
 2096                }
 2097
 2098                // wait for any concurrent CloseOutputSessions to finish
 2099                bool didOutputSessionClose;
 22100                (didOutputSessionClose, wasAborted) = await WaitForOutputSessionCloseAsync(ServiceDefaults.CloseTimeout)
 22101                if (wasAborted)
 2102                {
 02103                    return;
 2104                }
 2105
 22106                if (!didOutputSessionClose)
 2107                {
 02108                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new TimeoutException(SR.Format(SR.Servic
 2109                }
 2110
 22111                await CloseDuplexSessionChannelAsync(token);
 22112                await CloseCoreAsync(token);
 22113                Settings.RemoveSessionChannel(_session.Id);
 22114            }
 2115
 2116            private async Task CloseDuplexSessionChannelAsync(CancellationToken token)
 2117            {
 22118                TimeoutHelper timeoutHelper = new TimeoutHelper(TimeSpan.FromMinutes(30));
 22119                await ((ISessionChannel<IDuplexSession>)_duplexSessionChannel).Session.CloseOutputSessionAsync(timeoutHe
 2120
 22121                TimeSpan iterationTimeout = timeoutHelper.RemainingTime();
 22122                bool lastIteration = (iterationTimeout == TimeSpan.Zero);
 2123
 02124                while (true)
 2125                {
 22126                    Message message = null;
 22127                    bool receiveThrowing = true;
 2128                    try
 2129                    {
 22130                        (Message receiveMessage, bool success) = await _duplexSessionChannel.TryReceiveAsync(timeoutHelp
 2131
 22132                        receiveThrowing = false;
 22133                        if (success && receiveMessage == null)
 2134                        {
 22135                            await _duplexSessionChannel.CloseAsync(timeoutHelper.GetCancellationToken());
 22136                            return;
 2137                        }
 02138                    }
 2139                    catch (Exception e)
 2140                    {
 02141                        if (Fx.IsFatal(e))
 02142                            throw;
 2143
 02144                        if (receiveThrowing)
 2145                        {
 02146                            receiveThrowing = false;
 2147                        }
 2148                        else
 2149                        {
 02150                            throw;
 2151                        }
 02152                    }
 2153                    finally
 2154                    {
 22155                        if (message != null)
 02156                            message.Close();
 2157
 22158                        if (receiveThrowing)
 02159                            _duplexSessionChannel.Abort();
 2160                    }
 2161
 02162                    if (lastIteration || _duplexSessionChannel.State != CommunicationState.Opened)
 2163                        break;
 2164
 02165                    iterationTimeout = timeoutHelper.RemainingTime();
 02166                    lastIteration = (iterationTimeout == TimeSpan.Zero);
 02167                }
 2168
 02169                _duplexSessionChannel.Abort();
 22170            }
 2171
 2172            private void DetermineCloseOutputSessionMessage(out bool sendClose, out bool sendCloseResponse, out Message 
 2173            {
 22174                sendClose = false;
 22175                sendCloseResponse = false;
 22176                pendingCloseResponseMessage = null;
 22177                pendingCloseRequestContext = null;
 22178                lock (LocalLock)
 2179                {
 22180                    if (!_isOutputClosed)
 2181                    {
 22182                        _isOutputClosed = true;
 22183                        if (_receivedClose)
 2184                        {
 22185                            if (_closeResponseMessage != null)
 2186                            {
 22187                                pendingCloseResponseMessage = _closeResponseMessage;
 22188                                pendingCloseRequestContext = _closeRequestContext;
 22189                                _closeResponseMessage = null;
 22190                                _closeRequestContext = null;
 22191                                sendCloseResponse = true;
 2192                            }
 2193                        }
 2194                        else
 2195                        {
 02196                            sendClose = true;
 02197                            _sentClose = true;
 2198                        }
 2199
 22200                        _outputSessionCloseHandle.Reset();
 2201                    }
 22202                }
 22203            }
 2204
 2205            private async Task CloseOutputSessionAsync(CancellationToken token)
 2206            {
 22207                bool sendClose = false;
 22208                bool sendCloseResponse = false;
 2209                Message pendingCloseResponseMessage;
 2210                RequestContext pendingCloseRequestContext;
 2211                try
 2212                {
 22213                    DetermineCloseOutputSessionMessage(out sendClose, out sendCloseResponse, out pendingCloseResponseMes
 22214                    if (sendCloseResponse)
 2215                    {
 22216                        bool cleanupCloseState = true;
 2217                        try
 2218                        {
 22219                            await SendCloseResponseAsync(pendingCloseRequestContext, pendingCloseResponseMessage, token)
 22220                            cleanupCloseState = false;
 22221                        }
 2222                        finally
 2223                        {
 22224                            if (cleanupCloseState)
 2225                            {
 02226                                pendingCloseResponseMessage.Close();
 02227                                pendingCloseRequestContext.Abort();
 2228                            }
 2229                        }
 2230                    }
 02231                    else if (sendClose)
 2232                    {
 02233                        await SendCloseAsync(token);
 2234                    }
 22235                }
 02236                catch (CommunicationObjectAbortedException)
 2237                {
 02238                    if (State != CommunicationState.Closed) throw;
 2239                    // a parallel thread aborted the channel. ignore the exception
 02240                }
 2241                finally
 2242                {
 22243                    if (sendClose || sendCloseResponse)
 2244                    {
 22245                        _outputSessionCloseHandle.Set();
 2246                    }
 2247                }
 22248            }
 2249
 2250            protected override void OnCloseMessageReceived(RequestContext requestContext, Message message, SecurityProto
 2251            {
 22252                if (State == CommunicationState.Created)
 2253                {
 2254                    Fx.Assert("ServerSecurityDuplexSessionChannel.OnCloseMessageReceived (State == Created)");
 02255                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR
 2256                }
 2257
 22258                bool setInputSessionCloseHandle = false;
 22259                bool cleanupContext = true;
 2260                try
 2261                {
 22262                    lock (LocalLock)
 2263                    {
 22264                        _receivedClose = true;
 22265                        if (!_isInputClosed)
 2266                        {
 22267                            _isInputClosed = true;
 22268                            setInputSessionCloseHandle = true;
 2269
 22270                            if (!_isOutputClosed)
 2271                            {
 22272                                _closeRequestContext = requestContext;
 2273                                // CreateCloseResponse closes the message passed in
 22274                                _closeResponseMessage = CreateCloseResponse(message, null, token);
 22275                                cleanupContext = false;
 2276                            }
 2277                        }
 22278                    }
 2279
 22280                    if (setInputSessionCloseHandle)
 2281                    {
 22282                        _inputSessionCloseHandle.Set();
 2283                    }
 22284                    if (cleanupContext)
 2285                    {
 02286                        requestContext.CloseAsync();
 02287                        cleanupContext = false;
 2288                    }
 22289                }
 2290                finally
 2291                {
 22292                    message.Close();
 22293                    if (cleanupContext)
 2294                    {
 02295                        requestContext.Abort();
 2296                    }
 22297                }
 22298            }
 2299
 2300            protected override void OnCloseResponseMessageReceived(RequestContext requestContext, Message message, Secur
 2301            {
 02302                bool cleanupContext = true;
 2303                try
 2304                {
 02305                    bool isCloseResponseExpected = false;
 02306                    bool setInputSessionCloseHandle = false;
 02307                    lock (LocalLock)
 2308                    {
 02309                        isCloseResponseExpected = _sentClose;
 02310                        if (isCloseResponseExpected && !_isInputClosed)
 2311                        {
 02312                            _isInputClosed = true;
 02313                            setInputSessionCloseHandle = true;
 2314                        }
 02315                    }
 02316                    if (!isCloseResponseExpected)
 2317                    {
 02318                        _duplexCommObj.Fault(new ProtocolException(SR.Format(SR.UnexpectedSecuritySessionCloseResponse))
 02319                        return;
 2320                    }
 02321                    if (setInputSessionCloseHandle)
 2322                    {
 02323                        _inputSessionCloseHandle.Set();
 2324                    }
 2325
 02326                    requestContext.CloseAsync();
 02327                    cleanupContext = false;
 02328                }
 2329                finally
 2330                {
 02331                    message.Close();
 02332                    if (cleanupContext)
 2333                    {
 02334                        requestContext.Abort();
 2335                    }
 02336                }
 02337            }
 2338
 2339            internal async Task<(bool success, bool wasAborted)> WaitForOutputSessionCloseAsync(TimeSpan timeout)
 2340            {
 2341                try
 2342                {
 22343                    return (await _outputSessionCloseHandle.WaitAsync(timeout, false), false);
 2344                }
 02345                catch (CommunicationObjectAbortedException)
 2346                {
 02347                    if (State != CommunicationState.Closed) throw;
 02348                    return (true, true);
 2349                }
 22350            }
 2351
 2352            private async Task<(bool success, bool wasAborted)> WaitForInputSessionCloseAsync(TimeSpan timeout)
 2353            {
 22354                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
 22355                bool wasAborted = false;
 2356                try
 2357                {
 22358                    (bool success, RequestContext requestContext) receivedRequestTry = await TryReceiveRequestAsync(time
 22359                    RequestContext context = receivedRequestTry.requestContext;
 22360                    if (!receivedRequestTry.success)
 2361                    {
 02362                        return (false, wasAborted);
 2363                    }
 2364
 22365                    if (context != null && context.RequestMessage != null)
 2366                    {
 02367                        Message message = context.RequestMessage;
 02368                        using (message)
 2369                        {
 02370                            ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message);
 02371                            throw TraceUtility.ThrowHelperWarning(error, message);
 2372                        }
 2373                    }
 2374
 22375                    bool result = await _inputSessionCloseHandle.WaitAsync(timeoutHelper.RemainingTime(), false);
 22376                    if (!result)
 2377                    {
 02378                        return (false, wasAborted);
 2379                    }
 2380                    else
 2381                    {
 22382                        lock (LocalLock)
 2383                        {
 22384                            if (!(_isInputClosed))
 2385                            {
 2386                                Fx.Assert("Shutdown request was not received.");
 02387                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
 2388                            }
 22389                        }
 2390
 22391                        return (true, wasAborted);
 2392                    }
 2393                }
 02394                catch (CommunicationObjectAbortedException)
 2395                {
 02396                    if (State != CommunicationState.Closed)
 2397                    {
 02398                        throw;
 2399                    }
 2400
 02401                    wasAborted = true;
 02402                }
 2403
 02404                return (false, wasAborted);
 22405            }
 2406
 2407            private class SoapSecurityServerDuplexSession : SoapSecurityInputSession, IDuplexSession
 2408            {
 2409                private ServerSecurityDuplexSessionChannel _channel;
 2410
 2411                public SoapSecurityServerDuplexSession(SecurityContextSecurityToken sessionToken, SecuritySessionServerS
 22412                    : base(sessionToken, settings, channel)
 2413                {
 22414                    _channel = channel;
 22415                }
 2416
 2417                public Task CloseOutputSessionAsync()
 2418                {
 02419                    return CloseOutputSessionAsync(ServiceDefaults.CloseTimeout); ;
 2420                }
 2421
 2422                public Task CloseOutputSessionAsync(CancellationToken token)
 2423                {
 02424                    return CloseOutputSessionAsync();
 2425                }
 2426
 2427                private async Task CloseOutputSessionAsync(TimeSpan timeout)
 2428                {
 2429                    // channel.ThrowIfFaulted();
 2430                    // channel.ThrowIfNotOpened();
 02431                    Exception pendingException = null;
 2432                    try
 2433                    {
 02434                        await _channel.CloseOutputSessionAsync(new TimeoutHelper(timeout).GetCancellationToken());
 02435                    }
 02436                    catch (Exception e)
 2437                    {
 02438                        if (Fx.IsFatal(e))
 2439                        {
 02440                            throw;
 2441                        }
 2442
 02443                        pendingException = e;
 02444                    }
 02445                    if (pendingException != null)
 2446                    {
 02447                        _channel.OnFaulted(pendingException);
 02448                        if (pendingException is CommunicationException)
 2449                        {
 02450                            throw pendingException;
 2451                        }
 2452                        else
 2453                        {
 02454                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(pendingException);
 2455                        }
 2456                    }
 02457                }
 2458            }
 2459
 2460            public class ServerSecurityDuplexSessionChannelDispatcher : ServerSecurityDuplexSessionChannel, IDuplexSessi
 2461            {
 2462                private readonly IServiceProvider _serviceProvider;
 2463                private volatile IServiceChannelDispatcher _channelDispatcher;
 2464
 2465                public ServerSecurityDuplexSessionChannelDispatcher(
 2466                    SecuritySessionServerSettings settings,
 2467                    SecurityContextSecurityToken sessionToken,
 2468                    object listenerSecurityState, SecurityListenerSettingsLifetimeManager settingsLifetimeManager
 2469                    , IChannel channel, EndpointAddress address)
 22470                    : base(settings,
 22471                          sessionToken, listenerSecurityState, settingsLifetimeManager, address, channel)
 2472                {
 22473                    IncomingChannel = (IDuplexSessionChannel)channel;
 22474                    _serviceProvider = IncomingChannel.GetProperty<IServiceScopeFactory>().CreateScope().ServiceProvider
 22475                }
 2476
 142477                public IDuplexSessionChannel IncomingChannel { get; set; }
 02478                public IServiceChannelDispatcher ChannelDispatcher { get => throw new NotImplementedException(); set => 
 2479
 2480#pragma warning disable CS0067 // The event is never used
 2481                public event EventHandler Closed;
 2482                public event EventHandler Closing;
 2483                public event EventHandler Faulted;
 2484                public event EventHandler Opened;
 2485                public event EventHandler Opening;
 2486#pragma warning restore CS0067 // The event is never used
 2487
 2488                public Task DispatchAsync(RequestContext context)
 2489                {
 02490                    return DispatchAsync(context.RequestMessage);
 2491                }
 2492
 2493                public async Task DispatchAsync(Message message)
 2494                {
 42495                    DuplexSessionRequestContext duplexSessionRequestContext = new DuplexSessionRequestContext(IncomingCh
 42496                    RequestContext context = await ReceiveRequestAsync(duplexSessionRequestContext);
 42497                    await _channelDispatcher.DispatchAsync(context == null ? null : context.RequestMessage);
 42498                }
 2499
 2500                public T GetProperty<T>() where T : class
 2501                {
 82502                    T tObj = _serviceProvider.GetService<T>();
 82503                    if (tObj == null)
 2504                    {
 42505                        return IncomingChannel.GetProperty<T>();
 2506                    }
 2507                    else
 2508                    {
 42509                        return tObj;
 2510                    }
 2511                }
 2512
 2513                public Task OpenAsync()
 2514                {
 22515                    return Task.CompletedTask;
 2516                    // NO op, call by Channel Handler in the upper chain from CreateServiceChannel dispatcher from below
 2517                }
 2518
 2519                public override async Task OpenAsync(TimeSpan timeout)
 2520                {
 22521                    await base.OpenAsync(timeout);
 22522                    _channelDispatcher = await Settings.SecurityServiceDispatcher.
 22523                        GetInnerServiceChannelDispatcher(this);
 22524                }
 2525
 2526                public Task OpenAsync(CancellationToken token)
 2527                {
 02528                    return OpenAsync();
 2529                }
 2530
 2531                public Task SendAsync(Message message)
 2532                {
 02533                    return SendAsync(message, new TimeoutHelper(ServiceDefaults.SendTimeout).GetCancellationToken());
 2534                }
 2535
 2536                public Task SendAsync(Message message, CancellationToken token)
 2537                {
 22538                    CheckOutputOpen();
 22539                    SecureApplicationMessage(ref message, null, token);
 2540                    // ChannelBinder.Send(message, timeoutHelper.RemainingTime());
 22541                    return IncomingChannel.SendAsync(message, token);
 2542                }
 2543
 02544                public Task<Message> ReceiveAsync(CancellationToken token) => throw new NotImplementedException();
 2545
 02546                public Task<(Message message, bool success)> TryReceiveAsync(CancellationToken token) => throw new NotIm
 2547            }
 2548
 2549            protected void CheckOutputOpen()
 2550            {
 2551                // ThrowIfClosedOrNotOpen();
 22552                lock (LocalLock)
 2553                {
 22554                    if (_isOutputClosed)
 2555                    {
 02556                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new CommunicationException(SR.Format
 2557                    }
 22558                }
 22559            }
 2560
 2561            internal override void OnFaulted(Exception ex)
 2562            {
 02563                AbortCore();
 02564                _inputSessionCloseHandle.Fault(_duplexCommObj);
 02565                _outputSessionCloseHandle.Fault(_duplexCommObj);
 02566                base.OnFaulted(ex);
 02567            }
 2568        }
 2569
 2570        //Dummy class to hold Communication object and not changing API.
 2571        //ServerSecuritySession channel not inheriting from ChannelBase as there is no use.
 2572        private class DuplexCommunication : ChannelManagerBase
 2573        {
 02574            protected override TimeSpan DefaultReceiveTimeout => ServiceDefaults.ReceiveTimeout;
 2575
 02576            protected override TimeSpan DefaultSendTimeout => ServiceDefaults.SendTimeout;
 2577
 02578            protected override TimeSpan DefaultCloseTimeout => ServiceDefaults.CloseTimeout;
 2579
 02580            protected override TimeSpan DefaultOpenTimeout => ServiceDefaults.OpenTimeout;
 2581
 02582            protected override void OnAbort() { }
 02583            protected override Task OnCloseAsync(CancellationToken token) => throw new NotImplementedException();
 02584            protected override Task OnOpenAsync(CancellationToken token) => throw new NotImplementedException();
 2585        }
 2586
 2587        internal class DuplexSessionRequestContext : RequestContextBase
 2588        {
 2589            private readonly IDuplexChannel _channel;
 2590            public DuplexSessionRequestContext(IDuplexChannel channel, Message request)
 42591                    : base(request, ServiceDefaults.CloseTimeout, ServiceDefaults.SendTimeout)
 2592            {
 42593                _channel = channel;
 42594            }
 2595
 02596            protected override void OnAbort() { }
 2597
 2598            protected override
 2599                Task OnCloseAsync(CancellationToken token)
 2600            {
 22601                return Task.CompletedTask;
 2602            }
 2603
 2604            protected override async Task OnReplyAsync(Message message, CancellationToken token)
 2605            {
 22606                if (message != null)
 2607                {
 22608                    await _channel.SendAsync(message, token);
 2609                }
 22610            }
 2611        }
 2612
 2613        private class SecuritySessionRequestContext : RequestContextBase
 2614        {
 2615            private readonly RequestContext _requestContext;
 2616            private readonly ServerSecuritySessionChannel _channel;
 2617            private readonly SecurityProtocolCorrelationState _correlationState;
 2618
 2619            public SecuritySessionRequestContext(RequestContext requestContext, Message requestMessage, SecurityProtocol
 102620                : base(requestMessage, ServiceDefaults.CloseTimeout, ServiceDefaults.SendTimeout)
 2621            {
 102622                _requestContext = requestContext;
 102623                _correlationState = correlationState;
 102624                _channel = channel;
 102625            }
 2626
 2627            protected override void OnAbort()
 2628            {
 02629                _requestContext.Abort();
 02630            }
 2631
 2632            protected override Task OnCloseAsync(CancellationToken token)
 2633            {
 82634                return _requestContext.CloseAsync(token);
 2635            }
 2636
 2637            protected override Task OnReplyAsync(Message message, CancellationToken token)
 2638            {
 82639                if (message != null)
 2640                {
 82641                    _channel.SecureApplicationMessage(ref message, _correlationState, token);
 82642                    return _requestContext.ReplyAsync(message);
 2643                }
 2644                else
 2645                {
 02646                    return Task.CompletedTask;
 2647                }
 2648            }
 2649        }
 2650
 2651        //Failure Demuxer handler
 2652        internal class SecuritySessionDemuxFailureHandler : IChannelDemuxFailureHandler
 2653        {
 2654            private readonly SecurityStandardsManager _standardsManager;
 2655
 222656            public SecuritySessionDemuxFailureHandler(SecurityStandardsManager standardsManager)
 2657            {
 222658                _standardsManager = standardsManager ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull
 222659            }
 2660
 2661            public void HandleDemuxFailure(Message message)
 2662            {
 02663                if (message == null)
 2664                {
 02665                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
 2666                }
 02667            }
 2668
 2669            public Message CreateSessionDemuxFaultMessage(Message message)
 2670            {
 02671                MessageFault fault = SecurityUtils.CreateSecurityContextNotFoundFault(_standardsManager, message.Headers
 02672                Message faultMessage = Message.CreateMessage(message.Version, fault, message.Version.Addressing.DefaultF
 02673                if (message.Headers.MessageId != null)
 2674                {
 02675                    faultMessage.InitializeReply(message);
 2676                }
 2677
 02678                return faultMessage;
 2679            }
 2680
 2681            public Task HandleDemuxFailureAsync(Message message)
 2682            {
 02683                throw new NotImplementedException();
 2684            }
 2685
 2686            public async Task HandleDemuxFailureAsync(Message message, RequestContext faultContext)
 2687            {
 02688                HandleDemuxFailure(message);
 02689                Message faultMessage = CreateSessionDemuxFaultMessage(message);
 2690                try
 2691                {
 02692                    await faultContext.ReplyAsync(faultMessage);
 02693                }
 2694                catch (Exception ex)
 2695                {
 02696                    if (Fx.IsFatal(ex))
 2697                    {
 02698                        throw;
 2699                    }
 02700                }
 2701                finally
 2702                {
 02703                    faultMessage.Close();
 2704                }
 02705            }
 2706        }
 2707    }
 2708}

Methods/Properties

.cctor()
.ctor()
ChannelBuilder()
ChannelBuilder(CoreWCF.Channels.ChannelBuilder)
WrapperCommunicationObj()
SettingsLifetimeManager()
SettingsLifetimeManager(CoreWCF.Security.SecurityListenerSettingsLifetimeManager)
SecurityServiceDispatcher()
SecurityServiceDispatcher(CoreWCF.Dispatcher.SecurityServiceDispatcher)
AcceptorChannelType()
ThisGlobalLock()
SessionTokenAuthenticator()
SessionTokenCache()
SessionTokenResolver()
IssuedSecurityTokenParameters()
IssuedSecurityTokenParameters(CoreWCF.Security.Tokens.SecurityTokenParameters)
SecurityStandardsManager()
SecurityStandardsManager(CoreWCF.Security.SecurityStandardsManager)
TolerateTransportFailures()
TolerateTransportFailures(System.Boolean)
CanRenewSession()
MaximumPendingSessions()
MaximumPendingSessions(System.Int32)
InactivityTimeout()
InactivityTimeout(System.TimeSpan)
MaximumKeyRenewalInterval()
MaximumKeyRenewalInterval(System.TimeSpan)
KeyRolloverInterval()
KeyRolloverInterval(System.TimeSpan)
MaximumPendingKeysPerSession()
MaximumPendingKeysPerSession(System.Int32)
SessionProtocolFactory()
SessionProtocolFactory(CoreWCF.Security.SecurityProtocolFactory)
MessageVersion()
DefaultOpenTimeout()
DefaultCloseTimeout()
OnFaulted()
OnOpened()
OnOpening()
OnAbort()
Abort()
OnCloseCore(System.TimeSpan)
OnAbortCore()
SetupSessionTokenAuthenticatorAsync()
StopAcceptingNewWork()
GetPendingSessionCount()
AbortPendingChannels(System.Threading.CancellationToken)
ClosePendingChannels()
ConfigureSessionSecurityProtocolFactory()
OnTokenRenewed(CoreWCF.IdentityModel.Tokens.SecurityToken,CoreWCF.IdentityModel.Tokens.SecurityToken)
CreateSessionMessageServiceDispatcher(CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.EndpointAddress)
OnTokenIssued(CoreWCF.IdentityModel.Tokens.SecurityToken,CoreWCF.EndpointAddress)
GetSecurityContextSecurityToken(System.Xml.UniqueId)
OnTimer(System.Object)
AddPendingSession(System.Xml.UniqueId,CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.Dispatcher.MessageFilter)
ClearPendingSessions()
RemovePendingSession(System.Xml.UniqueId)
FindSessionChannel(System.Xml.UniqueId)
AddSessionChannel(System.Xml.UniqueId,CoreWCF.Security.SecuritySessionServerSettings/IServerSecuritySessionChannel,CoreWCF.Dispatcher.MessageFilter)
RemoveSessionChannel(System.String)
RemoveSessionChannel(System.Xml.UniqueId)
RemoveServiceDispatcher(System.Xml.UniqueId)
CloseAsync(System.TimeSpan)
OnCloseAsync(System.TimeSpan)
OpenAsync(System.TimeSpan)
OnOpenAsync(System.TimeSpan)
OnClosed()
OnClosing()
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.Dispatcher.MessageFilter,CoreWCF.EndpointAddress)
BaseAddress()
Binding()
Host()
AsyncLock()
SupportedChannelTypes()
CreateServiceChannelDispatcherAsync()
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,System.Object,CoreWCF.Security.SecurityListenerSettingsLifetimeManager,CoreWCF.EndpointAddress)
Settings()
CanDoSecurityCorrelation()
InternalSendTimeout()
LocalAddress()
LocalLock()
State()
SecurityProtocol()
OpenAsync(System.TimeSpan)
AbortCore()
CloseCoreAsync()
RenewSessionToken(CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.Security.Tokens.SecurityContextSecurityToken)
GetSessionToken(CoreWCF.Security.SecurityMessageProperty)
CheckIncomingToken(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.TimeSpan)
ReceiveRequestAsync(CoreWCF.Channels.RequestContext)
ReceiveRequestAsync()
TryReceiveRequestAsync()
ThrowIfFaulted()
SendFaultIfRequired(System.Exception,CoreWCF.Channels.Message,CoreWCF.Channels.RequestContext,System.TimeSpan)
ShouldWrapException(System.Exception)
ProcessRequestContextAsync()
CheckOutgoingToken()
SecureApplicationMessage(CoreWCF.Channels.Message&,CoreWCF.Security.SecurityProtocolCorrelationState,System.Threading.CancellationToken)
ThrowIfClosedOrNotOpen()
VerifyIncomingMessageAsync()
PrepareReply(CoreWCF.Channels.Message,CoreWCF.Channels.Message)
InitializeFaultCodesIfRequired()
SendRenewFault(CoreWCF.Channels.RequestContext,CoreWCF.Security.SecurityProtocolCorrelationState,System.TimeSpan)
ProcessCloseRequest(CoreWCF.Channels.Message)
CreateCloseResponse(CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.Threading.CancellationToken)
TraceSessionClosedResponseSuccess()
TraceSessionClosedResponseFailure(System.Exception)
TraceSessionClosedSuccess()
TraceSessionClosedFailure(System.Exception)
SendCloseResponseAsync()
CreateCloseMessage(System.Threading.CancellationToken)
SendCloseAsync()
SendMessageAsync()
OnFaulted(System.Exception)
.ctor(CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.SecuritySessionServerSettings/ServerSecuritySessionChannel)
Id()
RemoteIdentity()
WriteSessionTokenIdentifier(System.Xml.XmlDictionaryWriter)
TryReadSessionTokenIdentifier(System.Xml.XmlReader)
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,System.Object,CoreWCF.Security.SecurityListenerSettingsLifetimeManager,CoreWCF.EndpointAddress)
Session()
CleanupPendingCloseState()
AbortCore()
CloseCoreAsync()
CloseAsync(System.Threading.CancellationToken)
OnCloseAsync()
ShouldSendCloseResponseOnClose(CoreWCF.Channels.RequestContext&,CoreWCF.Channels.Message&)
SendCloseResponseOnCloseIfRequiredAsync()
OnCloseResponseMessageReceived(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.TimeSpan)
Fault(CoreWCF.ProtocolException)
OnCloseMessageReceived(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.Threading.CancellationToken)
SendCloseResponseOnCloseReceivedIfRequiredAsync()
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,System.Object,CoreWCF.Security.SecurityListenerSettingsLifetimeManager,CoreWCF.Channels.IChannel,CoreWCF.EndpointAddress)
IncomingChannel()
ChannelDispatcher()
CanDoSecurityCorrelation()
Abort()
CloseAsync()
CloseAsync(System.Threading.CancellationToken)
DispatchAsync()
DispatchAsync(CoreWCF.Channels.Message)
GetProperty()
OpenAsync()
OpenAsync()
OpenAsync(System.Threading.CancellationToken)
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,System.Object,CoreWCF.Security.SecurityListenerSettingsLifetimeManager,CoreWCF.EndpointAddress,CoreWCF.Channels.IChannel)
RemoteAddress()
Via()
Session()
AbortCore()
CleanupPendingCloseState()
Abort()
CloseAsync()
CloseAsync()
CloseDuplexSessionChannelAsync()
DetermineCloseOutputSessionMessage(System.Boolean&,System.Boolean&,CoreWCF.Channels.Message&,CoreWCF.Channels.RequestContext&)
CloseOutputSessionAsync()
OnCloseMessageReceived(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.Threading.CancellationToken)
OnCloseResponseMessageReceived(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,System.TimeSpan)
WaitForOutputSessionCloseAsync()
WaitForInputSessionCloseAsync()
.ctor(CoreWCF.Security.Tokens.SecurityContextSecurityToken,CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.SecuritySessionServerSettings/ServerSecurityDuplexSessionChannel)
CloseOutputSessionAsync()
CloseOutputSessionAsync(System.Threading.CancellationToken)
CloseOutputSessionAsync()
.ctor(CoreWCF.Security.SecuritySessionServerSettings,CoreWCF.Security.Tokens.SecurityContextSecurityToken,System.Object,CoreWCF.Security.SecurityListenerSettingsLifetimeManager,CoreWCF.Channels.IChannel,CoreWCF.EndpointAddress)
IncomingChannel()
ChannelDispatcher()
DispatchAsync(CoreWCF.Channels.RequestContext)
DispatchAsync()
GetProperty()
OpenAsync()
OpenAsync()
OpenAsync(System.Threading.CancellationToken)
SendAsync(CoreWCF.Channels.Message)
SendAsync(CoreWCF.Channels.Message,System.Threading.CancellationToken)
ReceiveAsync(System.Threading.CancellationToken)
TryReceiveAsync(System.Threading.CancellationToken)
CheckOutputOpen()
OnFaulted(System.Exception)
DefaultReceiveTimeout()
DefaultSendTimeout()
DefaultCloseTimeout()
DefaultOpenTimeout()
OnAbort()
OnCloseAsync(System.Threading.CancellationToken)
OnOpenAsync(System.Threading.CancellationToken)
.ctor(CoreWCF.Channels.IDuplexChannel,CoreWCF.Channels.Message)
OnAbort()
OnCloseAsync(System.Threading.CancellationToken)
OnReplyAsync()
.ctor(CoreWCF.Channels.RequestContext,CoreWCF.Channels.Message,CoreWCF.Security.SecurityProtocolCorrelationState,CoreWCF.Security.SecuritySessionServerSettings/ServerSecuritySessionChannel)
OnAbort()
OnCloseAsync(System.Threading.CancellationToken)
OnReplyAsync(CoreWCF.Channels.Message,System.Threading.CancellationToken)
.ctor(CoreWCF.Security.SecurityStandardsManager)
HandleDemuxFailure(CoreWCF.Channels.Message)
CreateSessionDemuxFaultMessage(CoreWCF.Channels.Message)
HandleDemuxFailureAsync(CoreWCF.Channels.Message)
HandleDemuxFailureAsync()