Пример #1
1
        static void InvokeWithSameProxy()
        {
            ChannelFactory<IAdd> factory=new ChannelFactory<IAdd>("AddService");
            IAdd proxy = factory.CreateChannel();
            if (null != proxy as ICommunicationObject)
            {
                (proxy as ICommunicationObject).Open();
            }
            var datatime = DateTime.Now;
            Console.WriteLine(datatime);
            int num = 100;
            for (int i = 0; i < num; i++)
            {

                ThreadPool.QueueUserWorkItem(delegate
                                             	{
                                                    int clientId = Interlocked.Increment(ref index);
                                             		using (
                                             			OperationContextScope contextScope =
                                             				new OperationContextScope(proxy as IContextChannel))
                                             		{
                                                         Console.WriteLine(i);
                                                         MessageHeader<int> header = new MessageHeader<int>(clientId);
                                             			System.ServiceModel.Channels.MessageHeader messageHeader =
                                             				header.GetUntypedHeader(MessageWrapper.headerClientId,
                                             				                        MessageWrapper.headerNamespace);
                                             			OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
                                             			proxy.Add(1, 2);
                                             		    if (i == num-1) {
                                                             Console.WriteLine((DateTime.Now - datatime).Seconds);
                                                         }
                                             		}
                                             	});
            }
        }
Пример #2
0
        public FilterResult Out(MessageHeader header, IMessageDataContainer container)
        {
            var result = new FilterResult { OK = true };
            try
            {
                using (var scope = ObjectHost.Host.BeginLifetimeScope())
                {
                    var plainText = container.Take();
                    var keyId = container.Take().ToHex();
                    var keyProvider = scope.Resolve<ICryptoKeyProvider>();
                    var pubKey = keyProvider.GetPublicKey(keyId);
                    if (pubKey != null && pubKey.Length > 0)
                    {
                        container.Push(new RSACrypto().Encrypt(pubKey, plainText));
                    }
                    else result = new FilterResult { Error = ErrorCode.CryptoKeyReadFailed };
                }
            }
            catch (Exception ex)
            {
                result = new FilterResult { Error = ErrorCode.EncryptFailed };
                Log.Error(result.Error.ToString(), ex);

            }
            return result;
        }
Пример #3
0
        //其他成员
        private void MonitorForm_Load(object sender, EventArgs e)
        {
            string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
            this.listBoxExecutionProgress.Items.Add(header);
            _syncContext = SynchronizationContext.Current;
            _callbackInstance = new InstanceContext(new CalculatorCallbackService());
            _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice");

            EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;
            this.Disposed += delegate
            {
            EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;
            _channelFactory.Close();
            };

            for (int i = 0; i < 2; i++)
            {
            ThreadPool.QueueUserWorkItem(state =>
            {
                int clientId = Interlocked.Increment(ref _clientId);
                EventMonitor.Send(clientId, EventType.StartCall);
                ICalculator proxy = _channelFactory.CreateChannel();
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                    OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
                    proxy.Add(1, 2);
                }
                EventMonitor.Send(clientId, EventType.EndCall);
            }, null);
            }
        }
Пример #4
0
        /// <summary>
        /// one-way call to resample an image volume
        /// </summary>
        /// <param name="seriesInstanceUID"></param>
        public void ResampleImageVolume(ImageVolumeResampleRequest request)
        {
            _responseContext =
                OperationContext.Current.IncomingMessageHeaders.GetHeader<ResponseContext>(
                    "ResponseContext", "ServiceModelEx");
            _responseAddress =
                new EndpointAddress(_responseContext.ResponseAddress);

            ResampleEngineClient re = new ResampleEngineClient();

            ImageVolumeResampleResponse response = re.ResampleImageVolume(request);
            System.Diagnostics.Trace.Assert(response.ResampledImageVolumeGuid.CompareTo(Guid.Empty) != 0);

            MessageHeader<ResponseContext> responseHeader = new MessageHeader<ResponseContext>(_responseContext);
            NetMsmqBinding binding = new NetMsmqBinding("NoMsmqSecurity");
            ResampleResponseProxy proxy = new ResampleResponseProxy(binding, _responseAddress);

            using (OperationContextScope scope = new OperationContextScope(proxy.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(
                    responseHeader.GetUntypedHeader("ResponseContext", "ServiceModelEx"));

                proxy.OnResampleDone(response);
            }

            proxy.Close();
        }
        private MessageHeader CreateMessageHeader()
        {
            MessageHeader msgHeader = new MessageHeader();
            msgHeader.ConversationId = "TestSession";

            From from = new From();
            PartyId fromPartyId = new PartyId();
            PartyId[] fromPartyIdArr = new PartyId[1];
            fromPartyId.Value = "WebServiceClient";
            fromPartyIdArr[0] = fromPartyId;
            from.PartyId = fromPartyIdArr;
            msgHeader.From = from;

            To to = new To();
            PartyId toPartyId = new PartyId();
            PartyId[] toPartyIdArr = new PartyId[1];
            toPartyId.Value = "WebServiceSupplier";
            toPartyIdArr[0] = toPartyId;
            to.PartyId = toPartyIdArr;
            msgHeader.To = to;

            msgHeader.CPAId = "4REG";
            msgHeader.Action = "HotelPropertyDescriptionLLSRQ";
            Service service = new Service();
            service.Value = "HotelPropertyDescriptionLLSRQ";
            msgHeader.Service = service;

            MessageData msgData = new MessageData();
            msgData.MessageId = "mid:[email protected]";
            //msgData.Timestamp = tstamp;
            msgHeader.MessageData = msgData;
            return msgHeader;
        }
        private static void CallSimpleCustomHeaderService()
        {
            using (var client = new SimpleCustomHeaderServiceClient())
            {
                using (var scope = new OperationContextScope(client.InnerChannel))
                {
                    //Log the user who's web session resulted in this service call
                    var webUser = new MessageHeader<string>("joe.bloggs");
                    var webUserHeader = webUser.GetUntypedHeader("web-user", "ns");

                    //Log which webnode we were on behind the load balancer
                    var webNodeId = new MessageHeader<int>(1234);
                    var webNodeIdHeader = webNodeId.GetUntypedHeader("web-node-id", "ns");

                    //Log a unique session id
                    var webSessionId = new MessageHeader<Guid>(Guid.NewGuid());
                    var webSessionIdHeader = webSessionId.GetUntypedHeader("web-session-id", "ns");

                    OperationContext.Current.OutgoingMessageHeaders.Add(webUserHeader);
                    OperationContext.Current.OutgoingMessageHeaders.Add(webNodeIdHeader);
                    OperationContext.Current.OutgoingMessageHeaders.Add(webSessionIdHeader);

                    System.Console.WriteLine(client.DoWork());
                }
            }
        }
Пример #7
0
        public void DeleteFromServer(MessageHeader header)
        {
            PredefinedCommands.MsgDelete delete = new PredefinedCommands.MsgDelete()
            {
                MsgId = header.GetMsgID().ToString()
            };

            Log("Delete from server: " + header.GetMsgID().ToString());
            Send(Message.Create(new MessageInfo(), delete, false, null));
        }
Пример #8
0
 protected MessageHeader ReadHeader(BinaryReader reader)
 {
     MessageHeader hdr = new MessageHeader(OpCode.Reply);
     hdr.MessageLength = reader.ReadInt32();
     hdr.RequestId = reader.ReadInt32();
     hdr.ResponseTo = reader.ReadInt32();
     int op = reader.ReadInt32();
     if((OpCode)op != OpCode.Reply) throw new InvalidDataException("Should have been a reply but wasn't");
     return hdr;
 }
Пример #9
0
 public FilterResult Out(MessageHeader header, IMessageDataContainer container)
 {
     var headerBuffer = container.Take();
     var bodyBuffer = container.Take();
     var checkSum = BitConverter.GetBytes(
         Crc32.CalculateDigest(headerBuffer.Concat(bodyBuffer), 
         (uint)0, 
         (uint)(headerBuffer.Length + bodyBuffer.Length)));
     container.Push(checkSum);
     return new FilterResult { OK = true };
 }
Пример #10
0
        private void MessageListener(MessageHeader header, object obj, out bool handled)
        {
            handled = false;

            if (header.CommandID == MSG_ACK2)
            {
                PredefinedCommands.Ack2 a = (PredefinedCommands.Ack2)obj;

                Log("ACK2 Received: " + a.CreateUniqueID().ToString());
                _ackList.Add(a);

                handled = true;
                return;
            }
        }
Пример #11
0
 public FilterResult Out(MessageHeader header, IMessageDataContainer container)
 {
     var body = container.Take();
     if (body.Length >= ZIPPING_SIZE)
     {
         container.Push(body.Zip());
         header.FilterType |= MessageFilterType.Compression;
     }
     else
     {
         if (body.Length != 0) container.Push(body);
         if ((header.FilterType & MessageFilterType.Compression) == MessageFilterType.Compression)
             header.FilterType ^= MessageFilterType.Compression;
     }
     return new FilterResult { OK = true };
 }
Пример #12
0
 internal static unsafe Error SendMessage(SafeHandle socket, MessageHeader* messageHeader, SocketFlags flags, long* sent)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousSendMessage((int)socket.DangerousGetHandle(), messageHeader, flags, sent);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
Пример #13
0
		public void Write() {
			using(MemoryStream stream = new MemoryStream()) {
				using(BinaryWriter writer = new BinaryWriter(stream)) {
					byte[] expected = {
						0xF9, 0xBE, 0xB4, 0xD9,													// Magic
						0x76, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00, // Message ("version     ")
						0x64, 0x00, 0x00, 0x00,													// Payload length (100 bytes)
						0x35, 0x8D, 0x49, 0x32													// Payload checksum
					};

					MessageHeader header = new MessageHeader("version", 100, new byte[] { 0x35, 0x8D, 0x49, 0x32, 0xAA });

					header.Write(writer);
					Assert.AreEqual(expected, stream.ToArray());
				}
			}
		}
Пример #14
0
        public void Add(double x, double y)
        {
            //PreCallback
            EventMonitor.Send(EventType.StartExecute);
            Thread.Sleep(5000);
            double result = x + y;

            //Callback
            EventMonitor.Send(EventType.StartCallback);
            int clientId = OperationContext.Current.IncomingMessageHeaders.GetHeader<int>(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace);
            MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
            OperationContext.Current.GetCallbackChannel<ICalculatorCallback>().ShowResult(result);
            EventMonitor.Send(EventType.EndCallback);

            //PostCallback
            Thread.Sleep(5000);
            EventMonitor.Send(EventType.EndExecute);
        }
Пример #15
0
        private static void Main(string[] args)
        {
            string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
            Console.WriteLine(header);
            Console.WriteLine("Press any key to run clients");
            Console.ReadKey();

            _syncContext = SynchronizationContext.Current;
            _callbackInstance = new InstanceContext(new CalculatorCallbackService());

            //Create DuplexChannel 
            _channelFactory = new DuplexChannelFactory<ICalculator>(_callbackInstance, "calculatorservice");

            EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;

            for (int i = 0; i < 5; i++)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    int clientId = Interlocked.Increment(ref _clientId);
                    EventMonitor.Send(clientId, EventType.StartCall);
                    ICalculator proxy = _channelFactory.CreateChannel();
                    using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                    {
                        MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                        OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName, EventMonitor.CientIdHeaderNamespace));
                        proxy.Add(1, 2);
                    }
                    EventMonitor.Send(clientId, EventType.EndCall);
                }, null);
            }

            Console.WriteLine("Press any key to exit.Client");

            header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
            Console.WriteLine(header);

            Console.ReadKey();

            EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;

            _channelFactory.Close();
        }
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            // If we currently are running inside a MiniProfiler context, then add a request onto this request
            var miniProfiler = GetCurrentProfiler();
            if (miniProfiler != null)
            {
                var untypedHeader = new MessageHeader<MiniProfilerRequestHeader>(new MiniProfilerRequestHeader
                {
                    User = miniProfiler.User,
                    ParentProfilerId = miniProfiler.Id
                })
                .GetUntypedHeader(MiniProfilerRequestHeader.HeaderName, MiniProfilerRequestHeader.HeaderNamespace);

                request.Headers.Add(untypedHeader);

                return new MiniProfilerStart { StartTime = miniProfiler.DurationMilliseconds };
            }

            return null;
        }
Пример #17
0
        private static void Main(string[] args)
        {
            using (var _channelFactory = new ChannelFactory<ICalculator>("calculatorservice"))
            {
                Console.WriteLine("Press any key to run, Client.");
                Console.ReadKey();
                EventMonitor.MonitoringNotificationSended += ReceiveMonitoringNotification;

                for (int i = 1; i <= 5; i++)
                {
                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        int clientId = Interlocked.Increment(ref clientIdIndex);
                        ICalculator proxy = _channelFactory.CreateChannel();
                        using (proxy as IDisposable)
                        {
                            EventMonitor.Send(clientId, EventType.StartCall);
                            using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                            {
                                MessageHeader<int> messageHeader = new MessageHeader<int>(clientId);
                                OperationContext.Current.OutgoingMessageHeaders.Add(
                                    messageHeader.GetUntypedHeader(EventMonitor.CientIdHeaderLocalName,
                                        EventMonitor.CientIdHeaderNamespace));
                                proxy.Add(1, 2);
                            }
                            EventMonitor.Send(clientId, EventType.EndCall);
                        }
                    });
                }

                Console.WriteLine("Press any key to exit.Client");
                string header = string.Format("{0, -13}{1, -22}{2}", "Client", "Time", "Event");
                Console.WriteLine(header);

                Console.ReadKey();

                EventMonitor.MonitoringNotificationSended -= ReceiveMonitoringNotification;

                _channelFactory.Close();
            }
        }
Пример #18
0
        private static MessageHeader ReadMessageHeaders(RestMSMessage restMSMessage)
        {
            var messageId = Guid.Empty;
            if (!Guid.TryParse(restMSMessage.MessageId, out messageId))
                return FailureMessageHeader(messageId, restMSMessage.Address);

            var messageType = MessageType.MT_NONE;
            if (restMSMessage.Headers == null || !restMSMessage.Headers.Any())
                return FailureMessageHeader(messageId, restMSMessage.Address);

            var messageTypeString = restMSMessage.Headers.First(header => header.Name == "MessageType").Value;
            if (messageTypeString == null)
                return FailureMessageHeader(messageId, restMSMessage.Address);

            if (!Enum.TryParse<MessageType>(messageTypeString, out messageType))
                return FailureMessageHeader(messageId, restMSMessage.Address);

            var messageHeader = new MessageHeader(messageId, restMSMessage.Address, messageType);
            restMSMessage.Headers.Each(header => messageHeader.Bag.Add(header.Name, header.Value));
            return messageHeader;
        }
Пример #19
0
        /// <summary>
        /// begin meshing for a particular structure
        /// </summary>
        /// <param name="request"></param>
        public void MeshStructure(MeshingRequest request)
        {
            // store the return address
            _responseContext =
                OperationContext.Current.IncomingMessageHeaders.GetHeader<ResponseContext>(
                    "ResponseContext", "ServiceModelEx");
            _responseAddress =
                new EndpointAddress(_responseContext.ResponseAddress);

            // notify that we are performing a meshing
            System.Diagnostics.Trace.WriteLine(
                string.Format("Meshing for structure {0} ({1} contours)",
                    request.StructureGuid,
                    request.ContourGuids != null 
                        ? request.ContourGuids.Count.ToString() : "?"));

            // create the engine
            MeshingEngineClient meshingEngine = new MeshingEngineClient();

            // synchronous call to perform meshing
            MeshingResponse response = meshingEngine.MeshStructure(request);
            meshingEngine.Close();

            // now construct the response proxy based on the return address
            MessageHeader<ResponseContext> responseHeader = new MessageHeader<ResponseContext>(_responseContext);
            NetMsmqBinding binding = new NetMsmqBinding("NoMsmqSecurity");
            MeshingResponseProxy proxy = new MeshingResponseProxy(binding, _responseAddress);

            // and set up the operation context to relay response info
            using (OperationContextScope scope = new OperationContextScope(proxy.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(
                    responseHeader.GetUntypedHeader("ResponseContext", "ServiceModelEx"));

                // send the response
                proxy.OnMeshingDone(response);
            }

            proxy.Close();
        }
        public EnsureCredentialsUseContext(
            string username, string password, string accessKey, IContextChannel channel)
        {
            EsbCredentials credentials = new EsbCredentials
            {
                Username = username,
                Password = password,
            };

            _scope = new OperationContextScope(channel);
            MessageHeader<EsbCredentials> credentialsMessageHeader =
                new MessageHeader<EsbCredentials>(credentials);
            MessageHeader<string> accessKeyMessageHeader =
                new MessageHeader<string>(accessKey);

            OperationContext.Current.OutgoingMessageHeaders
                .Add(credentialsMessageHeader
                .GetUntypedHeader(Esbcredentials, HttpServicesSapoPtDefinitions));

            OperationContext.Current.OutgoingMessageHeaders
                .Add(accessKeyMessageHeader
                .GetUntypedHeader(Esbaccesskey, HttpServicesSapoPtMetadataMarket));
        }
Пример #21
0
        private MessageHeader Get(string actionName, string headerServiceValue)
        {
            //Create the message header and provide the conversation ID.
            MessageHeader msgHeader = new MessageHeader();
            msgHeader.ConversationId = new Guid().ToString();          // Set the ConversationId

            From from = new From();
            PartyId fromPartyId = new PartyId();
            PartyId[] fromPartyIdArr = new PartyId[1];
            fromPartyId.Value = "WebServiceClient";
            fromPartyIdArr[0] = fromPartyId;
            from.PartyId = fromPartyIdArr;
            msgHeader.From = from;

            To to = new To();
            PartyId toPartyId = new PartyId();
            PartyId[] toPartyIdArr = new PartyId[1];
            toPartyId.Value = "WebServiceSupplier";
            toPartyIdArr[0] = toPartyId;
            to.PartyId = toPartyIdArr;
            msgHeader.To = to;

            //Add the value for eb:CPAId, which is the IPCC.
            //Add the value for the action code of this Web service, SessionCreateRQ.

            msgHeader.CPAId = "4REG";
            msgHeader.Action = actionName;
            Service service = new Service();
            service.Value = headerServiceValue;
            msgHeader.Service = service;

            MessageData msgData = new MessageData();
            msgData.MessageId = "mid:[email protected]";
            //msgData.Timestamp = tstamp;
            msgHeader.MessageData = msgData;
            return msgHeader;
        }
Пример #22
0
        static void InvokeWithDiffrentProxy()
        {
            ChannelFactory<IAdd> factory = new ChannelFactory<IAdd>("AddService");

            for (int i = 0; i < 5; i++)
            {
                IAdd proxy = factory.CreateChannel();
                ThreadPool.QueueUserWorkItem(delegate
                                             	{
                                             		int clientId = Interlocked.Increment(ref index);
                                             		using (
                                             			OperationContextScope contextScope =
                                             				new OperationContextScope(proxy as IContextChannel))
                                             		{
                                             			MessageHeader<int> header = new MessageHeader<int>(clientId);
                                             			System.ServiceModel.Channels.MessageHeader messageHeader =
                                             				header.GetUntypedHeader(MessageWrapper.headerClientId,
                                             				                        MessageWrapper.headerNamespace);
                                             			OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
                                             			proxy.Add(1, 2);
                                             		}
                                             	});
            }
        }
Пример #23
0
        /// <summary>Processes a received ping or pong message.</summary>
        /// <param name="header">The message header.</param>
        /// <param name="cancellationToken">The cancellation token to use to cancel the websocket.</param>
        private async Task HandleReceivedPingPongAsync(MessageHeader header, CancellationToken cancellationToken)
        {
            // Consume any (optional) payload associated with the ping/pong.
            if (header.PayloadLength > 0 && _receiveBufferCount < header.PayloadLength)
            {
                await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false);
            }

            // If this was a ping, send back a pong response.
            if (header.Opcode == MessageOpcode.Ping)
            {
                if (_isServer)
                {
                    ApplyMask(_receiveBuffer, _receiveBufferOffset, header.Mask, 0, header.PayloadLength);
                }

                await SendFrameAsync(
                    MessageOpcode.Pong, true,
                    new ArraySegment<byte>(_receiveBuffer, _receiveBufferOffset, (int)header.PayloadLength), cancellationToken).ConfigureAwait(false);
            }

            // Regardless of whether it was a ping or pong, we no longer need the payload.
            if (header.PayloadLength > 0)
            {
                ConsumeFromBuffer((int)header.PayloadLength);
            }
        }
Пример #24
0
        /// <summary>
        /// Receive the next text, binary, continuation, or close message, returning information about it and
        /// writing its payload into the supplied buffer.  Other control messages may be consumed and processed
        /// as part of this operation, but data about them will not be returned.
        /// </summary>
        /// <param name="payloadBuffer">The buffer into which payload data should be written.</param>
        /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
        /// <returns>Information about the received message.</returns>
        private async Task<WebSocketReceiveResult> ReceiveAsyncPrivate(ArraySegment<byte> payloadBuffer, CancellationToken cancellationToken)
        {
            // This is a long method.  While splitting it up into pieces would arguably help with readability, doing so would
            // also result in more allocations, as each async method that yields ends up with multiple allocations.  The impact
            // of those allocations is amortized across all of the awaits in the method, and since we generally expect a receive
            // operation to require at most a single yield (while waiting for data to arrive), it's more efficient to have
            // everything in the one method.  We do separate out pieces for handling close and ping/pong messages, as we expect
            // those to be much less frequent (e.g. we should only get one close per websocket), and thus we can afford to pay
            // a bit more for readability and maintainability.

            CancellationTokenRegistration registration = cancellationToken.Register(s => ((ManagedWebSocket)s).Abort(), this);
            try
            {
                while (true) // in case we get control frames that should be ignored from the user's perspective
                {
                    // Get the last received header.  If its payload length is non-zero, that means we previously
                    // received the header but were only able to read a part of the fragment, so we should skip
                    // reading another header and just proceed to use that same header and read more data associated
                    // with it.  If instead its payload length is zero, then we've completed the processing of
                    // thta message, and we should read the next header.
                    MessageHeader header = _lastReceiveHeader;
                    if (header.PayloadLength == 0)
                    {
                        if (_receiveBufferCount < (_isServer ? (MaxMessageHeaderLength - MaskLength) : MaxMessageHeaderLength))
                        {
                            // Make sure we have the first two bytes, which includes the start of the payload length.
                            if (_receiveBufferCount < 2)
                            {
                                await EnsureBufferContainsAsync(2, cancellationToken, throwOnPrematureClosure: false).ConfigureAwait(false);
                                if (_receiveBufferCount < 2)
                                {
                                    // The connection closed; nothing more to read.
                                    return new WebSocketReceiveResult(0, WebSocketMessageType.Text, true);
                                }
                            }

                            // Then make sure we have the full header based on the payload length.
                            // If this is the server, we also need room for the received mask.
                            long payloadLength = _receiveBuffer[_receiveBufferOffset + 1] & 0x7F;
                            if (_isServer || payloadLength > 125)
                            {
                                int minNeeded =
                                    2 +
                                    (_isServer ? MaskLength : 0) +
                                    (payloadLength <= 125 ? 0 : payloadLength == 126 ? sizeof(ushort) : sizeof(ulong)); // additional 2 or 8 bytes for 16-bit or 64-bit length
                                await EnsureBufferContainsAsync(minNeeded, cancellationToken).ConfigureAwait(false);
                            }
                        }

                        if (!TryParseMessageHeaderFromReceiveBuffer(out header))
                        {
                            await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, cancellationToken).ConfigureAwait(false);
                        }
                        _receivedMaskOffsetOffset = 0;
                    }

                    // If the header represents a ping or a pong, it's a control message meant
                    // to be transparent to the user, so handle it and then loop around to read again.
                    // Alternatively, if it's a close message, handle it and exit.
                    if (header.Opcode == MessageOpcode.Ping || header.Opcode == MessageOpcode.Pong)
                    {
                        await HandleReceivedPingPongAsync(header, cancellationToken).ConfigureAwait(false);
                        continue;
                    }
                    else if (header.Opcode == MessageOpcode.Close)
                    {
                        return await HandleReceivedCloseAsync(header, cancellationToken).ConfigureAwait(false);
                    }

                    // If this is a continuation, replace the opcode with the one of the message it's continuing
                    if (header.Opcode == MessageOpcode.Continuation)
                    {
                        header.Opcode = _lastReceiveHeader.Opcode;
                    }

                    // The message should now be a binary or text message.  Handle it by reading the payload and returning the contents.
                    Debug.Assert(header.Opcode == MessageOpcode.Binary || header.Opcode == MessageOpcode.Text, $"Unexpected opcode {header.Opcode}");

                    // If there's no data to read, return an appropriate result.
                    int bytesToRead = (int)Math.Min(payloadBuffer.Count, header.PayloadLength);
                    if (bytesToRead == 0)
                    {
                        _lastReceiveHeader = header;
                        return new WebSocketReceiveResult(
                            0,
                            header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
                            header.PayloadLength == 0 ? header.Fin : false);
                    }

                    // Otherwise, read as much of the payload as we can efficiently, and upate the header to reflect how much data
                    // remains for future reads.

                    if (_receiveBufferCount == 0)
                    {
                        await EnsureBufferContainsAsync(1, cancellationToken, throwOnPrematureClosure: false).ConfigureAwait(false);
                    }

                    int bytesToCopy = Math.Min(bytesToRead, _receiveBufferCount);
                    if (_isServer)
                    {
                        _receivedMaskOffsetOffset = ApplyMask(_receiveBuffer, _receiveBufferOffset, header.Mask, _receivedMaskOffsetOffset, bytesToCopy);
                    }
                    Buffer.BlockCopy(_receiveBuffer, _receiveBufferOffset, payloadBuffer.Array, payloadBuffer.Offset, bytesToCopy);
                    ConsumeFromBuffer(bytesToCopy);
                    header.PayloadLength -= bytesToCopy;

                    // If this a text message, validate that it contains valid UTF8.
                    if (header.Opcode == MessageOpcode.Text &&
                        !TryValidateUtf8(new ArraySegment<byte>(payloadBuffer.Array, payloadBuffer.Offset, bytesToCopy), header.Fin, _utf8TextState))
                    {
                        await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.InvalidPayloadData, WebSocketError.Faulted, cancellationToken).ConfigureAwait(false);
                    }

                    _lastReceiveHeader = header;
                    return new WebSocketReceiveResult(
                        bytesToCopy,
                        header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
                        bytesToCopy == 0 || (header.Fin && header.PayloadLength == 0));
                }
            }
            catch (Exception exc)
            {
                throw _state == WebSocketState.Aborted ?
                    new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted"), exc) :
                    new WebSocketException(WebSocketError.ConnectionClosedPrematurely, exc);
            }
            finally
            {
                registration.Dispose();
            }
        }
Пример #25
0
        /// <summary>
        /// Sends an Attachment Response.
        /// </summary>
        /// <param name="result">The result of the attachment</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendAttachmentResponse6(AttachmentResult result, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetAttachmentResponseData(result);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.AttachmentResponse);

            SendMessage(messageHeader, data);
        }
Пример #26
0
        /// <summary>
        /// Sends an Attachment Response ACK.
        /// </summary>
        /// <param name="status">The status code</param>
        /// <param name="ackData">The ack data for the request</param>
        /// <param name="exception">The global exception</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendAttachmentResponseAck7(StatusCode status, AttachmentResponseAckTypeData ackData, string exception = null, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetAttachmentResponseAckData(status, ackData, exception);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.AttachmentResponseAck);

            SendMessage(messageHeader, data);
        }
Пример #27
0
		private void HandleConnectionlessMessage (SocketAsyncEventArgs args, MessageHeader header, ref BufferValueReader reader)
		{
			byte[] buffer = args.Buffer;

			int bufferOffset = 0;
			int messageOffset = 0;
			int remaining = args.BytesTransferred;

			List<Message> messages = this.connectionlessSerializer.BufferMessages (ref buffer, ref bufferOffset, ref messageOffset, ref remaining, ref header, ref reader);
			if (messages == null)
				return;

			foreach (Message m in messages)
			{
				var tempestMessage = m as TempestMessage;
				if (tempestMessage != null)
					OnConnectionlessTempestMessage (tempestMessage, args.RemoteEndPoint.ToTarget());
				else
					OnConnectionlessMessageReceived (new ConnectionlessMessageEventArgs (m, args.RemoteEndPoint.ToTarget(), this));
			}
		}
Пример #28
0
        /// <summary>
        /// Creates a message header containing a data signature for the object
        /// </summary>
        /// <param name="serializableObject">Object to sign</param>
        /// <returns>Message header</returns>
        public static MessageHeader CreateHeader(object serializableObject)
        {
            Guid dataSignature = Sign(serializableObject);

            return(MessageHeader.CreateHeader(Header.Name, Header.Namespace, dataSignature));
        }
Пример #29
0
        protected void Decode(byte[] data)
        {
            var receivedTime = DateTime.UtcNow;

            using (var inputStream = new MemoryStream(data))
            {
                // create avro binary decoder to read from memory stream
                var decoder = new BinaryDecoder(inputStream);

                var           record = Activator.CreateInstance <MessageHeader>();
                var           reader = new SpecificReader <MessageHeader>(new EtpSpecificReader(record.Schema, record.Schema));
                MessageHeader header = reader.Read(record, decoder);


                // string message = Encoding.UTF8.GetString(inputStream.ToArray());

                if (header.Protocol == 0 && header.MessageType == 2)
                {
                    lock (m_ConnectionLock)
                    {
                        m_HasConnected = true;
                    }
                    var recordSession = Activator.CreateInstance <OpenSession>();
                    var readerSession = new SpecificReader <OpenSession>(new EtpSpecificReader(recordSession.Schema, recordSession.Schema));
                    readerSession.Read(recordSession, decoder);
                    string message = ToString(recordSession);

                    message = $"\nResponse : [Protocol {header.Protocol} MessageType {header.MessageType}]\n{message}";
                    var timediff = receivedTime - m_Time;
                    Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info);
                }
                else if (header.Protocol == 3 && header.MessageType == 2)
                {
                    var responce   = Activator.CreateInstance <GetResourcesResponse>();
                    var bodyreader = new SpecificReader <GetResourcesResponse>(new EtpSpecificReader(responce.Schema, responce.Schema));
                    GetResourcesResponse bodyheader = bodyreader.Read(responce, decoder);

                    RequestInformation parent;
                    lock (m_RequestInformation)
                    {
                        parent = m_RequestInformation[header.CorrelationId];
                    }

                    var    timediff = receivedTime - parent.RequestTime;
                    string message  = ToString(responce);
                    message = $"\nResponse : [Protocol {header.Protocol} MessageType {header.MessageType}]\n{message}";
                    Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info);

                    if (parent.ChannelItem == null)
                    {
                        ChannelItem channelItem = new ChannelItem()
                        {
                            Name           = responce.Resource.Name,
                            Uid            = responce.Resource.Uuid,
                            Eml            = responce.Resource.Uri,
                            Level          = 0,
                            ChildrensCount = responce.Resource.HasChildren
                        };

                        ChannelItemsReceived?.Invoke(channelItem);
                    }
                    else
                    {
                        ChannelItem channelItem = new ChannelItem()
                        {
                            Name           = responce.Resource.Name,
                            Uid            = responce.Resource.Uuid,
                            Eml            = responce.Resource.Uri,
                            Level          = parent.ChannelItem.Level + 1,
                            ChildrensCount = responce.Resource.HasChildren
                        };
                        ChannelChildrensReceived?.Invoke(channelItem, parent.ChannelItem);
                    }
                }
                else if (header.Protocol == 1 && header.MessageType == 2)
                {
                    var timediff = receivedTime - m_Time;

                    string message        = "Channels received: [";
                    var    recordMetadata = Activator.CreateInstance <ChannelMetadata>();
                    var    readerMetadata = new SpecificReader <ChannelMetadata>(new EtpSpecificReader(recordMetadata.Schema, recordMetadata.Schema));
                    readerMetadata.Read(recordMetadata, decoder);


                    ChannelMetadata metadata = new ChannelMetadata();
                    metadata.Channels = new List <ChannelMetadataRecord>();
                    lock (m_ChannelStreamingInfo)
                    {
                        foreach (var channel in recordMetadata.Channels)
                        {
                            //if (m_LogCurveEml.Contains(channel.ChannelUri, StringComparer.InvariantCultureIgnoreCase))
                            {
                                metadata.Channels.Add(channel);
                                ChannelStreamingInfo channelStreamingInfo = new ChannelStreamingInfo()
                                {
                                    ChannelId  = channel.ChannelId,
                                    StartIndex = new StreamingStartIndex()
                                    {
                                        Item = null
                                    },
                                    ReceiveChangeNotification = true
                                };

                                m_ChannelStreamingInfo.Add(channelStreamingInfo);
                                message = message + $"\n{channel.ChannelId} {channel.ChannelName} {channel.ChannelUri}";

                                //ChannelMetaDataVM channelMetaData_VM = ETPMapper.Instance().Map<ChannelMetaDataVM>(channel);
                                //string json = JsonConvert.SerializeObject(channelMetaData_VM, Formatting.Indented);
                                //Message?.Invoke(json, timediff.TotalMilliseconds, TraceLevel.Info);
                            }
                        }

                        Metadata = metadata;

                        ChannelInfoReceived?.Invoke(metadata);
                    }

                    message = message + "\n]";

                    message = $"\nResponse : [Protocol {header.Protocol} MessageType {header.MessageType}]\n{message}";
                    Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info);

                    HasDescribing = false;
                }
                else if (header.Protocol == 1 && header.MessageType == 3)
                {
                    var recordData = Activator.CreateInstance <ChannelData>();
                    var readerdata = new SpecificReader <ChannelData>(new EtpSpecificReader(recordData.Schema, recordData.Schema));
                    readerdata.Read(recordData, decoder);

                    ChannelDataReceived?.Invoke(recordData.Data);
                }
                else if (header.MessageType == 1000)
                {
                    var timediff   = receivedTime - m_Time;
                    var bodyrecord = Activator.CreateInstance <ProtocolException>();
                    var bodyreader = new SpecificReader <ProtocolException>(new EtpSpecificReader(bodyrecord.Schema, bodyrecord.Schema));
                    ProtocolException bodyheader = bodyreader.Read(bodyrecord, decoder);
                    string            message    = $"Error Received ({bodyrecord.ErrorCode}): {bodyrecord.ErrorMessage}";

                    message = $"\nResponse : [Protocol {header.Protocol} MessageType {header.MessageType}]\n{message}";

                    Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Error);
                    HasDescribing = false;
                }
                else
                {
                    HasDescribing = false;
                }
            }
        }
Пример #30
0
        public MessageHeader ToMessageHeader()
        {
            MessageHeader header = MessageHeader.CreateHeader(CredentialsHeader, CredentialsNamespace, this);

            return(header);
        }
Пример #31
0
 MessageHeader CreateHeader(MessageHeaderDescription mh, object value)
 {
     return(MessageHeader.CreateHeader(mh.Name, mh.Namespace, value, mh.MustUnderstand, mh.Actor, mh.Relay));
 }
Пример #32
0
    private void SendMessage(Message msg)
    {
        var header = new MessageHeader(MessageHeader.HEADER_PROTOCOL_SKETCH);

        Globals.mainApp.SendMessage(Packet.Serialize(msg, header));
    }
Пример #33
0
 /// <summary>
 /// Create a Message object with the speficed Header and Data parts.
 /// </summary>
 /// <param name="header">The Header part of the message. See <see cref="GetHeader(string,DataType)"/>.</param>
 /// <param name="data">The Data part of the message. See the MessageManager.GetXXXData() methods.</param>
 /// <returns>The created Message object.</returns>
 public static Message GetMessage(MessageHeader header, MessageData data)
 {
     return(new Message(header, data));
 }
Пример #34
0
 /// <summary>
 /// Pack the specified header and data to a Message object.
 /// </summary>
 /// <param name="header">The Message Header object.</param>
 /// <param name="data">The Message Data object.</param>
 /// <returns>The packed message in byte array format.</returns>
 /// <exception cref="MessagePackSerializationException"></exception>
 public static byte[] GetBinaryFromMessage(MessageHeader header, MessageData data)
 {
     return(GetBinaryFromMessage(GetMessage(header, data)));
 }
 private async Task ProcessFailure(MessageHeader header, Exception exception)
 {
     Event validationFailed = ValidatorServiceEventFactory.BuildOtherReasonValidationFailedEvent(header.TransactionId, exception);
     await eventProducer.ProduceAsync(validationFailed);
 }
Пример #36
0
        /// <summary>
        /// Sends an event message
        /// </summary>
        /// <param name="operationsStringBlock">The operations in standard SQL statements, separated with ';' characters.</param>
        /// <param name="binaryContentsMapping">The mapping of the binary contents.</param>
        /// <param name="executionPriorityStructure">The execution priority structure.</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        /// <returns>The created EventData object.</returns>
        public void SendEvent2(string operationsStringBlock, Dictionary <string, byte[]> binaryContentsMapping = null,
                               List <List <Dictionary <int, bool> > > executionPriorityStructure = null, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetEventData(operationsStringBlock, binaryContentsMapping, executionPriorityStructure);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.Event);

            SendMessage(messageHeader, data);
        }
Пример #37
0
        public bool TryGetHeader(BufferValueReader reader, int remaining, ref MessageHeader header)
        {
            string callCategory = null;

                        #if TRACE
            int c = GetNextCallId();
            callCategory = String.Format("{0} {1}:TryGetHeader({2},{3})", this.connectionType, c, reader.Position, remaining);
                        #endif
            Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Entering {0}", (header == null) ? "without existing header" : "with existing header"), callCategory);

            int mlen; bool isContinued; Message msg = null; Protocol p;

            int headerLength = BaseHeaderLength;

            if (header == null)
            {
                header = new MessageHeader();
            }
            else if (header.State == HeaderState.Complete)
            {
                return(true);
            }
            else if (header.HeaderLength > 0)
            {
                headerLength = header.HeaderLength;
            }

            try
            {
                if (header.State >= HeaderState.Protocol)
                {
                    p = header.Protocol;
                }
                else
                {
                    byte pid = reader.ReadByte();

                    if (!this.protocols.TryGetValue(pid, out p))
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (Protocol " + pid + " not found)", callCategory);
                        return(true);
                    }

                    header.Protocol = p;
                    header.State    = HeaderState.Protocol;
                    if (this.serializationContext == null)
                    {
                        if (this.connection != null)
                        {
                            this.serializationContext = new SerializationContext(this.connection, this.protocols);
                        }
                        else
                        {
                            this.serializationContext = new SerializationContext(this.protocols);
                        }
                    }

                    header.SerializationContext = this.serializationContext;
                }

                if (header.State < HeaderState.CID)
                {
                    header.ConnectionId = reader.ReadInt32();
                    header.State        = HeaderState.CID;
                }

                if (header.State >= HeaderState.Type)
                {
                    msg = header.Message;
                }
                else
                {
                    ushort type = reader.ReadUInt16();

                    msg          = header.Message = p.Create(type);
                    header.State = HeaderState.Type;

                    if (msg == null)
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (Message " + type + " not found)", callCategory);
                        return(true);
                    }

                    msg.Header = header;

                    if (msg.Encrypted)
                    {
                        header.IsStillEncrypted = true;
                    }

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Have " + msg.GetType().Name), callCategory);
                }

                if (header.State >= HeaderState.Length)
                {
                    mlen = header.MessageLength;
                }
                else
                {
                    mlen = reader.ReadInt32();

                    if (mlen <= 0)
                    {
                        Trace.WriteLineIf(NTrace.TraceWarning, "Exiting (length invalid)", callCategory);
                        return(true);
                    }

                    header.MessageLength = mlen;
                    header.State         = HeaderState.Length;

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Have message of length: {0}", mlen), callCategory);
                }

                if (header.State == HeaderState.IV)
                {
                    if (header.IsStillEncrypted)
                    {
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message not buffered)", callCategory);
                        return(!(remaining < mlen));
                    }
                    else if (header.Message.Encrypted)
                    {
                        reader.Position = 0;
                    }
                }
                else if (msg.Encrypted)                // && AES != null)
                {
                    int ivLength = reader.ReadInt32(); //AES.IV.Length;
                    headerLength += ivLength + sizeof(int);

                    if (remaining < headerLength)
                    {
                        reader.Position -= sizeof(int);
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (header not buffered (IV))", callCategory);
                        return(false);
                    }

                    byte[] iv = reader.ReadBytes(ivLength);

                    header.HeaderLength = headerLength;
                    header.State        = HeaderState.IV;
                    header.IV           = iv;

                    if (remaining < mlen)
                    {
                        Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message not buffered)", callCategory);
                        return(false);
                    }

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (need to decrypt)", callCategory);
                    return(true);
                }

                if (header.State < HeaderState.MessageId)
                {
                    int identV = reader.ReadInt32();
                    header.MessageId  = identV & ~ResponseFlag;
                    header.IsResponse = (identV & ResponseFlag) == ResponseFlag;

                    header.State = (header.IsResponse) ? HeaderState.MessageId : HeaderState.Complete;

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Have message ID: " + header.MessageId, callCategory);
                }

                if (header.State < HeaderState.ResponseMessageId)
                {
                    header.ResponseMessageId = reader.ReadInt32();
                    header.State             = HeaderState.Complete;

                    Trace.WriteLineIf(NTrace.TraceVerbose, "Have message in resoponse to ID: " + header.ResponseMessageId);
                }

                Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting", callCategory);
                return(true);
            }
            catch (Exception ex)
            {
                Trace.WriteLineIf(NTrace.TraceError, "Exiting (error): " + ex, callCategory);
                header = null;
                return(true);
            }
        }
Пример #38
0
 private void AddEncryptionReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, bool sign,
                                     out MemoryStream plainTextStream, out string encryptedDataId)
 {
     throw new PlatformNotSupportedException();
 }
Пример #39
0
        /// <summary>
        /// Sends a Next Query Page Request
        /// </summary>
        /// <param name="queryContextDescriptor">Query status descriptor for querying the next pages.</param>
        /// <param name="timeout">The timeout value in milliseconds.</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendNextQueryPageRequest12(QueryContextDescriptor queryContextDescriptor, long timeout, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetNextQueryPageRequest(queryContextDescriptor, timeout);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.NextQueryPageRequest);

            SendMessage(messageHeader, data);
        }
Пример #40
0
 internal static void AddHeader(MessageHeaders headers, MessageHeader hContext)
 {
     headers.Add(hContext);
 }
Пример #41
0
        /// <summary>
        /// Sends a Query Request
        /// </summary>
        /// <param name="selectStringBlock">The SELECT statement.</param>
        /// <param name="consistencyType">The consistency type used for the query.</param>
        /// <param name="timeout">The timeout value in milliseconds.</param>
        /// <param name="queryPageSize">The number of records per page.</param>
        /// <param name="queryType">The query type</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendQueryRequest10(string selectStringBlock, ConsistencyType consistencyType, long?timeout = null, int?queryPageSize = null,
                                       QueryType?queryType = null, string messageID = null, MessageHeader header = null)
        {
            if (timeout == null)
            {
                timeout = this.timeout;
            }
            MessageData   data          = MessageManager.GetQueryRequest(selectStringBlock, consistencyType, (long)timeout, queryPageSize, queryType);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.QueryRequest);

            SendMessage(messageHeader, data);
        }
Пример #42
0
        /// <summary>
        /// 获取客户端消息头
        /// </summary>
        /// <returns></returns>
        internal static MessageHeader GetClientWcfHeader()
        {
            MessageHeader msgheader = (MessageHeader)CallContext.LogicalGetData("msgheader");

            return(msgheader);
        }
Пример #43
0
        /// <summary>
        /// Sends an Event Document ACK.
        /// </summary>
        /// <param name="status">The status code</param>
        /// <param name="ackData">The ack data for the request</param>
        /// <param name="exception">The global exception</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendEventDocumentAck9(StatusCode status, List <EventDocumentAckResult> ackData, string exception = null, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetEventDocumentAckData(status, ackData, exception);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.EventDocumentAck);

            SendMessage(messageHeader, data);
        }
Пример #44
0
 public static void AddCompressionHeader(this Message message, CompressionAlgorithm algorithm)
 {
     message.Headers.Add(MessageHeader.CreateHeader(Constants.CompressionMessageHeader, Constants.Namespace, string.Format("algorithm = \"{0}\"", algorithm)));
 }
Пример #45
0
        /// <summary>
        /// Sends an Event Document
        /// </summary>
        /// <param name="tableName">The name of the table</param>
        /// <param name="fieldDescriptors">The field descriptors</param>
        /// <param name="records">The records</param>
        /// <param name="messageID">The messageID to be used. If not present, random one will be generated.</param>
        /// <param name="header">The header to be used in the message. If not present, default one will be generated.</param>
        public void SendEventDocument8(string tableName, List <FieldDescriptor> fieldDescriptors, List <List <object> > records, string messageID = null, MessageHeader header = null)
        {
            MessageData   data          = MessageManager.GetEventDocumentData(tableName, fieldDescriptors, records);
            MessageHeader messageHeader = header ?? MessageManager.GetHeader(userName, messageID, DataType.EventDocument);

            SendMessage(messageHeader, data);
        }
Пример #46
0
        /// <summary>
        /// Retorna una lista de mensajes que cumplen el filtro de Asunto
        /// </summary>
        /// <param name="hostname"></param>
        /// <param name="port"></param>
        /// <param name="useSsl"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="idMessageEnd"></param>
        /// <param name="subject"></param>
        /// <returns></returns>

        public static List <Message> GetMessages(int port, string hostname, string username, string password,
                                                 bool useSsl, string subject, int idMessageRead, string[] subjectOther, out int idMessageFinal)
        {
            using (Pop3Client client = new Pop3Client())
            {
                // conectando al server
                client.Connect(hostname, port, useSsl);
                client.Authenticate(username, password);

                idMessageFinal = client.GetMessageCount();

                List <Message> allMessages = new List <Message>();
                if (idMessageFinal > idMessageRead)
                {
                    int idMessage = idMessageFinal;

                    //recupera mensajes sin revisar
                    while (idMessage > idMessageRead)
                    {
                        MessageHeader headers = client.GetMessageHeaders(idMessage);

                        bool valido = false;
                        for (int i = 0; i < subjectOther.Length; i++)
                        {
                            if (subjectOther[i].Trim().ToUpper().Equals(headers.Subject.Trim().ToUpper()))
                            {
                                valido = true;
                            }
                        }

                        //if (subject.ToUpper().Equals(headers.Subject.Trim().ToUpper()))
                        if (valido)
                        {
                            // Download the full message
                            allMessages.Add(client.GetMessage(idMessage));
                        }
                        //else
                        //{
                        //    if (subjectOther.Length>0)
                        //    {
                        //        for (int i = 0; i < subjectOther.Length; i++)
                        //        {
                        //            if (!subjectOther[i].ToUpper().Equals(headers.Subject.Trim().ToUpper()))
                        //            {
                        //                ReplyMsg(client.GetMessage(idMessage), headers, username, password);
                        //            }
                        //        }
                        //    }
                        //}

                        idMessage -= 1;
                    }
                    return(allMessages);
                }
                else
                {
                    if (idMessageFinal == idMessageRead)
                    {   //No hay cambio de idCorreo
                        idMessageFinal = 0;
                    }
                    return(new List <Message>());
                }
            }
        }
 public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
 {
     MessageHeader<ApplicationContext> contextHeader = new MessageHeader<ApplicationContext>(ApplicationContext.Current);
     request.Headers.Add(contextHeader.GetUntypedHeader(ApplicationContext.ContextHeaderLocalName, ApplicationContext.ContextHeaderNamespace));
     return null;
 }
Пример #48
0
 public MPac_UnsubscribedGlobalMessage(MessageHeader _unsubscribedHeader, string _unsubscribedMessage,
                                       string _messageHeader) : base(_messageHeader)
 {
     UnsubscribedHeader  = _unsubscribedHeader;
     UnsubscribedMessage = _unsubscribedMessage;
 }
Пример #49
0
 internal static extern unsafe bool TryGetIPPacketInformation(MessageHeader* messageHeader, bool isIPv4, IPPacketInformation* packetInfo);
Пример #50
0
        public void Header(int serialByte, MessageHeader messageHeader)
        {
            _messageHeader = messageHeader;

            var header = (MessageHeader1)(serialByte & 0xF0);

            switch (header)
            {
            case MessageHeader1.AnalogState:
                messageHeader._processMessage = ProcessAnalogStateMessage;
                break;

            case MessageHeader1.DigitalState:
                messageHeader._processMessage = ProcessDigitalStateMessage;
                break;

            case MessageHeader1.SystemExtension:
                header = (MessageHeader1)serialByte;

                switch (header)
                {
                case MessageHeader1.SystemExtension:
                    messageHeader._processMessage = ProcessSysExMessage;
                    break;

                case MessageHeader1.ProtocolVersion:
                    messageHeader._processMessage = ProcessProtocolVersionMessage;
                    break;

                //case MessageHeader1.SetPinMode:
                //case MessageHeader1.SystemReset:
                default:
                    // 0xF? command not supported.
                    throw new NotImplementedException(string.Format(global::Arduino.Firmata.Messages.NotImplementedEx_Command, serialByte));
                    //                    // 0xF? command not supported.
                    //                    //throw new NotImplementedException(string.Format(Messages.NotImplementedEx_Command, serialByte));
                    //                    //_messageBuffer[0] = 0;
                    //                    //_messageBufferIndex = 0;

                    //                    Console.WriteLine($"\r\n\r\n------------------\r\nUnknown sysex command {serialByte}\r\n\r\n------------------\r\n");
                    //                    // Stream is most likely out of sync or the baudrate is incorrect.
                    //                    // Don't throw an exception here, as we're in the middle of handling an event and
                    //                    // have no way of catching an exception, other than a global unhandled exception handler.
                    //                    // Just skip these bytes, until sync is found when a new message starts.
                    //                    return;
                }
                break;

            default:
                // Command not supported.
                throw new NotImplementedException(string.Format(global::Arduino.Firmata.Messages.NotImplementedEx_Command, serialByte));
                //            // Stream is most likely out of sync or the baudrate is incorrect.
                //            // Don't throw an exception here, as we're in the middle of handling an event from the serial port and
                //            // have no way of catching an exception, other than a global unhandled exception handler.
                //            // Just skip these bytes, until sync is found when a new message starts.
                //            //_messageBuffer[0] = 0;
                //            //_messageBufferIndex = 0;

                //            Console.WriteLine($"\r\n\r\n------------------\r\nCommand not supported {serialByte}\r\n\r\n------------------\r\n");
            }
#if DEBUG
            //Debug.Write(messageHeader._processMessage);
#endif
        }
Пример #51
0
        /// <summary>Processes a received close message.</summary>
        /// <param name="header">The message header.</param>
        /// <param name="cancellationToken">The cancellation token to use to cancel the websocket.</param>
        /// <returns>The received result message.</returns>
        private async Task<WebSocketReceiveResult> HandleReceivedCloseAsync(
            MessageHeader header, CancellationToken cancellationToken)
        {
            lock (StateUpdateLock)
            {
                _receivedCloseFrame = true;
                if (_state < WebSocketState.CloseReceived)
                {
                    _state = WebSocketState.CloseReceived;
                }
            }

            WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure;
            string closeStatusDescription = string.Empty;

            // Handle any payload by parsing it into the close status and description.
            if (header.PayloadLength == 1)
            {
                // The close payload length can be 0 or >= 2, but not 1.
                await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, cancellationToken).ConfigureAwait(false);
            }
            else if (header.PayloadLength >= 2)
            {
                if (_receiveBufferCount < header.PayloadLength)
                {
                    await EnsureBufferContainsAsync((int)header.PayloadLength, cancellationToken).ConfigureAwait(false);
                }

                if (_isServer)
                {
                    ApplyMask(_receiveBuffer, _receiveBufferOffset, header.Mask, 0, header.PayloadLength);
                }

                closeStatus = (WebSocketCloseStatus)(_receiveBuffer[_receiveBufferOffset] << 8 | _receiveBuffer[_receiveBufferOffset + 1]);
                if (!IsValidCloseStatus(closeStatus))
                {
                    await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, cancellationToken).ConfigureAwait(false);
                }

                if (header.PayloadLength > 2)
                {
                    try
                    {
                        closeStatusDescription = s_textEncoding.GetString(_receiveBuffer, _receiveBufferOffset + 2, (int)header.PayloadLength - 2);
                    }
                    catch (DecoderFallbackException exc)
                    {
                        await CloseWithReceiveErrorAndThrowAsync(WebSocketCloseStatus.ProtocolError, WebSocketError.Faulted, cancellationToken, exc).ConfigureAwait(false);
                    }
                }
                ConsumeFromBuffer((int)header.PayloadLength);
            }

            // Store the close status and description onto the instance.
            _closeStatus = closeStatus;
            _closeStatusDescription = closeStatusDescription;

            // And return them as part of the result message.
            return new WebSocketReceiveResult(0, WebSocketMessageType.Close, true, closeStatus, closeStatusDescription);
        }
Пример #52
0
        /// <summary>
        /// Récupère les nouveaux Messaegs du serveur de Mails POP3 dont les informations de
        /// connextion sont indiqués dans le paramètre
        /// </summary>
        /// <param name="parametre">Parametres de connexion au serveur de mails POP3</param>
        /// <returns>Le Data du Result contient un liste de MailMessageEx</returns>
        public CResultAErreur RetrieveMails(CCompteMail compteMail)
        {
            CResultAErreur result = CResultAErreur.True;

            if (compteMail == null)
            {
                result.EmpileErreur("Erreur dans CRecepteurMail: compteMail est nul");
            }

            m_compteMail = compteMail;
            m_compteMail.BeginEdit();
            m_compteMail.DateDernierReleve = DateTime.Now;

            CParametreCompteMail parametre = compteMail.ParametreCompteMail;

            if (parametre == null)
            {
                result.EmpileErreur("Erreur dans CRecepteurMail: Le ¨Parametre de compte est nul");
                return(result);
            }
            using (Pop3Client client = new Pop3Client())
            {
                try
                {
                    client.Connect(parametre.PopServer, parametre.PopPort, parametre.UseSsl);
                    // Authenticate ourselves towards the server
                    client.Authenticate(parametre.User, parametre.Password);
                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    // Messages are numbered in the interval: [1, messageCount]
                    // Ergo: message numbers are 1-based.
                    for (int i = 1; i <= messageCount; i++)
                    {
                        MessageHeader    messageHead   = client.GetMessageHeaders(i);
                        Message          messageRecu   = null;
                        CTracabiliteMail traceMail     = new CTracabiliteMail(m_compteMail.ContexteDonnee);
                        CFiltreData      filtreIfExist = new CFiltreData(
                            CTracabiliteMail.c_champMessageUid + " = @1 and " +
                            CCompteMail.c_champId + " = @2 ",
                            messageHead.MessageId,
                            compteMail.Id);
                        if (!traceMail.ReadIfExists(filtreIfExist))
                        {
                            try
                            {
                                C2iMail mail = new C2iMail(compteMail.ContexteDonnee);
                                mail.CreateNewInCurrentContexte();
                                mail.CompteMail = m_compteMail;
                                if (parametre.HeaderOnly)
                                {
                                    mail.FillFromHeader(messageHead);
                                }
                                else
                                {
                                    messageRecu = client.GetMessage(i);
                                    mail.FillFromMessage(messageRecu);
                                }
                            }
                            catch (Exception ex)
                            {
                                result.EmpileErreur(ex.Message);
                            }
                        }
                        if (parametre.SupprimerDuServeur)
                        {
                            if (parametre.DelaiSuppression <= 0)
                            {
                                client.DeleteMessage(i);
                            }
                            else
                            {
                                DateTime dateMessage = messageHead.DateSent;
                                TimeSpan dureeDeVie  = DateTime.Now - dateMessage;
                                if (dureeDeVie.Days >= parametre.DelaiSuppression)
                                {
                                    client.DeleteMessage(i);
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    result.EmpileErreur(exception.Message);
                }
                finally
                {
                    client.Disconnect();
                }
            }

            if (!result)
            {
                m_compteMail.LastErreur = result.MessageErreur;
            }
            else
            {
                m_compteMail.LastErreur = I.T("Mails succesfully retrived|10000");
            }

            result += m_compteMail.CommitEdit();

            return(result);
        }
Пример #53
0
        /// <summary>Parses a message header from the buffer.  This assumes the header is in the buffer.</summary>
        /// <param name="resultHeader">The read header.</param>
        /// <returns>true if a header was read; false if the header was invalid.</returns>
        private bool TryParseMessageHeaderFromReceiveBuffer(out MessageHeader resultHeader)
        {
            Debug.Assert(_receiveBufferCount >= 2, $"Expected to at least have the first two bytes of the header.");

            var header = new MessageHeader();

            header.Fin = (_receiveBuffer[_receiveBufferOffset] & 0x80) != 0;
            bool reservedSet = (_receiveBuffer[_receiveBufferOffset] & 0x70) != 0;
            header.Opcode = (MessageOpcode)(_receiveBuffer[_receiveBufferOffset] & 0xF);

            bool masked = (_receiveBuffer[_receiveBufferOffset + 1] & 0x80) != 0;
            header.PayloadLength = _receiveBuffer[_receiveBufferOffset + 1] & 0x7F;

            ConsumeFromBuffer(2);

            // Read the remainder of the payload length, if necessary
            if (header.PayloadLength == 126)
            {
                Debug.Assert(_receiveBufferCount >= 2, $"Expected to have two bytes for the payload length.");
                header.PayloadLength = (_receiveBuffer[_receiveBufferOffset] << 8) | _receiveBuffer[_receiveBufferOffset + 1];
                ConsumeFromBuffer(2);
            }
            else if (header.PayloadLength == 127)
            {
                Debug.Assert(_receiveBufferCount >= 8, $"Expected to have eight bytes for the payload length.");
                header.PayloadLength = 0;
                for (int i = 0; i < 8; i++)
                {
                    header.PayloadLength = (header.PayloadLength << 8) | _receiveBuffer[_receiveBufferOffset + i];
                }
                ConsumeFromBuffer(8);
            }

            bool shouldFail = reservedSet;
            if (masked)
            {
                if (!_isServer)
                {
                    shouldFail = true;
                }
                header.Mask = CombineMaskBytes(_receiveBuffer, _receiveBufferOffset);

                // Consume the mask bytes
                ConsumeFromBuffer(4);
            }

            // Do basic validation of the header
            switch (header.Opcode)
            {
                case MessageOpcode.Continuation:
                    if (_lastReceiveHeader.Fin)
                    {
                        // Can't continue from a final message
                        shouldFail = true;
                    }
                    break;

                case MessageOpcode.Binary:
                case MessageOpcode.Text:
                    if (!_lastReceiveHeader.Fin)
                    {
                        // Must continue from a non-final message
                        shouldFail = true;
                    }
                    break;

                case MessageOpcode.Close:
                case MessageOpcode.Ping:
                case MessageOpcode.Pong:
                    if (header.PayloadLength > MaxControlPayloadLength || !header.Fin)
                    {
                        // Invalid control messgae
                        shouldFail = true;
                    }
                    break;

                default:
                    // Unknown opcode
                    shouldFail = true;
                    break;
            }

            // Return the read header
            resultHeader = header;
            return !shouldFail;
        }
Пример #54
0
        private void ReceiveMessage(byte[] message)
        {
            MessageHeader header = (MessageHeader)((int)message[0]);

            if (header == MessageHeader.ACK)
            {
                this.SendAck();
                ZWaveMessageReceived(this, new ZWaveMessageReceivedEventArgs(new byte[] { (byte)MessageHeader.ACK }));
                if (message.Length > 1)
                {
                    byte[] msg = new byte[message.Length - 1];
                    Array.Copy(message, 1, msg, 0, msg.Length);
                    ReceiveMessage(msg);
                }
                return;
            }
            //
            int msgLength = 0;

            byte[] nextMessage = null;
            if (message.Length > 1)
            {
                msgLength = (int)message[1];
                if (message.Length > msgLength + 2)
                {
                    nextMessage = new byte[message.Length - msgLength - 2];
                    Array.Copy(message, msgLength + 2, nextMessage, 0, nextMessage.Length);
                    byte[] tmpmsg = new byte[msgLength + 2];
                    Array.Copy(message, 0, tmpmsg, 0, msgLength + 2);
                    message = tmpmsg;
                }
            }
            //
            //Console.WriteLine("=== > " + ByteArrayToString(message));
            //
            if (header == MessageHeader.SOF)
            {
                byte[] cmdAck = new byte[] { 0x01, 0x04, 0x01, 0x13, 0x01, 0xE8 };
                if (message.SequenceEqual(cmdAck))
                {
                    // TODO: ?!?
                }
                else if (VerifyChecksum(message))
                {
                    this.SendAck();
                    ZWaveMessageReceived(this, new ZWaveMessageReceivedEventArgs(message));
                }
                else
                {
                    this.SendNack();
                    Utility.DebugLog(DebugMessageType.Warning, "Bad checksum message " + Utility.ByteArrayToString(message));
                }
            }
            else if (header == MessageHeader.CAN)
            {
                // Resend
                ResendPendingMessage();
                ZWaveMessageReceived(this, new ZWaveMessageReceivedEventArgs(new byte[] { (byte)MessageHeader.CAN }));
            }
            else
            {
                Utility.DebugLog(DebugMessageType.Warning, "Unhandled message " + Utility.ByteArrayToString(message));
                // ZWaveMessageReceived(this, new ZWaveMessageReceivedEventArgs(new byte[] { (byte)ZWaveMessageHeader.NAK }));
            }
            if (nextMessage != null)
            {
                ReceiveMessage(nextMessage);
            }
        }
Пример #55
0
 public PublishMessage(MessageHeader header) : base(header)
 {
 }
Пример #56
0
        private void OnMessageReceived(object sender, DataReceivedEventArgs eventArgs)
        {
            LogInfo("WebSocket client received message");
            try
            {
                byte[]        binary  = eventArgs.Data;
                Message       message = MessageManager.GetMessageFromBinary(binary);
                MessageHeader header  = message.Header;
                MessageData   data    = message.Data;

                switch (message.Data.GetDataType())
                {
                case DataType.ConnectionAck:
                {
                    countdown.Signal();
                    ConnectionAckData ackData = data.AsConnectionAckData();
                    if (ackData.Status != StatusCode.OK)
                    {
                        int oldState = Interlocked.CompareExchange(ref state, ConnectionState.FAILED, ConnectionState.LOGGING_IN);
                        if (oldState != ConnectionState.LOGGING_IN)
                        {
                            int currentState = State;
                            if (currentState != ConnectionState.DISCONNECTED)
                            {
                                throw new InvalidOperationException(string.Format("Expected state LOGGING_IN but got {0}", ConnectionState.AsText(currentState)));
                            }
                            else
                            {
                                return;
                            }
                        }
                        Close();
                        listener.OnConnectionFailure(new KeyValuePair <MessageHeader, ConnectionAckData>(header, ackData));
                    }
                    else
                    {
                        int oldState = Interlocked.CompareExchange(ref state, ConnectionState.LOGGED_IN, ConnectionState.LOGGING_IN);
                        if (oldState != ConnectionState.LOGGING_IN)
                        {
                            int currentState = State;
                            if (currentState != ConnectionState.DISCONNECTED)
                            {
                                throw new InvalidOperationException(string.Format("Expected state LOGGING_IN but got {0}", ConnectionState.AsText(currentState)));
                            }
                            else
                            {
                                return;
                            }
                        }
                        listener.OnConnectionSuccess(header, ackData);
                    }
                }
                break;

                case DataType.EventAck:
                    listener.OnEventAck3(header, data.AsEventAckData());
                    break;

                case DataType.AttachmentRequest:
                    listener.OnAttachmentRequest4(header, data.AsAttachmentRequestData());
                    break;

                case DataType.AttachmentRequestAck:
                    listener.OnAttachmentRequestAck5(header, data.AsAttachmentRequestAckData());
                    break;

                case DataType.AttachmentResponse:
                    listener.OnAttachmentResponse6(header, data.AsAttachmentResponseData());
                    break;

                case DataType.AttachmentResponseAck:
                    listener.OnAttachmentResponseAck7(header, data.AsAttachmentResponseAckData());
                    break;

                case DataType.EventDocument:
                    listener.OnEventDocument8(header, data.AsEventDocumentData());
                    break;

                case DataType.EventDocumentAck:
                    listener.OnEventDocumentAck9(header, data.AsEventDocumentAckData());
                    break;

                case DataType.QueryRequestAck:
                    listener.OnQueryRequestAck11(header, data.AsQueryRequestAck());
                    break;

                default:
                    LogWarn(string.Format("Unexpected type of message received: {0}", message.Data.GetDataType()));
                    break;
                }
            }
            catch (MessagePackSerializationException e)
            {
                LogError(string.Format("The format of the received binary message is invalid! {0}", e.ToString()));
            }
        }
Пример #57
0
        List <Message> BufferMessages(ref byte[] buffer, ref int bufferOffset, ref int messageOffset, ref int remainingData, ref MessageHeader header, ref BufferValueReader reader, Func <MessageHeader, bool> messageIdCallback = null)
        {
            List <Message> messages = new List <Message>();

            string callCategory = null;

                        #if TRACE
            int c = GetNextCallId();
            callCategory = String.Format("{0} {1}:BufferMessages({2},{3},{4},{5},{6})", this.connectionType, c, buffer.Length, bufferOffset, messageOffset, remainingData, reader.Position);
                        #endif
            Trace.WriteLineIf(NTrace.TraceVerbose, "Entering", callCategory);

            BufferValueReader currentReader = reader;

            int length = 0;
            while (remainingData >= BaseHeaderLength)
            {
                if (!TryGetHeader(currentReader, remainingData, ref header))
                {
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Message not ready", callCategory);
                    break;
                }

                if (header == null || header.Message == null)
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (header not found)", callCategory);
                    return(null);
                }

                length = header.MessageLength;
                if (length > MaxMessageSize)
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (bad message size)", callCategory);
                    return(null);
                }

                if (header.State == HeaderState.IV)
                {
                    DecryptMessage(header, ref currentReader);
                    header.IsStillEncrypted = false;
                    continue;
                }

                if (messageIdCallback != null && !messageIdCallback(header))
                {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message id callback was false)", callCategory);
                    return(null);
                }

                if (remainingData < length)
                {
                    bufferOffset += remainingData;
                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Message not fully received (boffset={0})", bufferOffset), callCategory);
                    break;
                }

                try
                {
                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Reading payload for message {0}", header.Message), callCategory);
                    header.Message.ReadPayload(header.SerializationContext, currentReader);

                    if (!header.Message.Encrypted && header.Message.Authenticated)
                    {
                        // Zero out length for message signing comparison
                                                #if SAFE
                        for (int i = LengthOffset + messageOffset; i < LengthOffset + sizeof(int) + messageOffset; ++i)
                        {
                            buffer[i] = 0;
                        }
                                                #else
                        fixed(byte *bptr = buffer)
                        * ((int *)(bptr + (LengthOffset + messageOffset))) = 0;
                                                #endif

                        int    payloadLength = reader.Position;
                        byte[] signature     = reader.ReadBytes();
                        if (!VerifyMessage(this.signingHashAlgorithm, header.Message, signature, buffer, messageOffset, payloadLength - messageOffset))
                        {
                            Disconnect(ConnectionResult.MessageAuthenticationFailed);
                            Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting (message auth failed)", callCategory);
                            return(null);
                        }
                    }
                } catch (Exception ex) {
                    header = null;
                    Disconnect();
                    Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting for error: " + ex, callCategory);
                    return(null);
                }

                messages.Add(header.Message);

                currentReader = reader;
                header        = null;

                if (length < buffer.Length)
                {
                    messageOffset += length;
                    bufferOffset   = messageOffset;
                    remainingData -= length;
                }
                else
                {
                    messageOffset          = 0;
                    bufferOffset           = 0;
                    remainingData          = 0;
                    currentReader.Position = 0;
                }

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("EOL: moffset={0},boffest={1},rdata={2},rpos={3}", messageOffset, bufferOffset, remainingData, reader.Position), callCategory);
            }

            if (remainingData > 0 || messageOffset + BaseHeaderLength >= buffer.Length)
            {
                Trace.WriteLineIf(NTrace.TraceVerbose, (remainingData > 0) ? String.Format("Data remaining: {0:N0}", remainingData) : "Insufficient room for a header", callCategory);

                int knownRoomNeeded = (remainingData > BaseHeaderLength) ? remainingData : BaseHeaderLength;
                if (header != null && remainingData >= BaseHeaderLength)
                {
                    knownRoomNeeded = header.MessageLength;
                }

                int pos = reader.Position - messageOffset;

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Room needed: {0:N0} bytes", knownRoomNeeded), callCategory);
                if (messageOffset + knownRoomNeeded <= buffer.Length)
                {
                    // bufferOffset is only moved on complete headers, so it's still == messageOffset.
                    bufferOffset = messageOffset + remainingData;
                    //reader.Position = pos;

                    Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Exiting (sufficient room; boffest={0},rpos={1})", bufferOffset, pos), callCategory);
                    return(messages);
                }

                byte[] destinationBuffer = buffer;
                if (knownRoomNeeded > buffer.Length)
                {
                    reader.Dispose();

                    destinationBuffer = new byte[header.MessageLength];
                    reader            = new BufferValueReader(destinationBuffer);
                }

                Buffer.BlockCopy(buffer, messageOffset, destinationBuffer, 0, remainingData);
                reader.Position = pos;
                messageOffset   = 0;
                bufferOffset    = remainingData;
                buffer          = destinationBuffer;

                Trace.WriteLineIf(NTrace.TraceVerbose, String.Format("Exiting (moved message to front, moffset={1},boffset={2},rpos={0})", reader.Position, messageOffset, bufferOffset), callCategory);
            }
            else
            {
                Trace.WriteLineIf(NTrace.TraceVerbose, "Exiting", callCategory);
            }

            return(messages);
        }
        public override Message ProcessIncoming(MessageHeader header, BufferStream stream, ref byte[] raw, ref byte[] plaintext)
        {
            var messageDirection = Message.GetMessageDirection(header.Id);
            // Message instance that we will return to the caller.
            var message = MessageFactory.Create(header.Id);
            var chiper  = new byte[header.Length];

            stream.Read(chiper, 0, header.Length);

            // Unencrypted byte array.
            plaintext = null;
            lock (_lock)
            {
                // Handshaking.
                if (_state <= 1)
                {
                    // Handshakes are sent unencrypted.
                    // First message by both ends is always sent unencrypted.
                    plaintext = (byte[])chiper.Clone();

                    // Use the first message direction to configure the processor.
                    if (_state == 0)
                    {
                        _clientCrypto = new Crypto8(GetOppositeDirection(messageDirection), _keyPair);
                    }
                    if (_state == 1)
                    {
                        _serverCrypto = new Crypto8(GetOppositeDirection(messageDirection), Crypto8.GenerateKeyPair());
                    }
                }

                if (_state == 4)
                {
                    _clientCrypto.UpdateNonce((byte[])_serverNonce.Clone(), UpdateNonceType.Encrypt);
                    _clientCrypto.UpdateNonce((byte[])_clientNonce.Clone(), UpdateNonceType.Decrypt);
                    _clientCrypto.UpdateSharedKey(_serverCrypto.SharedKey);
                }

                // _state == 1 means we are the server.
                // Usually processing 10101 - LoginRequestMessage.
                if (_state == 2)
                {
                    _serverCrypto.UpdateSharedKey(Crypto8.SupercellPublicKey);

                    // -> Pre-Encryption.
                    // Copies the public key appended to the beginning of the message.
                    var publicKey = new byte[KeyPair.KeyLength];
                    Buffer.BlockCopy(chiper, 0, publicKey, 0, KeyPair.KeyLength);

                    Debug.WriteLine($"Public-Key from {header.Id}: {ToHexString(publicKey)}");

                    // Copies the remaining bytes into the plaintext buffer
                    var plaintextLen = header.Length - KeyPair.KeyLength;
                    plaintext = new byte[plaintextLen];
                    Buffer.BlockCopy(chiper, KeyPair.KeyLength, plaintext, 0, plaintextLen);

                    // Crypto8 will take publicKey & _keyPair.PublicKey and generate a blake2b nonce
                    _clientCrypto.UpdateSharedKey(publicKey);
                    // Then use _keyPair.PrivateKey, publicKey and nonce to decrypt.
                    _clientCrypto.Decrypt(ref plaintext);

                    // -> Post-Encryption.
                    _sessionKey  = new byte[KeyPair.NonceLength];
                    _clientNonce = new byte[KeyPair.NonceLength];

                    // Copy the SessionKey and the ClientNonce.
                    Buffer.BlockCopy(plaintext, 0, _sessionKey, 0, KeyPair.NonceLength);
                    Buffer.BlockCopy(plaintext, KeyPair.NonceLength, _clientNonce, 0, KeyPair.NonceLength);

                    Debug.WriteLine($"Session-key from {header.Id}: {ToHexString(_sessionKey)}");
                    Debug.WriteLine($"Client-nonce from {header.Id}: {ToHexString(_clientNonce)}");

                    var actualMessage = new byte[plaintext.Length - (KeyPair.NonceLength * 2)];
                    Buffer.BlockCopy(plaintext, KeyPair.NonceLength * 2, actualMessage, 0, actualMessage.Length);

                    plaintext = actualMessage;
                }
                else if (_state == 3)
                {
                    _clientCrypto.UpdateNonce(_clientNonce, UpdateNonceType.Blake);
                    _serverCrypto.UpdateNonce(_clientNonce, UpdateNonceType.Blake);
                    _serverCrypto.Decrypt(ref chiper);

                    // Post-Encryption
                    // Copies the public key appended to the beginning of the message.
                    _serverNonce = new byte[KeyPair.NonceLength];
                    Buffer.BlockCopy(chiper, 0, _serverNonce, 0, KeyPair.NonceLength);

                    var publicKey = new byte[KeyPair.KeyLength];
                    Buffer.BlockCopy(chiper, KeyPair.NonceLength, publicKey, 0, KeyPair.KeyLength);

                    _serverCrypto.UpdateNonce((byte[])_serverNonce.Clone(), UpdateNonceType.Decrypt);
                    _serverCrypto.UpdateNonce((byte[])_clientNonce.Clone(), UpdateNonceType.Encrypt);
                    _serverCrypto.UpdateSharedKey(publicKey);

                    Debug.WriteLine($"Server-Nonce from {header.Id}: {ToHexString(_serverNonce)}");
                    Debug.WriteLine($"New Public-Key from {header.Id}: {ToHexString(publicKey)}");

                    // Copies the remaining bytes into the plaintext buffer.
                    var plaintextLen = chiper.Length - KeyPair.KeyLength - KeyPair.NonceLength;
                    plaintext = new byte[plaintextLen];

                    Buffer.BlockCopy(chiper, KeyPair.KeyLength + KeyPair.NonceLength, plaintext, 0, plaintextLen);
                }
                else if (_state > 3)
                {
                    if (messageDirection == MessageDirection.Client)
                    {
                        _serverCrypto.Decrypt(ref chiper);
                    }

                    if (messageDirection == MessageDirection.Server)
                    {
                        _clientCrypto.Decrypt(ref chiper);
                    }

                    plaintext = chiper;
                }

                _state++;
            }
            try
            {
                using (var reader = new MessageReader(new MemoryStream(plaintext)))
                    message.ReadMessage(reader);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ex: " + ex);
            }
            return(message);
        }
Пример #59
0
 internal static extern unsafe Error SendMessage(int socket, MessageHeader* messageHeader, SocketFlags flags, long* sent);
Пример #60
0
 protected abstract Task DispatchRequest(MessageHeader messageHeader, TRequest request);