コード例 #1
0
        public TcpConnectionFactory(IProtocol protocol, IProtocolHandler protocolHandler,
                                    int chunkSize = 25, int chunkDelay = 250, bool closeConnectionAfterResponse = false)
        {
            if (protocol == null)
            {
                throw new ArgumentNullException(nameof(protocol));
            }

            if (protocolHandler == null)
            {
                throw new ArgumentNullException(nameof(protocolHandler));
            }

            if (chunkSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(chunkSize));
            }

            if (chunkDelay <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(chunkDelay));
            }

            m_protocol        = protocol;
            m_protocolHandler = protocolHandler;
            m_chunkSize       = chunkSize;
            m_chunkDelay      = chunkDelay;
            m_closeConnectionAfterResponse = closeConnectionAfterResponse;
        }
コード例 #2
0
 public WebSocketHandler(
     IConnectionManager webSocketConnectionManager,
     IProtocolHandler protocolHandler)
 {
     this._wsConnectionManager = webSocketConnectionManager;
     this._protocolHandler     = protocolHandler;
 }
コード例 #3
0
        public static string Inspect(this IProtocolHandler message)
        {
            if (message == null)
            {
                return("null");
            }

            var    type       = message.GetType();
            string result     = type.FullName + Environment.NewLine;
            var    properties = type.GetProperties();

            foreach (var property in properties)
            {
                if (!property.IsDefined(typeof(ProtoBuf.ProtoMemberAttribute), false))
                {
                    continue;
                }

                var  specified = properties.FirstOrDefault(p => p.Name == property.Name + "Specified");
                bool?hasField  = null;
                if (specified != null)
                {
                    hasField = specified.GetValue(message, null) as bool?;
                }

                result += " " + property.Name + ": " + FormatValue(hasField, property.GetValue(message, null)) + Environment.NewLine;
            }

            return(result);
        }
コード例 #4
0
 public TestZoneImpl(String zoneId, String zoneUrl, Agent agent, AgentProperties props,
                   MessageDispatcher dispatcher, IProtocolHandler proto)
     : base(zoneId, zoneUrl, agent, props)
 {
     this.Dispatcher = dispatcher;
      fProtocolHandler = proto;
 }
コード例 #5
0
        public async Task Adding_protocols_when_disconnecting_will_not_cause_trouble()
        {
            bool shouldStop = false;
            int i = 0;
            Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, NullDisconnectsAnalyzer.Instance, LimboLogs.Instance);
            Action addProtocol = () =>
            {
                IProtocolHandler required = Substitute.For<IProtocolHandler>();
                required.ProtocolCode.Returns("p2p");
                required.MessageIdSpaceSize.Returns(16);
                session.AddProtocolHandler(required);
                while (!shouldStop)
                {
                    IProtocolHandler protocolHandler = Substitute.For<IProtocolHandler>();
                    protocolHandler.ProtocolCode.Returns("aa" + i++);
                    protocolHandler.MessageIdSpaceSize.Returns(10);
                    session.AddProtocolHandler(protocolHandler);
                }
            };

            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            Task task = new(addProtocol);
            task.Start();

            await Task.Delay(20);
            session.InitiateDisconnect(DisconnectReason.Other, "test");
            await Task.Delay(10);
            shouldStop = true;
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: urb31075/ProgramTemplate
 /// <summary>
 /// The accept.
 /// </summary>
 /// <param name="visitor">
 /// The visitor.
 /// </param>
 public void ExecuteOperation(IProtocolHandler visitor)
 {
     foreach (IExecuteOperation acc in this.accounts)
     {
         acc.ExecuteOperation(visitor);
     }
 }
コード例 #7
0
 public static void RegisterProtocolHandler(string name, IProtocolHandler handler)
 {
     if (!_protocolHandlerMap.TryAdd(name, handler))
     {
         throw new MornException(MornErrorType.MornException, "已经注册过同名的协议处理接口");
     }
 }
コード例 #8
0
 private IProtocolHandler BuildHandler(string code, int spaceSize)
 {
     IProtocolHandler handler = Substitute.For<IProtocolHandler>();
     handler.ProtocolCode.Returns(code);
     handler.MessageIdSpaceSize.Returns(spaceSize);
     return handler;
 }
コード例 #9
0
        public IProtocolHandler Create(ISession session)
        {
            IProtocolHandler handler = _subprotocolFactory.Create(session);

            handler.ProtocolInitialized += (sender, args) =>
            {
                var ndmEventArgs = (NdmProtocolInitializedEventArgs)args;
                _protocolValidator.DisconnectOnInvalid(Protocol.Ndm, session, ndmEventArgs);
                if (_logger.IsTrace)
                {
                    _logger.Trace($"NDM version {handler.ProtocolVersion}: {session.RemoteNodeId}, host: {session.Node.Host}");
                }
                if (string.IsNullOrWhiteSpace(_ethRequestService.FaucetHost) ||
                    !session.Node.Host.Contains(_ethRequestService.FaucetHost))
                {
                    return;
                }

                INdmPeer?peer = handler as INdmPeer;
                if (peer != null)
                {
                    _ethRequestService.UpdateFaucet(peer);
                }
                else
                {
                    _logger.Warn($"NDM handler cannot serve as faucet since it is not implementing {nameof(INdmPeer)}");
                }
            };

            return(handler);
        }
コード例 #10
0
        public void Factory2()
        {
            _facility.AddTypedFactoryEntry(
                new FactoryEntry(
                    "protocolHandlerFactory", typeof(IProtocolHandlerFactory2), "Create", "Release"));

            _container.AddComponent("miranda", typeof(IProtocolHandler), typeof(MirandaProtocolHandler));
            _container.AddComponent("messenger", typeof(IProtocolHandler), typeof(MessengerProtocolHandler));

            IProtocolHandlerFactory2 factory =
                (IProtocolHandlerFactory2)_container["protocolHandlerFactory"];

            Assert.IsNotNull(factory);

            IProtocolHandler handler = factory.Create("miranda");

            Assert.IsNotNull(handler);
            Assert.IsTrue(handler is MirandaProtocolHandler);
            factory.Release(handler);

            handler = factory.Create("messenger");
            Assert.IsNotNull(handler);
            Assert.IsTrue(handler is MessengerProtocolHandler);
            factory.Release(handler);
        }
コード例 #11
0
        public void Can_receive_messages()
        {
            Metrics.P2PBytesReceived = 0;
            
            Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, NullDisconnectsAnalyzer.Instance, LimboLogs.Instance);
            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            IProtocolHandler p2p = BuildHandler("p2p", 10);
            IProtocolHandler aaa = BuildHandler("aaa", 10);
            IProtocolHandler bbb = BuildHandler("bbb", 5);
            IProtocolHandler ccc = BuildHandler("ccc", 1);
            session.AddProtocolHandler(p2p);
            session.AddProtocolHandler(aaa);
            session.AddProtocolHandler(bbb);
            session.AddProtocolHandler(ccc);

            byte[] data = new byte[10];
            session.ReceiveMessage(new Packet("---", 3, data));
            p2p.Received().HandleMessage(Arg.Is<Packet>(p => p.Protocol == "p2p" && p.PacketType == 3));

            session.ReceiveMessage(new Packet("---", 11, data));
            aaa.Received().HandleMessage(Arg.Is<Packet>(p => p.Protocol == "aaa" && p.PacketType == 1));

            session.ReceiveMessage(new Packet("---", 21, data));
            bbb.Received().HandleMessage(Arg.Is<Packet>(p => p.Protocol == "bbb" && p.PacketType == 1));

            session.ReceiveMessage(new Packet("---", 25, data));
            ccc.Received().HandleMessage(Arg.Is<Packet>(p => p.Protocol == "ccc" && p.PacketType == 0));

            session.ReceiveMessage(new Packet("---", 100, data));

            Metrics.P2PBytesReceived.Should().Be(data.Length * 5);
        }
コード例 #12
0
 public TestZoneImpl(String zoneId, String zoneUrl, Agent agent, AgentProperties props,
                     MessageDispatcher dispatcher, IProtocolHandler proto)
     : base(zoneId, zoneUrl, agent, props)
 {
     this.Dispatcher  = dispatcher;
     fProtocolHandler = proto;
 }
コード例 #13
0
        public void Updates_local_and_remote_metrics_on_disconnects()
        {
            Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, new MetricsDisconnectsAnalyzer(), LimboLogs.Instance);
            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            IProtocolHandler p2p = BuildHandler("p2p", 10);
            session.AddProtocolHandler(p2p);

            long beforeLocal = Network.Metrics.LocalOtherDisconnects;
            long beforeRemote = Network.Metrics.OtherDisconnects;
            session.MarkDisconnected(DisconnectReason.Other, DisconnectType.Local, string.Empty);
            long afterLocal = Network.Metrics.LocalOtherDisconnects;
            long afterRemote = Network.Metrics.OtherDisconnects;
            Assert.AreEqual(beforeLocal + 1, afterLocal);
            Assert.AreEqual(beforeRemote, afterRemote);

            session = new Session(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, new MetricsDisconnectsAnalyzer(), LimboLogs.Instance);
            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            p2p = BuildHandler("p2p", 10);
            session.AddProtocolHandler(p2p);

            beforeLocal = Network.Metrics.LocalOtherDisconnects;
            beforeRemote = Network.Metrics.OtherDisconnects;
            session.MarkDisconnected(DisconnectReason.Other, DisconnectType.Remote, string.Empty);
            afterLocal = Network.Metrics.LocalOtherDisconnects;
            afterRemote = Network.Metrics.OtherDisconnects;
            Assert.AreEqual(beforeLocal, afterLocal);
            Assert.AreEqual(beforeRemote + 1, afterRemote);
        }
コード例 #14
0
        private void InitProtocol(ISession session, string protocolCode, int version, bool addCapabilities = false)
        {
            if (session.State < SessionState.Initialized)
            {
                throw new InvalidOperationException($"{nameof(InitProtocol)} called on {session}");
            }

            if (session.State != SessionState.Initialized)
            {
                return;
            }

            string code = protocolCode.ToLowerInvariant();

            if (!_protocolFactories.TryGetValue(code, out Func <ISession, int, IProtocolHandler> protocolFactory))
            {
                throw new NotSupportedException($"Protocol {code} {version} is not supported");
            }

            IProtocolHandler protocolHandler = protocolFactory(session, version);

            protocolHandler.SubprotocolRequested += (s, e) => InitProtocol(session, e.ProtocolCode, e.Version);
            session.AddProtocolHandler(protocolHandler);
            if (addCapabilities)
            {
                foreach (Capability capability in _capabilities)
                {
                    session.AddSupportedCapability(capability);
                }
            }

            protocolHandler.Init();
        }
コード例 #15
0
        public void ExternalConfigurationUsage()
        {
            WindsorContainer container = new WindsorContainer("../aop_castle_config.xml");

            container.AddFacility("aspectsharp", new AspectSharpFacility());

            // Logger implementation
            container.AddComponent("logger", typeof(ILogger), typeof(MemoryLogger));

            // AopAlliance interceptors
            container.AddComponent("log4netinterceptor", typeof(LoggerTraceInterceptor));

            // Protocol handlers
            container.AddComponent("protocolhandler.miranda",
                                   typeof(IProtocolHandler), typeof(MirandaProtocolHandler));
            container.AddComponent("protocolhandler.messenger",
                                   typeof(IProtocolHandler), typeof(MessengerProtocolHandler));

            // using...

            ILogger logger = (ILogger)container[typeof(ILogger)];

            Assert.AreEqual(0, logger.Contents.Length);

            IProtocolHandler handler = (IProtocolHandler)
                                       container["protocolhandler.miranda"];

            handler.Handle("contents");

            handler = (IProtocolHandler)container["protocolhandler.messenger"];
            handler.Handle("contents");

            Assert.AreEqual("Entering Handle Leaving Handle Entering Handle Leaving Handle ",
                            logger.Contents);
        }
コード例 #16
0
ファイル: P2PSessionTests.cs プロジェクト: FIVIL/nethermind
        public void Cannot_dispose_unless_disconnected()
        {
            Session session = new Session(30312, LimboLogs.Instance, _channel, new Node("127.0.0.1", 8545));

            session.Handshake(TestItem.PublicKeyA);
            Assert.Throws <InvalidOperationException>(() => session.Dispose());
            session.Init(5, _channelHandlerContext, _packetSender);
            Assert.Throws <InvalidOperationException>(() => session.Dispose());

            IProtocolHandler p2p = BuildHandler("p2p", 10);
            IProtocolHandler aaa = BuildHandler("aaa", 10);
            IProtocolHandler bbb = BuildHandler("bbb", 5);
            IProtocolHandler ccc = BuildHandler("ccc", 1);

            session.AddProtocolHandler(p2p);
            session.AddProtocolHandler(aaa);
            session.AddProtocolHandler(bbb);
            session.AddProtocolHandler(ccc);

            session.InitiateDisconnect(DisconnectReason.ClientQuitting);
            session.Dispose();

            aaa.Received().InitiateDisconnect(DisconnectReason.ClientQuitting, "test");
            bbb.Received().InitiateDisconnect(DisconnectReason.ClientQuitting, "test");
            ccc.Received().InitiateDisconnect(DisconnectReason.ClientQuitting, "test");

            aaa.Received().Dispose();
            bbb.Received().Dispose();
            ccc.Received().Dispose();
        }
コード例 #17
0
ファイル: P2PSessionTests.cs プロジェクト: FIVIL/nethermind
        public void Can_receive_messages()
        {
            Session session = new Session(30312, LimboLogs.Instance, _channel, new Node("127.0.0.1", 8545));

            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            IProtocolHandler p2p = BuildHandler("p2p", 10);
            IProtocolHandler aaa = BuildHandler("aaa", 10);
            IProtocolHandler bbb = BuildHandler("bbb", 5);
            IProtocolHandler ccc = BuildHandler("ccc", 1);

            session.AddProtocolHandler(p2p);
            session.AddProtocolHandler(aaa);
            session.AddProtocolHandler(bbb);
            session.AddProtocolHandler(ccc);

            session.ReceiveMessage(new Packet("---", 3, Bytes.Empty));
            p2p.Received().HandleMessage(Arg.Is <Packet>(p => p.Protocol == "p2p" && p.PacketType == 3));

            session.ReceiveMessage(new Packet("---", 11, Bytes.Empty));
            aaa.Received().HandleMessage(Arg.Is <Packet>(p => p.Protocol == "aaa" && p.PacketType == 1));

            session.ReceiveMessage(new Packet("---", 21, Bytes.Empty));
            bbb.Received().HandleMessage(Arg.Is <Packet>(p => p.Protocol == "bbb" && p.PacketType == 1));

            session.ReceiveMessage(new Packet("---", 25, Bytes.Empty));
            ccc.Received().HandleMessage(Arg.Is <Packet>(p => p.Protocol == "ccc" && p.PacketType == 0));

            session.ReceiveMessage(new Packet("---", 100, Bytes.Empty));
        }
コード例 #18
0
 public void Cannot_add_handlers_before_p2p()
 {
     Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, NullDisconnectsAnalyzer.Instance, LimboLogs.Instance);
     session.Handshake(TestItem.PublicKeyA);
     session.Init(5, _channelHandlerContext, _packetSender);
     IProtocolHandler aaa = BuildHandler("aaa", 10);
     Assert.Throws<InvalidOperationException>(() => session.AddProtocolHandler(aaa));
 }
コード例 #19
0
        /// <summary>
        /// Sends a <see cref="IProtocolException"/> message for an invalid object X.
        /// </summary>
        /// <param name="handler">The protocol handler.</param>
        /// <param name="ex">The exception.</param>
        /// <param name="uri">The URI.</param>
        /// <param name="messageId">The message identifier.</param>
        /// <returns>The <see cref="IProtocolException"/> message identifier.</returns>
        public static long InvalidObjectX(this IProtocolHandler handler, Exception ex, string uri, long messageId = 0)
        {
            if (ex != null)
            {
                (handler as EtpProtocolHandler)?.Logger?.Debug($"Invalid Object XML: {uri}", ex);
            }

            return(handler.ProtocolException((int)EtpErrorCodes.InvalidObjectX, "Invalid Object. URI: " + uri, messageId));
        }
コード例 #20
0
ファイル: Protocol.cs プロジェクト: AnCh7/StreamingServer
        /// <exception cref="ArgumentNullException">The value of '' cannot be null. </exception>
        public Protocol(IProtocolHandler handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException();
            }

            _handler = handler;
        }
コード例 #21
0
        /// <summary>
        /// Sends a <see cref="IProtocolException"/> message for an unsupported object.
        /// </summary>
        /// <param name="handler">The protocol handler.</param>
        /// <param name="ex">The exception.</param>
        /// <param name="uri">The URI.</param>
        /// <param name="messageId">The message identifier.</param>
        /// <returns>The <see cref="IProtocolException"/> message identifier.</returns>
        public static long UnsupportedObject(this IProtocolHandler handler, Exception ex, string uri, long messageId = 0)
        {
            if (ex != null)
            {
                (handler as EtpProtocolHandler)?.Logger?.Debug($"Unsupported Object: {uri}", ex);
            }

            return(handler.ProtocolException((int)EtpErrorCodes.UnsupportedObject, "Data object not supported. URI: " + uri, messageId));
        }
コード例 #22
0
        private Guid GetSessionId(IProtocolHandler handler)
        {
            var guid = handler.EtpVersion == EtpVersion.v11
                ? GuidUtility.Create(handler.Session.SessionId, v11.ProtocolNames.GetProtocolName(handler.Protocol))
                : GuidUtility.Create(handler.Session.SessionId, v12.ProtocolNames.GetProtocolName(handler.Protocol));

            SessionIds[guid] = guid;
            return(guid);
        }
コード例 #23
0
ファイル: EtpExtensions.cs プロジェクト: wdstest/witsml
        /// <summary>
        /// Validates URI Object Type.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="etpUri">The ETP URI.</param>
        /// <param name="messageId">The message identifier.</param>
        /// <returns></returns>
        public static bool ValidateUriObjectType(this IProtocolHandler handler, EtpUri etpUri, long messageId = 0)
        {
            if (!string.IsNullOrWhiteSpace(etpUri.ObjectType))
            {
                return(true);
            }

            handler.UnsupportedObject(null, $"{etpUri.Uri}", messageId);
            return(false);
        }
コード例 #24
0
 public void Cannot_receive_before_initialized()
 {
     Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, NullDisconnectsAnalyzer.Instance, LimboLogs.Instance);
     Assert.Throws<InvalidOperationException>(() => session.ReceiveMessage(new Packet("p2p", 1, Array.Empty<byte>())));
     session.Handshake(TestItem.PublicKeyA);
     Assert.Throws<InvalidOperationException>(() => session.ReceiveMessage(new Packet("p2p", 1, Array.Empty<byte>())));
     session.Init(5, _channelHandlerContext, _packetSender);
     IProtocolHandler p2p = BuildHandler("p2p", 10);
     session.AddProtocolHandler(p2p);
 }
コード例 #25
0
ファイル: EtpExtensions.cs プロジェクト: wdstest/witsml
        /// <summary>
        /// Validates URI Parent Hierarchy.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="etpUri">The ETP URI.</param>
        /// <param name="messageId">The message identifier.</param>
        /// <returns></returns>
        public static bool ValidateUriParentHierarchy(this IProtocolHandler handler, EtpUri etpUri, long messageId = 0)
        {
            if (etpUri.ValidateUriParentHierarchy())
            {
                return(true);
            }

            handler.InvalidUri($"{etpUri} is missing the objectId of a parent.", messageId);

            return(false);
        }
コード例 #26
0
ファイル: EtpExtensions.cs プロジェクト: wdstest/witsml
        /// <summary>
        /// Creates and validates the specified URI.
        /// </summary>
        /// <param name="handler">The protocol handler.</param>
        /// <param name="uri">The URI.</param>
        /// <param name="messageId">The message identifier.</param>
        /// <returns>A new <see cref="EtpUri" /> instance.</returns>
        public static EtpUri CreateAndValidateUri(this IProtocolHandler handler, string uri, long messageId = 0)
        {
            var etpUri = new EtpUri(uri);

            if (!etpUri.IsValid)
            {
                handler.InvalidUri(uri, messageId);
            }

            return(etpUri);
        }
コード例 #27
0
        public void Connect()
        {
            CheckAuthenticated();
            CheckNotConnected();

            protocolHandler            = protocolHandlerFactory.Create();
            protocolHandler.Dispatcher = messageBroker;
            protocolHandler.Connect(config.GameServerAddress, sessionId, sessionCookie);

            this.state = GameClientState.Connected;
        }
コード例 #28
0
        private void RegisterHandler(IProtocolHandler handler)
        {
            var type = handler.GetType();

            foreach (var scheme in handler.Scheme)
            {
                if (!this.handlers.ContainsKey(scheme))
                {
                    this.handlers.Add(scheme.ToLower(), type);
                }
            }
        }
コード例 #29
0
ファイル: P2PSessionTests.cs プロジェクト: FIVIL/nethermind
        public void Cannot_deliver_before_initialized()
        {
            Session session = new Session(30312, LimboLogs.Instance, _channel, new Node("127.0.0.1", 8545));

            Assert.Throws <InvalidOperationException>(() => session.DeliverMessage(new Packet("p2p", 1, Bytes.Empty)));
            session.Handshake(TestItem.PublicKeyA);
            Assert.Throws <InvalidOperationException>(() => session.DeliverMessage(new Packet("p2p", 1, Bytes.Empty)));
            session.Init(5, _channelHandlerContext, _packetSender);
            IProtocolHandler p2p = BuildHandler("p2p", 10);

            session.AddProtocolHandler(p2p);
        }
コード例 #30
0
ファイル: P2PSessionTests.cs プロジェクト: FIVIL/nethermind
        public void Cannot_add_handler_twice()
        {
            Session session = new Session(30312, LimboLogs.Instance, _channel, new Node("127.0.0.1", 8545));

            session.Handshake(TestItem.PublicKeyA);
            session.Init(5, _channelHandlerContext, _packetSender);
            IProtocolHandler p2p      = BuildHandler("p2p", 10);
            IProtocolHandler p2pAgain = BuildHandler("p2p", 10);

            session.AddProtocolHandler(p2p);
            Assert.Throws <InvalidOperationException>(() => session.AddProtocolHandler(p2pAgain));
        }
コード例 #31
0
        public SocketProtocolHandler(IResolverSession session, IPacketStream packetStream, IProtocolConverter protocolConverter, IProtocolHandler protocolHandler)
        {
            this.ResolverSession   = session;
            this.packetStream      = packetStream ?? throw new ArgumentNullException(nameof(packetStream));
            this.protocolHandler   = protocolHandler ?? throw new ArgumentNullException(nameof(protocolHandler));
            this.protocolConverter = protocolConverter ?? throw new ArgumentNullException(nameof(protocolConverter));

            this.ConverterHeader = new ConverterHeader()
            {
                VersionMajor = 1
            };
        }
コード例 #32
0
 protected void SetProto(IProtocolHandler proto)
 {
     fProtocolHandler = this.fProtocolHandler;
 }