Example #1
0
 public static void Ctor_HostPort_AddressFamily_Success()
 {
     DnsEndPoint ep = new DnsEndPoint("host", 500, AddressFamily.InterNetwork);
     Assert.Equal("host", ep.Host);
     Assert.Equal(500, ep.Port);
     Assert.Equal(AddressFamily.InterNetwork, ep.AddressFamily);
 }
Example #2
0
 public static void Ctor_HostPort_Success()
 {
     DnsEndPoint ep = new DnsEndPoint("host", 500);
     Assert.Equal("host", ep.Host);
     Assert.Equal(500, ep.Port);
     Assert.Equal(AddressFamily.Unspecified, ep.AddressFamily);
 }
Example #3
0
		/// <summary>
		/// Connects to the server and begins listening for time updates.
		/// </summary>
		public void BeginRequestTime()
		{
			byte[] buffer = new byte[48];
			buffer[0] = 0x1B;
			for (var i = 1; i < buffer.Length; ++i)
			{
				buffer[i] = 0;
			}

			var endPoint = new DnsEndPoint(_ServerAddress, 123);

			_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			var socketArgs = new SocketAsyncEventArgs() { RemoteEndPoint = endPoint };
			socketArgs.Completed += (o, e) =>
			{
				if (e.SocketError == SocketError.Success)
				{
					var sArgs = new SocketAsyncEventArgs()
					{
						RemoteEndPoint = endPoint
					};

					sArgs.Completed += new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
					sArgs.SetBuffer(buffer, 0, buffer.Length);
					sArgs.UserToken = buffer;
					_Socket.SendAsync(sArgs);
				}
			};
			_Socket.ConnectAsync(socketArgs);
		}
Example #4
0
        // Called by Socket to kick off the ConnectAsync process.  We'll complete the user's SAEA
        // when it's done.  Returns true if the operation will be asynchronous, false if it has failed synchronously
        public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
        {
            lock (lockObject)
            {
                GlobalLog.Assert(endPoint.AddressFamily == AddressFamily.Unspecified ||
                     endPoint.AddressFamily == AddressFamily.InterNetwork ||
                     endPoint.AddressFamily == AddressFamily.InterNetworkV6,
                     "MultipleConnectAsync.StartConnectAsync(): Unexpected endpoint address family - " + endPoint.AddressFamily.ToString());

                this.userArgs = args;
                this.endPoint = endPoint;

                // If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
                // fail synchronously from here.  Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
                if (state == State.Canceled)
                {
                    SyncFail(new SocketException(SocketError.OperationAborted));
                    return false;
                }

                GlobalLog.Assert(state == State.NotStarted, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");

                state = State.DnsQuery;

                IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
                if (result.CompletedSynchronously)
                {
                    return DoDnsCallback(result, true);
                }
                else
                {
                    return true;
                }
            }
        }
Example #5
0
        public void Socket_ReceiveFromDnsEndPoint_ArgumentException()
        {
            using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int port = sock.BindToAnonymousPort(IPAddress.Loopback);
                EndPoint endpoint = new DnsEndPoint("localhost", port);

                Assert.Throws<ArgumentException>(() =>
                {
                    sock.ReceiveFrom(new byte[10], ref endpoint);
                });
            }
        }
Example #6
0
        public static void Equals_Compare_Success()
        {
            DnsEndPoint ep1 = new DnsEndPoint("name", 500, AddressFamily.InterNetwork);
            DnsEndPoint ep2 = new DnsEndPoint("name", 500, AddressFamily.InterNetwork);
            DnsEndPoint ep3 = new DnsEndPoint("name", 700, AddressFamily.InterNetwork);
            DnsEndPoint ep4 = new DnsEndPoint("name", 500, AddressFamily.InterNetworkV6);

            Assert.NotEqual(ep1, null);
            Assert.False(ep1.Equals("string"));

            Assert.Equal(ep1, ep2);
            Assert.Equal(ep2, ep1);
            Assert.Equal(ep1.GetHashCode(), ep2.GetHashCode());

            Assert.NotEqual(ep1, ep3);
            Assert.NotEqual(ep1.GetHashCode(), ep3.GetHashCode());

            Assert.NotEqual(ep1, ep4);
            Assert.NotEqual(ep1.GetHashCode(), ep4.GetHashCode());
        }
Example #7
0
        // Called by Socket to kick off the ConnectAsync process.  We'll complete the user's SAEA
        // when it's done.  Returns true if the operation will be asynchronous, false if it has failed synchronously
        public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
        {
            lock (_lockObject)
            {
                if (endPoint.AddressFamily != AddressFamily.Unspecified &&
                    endPoint.AddressFamily != AddressFamily.InterNetwork &&
                    endPoint.AddressFamily != AddressFamily.InterNetworkV6)
                {
                    NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
                }

                _userArgs = args;
                _endPoint = endPoint;

                // If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
                // fail synchronously from here.  Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
                if (_state == State.Canceled)
                {
                    SyncFail(new SocketException((int)SocketError.OperationAborted));
                    return false;
                }

                if (_state != State.NotStarted)
                {
                    NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
                }

                _state = State.DnsQuery;

                IAsyncResult result = DnsAPMExtensions.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
                if (result.CompletedSynchronously)
                {
                    return DoDnsCallback(result, true);
                }
                else
                {
                    return true;
                }
            }
        }
Example #8
0
        /// <summary>
        /// Tries to parse the string representation of an end point.
        /// </summary>
        /// <param name="value">The value to parse.</param>
        /// <param name="result">The result.</param>
        /// <returns>True if the string representation was parsed successfully.</returns>
        public static bool TryParse(string value, out EndPoint result)
        {
            result = null;

            if (value != null)
            {
                value = value.ToLowerInvariant();
                var match = Regex.Match(value, @"^(?<address>\[[^]]+\])(:(?<port>\d+))?$");
                if (match.Success)
                {
                    var addressString = match.Groups["address"].Value;
                    var portString    = match.Groups["port"].Value;
                    var port          = 27017;
                    if (portString.Length != 0 && !int.TryParse(portString, out port))
                    {
                        return(false);
                    }

                    if (!IsValidPort(port))
                    {
                        return(false);
                    }

                    IPAddress address;
                    if (IPAddress.TryParse(addressString, out address))
                    {
                        result = new IPEndPoint(address, port);
                        return(true);
                    }
#if NETCORE50 || NETSTANDARD1_5 || NETSTANDARD1_6
                    var hostAddresses = Dns.GetHostAddressesAsync(addressString).GetAwaiter().GetResult();
                    if (hostAddresses != null && hostAddresses.Length > 0)
                    {
                        result = new IPEndPoint(hostAddresses[0], port);
                        return(true);
                    }
#endif
                    return(false);
                }

                match = Regex.Match(value, @"^(?<host>[^:]+)(:(?<port>\d+))?$");
                if (match.Success)
                {
                    var host       = match.Groups["host"].Value;
                    var portString = match.Groups["port"].Value;
                    var port       = 27017;
                    if (portString.Length != 0 && !int.TryParse(portString, out port))
                    {
                        return(false);
                    }

                    if (!IsValidPort(port))
                    {
                        return(false);
                    }

                    IPAddress address;
                    if (IPAddress.TryParse(host, out address))
                    {
                        result = new IPEndPoint(address, port);
                        return(true);
                    }

                    try
                    {
                        result = new DnsEndPoint(host, port);
                        return(true);
                    }
                    catch (ArgumentException)
                    {
                        return(false);
                    }
                }
            }

            return(false);
        }
Example #9
0
 /// <summary>
 /// Generate CheckName
 /// </summary>
 /// <param name="serviceName"></param>
 /// <param name="dnsEndPoint"></param>
 /// <returns></returns>
 private string GenCheckName(string serviceName, DnsEndPoint dnsEndPoint)
 {
     return($"{serviceName}-{dnsEndPoint.Host}:{dnsEndPoint.Port}");
 }
Example #10
0
        public void Connect(string host, int port)
        {
            var myEndPoint = new DnsEndPoint(host, port);

            InnerConnect(myEndPoint);
        }
        public void With_should_return_new_instance_when_a_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var canonicalEndPoint    = new DnsEndPoint("localhost", 27017);
            var electionId           = new ElectionId(ObjectId.GenerateNewId());
            var heartbeatException   = new Exception();
            var heartbeatInterval    = TimeSpan.FromSeconds(10);
            var helloOk               = false;
            var lastUpdateTimestamp   = DateTime.UtcNow;
            var lastWriteTimestamp    = DateTime.UtcNow;
            var logicalSessionTimeout = TimeSpan.FromMinutes(1);
            var maxBatchCount         = 1000;
            var maxDocumentSize       = 16000000;
            var maxMessageSize        = 48000000;
            var maxWireDocumentSize   = 16000000;
            var replicaSetConfig      = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var state            = ServerState.Connected;
            var tags             = new TagSet(new[] { new Tag("x", "a") });
            var type             = ServerType.ReplicaSetPrimary;
            var version          = new SemanticVersion(3, 6, 0);
            var wireVersionRange = new Range <int>(6, 14);

            var subject = new ServerDescription(
                __serverId,
                __endPoint,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                heartbeatException: heartbeatException,
                heartbeatInterval: heartbeatInterval,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                lastWriteTimestamp: lastWriteTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                maxBatchCount: maxBatchCount,
                maxDocumentSize: maxDocumentSize,
                maxMessageSize: maxMessageSize,
                maxWireDocumentSize: maxWireDocumentSize,
                replicaSetConfig: replicaSetConfig,
                state: state,
                tags: tags,
                type: type,
                version: version,
                wireVersionRange: wireVersionRange);

            switch (notEqualField)
            {
            case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;

            case "CanonicalEndPoint": canonicalEndPoint = new DnsEndPoint("localhost", 27018); break;

            case "ElectionId": electionId = new ElectionId(ObjectId.Empty); break;

            case "HeartbeatException": heartbeatException = new Exception("NewMessage"); break;

            case "HeartbeatInterval": heartbeatInterval = TimeSpan.FromSeconds(11); break;

            case "HelloOk": helloOk = !helloOk; break;

            case "LastUpdateTimestamp": lastUpdateTimestamp = lastUpdateTimestamp.Add(TimeSpan.FromSeconds(1)); break;

            case "LastWriteTimestamp": lastWriteTimestamp = lastWriteTimestamp.Add(TimeSpan.FromSeconds(1)); break;

            case "LogicalSessionTimeout": logicalSessionTimeout = TimeSpan.FromMinutes(2); break;

            case "MaxBatchCount": maxBatchCount += 1; break;

            case "MaxDocumentSize": maxDocumentSize += 1; break;

            case "MaxMessageSize": maxMessageSize += 1; break;

            case "MaxWireDocumentSize": maxWireDocumentSize += 1; break;

            case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;

            case "State": state = ServerState.Disconnected; break;

            case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;

            case "Type": type = ServerType.ReplicaSetSecondary; break;

            case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;

            case "WireVersionRange": wireVersionRange = new Range <int>(0, 0); break;
            }

            var result = subject.With(
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                heartbeatException: heartbeatException,
                heartbeatInterval: heartbeatInterval,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                lastWriteTimestamp: lastWriteTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                maxBatchCount: maxBatchCount,
                maxDocumentSize: maxDocumentSize,
                maxMessageSize: maxMessageSize,
                maxWireDocumentSize: maxWireDocumentSize,
                replicaSetConfig: replicaSetConfig,
                state: state,
                tags: tags,
                type: type,
                version: version,
                wireVersionRange: wireVersionRange);

            result.Should().NotBeSameAs(subject);
            result.Equals(subject).Should().BeFalse();
            result.Equals((object)subject).Should().BeFalse();
            result.GetHashCode().Should().NotBe(subject.GetHashCode());
        }
Example #12
0
        public TelnetClient(string host, int port)
        {
            var endpoint = new DnsEndPoint(host, port);

            Context.System.Tcp().Tell(new Tcp.Connect(endpoint));
        }
Example #13
0
        /// <param name="defaultPort">If invalid and it's needed to use, then this function returns false.</param>
        public static bool TryParse(string?endPointString, int defaultPort, [NotNullWhen(true)] out EndPoint?endPoint)
        {
            endPoint = null;

            try
            {
                if (string.IsNullOrWhiteSpace(endPointString))
                {
                    return(false);
                }

                endPointString = Guard.Correct(endPointString);
                endPointString = endPointString.TrimEnd(':', '/');
                endPointString = endPointString.TrimStart("bitcoin-p2p://", StringComparison.OrdinalIgnoreCase);
                endPointString = endPointString.TrimStart("tcp://", StringComparison.OrdinalIgnoreCase);

                var parts = endPointString.Split(':', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().TrimEnd('/').TrimEnd()).ToArray();

                if (parts.Length == 0)
                {
                    return(false);
                }

                ushort p;
                int    port;

                if (parts.Length == 1)
                {
                    if (IsValidPort(defaultPort.ToString(), out p))
                    {
                        port = p;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (parts.Length == 2)
                {
                    var portString = parts[1];

                    if (IsValidPort(portString, out p))
                    {
                        port = p;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

                var host = parts[0];

                if (host == "localhost")
                {
                    host = IPAddress.Loopback.ToString();
                }

                if (IPAddress.TryParse(host, out IPAddress? addr))
                {
                    endPoint = new IPEndPoint(addr, port);
                }
                else
                {
                    endPoint = new DnsEndPoint(host, port);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #14
0
        private NodeEndPoints?TryDetermineBestNode(IEnumerable <ClusterMessages.MemberInfoDto> members,
                                                   NodePreference nodePreference)
        {
            var notAllowedStates = new[] {
                ClusterMessages.VNodeState.Manager,
                ClusterMessages.VNodeState.ShuttingDown,
                ClusterMessages.VNodeState.Manager,
                ClusterMessages.VNodeState.Shutdown,
                ClusterMessages.VNodeState.Unknown,
                ClusterMessages.VNodeState.Initializing,
                ClusterMessages.VNodeState.CatchingUp,
                ClusterMessages.VNodeState.ShuttingDown,
                ClusterMessages.VNodeState.PreLeader,
                ClusterMessages.VNodeState.PreReplica,
                ClusterMessages.VNodeState.PreReadOnlyReplica,
                ClusterMessages.VNodeState.Clone
            };

            var nodes = members.Where(x => x.IsAlive)
                        .Where(x => !notAllowedStates.Contains(x.State))
                        .OrderByDescending(x => x.State)
                        .ToArray();

            switch (nodePreference)
            {
            case NodePreference.Random:
                RandomShuffle(nodes, 0, nodes.Length - 1);
                break;

            case NodePreference.Leader:
                nodes = nodes.OrderBy(nodeEntry => nodeEntry.State != ClusterMessages.VNodeState.Leader)
                        .ToArray();                         // OrderBy is a stable sort and only affects order of matching entries
                break;

            case NodePreference.Follower:
                nodes = nodes.OrderBy(nodeEntry =>
                                      nodeEntry.State != ClusterMessages.VNodeState.Follower &&
                                      nodeEntry.State != ClusterMessages.VNodeState.Slave)
                        .ToArray();                         // OrderBy is a stable sort and only affects order of matching entries
                RandomShuffle(nodes, 0,
                              nodes.Count(nodeEntry => nodeEntry.State == ClusterMessages.VNodeState.Follower ||
                                          nodeEntry.State == ClusterMessages.VNodeState.Slave) - 1);
                break;

            case NodePreference.ReadOnlyReplica:
                nodes = nodes.OrderBy(nodeEntry => !IsReadOnlyReplicaState(nodeEntry.State))
                        .ToArray();                         // OrderBy is a stable sort and only affects order of matching entries
                RandomShuffle(nodes, 0,
                              nodes.Count(nodeEntry => IsReadOnlyReplicaState(nodeEntry.State)) - 1);
                break;
            }

            var node = nodes.FirstOrDefault();

            if (node == default(ClusterMessages.MemberInfoDto))
            {
                //_log.Info("Unable to locate suitable node. Gossip info:\n{0}.", string.Join("\n", members.Select(x => x.ToString())));
                return(null);
            }

            var normTcp = new DnsEndPoint(node.ExternalTcpIp, node.ExternalTcpPort);
            var secTcp  = node.ExternalSecureTcpPort > 0
                                ? new DnsEndPoint(node.ExternalTcpIp, node.ExternalSecureTcpPort)
                                : null;

            _log.Info("Discovering: found best choice [{0},{1}] ({2}).", normTcp,
                      secTcp == null ? "n/a" : secTcp.ToString(), node.State);
            return(new NodeEndPoints(normTcp, secTcp));
        }
Example #15
0
        public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var endPoint             = new DnsEndPoint("localhost", 27017);
            var replicaSetConfig     = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var serverId         = new ServerId(__clusterId, endPoint);
            var state            = ServerState.Connected;
            var tags             = new TagSet(new[] { new Tag("x", "a") });
            var type             = ServerType.ReplicaSetPrimary;
            var version          = new SemanticVersion(2, 6, 3);
            var wireVersionRange = new Range <int>(2, 3);

            var subject = new ServerDescription(
                serverId,
                endPoint,
                state,
                type,
                averageRoundTripTime,
                replicaSetConfig,
                tags,
                version,
                wireVersionRange);

            switch (notEqualField)
            {
            case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;

            case "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break;

            case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;

            case "State": state = ServerState.Disconnected; break;

            case "ServerId": serverId = new ServerId(new ClusterId(), endPoint); break;

            case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;

            case "Type": type = ServerType.ReplicaSetSecondary; break;

            case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;

            case "WireVersionRange": wireVersionRange = new Range <int>(0, 0); break;
            }

            var serverDescription2 = new ServerDescription(
                serverId,
                endPoint,
                state,
                type,
                averageRoundTripTime,
                replicaSetConfig,
                tags,
                version,
                wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
Example #16
0
        public void Endpoint_payload_fragment_combination_tests(
            [CombinatorialValues(AddressType.Ipv4, AddressType.Ipv6, AddressType.DomainName)] AddressType addressType,
            bool isFragment,
            bool hasPayload,
            bool testInsufficientBuffer)
        {
            EndPoint endPoint;

            byte[] expectedEndPointBytes;

            switch (addressType)
            {
            case AddressType.Ipv4:
                endPoint = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 127);
                expectedEndPointBytes = new byte[] { 1, 2, 3, 4, 0, 127 };
                break;

            case AddressType.Ipv6:
                endPoint = new IPEndPoint(IPAddress.Parse("::1"), 127);
                expectedEndPointBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 127 };
                break;

            case AddressType.DomainName:
                endPoint = new DnsEndPoint("google.com", 127);
                var addressByteCount = Encoding.ASCII.GetByteCount("google.com");
                expectedEndPointBytes = new[] { (byte)addressByteCount }
                .Concat(Encoding.ASCII.GetBytes("google.com"))
                .Concat(new byte[] { 0, 127 })
                .ToArray();
                break;

            default:
                throw new AssertionFailedException($"Unknown address type: {addressType}");
            }

            var datagram = new Datagram(
                new DatagramHeader(isFragment ? (byte)2 : (byte)0, isFragment, endPoint),
                hasPayload ? new ArraySegment <byte>(new byte[] { 1, 2, 3, 4 }) : new ArraySegment <byte>());

            // Intentional bytes of empty space before the actual space
            const int emptySpacePrefix      = 1;
            var       buffer                = new byte[emptySpacePrefix + 2 + 1 + 1 + expectedEndPointBytes.Length + datagram.Payload.Count];
            int       bufferLengthToCompare = buffer.Length - emptySpacePrefix;

            if (testInsufficientBuffer)
            {
                bufferLengthToCompare--;
                datagram
                .Invoking(d => d.WriteTo(new ArraySegment <byte>(buffer, emptySpacePrefix, bufferLengthToCompare)))
                .Should().Throw <ArgumentException>().And.Message.Should().ContainEquivalentOf("insufficient");
                return;
            }

            datagram.WriteTo(new ArraySegment <byte>(buffer, emptySpacePrefix, bufferLengthToCompare));
            var expectedBytes = Enumerable.Repeat((byte)0, emptySpacePrefix)
                                .Concat(new byte[] { 0, 0, isFragment ? (byte)130 : (byte)0, (byte)addressType })
                                .Concat(expectedEndPointBytes)
                                .Concat(datagram.Payload)
                                .ToArray();

            buffer.Should().Equal(expectedBytes);
        }
Example #17
0
 public void Connect(DnsEndPoint endpoint)
 {
     throw new NotImplementedException();
 }
Example #18
0
 public TcpClient(string host, int port)
     : this(AddressFamily.InterNetwork)
 {
     var endpoint = new DnsEndPoint(host, port);
     Connect(endpoint);
 }
Example #19
0
        internal static bool TryParse(string value, int defaultPort, out EndPoint result)
        {
            result = null;

            if (value != null)
            {
                value = value.ToLowerInvariant();
                var match = Regex.Match(value, @"^(?<address>\[[^]]+\])(:(?<port>\d+))?$");
                if (match.Success)
                {
                    var addressString = match.Groups["address"].Value;
                    var portString    = match.Groups["port"].Value;
                    var port          = defaultPort;
                    if (portString.Length != 0 && !int.TryParse(portString, out port))
                    {
                        return(false);
                    }

                    if (!IsValidPort(port))
                    {
                        return(false);
                    }

                    IPAddress address;
                    if (IPAddress.TryParse(addressString, out address))
                    {
                        result = new IPEndPoint(address, port);
                        return(true);
                    }

                    return(false);
                }

                match = Regex.Match(value, @"^(?<host>[^:]+)(:(?<port>\d+))?$");
                if (match.Success)
                {
                    var host       = match.Groups["host"].Value;
                    var portString = match.Groups["port"].Value;
                    var port       = defaultPort;
                    if (portString.Length != 0 && !int.TryParse(portString, out port))
                    {
                        return(false);
                    }

                    if (!IsValidPort(port))
                    {
                        return(false);
                    }

                    IPAddress address;
                    if (IPAddress.TryParse(host, out address))
                    {
                        result = new IPEndPoint(address, port);
                        return(true);
                    }

                    try
                    {
                        result = new DnsEndPoint(host, port);
                        return(true);
                    }
                    catch (ArgumentException)
                    {
                        return(false);
                    }
                }
            }

            return(false);
        }
Example #20
0
 public NewConnection(DnsEndPoint endpoint)
 {
     EndPoint = endpoint;
 }
Example #21
0
        public override Task <bool> OpenAsyncTask()
        {
            TaskCompletionSource <bool> retSource = new TaskCompletionSource <bool>();

            if (this.IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
            }

            if (String.IsNullOrEmpty(Host))
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
            }

            if (port <= 0)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
            }

            if (socket == null)
            {
                InitSocket();
            }


            {
                // Create DnsEndPoint. The hostName and port are passed in to this method.
                DnsEndPoint hostEntry = new DnsEndPoint(this.host, this.port);

                // Create a SocketAsyncEventArgs object to be used in the connection request
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = hostEntry;

                socketEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    if (connectHandler != null)
                    {
                        connectHandler(this, e);
                    }
                    if (e.SocketError == SocketError.Success)
                    {
                        retSource.SetResult(true);
                    }
                    else
                    {
                        retSource.SetException(new TTransportException(e.SocketError.ToString()));
                    }
                });


                // Make an asynchronous Connect request over the socket
                if (!socket.ConnectAsync(socketEventArg))
                {
                    if (socketEventArg.SocketError == SocketError.Success)
                    {
                        retSource.SetResult(true);
                    }
                    else
                    {
                        retSource.SetException(new TTransportException(socketEventArg.SocketError.ToString()));
                    }
                }
            }

            return(retSource.Task);
        }
Example #22
0
        public static async Task <Socket> ConnectSocksAsync(EndPoint socksEndpoint, DnsEndPoint endpoint, CancellationToken cancellation)
        {
            Socket s        = null;
            int    maxTries = 3;
            int    retry    = 0;

            try
            {
                while (true)
                {
                    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    await s.ConnectAsync(socksEndpoint).WithCancellation(cancellation).ConfigureAwait(false);

                    NetworkStream stream = new NetworkStream(s, false);

                    await stream.WriteAsync(SelectionMessage, 0, SelectionMessage.Length, cancellation).ConfigureAwait(false);

                    await stream.FlushAsync(cancellation).ConfigureAwait(false);

                    var selectionResponse = new byte[2];
                    await stream.ReadAsync(selectionResponse, 0, 2, cancellation);

                    if (selectionResponse[0] != 5)
                    {
                        throw new SocksException("Invalid version in selection reply");
                    }
                    if (selectionResponse[1] != 0)
                    {
                        throw new SocksException("Unsupported authentication method in selection reply");
                    }

                    var connectBytes = CreateConnectMessage(endpoint.Host, endpoint.Port);
                    await stream.WriteAsync(connectBytes, 0, connectBytes.Length, cancellation).ConfigureAwait(false);

                    await stream.FlushAsync(cancellation).ConfigureAwait(false);

                    var connectResponse = new byte[10];
                    await stream.ReadAsync(connectResponse, 0, 10, cancellation);

                    if (connectResponse[0] != 5)
                    {
                        throw new SocksException("Invalid version in connect reply");
                    }
                    if (connectResponse[1] != 0)
                    {
                        var code = (SocksErrorCode)connectResponse[1];
                        if (!IsTransient(code) || retry++ >= maxTries)
                        {
                            throw new SocksException(code);
                        }
                        CloseSocket(ref s);
                        await Task.Delay(1000, cancellation).ConfigureAwait(false);

                        continue;
                    }
                    if (connectResponse[2] != 0)
                    {
                        throw new SocksException("Invalid RSV in connect reply");
                    }
                    if (connectResponse[3] != 1)
                    {
                        throw new SocksException("Invalid ATYP in connect reply");
                    }
                    for (int i = 4; i < 4 + 4; i++)
                    {
                        if (connectResponse[i] != 0)
                        {
                            throw new SocksException("Invalid BIND address in connect reply");
                        }
                    }

                    if (connectResponse[8] != 0 || connectResponse[9] != 0)
                    {
                        throw new SocksException("Invalid PORT address connect reply");
                    }
                    return(s);
                }
            }
            catch
            {
                CloseSocket(ref s);
                throw;
            }
        }
Example #23
0
        [Fact] // Base case
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_ReceiveMessageFromDnsEndPoint_Throws()
        {
            using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                EndPoint receivedFrom = new DnsEndPoint("localhost", TestPortBase + 231, AddressFamily.InterNetworkV6);
                socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, TestPortBase + 231));
                SocketFlags socketFlags = SocketFlags.None;
                IPPacketInformation ipPacketInformation;

                Assert.Throws<ArgumentException>(() =>
                {
                    int received = socket.ReceiveMessageFrom(new byte[1], 0, 1, ref socketFlags, ref receivedFrom, out ipPacketInformation);
                });
            }
        }
Example #24
0
 /// <summary>
 /// Initialize TCP client with a given DNS endpoint
 /// </summary>
 /// <param name="endpoint">DNS endpoint</param>
 public TcpClient(DnsEndPoint endpoint) : this(endpoint as EndPoint, endpoint.Host, endpoint.Port)
 {
 }
Example #25
0
        private static readonly byte[] EndPointPortKey = { 0x65 }; // 'e'

        /// <summary>
        /// Initializes a new instance of the <see cref="BoundPeer"/> class.
        /// </summary>
        /// <param name="publicKey">A <see cref="PublicKey"/> of the
        /// <see cref="Peer"/>.</param>
        /// <param name="endPoint">A <see cref="DnsEndPoint"/> consisting of the
        /// host and port of the <see cref="Peer"/>.</param>
        public BoundPeer(
            PublicKey publicKey,
            DnsEndPoint endPoint)
            : this(publicKey, endPoint, null)
        {
        }
Example #26
0
 public static Uri ToUri(this DnsEndPoint self, ProtocolType protocol)
 {
     return(new Uri($"{protocol}://{self.Host}:{self.Port}"));
 }
 public static IPEndPoint ToIPEndPoint(this DnsEndPoint dnsEndPoint) => new IPEndPoint(Dns.GetHostAddresses(dnsEndPoint.Host)[0], dnsEndPoint.Port);
        private (IConnectionPool, FailPoint, ICluster, Func <object, bool>) SetupConnectionData(BsonDocument test, EventCapturer eventCapturer, bool isUnit)
        {
            ParseSettings(test, out var connectionPoolSettings, out var connectionSettings);

            IConnectionPool     connectionPool;
            ICluster            cluster      = null;
            FailPoint           failPoint    = null;
            Func <object, bool> eventsFilter = _ => true;

            if (isUnit)
            {
                var endPoint = new DnsEndPoint("localhost", 27017);
                var serverId = new ServerId(new ClusterId(), endPoint);

                var connectionFactory          = new Mock <IConnectionFactory>();
                var connectionExceptionHandler = new Mock <IConnectionExceptionHandler>();

                connectionFactory
                .Setup(c => c.CreateConnection(serverId, endPoint))
                .Returns(() =>
                {
                    var connection = new MockConnection(serverId, connectionSettings, eventCapturer);
                    return(connection);
                });

                connectionPool = new ExclusiveConnectionPool(
                    serverId,
                    endPoint,
                    connectionPoolSettings,
                    connectionFactory.Object,
                    eventCapturer,
                    connectionExceptionHandler.Object);

                connectionPool.Initialize();
            }
            else
            {
                var async = test.GetValue(Schema.async).ToBoolean();
                cluster = CoreTestConfiguration.CreateCluster(b => b
                                                              .ConfigureServer(s => s.With(
                                                                                   heartbeatInterval: TimeSpan.FromMinutes(10)))
                                                              .ConfigureConnectionPool(c => c.With(
                                                                                           maxConnecting: connectionPoolSettings.MaxConnecting,
                                                                                           maxConnections: connectionPoolSettings.MaxConnections,
                                                                                           minConnections: connectionPoolSettings.MinConnections,
                                                                                           maintenanceInterval: connectionPoolSettings.MaintenanceInterval,
                                                                                           waitQueueTimeout: connectionPoolSettings.WaitQueueTimeout))
                                                              .ConfigureConnection(s => s.With(applicationName: $"{connectionSettings.ApplicationName}_async_{async}"))
                                                              .Subscribe(eventCapturer));

                var server = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None);
                connectionPool = server._connectionPool();

                if (test.TryGetValue(Schema.Intergration.failPoint, out var failPointDocument))
                {
                    if (failPointDocument.AsBsonDocument.Contains("data"))
                    {
                        var data = failPointDocument["data"].AsBsonDocument;
                        if (data.TryGetValue("appName", out var appNameValue))
                        {
                            data["appName"] = $"{appNameValue}_async_{async}";
                        }
                    }

                    var resetPool = connectionPoolSettings.MinConnections > 0;

                    if (resetPool)
                    {
                        eventCapturer.WaitForOrThrowIfTimeout(events => events.Any(e => e is ConnectionCreatedEvent), TimeSpan.FromMilliseconds(500));

                        var connectionIdsToIgnore = new HashSet <int>(eventCapturer.Events
                                                                      .OfType <ConnectionCreatedEvent>()
                                                                      .Select(c => c.ConnectionId.LocalValue)
                                                                      .ToList());

                        eventsFilter = o =>
                        {
                            if (o is ConnectionOpenedEvent
                                or ConnectionClosedEvent
                                or ConnectionCreatedEvent
                                or ConnectionFailedEvent)
                            {
                                var connectionId = o.ConnectionId();
                                return(!connectionIdsToIgnore.Contains(connectionId.LocalValue) &&
                                       EndPointHelper.Equals(connectionId.ServerId.EndPoint, server.EndPoint));
                            }

                            if (o is ConnectionPoolReadyEvent
                                or ConnectionPoolClearedEvent)
                            {
                                var serverId = o.ServerId();
                                return(EndPointHelper.Equals(serverId.EndPoint, server.EndPoint));
                            }

                            return(true);
                        };

                        connectionPool.Clear(closeInUseConnections: false);
                        eventCapturer.WaitForOrThrowIfTimeout(events => events.Any(e => e is ConnectionPoolClearedEvent), TimeSpan.FromMilliseconds(500));
                    }

                    var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), default);
                    failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointDocument.AsBsonDocument);

                    if (resetPool)
                    {
                        eventCapturer.Clear();
                        connectionPool.SetReady();
                    }
                }
            }

            return(connectionPool, failPoint, cluster, eventsFilter);
        }
Example #29
0
 /// <summary>
 /// Converts provided endpoint to <see cref="IDnsEndPoint"/>.
 /// </summary>
 /// <param name="endPoint">Endpoint to convert.</param>
 /// <returns>Converted endpoint.</returns>
 public static IDnsEndPoint ToInterface(this DnsEndPoint endPoint)
 {
     return((endPoint == null) ? null : new DnsEndPointAdapter(endPoint));
 }
Example #30
0
        public override async Task <(Address, TaskCompletionSource <IAssociationEventListener>)> Listen()
        {
            EndPoint  listenAddress;
            IPAddress ip;

            if (IPAddress.TryParse(Settings.Hostname, out ip))
            {
                listenAddress = new IPEndPoint(ip, Settings.Port);
            }
            else
            {
                listenAddress = new DnsEndPoint(Settings.Hostname, Settings.Port);
            }

            try
            {
                var newServerChannel = await NewServer(listenAddress).ConfigureAwait(false);

                // Block reads until a handler actor is registered
                // no incoming connections will be accepted until this value is reset
                // it's possible that the first incoming association might come in though
                newServerChannel.Configuration.AutoRead = false;
                ConnectionGroup.TryAdd(newServerChannel);
                ServerChannel = newServerChannel;

                var addr = MapSocketToAddress(
                    socketAddress: (IPEndPoint)newServerChannel.LocalAddress,
                    schemeIdentifier: SchemeIdentifier,
                    systemName: System.Name,
                    hostName: Settings.PublicHostname,
                    publicPort: Settings.PublicPort);

                if (addr == null)
                {
                    throw new ConfigurationException($"Unknown local address type {newServerChannel.LocalAddress}");
                }

                LocalAddress = addr;
                // resume accepting incoming connections
#pragma warning disable 4014 // we WANT this task to run without waiting
                AssociationListenerPromise.Task.ContinueWith(result => newServerChannel.Configuration.AutoRead = true,
                                                             TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
#pragma warning restore 4014


                return(addr, AssociationListenerPromise);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to bind to {0}; shutting down DotNetty transport.", listenAddress);
                try
                {
                    await Shutdown().ConfigureAwait(false);
                }
                catch
                {
                    // ignore errors occurring during shutdown
                }
                throw;
            }
        }
        public void Equals_should_return_false_when_any_field_is_not_equal(string notEqualField)
        {
            var averageRoundTripTime = TimeSpan.FromSeconds(1);
            var canonicalEndPoint    = new DnsEndPoint("localhost", 27017);
            var electionId           = new ElectionId(ObjectId.GenerateNewId());
            var endPoint             = new DnsEndPoint("localhost", 27017);
            var helloOk               = false;
            var lastUpdateTimestamp   = DateTime.UtcNow;
            var logicalSessionTimeout = TimeSpan.FromMinutes(1);
            var replicaSetConfig      = new ReplicaSetConfig(
                new[] { new DnsEndPoint("localhost", 27017), new DnsEndPoint("localhost", 27018) },
                "name",
                new DnsEndPoint("localhost", 27017),
                1);
            var serverId         = new ServerId(__clusterId, endPoint);
            var state            = ServerState.Connected;
            var tags             = new TagSet(new[] { new Tag("x", "a") });
            var type             = ServerType.ReplicaSetPrimary;
            var version          = new SemanticVersion(3, 6, 0);
            var wireVersionRange = new Range <int>(6, 14);

            var subject = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            switch (notEqualField)
            {
            case "AverageRoundTripTime": averageRoundTripTime = averageRoundTripTime.Add(TimeSpan.FromSeconds(1)); break;

            case "CanonicalEndPoint": canonicalEndPoint = new DnsEndPoint("localhost", 27018); break;

            case "ElectionId": electionId = new ElectionId(ObjectId.Empty); break;

            case "EndPoint": endPoint = new DnsEndPoint(endPoint.Host, endPoint.Port + 1); serverId = new ServerId(__clusterId, endPoint); break;

            case "HelloOk": helloOk = !helloOk; break;

            case "LogicalSessionTimeout": logicalSessionTimeout = TimeSpan.FromMinutes(2); break;

            case "ReplicaSetConfig": replicaSetConfig = new ReplicaSetConfig(replicaSetConfig.Members, "newname", replicaSetConfig.Primary, replicaSetConfig.Version); break;

            case "State": state = ServerState.Disconnected; break;

            case "ServerId": serverId = new ServerId(new ClusterId(), endPoint); break;

            case "Tags": tags = new TagSet(new[] { new Tag("x", "b") }); break;

            case "Type": type = ServerType.ReplicaSetSecondary; break;

            case "Version": version = new SemanticVersion(version.Major, version.Minor, version.Patch + 1); break;

            case "WireVersionRange": wireVersionRange = new Range <int>(0, 0); break;
            }

            var serverDescription2 = new ServerDescription(
                serverId,
                endPoint,
                state: state,
                type: type,
                averageRoundTripTime: averageRoundTripTime,
                canonicalEndPoint: canonicalEndPoint,
                electionId: electionId,
                helloOk: helloOk,
                lastUpdateTimestamp: lastUpdateTimestamp,
                logicalSessionTimeout: logicalSessionTimeout,
                replicaSetConfig: replicaSetConfig,
                tags: tags,
                version: version,
                wireVersionRange: wireVersionRange);

            subject.Equals(serverDescription2).Should().BeFalse();
            subject.Equals((object)serverDescription2).Should().BeFalse();
            subject.GetHashCode().Should().NotBe(serverDescription2.GetHashCode());
        }
Example #32
0
 private bool IsValidHost(DnsEndPoint endPoint)
 {
     return(ConnectionString.HasValidParentDomain(_lookupDomainName, endPoint));
 }
 // static constructor
 static ServerDescriptionTests()
 {
     __clusterId = new ClusterId();
     __endPoint  = new DnsEndPoint("localhost", 27017);
     __serverId  = new ServerId(__clusterId, __endPoint);
 }
Example #34
0
 public void Socket_ReceiveFromDnsEndPoint_Throws()
 {
     // "The parameter remoteEP must not be of type DnsEndPoint."
     using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
     {
         int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback);
         EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6);
         Assert.Throws<ArgumentException>(() =>
         {
             int received = socket.ReceiveFrom(new byte[1], ref receivedFrom);
         });
     }
 }
Example #35
0
 public void Connect(string host, int port)
 {
     var endpoint = new DnsEndPoint(host, port);
     Connect(endpoint);
 }
Example #36
0
        static byte[] Encode(DnsEndPoint ep)
        {
            string dns = ep.DNS.ToLowerInvariant ();

            for (int i = 0; i < dns.Length; i ++) {
                char c = dns[i];
                if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '.' || c == '-')
                    continue;
                throw new FormatException ();
            }

            dns = Compress (dns);
            byte[] raw = new byte[dns.Length];
            for (int i = 0; i < dns.Length; i ++)
                raw[i] = DNS_MAP[dns[i]];
            raw = Compress (raw);

            raw = new byte[]{TYPE_DNS}.Join (raw, new byte[] {
                (byte)(ep.Port >> 8), (byte)(ep.Port & 0xFF)
            });
            return raw;
        }
Example #37
0
 /// <summary>
 /// Creates a new instance of <see cref="QueryManager"/>.
 /// </summary>
 /// <param name="log">An instance of <see cref="ILogger"/> to use for logging.</param>
 /// <param name="dnsHttpEndPoint">HTTP DNS endpoint of an Event Store server.</param>
 /// <param name="projectionOperationTimeout">Timeout of projection API operations</param>
 /// <param name="queryTimeout">Timeout of query execution</param>
 /// <param name="clienthandler">Overideable HTTP Client Handler</param>
 public QueryManager(ILogger log, DnsEndPoint dnsHttpEndPoint, TimeSpan projectionOperationTimeout, TimeSpan queryTimeout, HttpClientHandler clienthandler = null)
 {
     _queryTimeout       = queryTimeout;
     _projectionsManager = new ProjectionsManager(log, dnsHttpEndPoint, projectionOperationTimeout, clienthandler);
 }
Example #38
0
 public NsqTcpConnection(DnsEndPoint endPoint, ConsumerOptions options)
     : this(endPoint, options, new ExponentialBackoffStrategy(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30)))
 {
 }
Example #39
0
        [Fact] // Base case
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_BeginReceiveFromDnsEndPoint_Throws()
        {
            using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                EndPoint receivedFrom = new DnsEndPoint("localhost", TestPortBase + 211, AddressFamily.InterNetworkV6);
                socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, TestPortBase + 211));

                Assert.Throws<ArgumentException>(() =>
                {
                    socket.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref receivedFrom, null, null);
                });
            }
        }
Example #40
0
 public static Task <int> SendAsync(this UdpClient udpClient, byte[] datagram, DnsEndPoint dnsEndPoint)
 {
     if (udpClient == null)
     {
         throw new ArgumentNullException("udpClient");
     }
     if (dnsEndPoint == null)
     {
         throw new ArgumentNullException("dnsEndPoint");
     }
     return(udpClient.SendAsync(datagram, datagram.Length, dnsEndPoint.Host, dnsEndPoint.Port));
 }
Example #41
0
 public NetworkStreamFactory(DnsEndPoint endPoint, int networkTimeout = DefaultTimeout)
 {
     EndPoint       = endPoint;
     NetworkTimeout = networkTimeout;
 }
Example #42
0
 public SrvRecord(DnsEndPoint endPoint, TimeSpan timeToLive)
 {
     EndPoint   = Ensure.IsNotNull(endPoint, nameof(endPoint));
     TimeToLive = timeToLive;
 }
Example #43
0
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_BeginReceiveMessageFromDnsEndPoint_Throws()
        {
            using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback);

                EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6);
                SocketFlags socketFlags = SocketFlags.None;
                Assert.Throws<ArgumentException>(() =>
                {
                    socket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null);
                });
            }
        }
 internal SocketsHttpConnectionContext(DnsEndPoint dnsEndPoint, HttpRequestMessage initialRequestMessage)
 {
     _dnsEndPoint           = dnsEndPoint;
     _initialRequestMessage = initialRequestMessage;
 }