Пример #1
0
 public static ServiceModelChannels.Message CopyMessageFromBuffer(ref ServiceModelChannels.Message message)
 {
     using (ServiceModelChannels.MessageBuffer msgbuf = message.CreateBufferedCopy(int.MaxValue))
     {
         ServiceModelChannels.Message returnMessage = msgbuf.CreateMessage();
         message = msgbuf.CreateMessage();
         return(returnMessage);
     }
 }
Пример #2
0
        public Message DecryptMessage()
        {
            Message srcmsg = buf.CreateMessage();

            if (srcmsg.Version.Envelope == EnvelopeVersion.None)
            {
                throw new ArgumentException("The message to decrypt is not an expected SOAP envelope.");
            }

            string action = GetAction();

            if (action == null)
            {
                throw new ArgumentException("SOAP action could not be retrieved from the message to decrypt.");
            }

            XPathNavigator nav = doc.CreateNavigator();

            using (XmlWriter writer = nav.AppendChild()) {
                buf.CreateMessage().WriteMessage(writer);
            }

/*
 * doc.PreserveWhitespace = false;
 * doc.Save (Console.Out);
 * doc.PreserveWhitespace = true;
 */

            // read and store headers, wsse:Security and setup in-band resolver.
            ReadHeaders(srcmsg);

            ExtractSecurity();

            Message msg = Message.CreateMessage(new XmlNodeReader(doc), srcmsg.Headers.Count, srcmsg.Version);

            for (int i = 0; i < srcmsg.Headers.Count; i++)
            {
                MessageHeaderInfo header = srcmsg.Headers [i];
                if (header == wss_header)
                {
                    msg.Headers.Add(wss_header);
                }
                else
                {
                    msg.Headers.CopyHeaderFrom(srcmsg, i);
                }
            }

            // FIXME: when Local[Client|Service]SecuritySettings.DetectReplays
            // is true, reject such messages which don't have <wsu:Timestamp>

            msg.Properties.Add("Security", sec_prop);
            return(msg);
        }
 private Message TraceMessage(MessageBuffer buffer)
 {
     Message msg = buffer.CreateMessage();
     string appPath = HostingEnvironment.ApplicationPhysicalPath;
     string logPath = appPath + "\\log.txt";
     File.AppendAllText(logPath, DateTime.Now.ToString("G"));
     File.AppendAllText(logPath, "\r\n");
     File.AppendAllText(logPath, "HelloWorldService is invoked");
     File.AppendAllText(logPath, "\r\n");
     File.AppendAllText(logPath, string.Format("Message={0}", msg));
     File.AppendAllText(logPath, "\r\n");
     return buffer.CreateMessage();
 }
        public override bool Match(MessageBuffer buffer)
        {
            if (buffer == null)
            {
                throw FxTrace.Exception.ArgumentNull("buffer");
            }

            return this.Match(buffer.CreateMessage());
        }
 public override bool Match(MessageBuffer buffer)
 {
     if (buffer == null)
     {
         throw FxTrace.Exception.ArgumentNull("buffer");
     }
     using (Message tempMessage = buffer.CreateMessage())
     {
         return MatchInternal(tempMessage.Properties);
     }
 }
Пример #6
0
        public static XDocument ReadWcfMessageBuffer(ref ServiceModelChannels.Message message)
        {
            using (ServiceModelChannels.MessageBuffer msgbuf = message.CreateBufferedCopy(int.MaxValue))
            {
                ServiceModelChannels.Message messageCopy = msgbuf.CreateMessage();

                using (MemoryStream stream = new MemoryStream())
                {
                    using (XmlWriter writer = XmlWriter.Create(stream))
                    {
                        messageCopy.WriteMessage(writer);
                        writer.Flush();
                        stream.Position = 0;
                        XDocument xdoc = XDocument.Load(XmlReader.Create(stream));
                        message = msgbuf.CreateMessage();
                        return(xdoc);
                    }
                }
            }
        }
        private async Task<XDocument> GetMessageEnvelope(MessageBuffer buffer)
        {
            using (var stream = new MemoryStream())
            {
                var msg = buffer.CreateMessage();
                XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
                msg.WriteMessage(writer);
                await writer.FlushAsync();
                stream.Seek(0, SeekOrigin.Begin);
                XDocument doc = XDocument.Load(stream);
                return doc;

            }
        }
 /// <summary>
 /// Reads the whole message contained in a <see cref="MessageBuffer"/> to <seealso cref="string"/>.
 /// </summary>
 /// <param name="buffer">The <see cref="MessageBuffer"/> to read from.</param>
 /// <param name="indent">A flag to set whether the output XML will be indented or not.</param>
 /// <returns>An XML <see cref="string"/>.</returns>
 public static string ReadAll(this MessageBuffer buffer, bool indent = true)
 {
     using (var message = buffer.CreateMessage())
         using (var stream = new MemoryStream())
         {
             using (var writer = XmlWriter.Create(stream, new XmlWriterSettings {
                 CloseOutput = false, Indent = indent, Encoding = new UTF8Encoding(false)
             }))
                 message.WriteMessage(writer);
             stream.Position = 0;
             using (var reader = XmlReader.Create(stream))
             {
                 reader.MoveToContent();
                 return(reader.ReadOuterXml());
             }
         }
 }
Пример #9
0
        public override bool Match(MessageBuffer buffer)
        {
            if (buffer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
            }

            Message message = buffer.CreateMessage();
            try
            {
                return Match(message);
            }
            finally
            {
                message.Close();
            }
        }
Пример #10
0
        protected virtual IAsyncResult FloodMessageToNeighbors(MessageBuffer messageBuffer,
                                                               TimeSpan timeout, AsyncCallback callback, object state,
                                                               int index, MessageHeader hopHeader, IPeerNeighbor except,
                                                               EventHandler OnMessageSentCallback)
        {
            long             temp    = Interlocked.Increment(ref messageSequence);
            FloodAsyncResult fresult = new FloodAsyncResult(this.neighborManager, timeout, callback, state);

            fresult.OnMessageSent += OnMessageSentCallback;
            List <IPeerNeighbor> neighbors = this.Neighbors;

            foreach (IPeerNeighbor neighbor in neighbors)
            {
                if (neighbor.Equals(except))
                {
                    continue;
                }
                // Don't do anything if the neighbor is not connected
                if (PeerNeighborStateHelper.IsConnected(neighbor.State))
                {
                    Message fmessage = messageBuffer.CreateMessage();
                    if (index != -1)
                    {
                        fmessage.Headers.ReplaceAt(index, hopHeader);
                    }

                    // Don't do anything if the neighbor is not connected
                    if (PeerNeighborStateHelper.IsConnected(neighbor.State))
                    {
                        BeginSendHelper(neighbor, timeout, fmessage, fresult);
                    }
                }
            }
            fresult.MarkEnd(true);
            return(fresult);
        }
        protected virtual IAsyncResult FloodMessageToNeighbors(MessageBuffer messageBuffer, TimeSpan timeout, AsyncCallback callback, object state, int index, MessageHeader hopHeader, IPeerNeighbor except, EventHandler OnMessageSentCallback)
        {
            Interlocked.Increment(ref this.messageSequence);
            FloodAsyncResult fresult = new FloodAsyncResult(this.neighborManager, timeout, callback, state);

            fresult.OnMessageSent += OnMessageSentCallback;
            foreach (IPeerNeighbor neighbor in this.Neighbors)
            {
                if (!neighbor.Equals(except) && PeerNeighborStateHelper.IsConnected(neighbor.State))
                {
                    Message message = messageBuffer.CreateMessage();
                    if (index != -1)
                    {
                        message.Headers.ReplaceAt(index, hopHeader);
                    }
                    if (PeerNeighborStateHelper.IsConnected(neighbor.State))
                    {
                        this.BeginSendHelper(neighbor, timeout, message, fresult);
                    }
                }
            }
            fresult.MarkEnd(true);
            return(fresult);
        }
Пример #12
0
        public virtual IAsyncResult OnFloodedMessage(IPeerNeighbor neighbor, TFloodContract floodInfo, AsyncCallback callback, object state)
        {
            bool                process       = false;
            MessageBuffer       messageBuffer = null;
            Message             message       = null;
            Uri                 via;
            Uri                 to;
            int                 index         = 0;
            ulong               remainingHops = PeerTransportConstants.MaxHopCount;
            MessageHeader       hopHeader     = null;
            bool                fatal         = false;
            PeerMessageProperty peerProperty  = null;
            IAsyncResult        result        = null;

            try
            {
                peerProperty = (PeerMessageProperty)floodInfo.Properties[PeerStrings.PeerProperty];
                if (!peerProperty.MessageVerified)
                {
                    if (peerProperty.CacheMiss > UtilityExtension.AcceptableMissDistance)
                    {
                        UtilityExtension.ReportCacheMiss(neighbor, peerProperty.CacheMiss);
                    }
                    result = new CompletedAsyncResult(callback, state);
                }
                else
                {
                    process            = true;
                    messageBuffer      = floodInfo.CreateBufferedCopy((int)this.config.MaxReceivedMessageSize);
                    message            = messageBuffer.CreateMessage();
                    via                = peerProperty.PeerVia;
                    to                 = peerProperty.PeerTo;
                    message.Headers.To = message.Properties.Via = via;

                    index = UpdateHopCount(message, out hopHeader, out remainingHops);

                    PeerMessagePropagation propagateFlags = PeerMessagePropagation.LocalAndRemote;
                    if (peerProperty.SkipLocalChannels)
                    {
                        propagateFlags = PeerMessagePropagation.Remote;
                    }
                    else if (messageHandler.HasMessagePropagation)
                    {
                        using (Message filterMessage = messageBuffer.CreateMessage())
                        {
                            propagateFlags = messageHandler.DetermineMessagePropagation(filterMessage, PeerMessageOrigination.Remote);
                        }
                    }

                    if ((propagateFlags & PeerMessagePropagation.Remote) != 0)
                    {
                        if (remainingHops == 0)
                        {
                            propagateFlags &= ~PeerMessagePropagation.Remote;
                        }
                    }
                    if ((propagateFlags & PeerMessagePropagation.Remote) != 0)
                    {
                        result = BeginFloodReceivedMessage(neighbor, messageBuffer, PeerTransportConstants.ForwardTimeout, callback, state, index, hopHeader);
                    }
                    else
                    {
                        result = new CompletedAsyncResult(callback, state);
                    }
                    if ((propagateFlags & PeerMessagePropagation.Local) != 0)
                    {
                        messageHandler.HandleIncomingMessage(messageBuffer, propagateFlags, index, hopHeader, via, to);
                    }
                }
                UtilityExtension.UpdateLinkUtility(neighbor, process);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    fatal = true;
                    throw;
                }
                if (null != CloseNeighborIfKnownException(neighborManager, e, neighbor))
                {
                    throw;
                }
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            finally
            {
                if (!fatal)
                {
                    if (message != null)
                    {
                        message.Close();
                    }
                    if (messageBuffer != null)
                    {
                        messageBuffer.Close();
                    }
                }
            }
            return(result);
        }
Пример #13
0
 public override bool Match(System.ServiceModel.Channels.MessageBuffer buffer)
 {
     return Match(buffer.CreateMessage());
 }
Пример #14
0
 private Message TraceMessage(MessageBuffer buffer)
 {
     Message msg = buffer.CreateMessage();
     Console.WriteLine("\n{0}\n", msg);
     return buffer.CreateMessage();
 }
		/// <summary>
		/// 	Gets the message envelope.
		/// </summary>
		/// <param name="buffer"> The buffer. </param>
		/// <returns> </returns>
		private static XDocument GetMessageEnvelope(MessageBuffer buffer)
		{
			return MessageEnvelope(buffer.CreateMessage());
		}
Пример #16
0
		protected SecureMessageDecryptor (
			Message source, MessageSecurityBindingSupport security)
		{
			source_message = source;
			this.security = security;

			// FIXME: use proper max buffer
			buf = source.CreateBufferedCopy (int.MaxValue);
Console.WriteLine ("####### " + buf.CreateMessage ());

			doc = new XmlDocument ();
			doc.PreserveWhitespace = true;

			nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nsmgr.AddNamespace ("c", Constants.WsscNamespace);
			nsmgr.AddNamespace ("o", Constants.WssNamespace);
			nsmgr.AddNamespace ("e", EncryptedXml.XmlEncNamespaceUrl);
			nsmgr.AddNamespace ("u", Constants.WsuNamespace);
			nsmgr.AddNamespace ("dsig", SignedXml.XmlDsigNamespaceUrl);

		}
 private Message TraceMessage(MessageBuffer buffer)
 {
     Message msg = buffer.CreateMessage();
     System.Diagnostics.Trace.WriteLine(msg);
     return buffer.CreateMessage();
 }
Пример #18
0
 public override bool Match(MessageBuffer buffer)
 {
     return Match(buffer.CreateMessage());
 }
        private object HandleResult(MessageBuffer responseBuffer, Type returnType)
        {
            if (returnType == typeof(void))
            {
                return null;
            }

            var xml = responseBuffer.CreateMessage().GetReaderAtBodyContents().ReadOuterXml();

            return Deserialize(xml, returnType);
        }
        private static void HandleFaults(MessageBuffer responseBuffer)
        {
            var response = responseBuffer.CreateMessage();
            if (!response.IsFault)
            {
                return;
            }

            var exception = CreateExceptionOnFault(response.GetReaderAtBodyContents());

            throw exception;
        }
 /// <summary>
 /// Logs the request or response
 /// </summary>
 /// <param name="buffer"></param>
 /// <param name="message"></param>
 private void LogRequestResponse(MessageBuffer buffer, string message)
 {
     Message msg = buffer.CreateMessage();
     StringBuilder sb = new StringBuilder();
     using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb))
     {
         msg.WriteMessage(xw);
         xw.Close();
     }
     _logger.Debug(message, sb.ToString());
 }
 internal FilterResult Match(MessageBuffer messageBuffer)
 {
     FilterResult result;
     Message message = messageBuffer.CreateMessage();
     try
     {
         result = this.Match(message, true);
     }
     finally
     {
         message.Close();
     }
     return result;
 }
        void IPeerNodeMessageHandling.HandleIncomingMessage(MessageBuffer messageBuffer, PeerMessagePropagation propagateFlags,
            int index, MessageHeader hopHeader, Uri via, Uri to)
        {
            if (DiagnosticUtility.ShouldTraceVerbose)
            {
                TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerFloodedMessageReceived, SR.GetString(SR.TraceCodePeerFloodedMessageReceived), this.traceRecord, this, null);
            }

            if (via == null)
            {
                Fx.Assert("No VIA in the forwarded message!");
                using (Message message = messageBuffer.CreateMessage())
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.PeerMessageMustHaveVia, message.Headers.Action)));
                }
            }
            if ((propagateFlags & PeerMessagePropagation.Local) != 0)
            {
                DeliverMessageToClientChannels(null, messageBuffer, via, to, messageBuffer.MessageContentType, (int)maxReceivedMessageSize, index, hopHeader);
                messageBuffer = null;
            }
            else
            {
                if (DiagnosticUtility.ShouldTraceVerbose)
                {
                    using (Message traceMessage = messageBuffer.CreateMessage())
                    {
                        TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerFloodedMessageNotPropagated, SR.GetString(SR.TraceCodePeerFloodedMessageNotPropagated), this.traceRecord, this, null, traceMessage);
                    }
                }
            }
        }
		void VerifyInput (MessageBuffer buf)
		{
			Message input = buf.CreateMessage ();
/*
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
using (XmlWriter w = XmlWriter.Create (Console.Error, settings)) {
buf.CreateMessage ().WriteMessage (w);
}
Console.Error.WriteLine ("******************** DONE ********************");
Console.Error.Flush ();
*/

			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", input.Headers.Action, "GetToken.Request.Action");
			Assert.IsNotNull (input.Headers.MessageId, "GetToken.Request.MessageID");
			// in the raw Message it is "http://www.w3.org/2005/08/addressing/anonymous", but it is replaced by MessageHeaders implementation.
			Assert.AreEqual (new EndpointAddress ("http://schemas.microsoft.com/2005/12/ServiceModel/Addressing/Anonymous"), input.Headers.ReplyTo, "GetToken.Request.ReplyTo");

			// o:Security
			// FIXME: test WSSecurity more
			// <o:Security>
			//  <u:Timestamp>
			//   <u:Created>...</u:Created>
			//   <u:Expires>...</u:Expires>
			//  </u:Timestamp>
			//  <o:BinarySecurityToken>...</o:BinarySecurityToken>
			//  <e:EncryptedKey>
			//   <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
			//   <KeyInfo>
			//    <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   </KeyInfo>
			//   <e:CipherData>
			//    <e:CipherValue>...</e:CipherValue>
			//   </e:CipherData>
			//  </e:EncryptedKey>
			//  [
			//  <c:DerivedKeyToken>
			//   <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   <c:Offset>...</c:Offset>
			//   <c:Length>...</c:Length>
			//   <c:Nonce>...</c:Nonce>
			//  </c:DerivedKeyToken>
			//  ]
			//  <e:ReferenceList>
			//   [
			//   <e:DataReference>
			//   ]
			//  </e:ReferenceList>
			//  <e:EncryptedData>
			//   <e:EncryptionMethod/>
			//   <KeyInfo> {{....}} </KeyInfo>
			//   <e:CipherData> {{....}} </e:CipherData>
			//  </e:EncryptedData>
			// </o:Security>
			int i = input.Headers.FindHeader ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			Assert.IsTrue (i >= 0, "Security header existence");
			MessageHeaderInfo info = input.Headers [i];
			Assert.IsNotNull (info, "Security header item");
			XmlReader r = input.Headers.GetReaderAtHeader (i);

			// FIXME: test WSSecurity more
			// <o:Security>
			r.MoveToContent ();
			r.ReadStartElement ("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			//  <u:Timestamp>
			r.MoveToContent ();
			r.ReadStartElement ("Timestamp", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			//   <u:Created>...</u:Created>
			r.MoveToContent ();
			r.ReadStartElement ("Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			r.ReadString ();
			r.MoveToContent ();
			r.ReadEndElement ();
			//   <u:Expires>...</u:Expires>
			r.MoveToContent ();
			r.ReadStartElement ("Expires", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
			r.ReadString ();
			r.MoveToContent ();
			r.ReadEndElement ();
			//  </u:Timestamp>
			r.MoveToContent ();
			r.ReadEndElement ();
			//  <o:BinarySecurityToken>...</o:BinarySecurityToken>
			r.MoveToContent ();
			r.ReadStartElement ("BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			byte [] rawcert = Convert.FromBase64String (r.ReadString ());
			r.ReadEndElement ();
			X509Certificate2 cert = new X509Certificate2 (rawcert);

			// FIXME: test EncryptedKey
			r.MoveToContent ();
			r.Skip ();
			//  <e:EncryptedKey>
			//   <e:EncryptionMethod><DigestMethod/></e:EncryptionMethod>
			//   <KeyInfo>
			//    <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   </KeyInfo>
			//   <e:CipherData>
			//    <e:CipherValue>...</e:CipherValue>
			//   </e:CipherData>
			//  </e:EncryptedKey>

			// FIXME: test DerivedKeyTokens
			r.MoveToContent ();
			while (r.LocalName == "DerivedKeyToken") {
				r.Skip ();
				r.MoveToContent ();
			}
			//  [
			//  <c:DerivedKeyToken>
			//   <o:SecurityTokenReference><o:Reference/></o:SecurityTokenReference>
			//   <c:Offset>...</c:Offset>
			//   <c:Length>...</c:Length>
			//   <c:Nonce>...</c:Nonce>
			//  </c:DerivedKeyToken>
			//  ]
			
			//  <e:ReferenceList>
			//   [
			//   <e:DataReference>
			//   ]
			//  </e:ReferenceList>
			//  <e:EncryptedData>
			//   <e:EncryptionMethod/>
			//   <KeyInfo> {{....}} </KeyInfo>
			//   <e:CipherData> {{....}} </e:CipherData>
			//  </e:EncryptedData>
			// </o:Security>

			// SOAP Body
			r = input.GetReaderAtBodyContents (); // just verifying itself ;)
		}
Пример #25
0
		internal static Message BufferToMessage(MessageBuffer buffer)
		{
			return buffer.CreateMessage();
		}
        public virtual IAsyncResult OnFloodedMessage(IPeerNeighbor neighbor, TFloodContract floodInfo, AsyncCallback callback, object state)
        {
            bool                useful        = false;
            MessageBuffer       messageBuffer = null;
            Message             message       = null;
            int                 index         = 0;
            ulong               maxValue      = ulong.MaxValue;
            MessageHeader       hopHeader     = null;
            bool                flag2         = false;
            PeerMessageProperty property      = null;
            IAsyncResult        result        = null;

            try
            {
                property = (PeerMessageProperty)floodInfo.Properties["PeerProperty"];
                if (!property.MessageVerified)
                {
                    if (property.CacheMiss > 2)
                    {
                        UtilityExtension.ReportCacheMiss(neighbor, property.CacheMiss);
                    }
                    result = new CompletedAsyncResult(callback, state);
                }
                else
                {
                    useful        = true;
                    messageBuffer = floodInfo.CreateBufferedCopy((int)this.config.MaxReceivedMessageSize);
                    message       = messageBuffer.CreateMessage();
                    Uri peerVia = property.PeerVia;
                    Uri peerTo  = property.PeerTo;
                    message.Headers.To = message.Properties.Via = peerVia;
                    index = this.UpdateHopCount(message, out hopHeader, out maxValue);
                    PeerMessagePropagation localAndRemote = PeerMessagePropagation.LocalAndRemote;
                    if (property.SkipLocalChannels)
                    {
                        localAndRemote = PeerMessagePropagation.Remote;
                    }
                    else if (this.messageHandler.HasMessagePropagation)
                    {
                        using (Message message2 = messageBuffer.CreateMessage())
                        {
                            localAndRemote = this.messageHandler.DetermineMessagePropagation(message2, PeerMessageOrigination.Remote);
                        }
                    }
                    if (((localAndRemote & PeerMessagePropagation.Remote) != PeerMessagePropagation.None) && (maxValue == 0L))
                    {
                        localAndRemote &= ~PeerMessagePropagation.Remote;
                    }
                    if ((localAndRemote & PeerMessagePropagation.Remote) != PeerMessagePropagation.None)
                    {
                        result = this.BeginFloodReceivedMessage(neighbor, messageBuffer, PeerTransportConstants.ForwardTimeout, callback, state, index, hopHeader);
                    }
                    else
                    {
                        result = new CompletedAsyncResult(callback, state);
                    }
                    if ((localAndRemote & PeerMessagePropagation.Local) != PeerMessagePropagation.None)
                    {
                        this.messageHandler.HandleIncomingMessage(messageBuffer, localAndRemote, index, hopHeader, peerVia, peerTo);
                    }
                }
                UtilityExtension.UpdateLinkUtility(neighbor, useful);
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    flag2 = true;
                    throw;
                }
                if (PeerFlooderBase <TFloodContract, TLinkContract> .CloseNeighborIfKnownException(this.neighborManager, exception, neighbor) != null)
                {
                    throw;
                }
                System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
            }
            finally
            {
                if (!flag2)
                {
                    if (message != null)
                    {
                        message.Close();
                    }
                    if (messageBuffer != null)
                    {
                        messageBuffer.Close();
                    }
                }
            }
            return(result);
        }
		XmlElement VerifyInput2 (MessageBuffer buf)
		{
			Message msg2 = buf.CreateMessage ();
			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
				msg2.WriteMessage (w);
			}
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.LoadXml (sw.ToString ());

			// decrypt the key with service certificate privkey
			PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
			EncryptedXml encXml = new EncryptedXml (doc);
			encXml.Padding = mode;
			X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
			nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
			nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
			XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: enckey does not exist");
			string raw = n.InnerText;
			byte [] rawbytes = Convert.FromBase64String (raw);
			RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
			byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);

#if false
			// create derived keys
			Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
			InMemorySymmetricSecurityKey skey =
				new InMemorySymmetricSecurityKey (decryptedKey);
			foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
				n = el.SelectSingleNode ("c:Offset", nsmgr);
				int offset = (n == null) ? 0 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Length", nsmgr);
				int length = (n == null) ? 32 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Label", nsmgr);
				byte [] label = (n == null) ? decryptedKey :
					Convert.FromBase64String (n.InnerText);
				n = el.SelectSingleNode ("c:Nonce", nsmgr);
				byte [] nonce = (n == null) ? new byte [0] :
					Convert.FromBase64String (n.InnerText);
				byte [] derkey = skey.GenerateDerivedKey (
					//SecurityAlgorithms.Psha1KeyDerivation,
					"http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
					label,
					nonce,
					length * 8,
					offset);

				keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
			}
#endif

			// decrypt the signature with the decrypted key
#if true
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;
			MemoryStream ms = new MemoryStream ();
			CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedSignature = ms.ToArray ();
#else
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;

			EncryptedData ed = new EncryptedData ();
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			ed.LoadXml (n as XmlElement);
			byte [] decryptedSignature = encXml.DecryptData (ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

			// decrypt the body with the decrypted key
#if true
			n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			ms = new MemoryStream ();
			cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedBody = ms.ToArray ();
#else
			// decrypt the body with the decrypted key
			EncryptedData ed2 = new EncryptedData ();
			XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
			ed2.LoadXml (el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			byte [] decryptedBody = encXml.DecryptData (ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
Console.Error.WriteLine ("============= Decrypted Body End ===========");

			// FIXME: find out what first 16 bytes mean.
			for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
			doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
			Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

			return doc.DocumentElement;
		}
        void DeliverMessageToClientChannels(
                                object registrant,
                                MessageBuffer messageBuffer,
                                Uri via,
                                Uri peerTo,
                                string contentType,
                                int messageSize,
                                int index,
                                MessageHeader hopHeader)
        {
            Message message = null;
            try
            {
                // create a list of callbacks so they can each be called outside the lock
                ArrayList callbacks = new ArrayList();
                Uri to = peerTo;
                Fx.Assert(peerTo != null, "Invalid To header value!");
                if (isOpen)
                {
                    lock (ThisLock)
                    {
                        if (isOpen)
                        {
                            foreach (MessageFilterRegistration mfr in messageFilters.Values)
                            {
                                // first, the via's must match
                                bool match = CompareVia(via, mfr.via);
                                if (messageSize < 0)
                                {
                                    //messageSize <0 indicates that this message is coming from BeginSend
                                    //and the size is not computed yet.
                                    if (message == null)
                                    {
                                        message = messageBuffer.CreateMessage();
                                        Fx.Assert(message.Headers.To == to, "To Header is inconsistent in Send() case!");
                                        Fx.Assert(message.Properties.Via == via, "Via property is inconsistent in Send() case!");
                                    }
                                    //incoming message need not be verified MaxReceivedSize
                                    //only do this for local channels
                                    if (registrant != null)
                                    {
                                        ArraySegment<byte> buffer = encoder.WriteMessage(message, int.MaxValue, bufferManager);
                                        messageSize = (int)buffer.Count;
                                    }
                                }
                                // only queue the message for registrants expecting this size
                                match = match && (messageSize <= mfr.settings.MaxReceivedMessageSize);

                                // if a filter is specified, it must match as well
                                if (match && mfr.filters != null)
                                {
                                    for (int i = 0; match && i < mfr.filters.Length; i++)
                                    {
                                        match = mfr.filters[i].Match(via, to);
                                    }
                                }

                                if (match)
                                {
                                    callbacks.Add(mfr.callback);
                                }
                            }
                        }
                    }
                }
                foreach (MessageAvailableCallback callback in callbacks)
                {
                    Message localCopy;
                    try
                    {
                        //this copy is free'd by SFx.
                        localCopy = messageBuffer.CreateMessage();
                        localCopy.Properties.Via = via;
                        localCopy.Headers.To = to;
                        //mark security header as understood.
                        try
                        {
                            int i = localCopy.Headers.FindHeader(SecurityJan2004Strings.Security, SecurityJan2004Strings.Namespace);
                            if (i >= 0)
                            {
                                localCopy.Headers.AddUnderstood(i);
                            }
                        }
                        catch (MessageHeaderException e)
                        {
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                        }
                        catch (SerializationException e)
                        {
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                        }
                        catch (XmlException e)
                        {
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                        }

                        if (index != -1)
                        {
                            localCopy.Headers.ReplaceAt(index, hopHeader);
                        }

                        callback(localCopy);
                    }
                    catch (ObjectDisposedException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    }
                    catch (CommunicationObjectAbortedException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    }
                    catch (CommunicationObjectFaultedException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    }
                }
            }
            finally
            {
                if (message != null)
                    message.Close();
            }
        }
 void IPeerNodeMessageHandling.HandleIncomingMessage(MessageBuffer messageBuffer, PeerMessagePropagation propagateFlags, int index, MessageHeader hopHeader, Uri via, Uri to)
 {
     if (System.ServiceModel.DiagnosticUtility.ShouldTraceVerbose)
     {
         TraceUtility.TraceEvent(TraceEventType.Verbose, 0x40045, System.ServiceModel.SR.GetString("TraceCodePeerFloodedMessageReceived"), this.traceRecord, this, null);
     }
     if (via == null)
     {
         using (Message message = messageBuffer.CreateMessage())
         {
             throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("PeerMessageMustHaveVia", new object[] { message.Headers.Action })));
         }
     }
     if ((propagateFlags & PeerMessagePropagation.Local) != PeerMessagePropagation.None)
     {
         this.DeliverMessageToClientChannels(null, messageBuffer, via, to, messageBuffer.MessageContentType, (int) this.maxReceivedMessageSize, index, hopHeader);
         messageBuffer = null;
     }
     else if (System.ServiceModel.DiagnosticUtility.ShouldTraceVerbose)
     {
         using (Message message2 = messageBuffer.CreateMessage())
         {
             TraceUtility.TraceEvent(TraceEventType.Verbose, 0x40046, System.ServiceModel.SR.GetString("TraceCodePeerFloodedMessageNotPropagated"), this.traceRecord, this, null, message2);
         }
     }
 }
 private void DeliverMessageToClientChannels(object registrant, MessageBuffer messageBuffer, Uri via, Uri peerTo, string contentType, int messageSize, int index, MessageHeader hopHeader)
 {
     Message message = null;
     try
     {
         ArrayList list = new ArrayList();
         Uri toCond = peerTo;
         if (this.isOpen)
         {
             lock (this.ThisLock)
             {
                 if (this.isOpen)
                 {
                     foreach (MessageFilterRegistration registration in this.messageFilters.Values)
                     {
                         bool flag = this.CompareVia(via, registration.via);
                         if (messageSize < 0)
                         {
                             if (message == null)
                             {
                                 message = messageBuffer.CreateMessage();
                             }
                             if (registrant != null)
                             {
                                 messageSize = this.encoder.WriteMessage(message, 0x7fffffff, this.bufferManager).Count;
                             }
                         }
                         flag = flag && (messageSize <= registration.settings.MaxReceivedMessageSize);
                         if (flag && (registration.filters != null))
                         {
                             for (int i = 0; flag && (i < registration.filters.Length); i++)
                             {
                                 flag = registration.filters[i].Match(via, toCond);
                             }
                         }
                         if (flag)
                         {
                             list.Add(registration.callback);
                         }
                     }
                 }
             }
         }
         foreach (MessageAvailableCallback callback in list)
         {
             try
             {
                 Message message2 = messageBuffer.CreateMessage();
                 message2.Properties.Via = via;
                 message2.Headers.To = toCond;
                 try
                 {
                     int num2 = message2.Headers.FindHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                     if (num2 >= 0)
                     {
                         message2.Headers.AddUnderstood(num2);
                     }
                 }
                 catch (MessageHeaderException exception)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                 }
                 catch (SerializationException exception2)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
                 }
                 catch (XmlException exception3)
                 {
                     System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Warning);
                 }
                 if (index != -1)
                 {
                     message2.Headers.ReplaceAt(index, hopHeader);
                 }
                 callback(message2);
             }
             catch (ObjectDisposedException exception4)
             {
                 System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Information);
             }
             catch (CommunicationObjectAbortedException exception5)
             {
                 System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception5, TraceEventType.Information);
             }
             catch (CommunicationObjectFaultedException exception6)
             {
                 System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception6, TraceEventType.Information);
             }
         }
     }
     finally
     {
         if (message != null)
         {
             message.Close();
         }
     }
 }
 public override bool Match(MessageBuffer buffer)
 {
     return buffer.CreateMessage().Headers.Action.Contains(_serviceContractName);
 }