public TwoPhaseCommitParticipantEvent(ParticipantEnlistment participant) : base(participant)
 {
     MessageHeaders incomingMessageHeaders = OperationContext.Current.IncomingMessageHeaders;
     this.faultTo = Library.GetFaultToHeader(incomingMessageHeaders, base.state.ProtocolVersion);
     this.replyTo = Library.GetReplyToHeader(incomingMessageHeaders);
     this.messageID = incomingMessageHeaders.MessageId;
 }
 public WsrmAcknowledgmentHeader(ReliableMessagingVersion reliableMessagingVersion, UniqueId sequenceID, SequenceRangeCollection ranges, bool final, int bufferRemaining) : base(reliableMessagingVersion)
 {
     this.sequenceID = sequenceID;
     this.ranges = ranges;
     this.final = final;
     this.bufferRemaining = bufferRemaining;
 }
 public ServerReliableDuplexSessionChannel(ReliableChannelListenerBase<IDuplexSessionChannel> listener, IReliableChannelBinder binder, FaultHelper faultHelper, UniqueId inputID, UniqueId outputID) : base(listener, listener, binder)
 {
     this.listener = listener;
     DuplexServerReliableSession session = new DuplexServerReliableSession(this, listener, faultHelper, inputID, outputID);
     base.SetSession(session);
     session.Open(TimeSpan.Zero);
     base.SetConnections();
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         this.perfCounterId = this.listener.Uri.ToString().ToUpperInvariant();
     }
     if (binder.HasSession)
     {
         try
         {
             base.StartReceiving(false);
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             base.ReliableSession.OnUnknownException(exception);
         }
     }
 }
 protected WsrmHeaderFault(bool isSenderFault, string subcode, string faultReason, string exceptionMessage, UniqueId sequenceID, bool faultsInput, bool faultsOutput) : base(isSenderFault, subcode, faultReason, exceptionMessage)
 {
     this.subcode = subcode;
     this.sequenceID = sequenceID;
     this.faultsInput = faultsInput;
     this.faultsOutput = faultsOutput;
 }
 internal static void WriteAckRanges(XmlDictionaryWriter writer, ReliableMessagingVersion reliableMessagingVersion, UniqueId sequenceId, SequenceRangeCollection ranges)
 {
     WsrmFeb2005Dictionary dictionary = XD.WsrmFeb2005Dictionary;
     XmlDictionaryString namespaceUri = WsrmIndex.GetNamespace(reliableMessagingVersion);
     writer.WriteStartElement(dictionary.Identifier, namespaceUri);
     writer.WriteValue(sequenceId);
     writer.WriteEndElement();
     if (ranges.Count == 0)
     {
         if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
         {
             ranges = ranges.MergeWith((long) 0L);
         }
         else if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
         {
             writer.WriteStartElement(DXD.Wsrm11Dictionary.None, namespaceUri);
             writer.WriteEndElement();
         }
     }
     for (int i = 0; i < ranges.Count; i++)
     {
         writer.WriteStartElement(dictionary.AcknowledgementRange, namespaceUri);
         writer.WriteStartAttribute(dictionary.Lower, null);
         SequenceRange range = ranges[i];
         writer.WriteValue(range.Lower);
         writer.WriteEndAttribute();
         writer.WriteStartAttribute(dictionary.Upper, null);
         SequenceRange range2 = ranges[i];
         writer.WriteValue(range2.Upper);
         writer.WriteEndAttribute();
         writer.WriteEndElement();
     }
 }
 public VolatileTwoPhaseCommitCoordinatorEvent(VolatileCoordinatorEnlistment coordinator) : base(coordinator)
 {
     MessageHeaders incomingMessageHeaders = OperationContext.Current.IncomingMessageHeaders;
     this.faultTo = Library.GetFaultToHeader(incomingMessageHeaders, base.state.ProtocolVersion);
     this.replyTo = Library.GetReplyToHeader(incomingMessageHeaders);
     this.messageID = incomingMessageHeaders.MessageId;
 }
 public AddressingProperty(MessageHeaders headers)
 {
     this.action = headers.Action;
     this.to = headers.To;
     this.replyTo = headers.ReplyTo;
     this.messageId = headers.MessageId;
 }
 public CompletionParticipantEvent(CompletionEnlistment completion) : base(completion)
 {
     MessageHeaders incomingMessageHeaders = OperationContext.Current.IncomingMessageHeaders;
     this.faultTo = Library.GetFaultToHeader(incomingMessageHeaders, base.state.ProtocolVersion);
     this.replyTo = Library.GetReplyToHeader(incomingMessageHeaders);
     this.messageID = incomingMessageHeaders.MessageId;
 }
 private WsrmAcknowledgmentInfo(UniqueId sequenceID, SequenceRangeCollection ranges, bool final, int bufferRemaining, MessageHeaderInfo header) : base(header)
 {
     this.sequenceID = sequenceID;
     this.ranges = ranges;
     this.final = final;
     this.bufferRemaining = bufferRemaining;
 }
 public TerminateSequence(ReliableMessagingVersion reliableMessagingVersion, UniqueId identifier, Int64 last)
     : base(true)
 {
     this.reliableMessagingVersion = reliableMessagingVersion;
     this.identifier = identifier;
     this.lastMsgNumber = last;
 }
Beispiel #11
0
 public bool IsNotSeenBefore(Message message, out byte[] id, out int cacheHit)
 {
     cacheHit = -1;
     id       = PeerNodeImplementation.DefaultId;
     if (message is SecurityVerifiedMessage)
     {
         id = (message as SecurityVerifiedMessage).PrimarySignatureValue;
     }
     else
     {
         System.Xml.UniqueId messageId = PeerMessageHelpers.GetHeaderUniqueId(message.Headers, PeerStrings.MessageId, PeerStrings.Namespace);
         if (messageId == null)
         {
             return(false);
         }
         if (messageId.IsGuid)
         {
             id = new byte[16];
             messageId.TryGetGuid(id, 0);
         }
         else
         {
             return(false);
         }
     }
     cacheHit = messageIds.AddForLookup(id);
     if (cacheHit == -1)
     {
         return(true);
     }
     return(false);
 }
        public TransmissionStrategy(ReliableMessagingVersion reliableMessagingVersion, TimeSpan initRtt,
            int maxWindowSize, bool requestAcks, UniqueId id)
        {
            if (initRtt < TimeSpan.Zero)
            {
                if (DiagnosticUtility.ShouldTrace(TraceEventType.Warning))
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.WsrmNegativeElapsedTimeDetected,
                    SR.GetString(SR.TraceCodeWsrmNegativeElapsedTimeDetected), this);
                }

                initRtt = ReliableMessagingConstants.UnknownInitiationTime;
            }

            if (maxWindowSize <= 0)
            {
                throw Fx.AssertAndThrow("Argument maxWindow size must be positive.");
            }

            this.id = id;
            this.maxWindowSize = this.lossWindowSize = maxWindowSize;
            this.meanRtt = Math.Min((long)initRtt.TotalMilliseconds, Constants.MaxMeanRtt >> Constants.TimeMultiplier) << Constants.TimeMultiplier;
            this.serrRtt = this.meanRtt >> 1;
            this.window = new SlidingWindow(maxWindowSize);
            this.slowStartThreshold = maxWindowSize;
            this.timeout = Math.Max(((200 << Constants.TimeMultiplier) * 2) + this.meanRtt, this.meanRtt + (this.serrRtt << Constants.ChebychevFactor));
            this.quotaRemaining = Int32.MaxValue;
            this.retryTimer = new IOThreadTimer(new Action<object>(OnRetryElapsed), null, true);
            this.requestAcks = requestAcks;
            this.reliableMessagingVersion = reliableMessagingVersion;
        }
Beispiel #13
0
        public static void ReadHeaderValue(XmlDictionaryReader reader, AddressingVersion version, out Uri relationshipType, out System.Xml.UniqueId messageId)
        {
            AddressingDictionary addressingDictionary = XD.AddressingDictionary;

            relationshipType = ReplyRelationshipType;
            messageId        = reader.ReadElementContentAsUniqueId();
        }
Beispiel #14
0
		public void MatchesKeyIdentifierClause ()
		{
			UniqueId id = new UniqueId ();
			X509SecurityToken t = new X509SecurityToken (cert, id.ToString ());
			LocalIdKeyIdentifierClause l =
				new LocalIdKeyIdentifierClause (id.ToString ());
			Assert.IsTrue (t.MatchesKeyIdentifierClause (l), "#1-1");

			l = new LocalIdKeyIdentifierClause ("#" + id.ToString ());
			Assert.IsFalse (t.MatchesKeyIdentifierClause (l), "#1-2");

			X509ThumbprintKeyIdentifierClause h =
				new X509ThumbprintKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (h), "#2-1");

			h = new X509ThumbprintKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (h), "#2-2");

			X509IssuerSerialKeyIdentifierClause i =
				new X509IssuerSerialKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (i), "#3-1");

			i = new X509IssuerSerialKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (i), "#3-2");

			X509RawDataKeyIdentifierClause s =
				new X509RawDataKeyIdentifierClause (cert);
			Assert.IsTrue (t.MatchesKeyIdentifierClause (s), "#4-1");

			s = new X509RawDataKeyIdentifierClause (cert2);
			Assert.IsFalse (t.MatchesKeyIdentifierClause (s), "#4-2");
		}
 protected void SetMessageId(MessageVersion messageVersion, MessageHeaders headers)
 {
     this.messageId = headers.MessageId;
     if (this.messageId == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(System.ServiceModel.SR.GetString("MissingMessageIdOnWsrmRequest", new object[] { this.RequestName }), messageVersion.Addressing.Namespace, "MessageID", false));
     }
 }
 public CreateSequence(AddressingVersion addressingVersion, ReliableMessagingVersion reliableMessagingVersion, bool ordered, IClientReliableChannelBinder binder, UniqueId offerIdentifier) : base(true)
 {
     this.addressingVersion = addressingVersion;
     this.reliableMessagingVersion = reliableMessagingVersion;
     this.ordered = ordered;
     this.binder = binder;
     this.offerIdentifier = offerIdentifier;
 }
 internal SecurityContextSecurityToken(SecurityContextSecurityToken sourceToken, string id, byte[] key, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
     : base()
 {
     _id = id;
     this.Initialize(sourceToken._contextId, key, sourceToken.ValidFrom, sourceToken.ValidTo, authorizationPolicies, sourceToken._isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
     _cookieBlob = sourceToken._cookieBlob;
     _bootstrapMessageProperty = (sourceToken._bootstrapMessageProperty == null) ? null : (SecurityMessageProperty)sourceToken.BootstrapMessageProperty.CreateCopy();
 }
 protected MakeConnectionMessageFault(Message message, FaultCode code, string subcode, FaultReason reason)
 {
     this.code = code;
     this.subcode = subcode;
     this.reason = reason;
     this.isRemote = true;
     this.originalMessageId = message.Headers.MessageId;
 }
 internal SecurityContextSecurityToken(UniqueId contextId, string id, byte[] key, DateTime validFrom, DateTime validTo, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode, byte[] cookieBlob,
     UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime)
     : base()
 {
     _id = id;
     this.Initialize(contextId, key, validFrom, validTo, authorizationPolicies, isCookieMode, keyGeneration, keyEffectiveTime, keyExpirationTime);
     _cookieBlob = cookieBlob;
 }
		public SecurityContextSecurityToken GetContext (UniqueId contextId, UniqueId generation)
		{
			Table table;
			if (!cache.TryGetValue (contextId, out table))
				return null;
			SecurityContextSecurityToken ret;
			return table.TryGetValue (generation, out ret) ? ret : null;
		}
        public AddressingProperty(MessageHeaders headers)
        {
            Fx.Assert(null != headers, "");

            this.action = headers.Action;
            this.to = headers.To;
            this.replyTo = headers.ReplyTo;
            this.messageId = headers.MessageId;
        }
        public AddressingProperty(MessageHeaders headers)
        {
            Fx.Assert(null != headers, "");

            this.action    = headers.Action;
            this.to        = headers.To;
            this.replyTo   = headers.ReplyTo;
            this.messageId = headers.MessageId;
        }
 protected MakeConnectionMessageFault(Message message, string subcode, string faultReason, string exceptionMessage)
 {
     this.code = new FaultCode("Receiver", "");
     this.subcode = subcode;
     this.reason = new FaultReason(faultReason);
     this.exceptionMessage = exceptionMessage;
     this.isRemote = false;
     this.originalMessageId = message.Headers.MessageId;
 }
 public ReliableOutputConnection(UniqueId id, int maxTransferWindowSize, System.ServiceModel.Channels.MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, TimeSpan initialRtt, bool requestAcks, TimeSpan sendTimeout)
 {
     this.id = id;
     this.messageVersion = messageVersion;
     this.reliableMessagingVersion = reliableMessagingVersion;
     this.sendTimeout = sendTimeout;
     this.strategy = new TransmissionStrategy(reliableMessagingVersion, initialRtt, maxTransferWindowSize, requestAcks, id);
     this.strategy.RetryTimeoutElapsed = new RetryHandler(this.OnRetryTimeoutElapsed);
     this.strategy.OnException = new ComponentExceptionHandler(this.RaiseOnException);
 }
Beispiel #25
0
		public void DefaultValues ()
		{
			UniqueId id = new UniqueId ();
			X509SecurityToken t = new X509SecurityToken (cert, id.ToString ());
			Assert.AreEqual (id.ToString (), t.Id, "#1");
			Assert.AreEqual (cert, t.Certificate, "#2");
			Assert.AreEqual (cert.NotBefore.ToUniversalTime (), t.ValidFrom, "#3");
			Assert.AreEqual (cert.NotAfter.ToUniversalTime (), t.ValidTo, "#4");
			Assert.AreEqual (1, t.SecurityKeys.Count, "#5");
		}
		public Collection<SecurityContextSecurityToken> GetAllContexts (UniqueId contextId)
		{
			Table table;
			if (!cache.TryGetValue (contextId, out table))
				return new Collection<SecurityContextSecurityToken> ();
			SecurityContextSecurityToken [] arr =
				new SecurityContextSecurityToken [table.Count];
			table.Values.CopyTo (arr, 0);
			return new Collection<SecurityContextSecurityToken> (arr);
		}
 public SecurityContextKeyIdentifierClause(UniqueId contextId, UniqueId generation, byte[] derivationNonce, int derivationLength)
     : base(null, derivationNonce, derivationLength)
 {
     if (contextId == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextId");
     }
     _contextId = contextId;
     _generation = generation;
 }
Beispiel #28
0
        private Guid ProvideUrnFromHeaderFields(UniqueId headerField)
        {
            var urn = new Guid();

            if (headerField != null)
            {
                var possibleUrnAsString = StripFormattingFromHeaderFields(headerField.ToString());
                Guid.TryParseExact(possibleUrnAsString, "D", out urn);
            }
            return urn;
        }
 public static Message CreateFaultMessage(UniqueId messageID, MessageVersion messageVersion, Fault fault)
 {
     MessageFault fault2 = MessageFault.CreateFault(FaultCode.CreateSenderFaultCode(fault.Code), fault.Reason);
     Message message = Message.CreateMessage(messageVersion, fault2, messageVersion.Addressing.FaultAction);
     message.Headers.Action = fault.Action;
     if (messageID != null)
     {
         message.Headers.RelatesTo = messageID;
     }
     return message;
 }
		public void DefaultValues ()
		{
			UniqueId id = new UniqueId ();
			UserNameSecurityToken t = new UserNameSecurityToken ("mono", "poly", id.ToString ());
			Assert.AreEqual (id.ToString (), t.Id, "#1");
			Assert.AreEqual ("mono", t.UserName, "#2");
			Assert.AreEqual ("poly", t.Password,"#3");
			Assert.IsTrue (DateTime.Today.ToUniversalTime () <= t.ValidFrom && DateTime.Now.ToUniversalTime () >= t.ValidFrom, "#4");
			Assert.AreEqual (DateTime.MaxValue.AddDays (-1), t.ValidTo, "#5");
			Assert.AreEqual (0, t.SecurityKeys.Count, "#6");
		}
Beispiel #31
0
 public static RelatesToHeader Create(System.Xml.UniqueId messageId, AddressingVersion addressingVersion)
 {
     if (object.ReferenceEquals(messageId, null))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId"));
     }
     if (addressingVersion == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
     }
     return(new RelatesToHeader(messageId, addressingVersion));
 }
Beispiel #32
0
        static System.Xml.UniqueId GetAttributeAsUniqueId(XmlDictionaryReader reader, string name, string ns)
        {
            if (!reader.MoveToAttribute(name, ns))
            {
                return(null);
            }

            System.Xml.UniqueId id = reader.ReadContentAsUniqueId();
            reader.MoveToElement();

            return(id);
        }
 public static MessageIDHeader Create(UniqueId messageId, AddressingVersion addressingVersion)
 {
     if (object.ReferenceEquals(messageId, null))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageId"));
     }
     if (addressingVersion == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("addressingVersion"));
     }
     return new MessageIDHeader(messageId, addressingVersion);
 }
        internal AsyncOperationContext(UniqueId operationId, int maxResults, TimeSpan duration, object userState)
        {
            Fx.Assert(operationId != null, "The operation id must be non null.");
            Fx.Assert(maxResults > 0, "The maxResults parameter must be positive.");
            Fx.Assert(duration > TimeSpan.Zero, "The duration parameter must be positive.");

            this.maxResults = maxResults;
            this.duration = duration;            
            this.userState = userState;
            this.operationId = operationId;
            this.syncRoot = new object();
        }
 public void SetSessionTokenAuthenticator(UniqueId sessionId, SecurityTokenAuthenticator sessionTokenAuthenticator, SecurityTokenResolver sessionTokenResolver)
 {
     this.CommunicationObject.ThrowIfDisposedOrImmutable();
     this.sessionId = sessionId;
     this.sessionTokenResolver = sessionTokenResolver;
     Collection<SecurityTokenResolver> tmp = new Collection<SecurityTokenResolver>();
     tmp.Add(this.sessionTokenResolver);
     this.sessionTokenResolverList = new ReadOnlyCollection<SecurityTokenResolver>(tmp);
     this.sessionTokenAuthenticator = sessionTokenAuthenticator;
     SupportingTokenAuthenticatorSpecification spec = new SupportingTokenAuthenticatorSpecification(this.sessionTokenAuthenticator, this.sessionTokenResolver, SecurityTokenAttachmentMode.Endorsing, this.Factory.SecurityTokenParameters);
     this.sessionTokenAuthenticatorSpecificationList = new Collection<SupportingTokenAuthenticatorSpecification>();
     this.sessionTokenAuthenticatorSpecificationList.Add(spec);
 }
Beispiel #36
0
                public override SecurityKeyIdentifierClause ReadClause(XmlDictionaryReader reader, byte[] derivationNonce, int derivationLength, string tokenType)
                {
                    System.Xml.UniqueId uri        = XmlHelper.GetAttributeAsUniqueId(reader, XD.SecurityJan2004Dictionary.URI, null);
                    System.Xml.UniqueId generation = ReadGeneration(reader);

                    if (reader.IsEmptyElement)
                    {
                        reader.Read();
                    }
                    else
                    {
                        reader.ReadStartElement();
                        while (reader.IsStartElement())
                        {
                            reader.Skip();
                        }
                        reader.ReadEndElement();
                    }

                    return(new SecurityContextKeyIdentifierClause(uri, generation, derivationNonce, derivationLength));
                }
 /// <summary>
 /// Retrieves all tokens associated with a given key.
 /// </summary>
 /// <param name="endpointId">The endpointId to search for.</param>
 /// <param name="contextId">The contextId to search for.</param>
 /// <returns>In the derived class returns, the collection of tokens associated with the key.</returns>
 public abstract IEnumerable <SessionSecurityToken> GetAll(string endpointId, System.Xml.UniqueId contextId);
        /// <summary>
        /// Reads the SessionSecurityToken from the given reader.
        /// </summary>
        /// <param name="reader">XmlReader over the SessionSecurityToken.</param>
        /// <param name="tokenResolver">SecurityTokenResolver that can used to resolve SessionSecurityToken.</param>
        /// <returns>An instance of <see cref="SessionSecurityToken"/>.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception>
        /// <exception cref="SecurityTokenException">The 'reader' is not positioned at a SessionSecurityToken
        /// or the SessionSecurityToken cannot be read.</exception>
        public override SecurityToken ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (tokenResolver == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenResolver");
            }

            byte[]      encodedCookie = null;
            SysUniqueId contextId     = null;
            SysUniqueId keyGeneration = null;

            string ns         = null;
            string identifier = null;
            string instance   = null;

            SecurityToken     securityContextToken = null;
            SessionDictionary dictionary           = SessionDictionary.Instance;

            XmlDictionaryReader dicReader = XmlDictionaryReader.CreateDictionaryReader(reader);

            if (dicReader.IsStartElement(WSSecureConversationFeb2005Constants.ElementNames.Name, WSSecureConversationFeb2005Constants.Namespace))
            {
                ns         = WSSecureConversationFeb2005Constants.Namespace;
                identifier = WSSecureConversationFeb2005Constants.ElementNames.Identifier;
                instance   = WSSecureConversationFeb2005Constants.ElementNames.Instance;
            }
            else if (dicReader.IsStartElement(WSSecureConversation13Constants.ElementNames.Name, WSSecureConversation13Constants.Namespace))
            {
                ns         = WSSecureConversation13Constants.Namespace;
                identifier = WSSecureConversation13Constants.ElementNames.Identifier;
                instance   = WSSecureConversation13Constants.ElementNames.Instance;
            }
            else
            {
                //
                // Something is wrong
                //
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(
                                                                              SR.GetString(SR.ID4230, WSSecureConversationFeb2005Constants.ElementNames.Name, dicReader.Name)));
            }

            string id = dicReader.GetAttribute(WSUtilityConstants.Attributes.IdAttribute, WSUtilityConstants.NamespaceURI);

            dicReader.ReadFullStartElement();
            if (!dicReader.IsStartElement(identifier, ns))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(
                                                                              SR.GetString(SR.ID4230, WSSecureConversation13Constants.ElementNames.Identifier, dicReader.Name)));
            }

            contextId = dicReader.ReadElementContentAsUniqueId();
            if (contextId == null || string.IsNullOrEmpty(contextId.ToString()))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4242)));
            }

            //
            // The token can be a renewed token, in which case we need to know the
            // instance id, which will be the secondary key to the context id for
            // cache lookups
            //
            if (dicReader.IsStartElement(instance, ns))
            {
                keyGeneration = dicReader.ReadElementContentAsUniqueId();
            }

            if (dicReader.IsStartElement(CookieElementName, CookieNamespace))
            {
                // Get the token from the Cache, which is returned as an SCT
                SecurityToken cachedToken = null;

                SecurityContextKeyIdentifierClause sctClause = null;
                if (keyGeneration == null)
                {
                    sctClause = new SecurityContextKeyIdentifierClause(contextId);
                }
                else
                {
                    sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration);
                }

                tokenResolver.TryResolveToken(sctClause, out cachedToken);

                if (cachedToken != null)
                {
                    securityContextToken = cachedToken;

                    dicReader.Skip();
                }
                else
                {
                    //
                    // CookieMode
                    //
                    encodedCookie = dicReader.ReadElementContentAsBase64();

                    if (encodedCookie == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4237)));
                    }
                    //
                    // appply transforms
                    //
                    byte[] decodedCookie = ApplyTransforms(encodedCookie, false);

                    using (MemoryStream ms = new MemoryStream(decodedCookie))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        securityContextToken = formatter.Deserialize(ms) as SecurityToken;
                    }

                    SessionSecurityToken sessionToken = securityContextToken as SessionSecurityToken;
                    if (sessionToken != null && sessionToken.ContextId != contextId)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4229, sessionToken.ContextId, contextId)));
                    }

                    if (sessionToken != null && sessionToken.Id != id)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4227, sessionToken.Id, id)));
                    }
                }
            }
            else
            {
                //
                // SessionMode
                //

                // Get the token from the Cache.
                SecurityToken cachedToken = null;

                SecurityContextKeyIdentifierClause sctClause = null;
                if (keyGeneration == null)
                {
                    sctClause = new SecurityContextKeyIdentifierClause(contextId);
                }
                else
                {
                    sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration);
                }

                tokenResolver.TryResolveToken(sctClause, out cachedToken);

                if (cachedToken != null)
                {
                    securityContextToken = cachedToken;
                }
            }

            dicReader.ReadEndElement();

            if (securityContextToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4243)));
            }

            return(securityContextToken);
        }
Beispiel #39
0
 static public void WriteAttributeStringAsUniqueId(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString ns, System.Xml.UniqueId id)
 {
     writer.WriteStartAttribute(prefix, localName, ns);
     writer.WriteValue(id);
     writer.WriteEndAttribute();
 }
Beispiel #40
0
        // Process the document set that was received
        private XmlDocument ProcessReceiveDocumentSet(XmlDocument xmlDocRequest, System.Xml.UniqueId messageID, MessageVersion msgVersion, out StringDictionary atnaParameterValues)
        {
            XmlDocument     xmlDocResponse         = null;
            Message         registryMessage        = null;
            XmlDocument     xmlDocRegistryResponse = null;
            XDSHelper       xdsHelper = null;
            XmlElement      eltProvideAndRegDocSet  = null;
            XmlNodeList     nodeListExtrinsicObject = null;
            XmlNodeList     nodeListDocument        = null;
            XmlNode         nodeSubmissionSet       = null;
            XmlNode         nodeExternalIdentifier  = null;
            List <Document> docList    = null;
            StringBuilder   sbMetaData = null;
            string          xpathExternalIdentifierDocument = @".//*[local-name()='ExtrinsicObject'][@id='$id$']/*[local-name()='ExternalIdentifier'][@identificationScheme='$identificationScheme$']";
            string          xpath                 = null;
            string          entryUUID             = null;
            string          uniqueID              = null;
            string          eventOutcomeIndicator = "0";

            atnaParameterValues = new StringDictionary();

            try
            {
                xdsHelper = new XDSHelper();
                xpathExternalIdentifierDocument = xpathExternalIdentifierDocument.Replace("$identificationScheme$", GlobalValues.XDSDocumentEntry_uniqueIdUUID);

                // get the root document element of the XML Document which is metadata plus MTOM encoded documents
                eltProvideAndRegDocSet = xmlDocRequest.DocumentElement;

                // get the list of nodes from the root document element that are ExtrinsicObject nodes
                nodeListExtrinsicObject = eltProvideAndRegDocSet.SelectNodes(".//*[local-name()='ExtrinsicObject']");

                // get the list of nodes from the root doc element that are Document nodes
                nodeListDocument = eltProvideAndRegDocSet.SelectNodes(".//*[local-name()='Document']");

                // get the Submission Set node from the document element
                nodeSubmissionSet = eltProvideAndRegDocSet.SelectSingleNode("//*[local-name()='SubmitObjectsRequest']/*[local-name()=\"RegistryObjectList\"]/*[local-name()='RegistryPackage']/*[local-name()='ExternalIdentifier'][@identificationScheme='urn:uuid:96fdda7c-d067-4183-912e-bf5ee74998a8']/@value");

                //Proceed further only if any ExtrinsicObject Exists(with attachments)
                if (nodeListExtrinsicObject == null)
                {
                    throw new Exception();
                }

                // check each ExtrinsicObject node document Id and match with attached documents to see if anything is missing
                if (xdsHelper.IsMissingDocumentAttachment(eltProvideAndRegDocSet))
                {
                    throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSMissingDocumentAttachment);
                }

                //if (repositoryLogic.IsMissingDocumentMetadata(nodeListExtrinsicObject, eltProvideAndRegDocSet))
                if (xdsHelper.IsMissingDocumentMetadata(eltProvideAndRegDocSet))
                {
                    throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSMissingDocumentMetadata);
                }

                // does each document have a unique id?
                if (xdsHelper.IsDuplicateUniqueID(eltProvideAndRegDocSet))
                {
                    throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryDuplicateUniqueIdInMessage);
                }

                // if we have metadata for each document and actual documents (this seems redundant with the earlier checks - refactor?)
                if (nodeListExtrinsicObject.Count > 0 && eltProvideAndRegDocSet.SelectNodes(@"//*[local-name()='Document']").Count > 0)
                {
                    //No document OR Metadata is Missing

                    // DocumentEntry object should be replaced by the new Document/Message object we want to use to carry this info
//                    lstDocumentEntry = new List<DocumentEntry>();
                    sbMetaData = new StringBuilder();
                    int loopCount = 0;
                    foreach (XmlNode node in nodeListExtrinsicObject)
                    {
//                        DocumentEntry objDocumentEntry = new DocumentEntry();

                        if (node.Attributes["mimeType"].Value == string.Empty)
                        {
                            throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryMetadataError);
                        }

//                        objDocumentEntry.MimeType = node.Attributes["mimeType"].Value;

                        entryUUID = node.Attributes["id"].Value;
                        xpath     = xpathExternalIdentifierDocument.Replace("$id$", node.Attributes["id"].Value);
                        nodeExternalIdentifier = eltProvideAndRegDocSet.SelectSingleNode(xpath);
                        uniqueID = nodeExternalIdentifier.Attributes["value"].Value;

                        if (string.IsNullOrEmpty(uniqueID))
                        {
                            throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryMetadataError);
                        }

//                        objDocumentEntry.EntryUUID = entryUUID;
//                        objDocumentEntry.UniqueID = uniqueID;
//                        objDocumentEntry.Hash = xdsHelper.GetHashCode(xmlDocRequest, entryUUID);
//                        objDocumentEntry.Content = xdsHelper.GetDocumentContentStream(xmlDocRequest, entryUUID);
//                        objDocumentEntry.Size = (int)objDocumentEntry.Content.Length;

                        // CP-ITI-419
                        string  docHash     = string.Empty;
                        XmlNode docHashNode = eltProvideAndRegDocSet.SelectNodes("//*[local-name()='SubmitObjectsRequest']/*[local-name()=\"RegistryObjectList\"]/*[local-name()='ExtrinsicObject']/*[local-name()='Slot'][@name='hash']")[loopCount];
                        if (docHashNode != null)
                        {
                            docHash = docHashNode.InnerText.Trim();
                        }

                        string  docSize     = string.Empty;
                        XmlNode docSizeNode = eltProvideAndRegDocSet.SelectNodes("//*[local-name()='SubmitObjectsRequest']/*[local-name()=\"RegistryObjectList\"]/*[local-name()='ExtrinsicObject']/*[local-name()='Slot'][@name='size']")[loopCount];
                        if (docSizeNode != null)
                        {
                            docSize = docSizeNode.InnerText.Trim();
                        }

//                        if ((!string.IsNullOrEmpty(docHash) && (docHash.ToLower() != objDocumentEntry.Hash.ToLower()))
//                            || (!string.IsNullOrEmpty(docSize) && (Convert.ToInt32(docSize) != objDocumentEntry.Size)))
                        {
                            xmlDocResponse        = CommonUtility.ConstructRegistryErrorResponse(GlobalValues.CONST_RESPONSE_STATUS_TYPE_FAILURE, string.Empty, "Size/hash of document not matching Metadata.", GlobalValues.CONST_ERROR_CODE_XDSRepositoryMetadataError, GlobalValues.CONST_SEVERITY_TYPE_ERROR, string.Empty);
                            eventOutcomeIndicator = "8";
                            atnaParameterValues.Add("$EventIdentification.EventOutcomeIndicator$", eventOutcomeIndicator);
                            return(xmlDocResponse);
                        }
                        // CP-ITI-419

                        //                       lstDocumentEntry.Add(objDocumentEntry);
                    }
                }
                else
                {
                    xmlDocRegistryResponse = new XmlDocument();
                    xmlDocRegistryResponse.Load(registryMessage.GetReaderAtBodyContents());

                    XmlNode errorList = xmlDocRegistryResponse.SelectSingleNode(@"//*[local-name()='RegistryError']");
                    string  errorCode = null;

                    if (errorList != null)
                    {
                        errorCode = errorList.Attributes["errorCode"].Value;
                    }


                    //Assign Registry Response to Repository Response
                    xmlDocResponse = xmlDocRegistryResponse;
                }
            }
            catch
            {
                throw;
            }
            try
            {
                return(xmlDocResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 static internal PeerDictionaryHeader CreateMessageIdHeader(System.Xml.UniqueId messageId)
 {
     return(new PeerDictionaryHeader(XD.AddressingDictionary.MessageId, XD.PeerWireStringsDictionary.Namespace, messageId.ToString()));
 }
 /// <summary>
 /// Attempts to remove all matching entries from cache.
 /// </summary>
 /// <param name="endpointId">The endpoint id for the entry to be removed.</param>
 /// <param name="contextId">The context Id for the entry to be removed.</param>
 public abstract void RemoveAll(string endpointId, System.Xml.UniqueId contextId);
Beispiel #43
0
 public abstract void WriteUniqueIdText(UniqueId value);
 public override void WriteValue(UniqueId value)
 {
     CheckAsync();
     CoreWriter.WriteValue(value);
 }
Beispiel #45
0
        public virtual void WriteValue(UniqueId value)
        {
            ArgumentNullException.ThrowIfNull(value);

            WriteString(value.ToString());
        }
Beispiel #46
0
 public override void WriteValue(System.Xml.UniqueId value)
 {
     this.effectiveWriter.WriteValue(value);
 }
Beispiel #47
0
 private RelatesToHeader(System.Xml.UniqueId messageId, AddressingVersion version) : base(version)
 {
     this.messageId = messageId;
 }
 public override void WriteUniqueIdText(UniqueId value)
 {
 }
Beispiel #49
0
 public static string ToString(UniqueId value)
 {
     return(value.ToString());
 }