示例#1
0
        private void HandshakeReceive()
        {
            try
            {
                var bytesRead = _firstPacketLength;

                if (bytesRead > 1)
                {
                    if ((!string.IsNullOrEmpty(_config.AuthUser) || IPSubnet.IsLoopBack(((IPEndPoint)_connection.RemoteEndPoint).Address)) &&
                        _firstPacket[0] == 4 && _firstPacketLength >= 9)
                    {
                        RspSocks4aHandshakeReceive();
                    }
                    else if (_firstPacket[0] == 5 && _firstPacketLength >= 3)
                    {
                        RspSocks5HandshakeReceive();
                    }
                    else
                    {
                        RspHttpHandshakeReceive();
                    }
                }
                else
                {
                    Close();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
示例#2
0
        public static void Test()
        {
            IPSubnet ipRange = new IPSubnet("10.10.10.0", 24);

            Console.WriteLine(ipRange.NetworkAddress);
            Console.WriteLine(ipRange.BroadcastAddress);
            ipRange.setRandom(false);
            int count = (int)ipRange.size();

            ArrayList list = new ArrayList();


            foreach (String ip in ipRange)
            {
                //System.Console.Out.WriteLine(ip);
                list.Add(ip);
                if (--count == 0)
                {
                    break;
                }
            }

            IPAddressList ipList = new IPAddressList(list);

            ipList.setRandom(false);
            count = (int)ipList.size();
            foreach (String ip in ipList)
            {
                System.Console.Out.WriteLine(ip);
                if (--count == 0)
                {
                    break;
                }
            }
        }
示例#3
0
 public void IsLoopBackTest()
 {
     Assert.IsTrue(IPSubnet.IsLoopBack(IPAddress.Loopback));
     Assert.IsTrue(IPSubnet.IsLoopBack(IPAddress.IPv6Loopback));
     Assert.IsTrue(IPSubnet.IsLoopBack(IPAddress.Parse(@"127.0.0.255")));
     Assert.IsTrue(IPSubnet.IsLoopBack(IPAddress.Parse(@"127.255.255.255")));
     Assert.IsFalse(IPSubnet.IsLoopBack(IPAddress.Parse(@"192.168.1.1")));
     Assert.IsFalse(IPSubnet.IsLoopBack(IPAddress.Parse(@"2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")));
 }
示例#4
0
        /// <summary>
        /// Create IPSubnet instance.
        /// </summary>
        /// <returns>IPSubnet instance.</returns>
        private IPSubnet CreateDefaultIPSubnet()
        {
            var ipSubnet = new IPSubnet {
                AddressFamily  = HNVODLConstants.IP_SUBNET.ADDRESS_FAMILY, Id = HNVODLConstants.IP_SUBNET.ID,
                IPAddressPools = null, LastModifiedTimeStamp = DateTime.Now, Subnet = HNVODLConstants.IP_SUBNET.SUBNET,
                SupportsDHCP   = HNVODLConstants.IP_SUBNET.SUPPORTS_DHCP
            };

            return(ipSubnet);
        }
示例#5
0
 private bool AuthConnection(string authUser, string authPass)
 {
     if (string.IsNullOrEmpty(_config.AuthUser))
     {
         return(true);
     }
     if (_config.AuthUser == authUser && _config.AuthPass == authPass)
     {
         return(true);
     }
     return(IPSubnet.IsLoopBack(((IPEndPoint)_connection.RemoteEndPoint).Address));
 }
示例#6
0
 private bool AuthConnection(string authUser, string authPass)
 {
     if ((_config.AuthUser ?? string.Empty).Length == 0)
     {
         return(true);
     }
     if (_config.AuthUser == authUser && (_config.AuthPass ?? "") == authPass)
     {
         return(true);
     }
     return(IPSubnet.IsLoopBack(((IPEndPoint)_connection.RemoteEndPoint).Address));
 }
示例#7
0
        public static void Test()
        {
            IPSubnet ipRange = new IPSubnet("10.10.10.0", 24);

            Console.WriteLine(ipRange.NetworkAddress);
            Console.WriteLine(ipRange.BroadcastAddress);
            ipRange.setRandom(false);

            foreach (System.Net.IPAddress ip in ipRange)
            {
                System.Console.Out.WriteLine(ip);
            }
        }
示例#8
0
        private void RspSocks5HandshakeReceive()
        {
            byte[] response = { 5, 0 };
            if (_firstPacket[0] != 5)
            {
                response = new byte[] { 0, 91 };
                Console.WriteLine(@"socks 4/5 protocol error");
                _connection.Send(response);
                Close();
                return;
            }

            var auth       = false;
            var has_method = false;

            for (var index = 0; index < _firstPacket[1]; ++index)
            {
                if (_firstPacket[2 + index] == 0)
                {
                    has_method = true;
                }
                else if (_firstPacket[2 + index] == 2)
                {
                    auth       = true;
                    has_method = true;
                }
            }
            if (!has_method)
            {
                Console.WriteLine(@"Socks5 no acceptable auth method");
                Close();
                return;
            }
            if (auth)
            {
                response[1] = 2;
                _connection.BeginSend(response, 0, response.Length, SocketFlags.None, HandshakeAuthSendCallback, null);
            }
            else if (string.IsNullOrEmpty(_config.AuthUser) ||
                     IPSubnet.IsLoopBack(((IPEndPoint)_connection.RemoteEndPoint).Address))
            {
                _connection.BeginSend(response, 0, response.Length, SocketFlags.None, HandshakeSendCallback, null);
            }
            else
            {
                Console.WriteLine(@"Socks5 Auth failed");
                Close();
            }
        }
示例#9
0
        /// <summary>
        /// Validates the IP Subnet.
        /// AddressRangeStart less than AddressRangeEnd.
        /// AddressRangeStart,AddressRangeEnd,networkGateway.IPAddress lie in subnet logically.
        /// All of them exists and are valid IP Addresses.
        /// networkGateway is optional.
        /// </summary>
        /// <param name="subnet">IP address pool to validate.</param>
        /// <param name="id">IP address pool ID.</param>
        /// <returns>Error message.</returns>
        private static string IsIPSubnetValid(IPSubnet subnet, Guid id)
        {
            StringBuilder isvalid = new StringBuilder();

            if (subnet == null ||
                subnet.IPAddressPools == null ||
                subnet.IPAddressPools.Count() == 0)
            {
                return(isvalid.ToString());
            }

            if (id == Guid.Empty)
            {
                foreach (IPAddressPool pool in subnet.IPAddressPools)
                {
                    isvalid.Append(IsIPAddressPoolValid(pool));
                    if (!string.IsNullOrEmpty(isvalid.ToString()))
                    {
                        return(isvalid.ToString());
                    }
                    if (subnet.IPAddressPools.Any(poolCheck => pool.Id != poolCheck.Id &&
                                                  AreIPAddressPoolsOverlapping(pool, poolCheck)))
                    {
                        isvalid.Append("The range specified for the static IP address pool overlaps with the range of address managed by an existing static IP address pool.");
                        return(isvalid.ToString());
                    }
                }
            }
            else
            {
                isvalid.Append(IsIPAddressPoolValid(subnet.IPAddressPools.FirstOrDefault(pool =>
                                                                                         pool.Id == id)));
                if (!string.IsNullOrEmpty(isvalid.ToString()))
                {
                    return(isvalid.ToString());
                }
                if (subnet.IPAddressPools.Any(poolCheck => AreIPAddressPoolsOverlapping(
                                                  subnet.IPAddressPools.FirstOrDefault(pool => pool.Id == id),
                                                  poolCheck) &&
                                              id != poolCheck.Id))
                {
                    isvalid.Append("The range specified for the static IP address pool overlaps with the range of address managed by an existing static IP address pool.");
                    return(isvalid.ToString());
                }
            }
            return(isvalid.ToString());
        }
示例#10
0
 public void Start(Configuration config, byte[] firstPacket, int length, Socket socket, int targetPort)
 {
     _config            = config;
     _firstPacket       = firstPacket;
     _firstPacketLength = length;
     _local             = socket;
     _targetPort        = targetPort;
     if ((_config.AuthUser ?? string.Empty).Length == 0 ||
         IPSubnet.IsLoopBack(((IPEndPoint)_local.RemoteEndPoint).Address))
     {
         Connect();
     }
     else
     {
         RspHttpHandshakeReceive();
     }
 }
示例#11
0
        public static void TryCollectionToString()
        {
            List <IPSubnet> subnets = new List <IPSubnet>();

            for (int i = 0; i < 6; i++)
            {
                IPSubnet subnet = new IPSubnet();
                subnet.Name      = $"SubnetName{i}";
                subnet.IPAddress = System.Net.IPAddress.Parse($"10.0.0.{i}");
                subnet.Prefix    = 2;
                subnets.Add(subnet);
            }

            Console.WriteLine($"Subnets: {collectionToString(subnets)}");

            List <IPSubnet> subnetsEmpty = new List <IPSubnet>();

            Console.WriteLine($"Empty Subnets: {collectionToString(subnetsEmpty)}");
        }
示例#12
0
 private void RspHttpHandshakeReceive()
 {
     _command = 1; // Set TCP connect command
     if (httpProxyState == null)
     {
         httpProxyState = new HttpParser();
     }
     if (IPSubnet.IsLoopBack(((IPEndPoint)_connection.RemoteEndPoint).Address))
     {
         httpProxyState.httpAuthUser = string.Empty;
         httpProxyState.httpAuthPass = string.Empty;
     }
     else
     {
         httpProxyState.httpAuthUser = _config.AuthUser;
         httpProxyState.httpAuthPass = _config.AuthPass;
     }
     for (var i = 1; ; ++i)
     {
         var err = httpProxyState.HandshakeReceive(_firstPacket, _firstPacketLength, out _remoteHeaderSendBuffer);
         if (err == 1)
         {
             if (HttpHandshakeRecv())
             {
                 break;
             }
         }
         else if (err == 2)
         {
             var dataSend = HttpParser.Http407();
             var httpData = Encoding.UTF8.GetBytes(dataSend);
             _connection.Send(httpData);
             if (HttpHandshakeRecv())
             {
                 break;
             }
         }
         else if (err is 3 or 4)
         {
             Connect();
             break;
         }
示例#13
0
        /// <summary>
        /// Validates the IP Subnet.
        /// AddressRangeStart less than AddressRangeEnd.
        /// AddressRangeStart,AddressRangeEnd,networkGateway.IPAddress lie in subnet logically.
        /// All of them exists and are valid IP Addresses.
        /// networkGateway is optional.
        /// </summary>
        /// <param name="subnet">IP address pool to validate.</param>
        /// <param name="id">IP address pool ID.</param>
        /// <returns>Error message.</returns>
        private static string IsIPSubnetValid(IPSubnet subnet, Guid id)
        {
            StringBuilder isvalid = new StringBuilder();
            if (subnet == null
                || subnet.IPAddressPools == null
                || subnet.IPAddressPools.Count() == 0) {
                return isvalid.ToString();
            }

            if (id == Guid.Empty) {
                foreach (IPAddressPool pool in subnet.IPAddressPools) {
                    isvalid.Append(IsIPAddressPoolValid(pool));
                    if (!string.IsNullOrEmpty(isvalid.ToString())) {
                        return isvalid.ToString();
                    }
                    if (subnet.IPAddressPools.Any(poolCheck => pool.Id != poolCheck.Id
                        && AreIPAddressPoolsOverlapping(pool, poolCheck))) {
                        isvalid.Append("The range specified for the static IP address pool overlaps with the range of address managed by an existing static IP address pool.");
                        return isvalid.ToString();
                    }
                }
            } else {
                isvalid.Append(IsIPAddressPoolValid(subnet.IPAddressPools.FirstOrDefault(pool =>
                    pool.Id == id)));
                if (!string.IsNullOrEmpty(isvalid.ToString())) {
                    return isvalid.ToString();
                }
                if (subnet.IPAddressPools.Any(poolCheck => AreIPAddressPoolsOverlapping(
                    subnet.IPAddressPools.FirstOrDefault(pool => pool.Id == id),
                    poolCheck)
                    && id != poolCheck.Id)) {
                    isvalid.Append("The range specified for the static IP address pool overlaps with the range of address managed by an existing static IP address pool.");
                    return isvalid.ToString();
                }
            }
            return isvalid.ToString();
        }
示例#14
0
        private int IsHandle(byte[] firstPacket, int length)
        {
            if (length >= 7 && _config.proxyRuleMode != ProxyRuleMode.Disable)
            {
                IPAddress ipAddress = null;
                if (firstPacket[0] == 1)
                {
                    var addr = new byte[4];
                    Array.Copy(firstPacket, 1, addr, 0, addr.Length);
                    ipAddress = new IPAddress(addr);
                }
                else if (firstPacket[0] == 3)
                {
                    int len  = firstPacket[1];
                    var addr = new byte[len];
                    if (length >= len + 2)
                    {
                        Array.Copy(firstPacket, 2, addr, 0, addr.Length);
                        var host = Encoding.UTF8.GetString(firstPacket, 2, len);
                        if (IPAddress.TryParse(host, out ipAddress))
                        {
                            //pass
                        }
                        else
                        {
                            if ((_config.proxyRuleMode == ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null || _config.proxyRuleMode == ProxyRuleMode.UserCustom)
                            {
                                if (!IPAddress.TryParse(host, out ipAddress))
                                {
                                    if (_config.proxyRuleMode == ProxyRuleMode.UserCustom)
                                    {
                                        var hostMap = HostMap.Instance();
                                        if (hostMap.GetHost(host, out var host_addr))
                                        {
                                            if (!string.IsNullOrEmpty(host_addr))
                                            {
                                                var lower_host_addr = host_addr.ToLower();
                                                if (lower_host_addr.StartsWith("reject") ||
                                                    lower_host_addr.StartsWith("direct")
                                                    )
                                                {
                                                    return(CONNECT_DIRECT);
                                                }

                                                if (lower_host_addr.StartsWith("localproxy"))
                                                {
                                                    return(CONNECT_LOCALPROXY);
                                                }

                                                if (lower_host_addr.StartsWith("remoteproxy"))
                                                {
                                                    return(CONNECT_REMOTEPROXY);
                                                }

                                                if (lower_host_addr.IndexOf('.') >= 0 || lower_host_addr.IndexOf(':') >= 0)
                                                {
                                                    if (!IPAddress.TryParse(lower_host_addr, out ipAddress))
                                                    {
                                                        //
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (ipAddress == null)
                                    {
                                        ipAddress = DnsUtil.DnsBuffer.Get(host);
                                    }
                                }
                                if (ipAddress == null)
                                {
                                    ipAddress = DnsUtil.QueryDns(host, host.IndexOf('.') >= 0 ? _config.dnsServer : null);
                                    if (ipAddress != null)
                                    {
                                        DnsUtil.DnsBuffer.Set(host, new IPAddress(ipAddress.GetAddressBytes()));
                                        if (host.IndexOf('.') >= 0)
                                        {
                                            if (IPSubnet.IsLan(ipAddress)) // assume that it is polution if return LAN address
                                            {
                                                return(CONNECT_REMOTEPROXY);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Logging.Log(LogLevel.Debug, "DNS query fail: " + host);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (firstPacket[0] == 4)
                {
                    var addr = new byte[16];
                    Array.Copy(firstPacket, 1, addr, 0, addr.Length);
                    ipAddress = new IPAddress(addr);
                }
                if (ipAddress != null)
                {
                    if (_config.proxyRuleMode == ProxyRuleMode.UserCustom)
                    {
                        var hostMap = HostMap.Instance();
                        if (hostMap.GetIP(ipAddress, out var host_addr))
                        {
                            var lower_host_addr = host_addr.ToLower();
                            if (lower_host_addr.StartsWith("reject") ||
                                lower_host_addr.StartsWith("direct")
                                )
                            {
                                return(CONNECT_DIRECT);
                            }

                            if (lower_host_addr.StartsWith("localproxy"))
                            {
                                return(CONNECT_LOCALPROXY);
                            }

                            if (lower_host_addr.StartsWith("remoteproxy"))
                            {
                                return(CONNECT_REMOTEPROXY);
                            }
                        }
                    }
                    else
                    {
                        if (IPSubnet.IsLan(ipAddress))
                        {
                            return(CONNECT_DIRECT);
                        }
                        if ((_config.proxyRuleMode == ProxyRuleMode.BypassLanAndChina || _config.proxyRuleMode == ProxyRuleMode.BypassLanAndNotChina) && _IPRange != null &&
                            ipAddress.AddressFamily == AddressFamily.InterNetwork
                            )
                        {
                            if (_IPRange.IsInIPRange(ipAddress))
                            {
                                return(CONNECT_LOCALPROXY);
                            }
                            DnsUtil.DnsBuffer.Sweep();
                        }
                    }
                }
            }
            return(CONNECT_REMOTEPROXY);
        }
        /// <summary>
        /// Create a VM Subnet for the specified vBridge.
        /// </summary>
        /// <param name="vmNetworkId">Id of VM network this definition belongs to.</param>
        /// <param name="maxNumberOfPorts">Max number of ports.</param>
        /// <param name="ipSubnet">IP address pool to use.</param>
        /// <param name="name">Name for VM Subnet. If null, use the vBridge name.
        /// </param>
        /// <param name="logicalNetworkDefinitionId">Logical network definition ID to use.</param>
        /// <param name="vbrName">Vbridge name to use.</param>
        /// <param name="vlanId">Vlan ID to use.</param>
        /// <returns>VM Subnet.</returns>
        public static VMSubnet CreateVbrVmNetworkDefinition(Guid vmNetworkId,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnet,
            string name,
            Guid? logicalNetworkDefinitionId,
            string vbrName,
            long vlanId)
        {
            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");
                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }
            if (vmNetworkId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vmNetworkId' is null or invalid.");
                throw new ArgumentException("The parameter 'vmNetworkId' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (string.IsNullOrEmpty(vbrName)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vbrName' is null or invalid.");
                throw new ArgumentException("The parameter 'vbrName' is null or invalid.");
            }
            VMSubnet def = new VMSubnet();
            def.Id = Guid.NewGuid();

            def.Name = name;
            ODLVSEMETW.EventWriteValidateCreateVmNetworkDefinitionForvBr(
                MethodBase.GetCurrentMethod().Name,
                "VM Subnet for vBridge.");
            def.Description = string.Format(CultureInfo.CurrentCulture,
                "VM Subnet for vBridge {0}",
                vbrName);
            def.LogicalNetworkDefinitionId = logicalNetworkDefinitionId;
            def.VMNetworkId = vmNetworkId;
            def.AllowsIntraPortCommunication = true;
            def.IsolationType = NetworkDefinitionIsolationType.Vlan;
            if (ipSubnet != null) {
                for (int cntr = 0; cntr < ipSubnet.Count(); cntr++) {
                    if (ipSubnet[cntr].Id == Guid.Empty && !string.IsNullOrEmpty(ipSubnet[cntr].Subnet)) {
                        ipSubnet[cntr].Id = Guid.NewGuid();
                        ipSubnet[cntr].LastModifiedTimeStamp = DateTime.Now;
                    }
                    if (ipSubnet[cntr].IPAddressPools == null) {
                        ipSubnet[cntr].IPAddressPools = new IPAddressPool[0];
                    }
                }

                def.IPSubnets = ipSubnet;

                string error = Validations.IsIPSubnetListValid(
                    def.IPSubnets.ToList(), Guid.Empty);
                if (!string.IsNullOrEmpty(error)) {
                    ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                        MethodBase.GetCurrentMethod().Name,
                        error);
                    throw new ArgumentException(error);
                }
            }
            def.SegmentId = new NetworkSegmentIdentifier();
            def.SegmentId.PrimarySegmentIdentifier = Convert.ToUInt32(vlanId);
            def.LastModifiedTimeStamp = DateTime.Now;
            def.MaxNumberOfPorts = maxNumberOfPorts;
            return def;
        }
        /// <summary>
        /// Create a new VM subnet with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="name">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkId">Id of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnets">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition to associate with.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <param name="vbrName">Vbridge name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMSubnet CreateVMNetworkDefinition(TransactionManager txnMng,
            string name,
            Guid vMNetworkId,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnets,
            Guid logicalNetworkDefinitionId,
            VSEMConnection connection,
            out string vtnName,
            out string vbrName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"ipSubnets\":" + JavaScriptSerializer.Serialize(ipSubnets));
            json.Append("\"maxNumberOfPorts\":\"" + maxNumberOfPorts + "\"");
            json.Append("\"name\":\"" + name + "\"");
            json.Append("\"logicalNetworkDefinitionId\":\"" + logicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");

                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }

            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");

                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }

            if (vMNetworkId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkId' is null or invalid.");

                throw new ArgumentException("The parameter 'vMNetworkId' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");

                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }

            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");

                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var vmNw = vMNetworkConfig.VMNetwork.VmNetworks.FirstOrDefault(
                nwk => nwk.Id == vMNetworkId);

            if (vmNw == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found. VTN corresponding to this VM network may have been deleted from ODL.\nRefer Network Object Mapping screen.",
                    vMNetworkId.ToString("B")));
            }

            var LogicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(LogicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            if (LogicalNetworkConfig.LogicalNetworks.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var logicalNwDef = LogicalNetworkConfig.LogicalNetworks.First().LogicalNetworkDefinitions.FirstOrDefault(
                fabnw => fabnw.Id == logicalNetworkDefinitionId);

            if (logicalNwDef == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network definition '{0}' not found.",
                    logicalNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                logicalNetworkDefinitionId.ToString("B")));
            }

            string output = "\"logicalNwDef\":" + JavaScriptSerializer.Serialize(logicalNwDef);
            if (!logicalNwDef.SupportsVMNetworkProvisioning) {
                ODLVSEMETW.EventWriteSupportsVMNetworkProvisioningError(
                    "Logical does not support VM network creation.",
                    output);
                throw new InvalidOperationException(
                    "Logical does not support VM network creation.");
            }
            VMNetworkInfo vmnetworkInfo = vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.First(vmn => vmn.VMNetworkID.CompareTo(vmNw.Id) == 0);
            VSEMSynchronization vSEMSynchronization =
                new VSEMSynchronization(this.ConnectionString, this.Credential);
            Controller odl = new Controller(this.ConnectionString, this.Credential);
            List<Vtn> vtns = odl.ReadVTNObjects(vmnetworkInfo.VTNName);
            if (vtns.Count == 0) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        "Corresponding VTN is not found on ODL.");
                throw new DataMisalignedException("Corresponding VTN is not found on ODL.\nRefresh the Odl configuration and then retry.");
            }

            VMSubnet nw = this.CreateVMNetworkDefinitionforVtn(txnMng,
                LogicalNetworkConfig,
                vMNetworkConfig,
                name,
                vMNetworkId,
                maxNumberOfPorts,
                ipSubnets,
                logicalNetworkDefinitionId,
                connection,
                out vtnName,
                out vbrName);

            if (nw == null) {
                ODLVSEMETW.EventWriteProcessFailedVMSubNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Subnet.");
                throw new InvalidOperationException("Failed to create VM Subnet.");
            }

            odl = new Controller(this.ConnectionString, this.Credential);
            odl.UpdateStartupConfiguration();
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);

            string outputLib = "\"nw\":" + JavaScriptSerializer.Serialize(nw);
            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name, outputLib);
            return nw;
        }
        /// <summary>
        /// Create a new VM network with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="LogicalNetworkConfig">Config file of logical network.</param>
        /// <param name="vMNetworkConfig">Config file of vm network.</param>
        /// <param name="name">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkId">Id of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnet">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition
        /// to associate with.</param>
        /// <param name="conn">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <param name="vbrName">Vbridge name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMSubnet CreateVMNetworkDefinitionforVtn(
            TransactionManager txnMng,
            LogicalNetworkConfig LogicalNetworkConfig,
            VMNetworkConfig vMNetworkConfig,
            string name,
            Guid vMNetworkId,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnet,
            Guid logicalNetworkDefinitionId,
            VSEMConnection conn,
            out string vtnName,
            out string vbrName)
        {
            ODLVSEMETW.EventWriteCreateVMsubNetwork(MethodBase.GetCurrentMethod().Name,
                "Creating VM SubNetwork.");
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");
                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }
            if (LogicalNetworkConfig == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'LogicalNetworkConfig' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'LogicalNetworkConfig' is null or invalid.");
            }
            if (vMNetworkConfig == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkConfig' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'vMNetworkConfig' is null or invalid.");
            }
            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");
                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }
            if (vMNetworkId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkId' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkId' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (conn == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'conn' is null or invalid.");
                throw new ArgumentException("The parameter 'conn' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                ODLVSEMETW.EventWriteProcessLibraryError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
            }
            var vmNetInfo =
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Where(
                vmNw => vmNw.VMNetworkID == vMNetworkId).FirstOrDefault();
            if (vmNetInfo == null) {
                ODLVSEMETW.EventWriteProcessLibraryError(MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VM network {0} not found.",
                    vMNetworkId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM network '{0}' not found.",
                    vMNetworkId.ToString("B")));
            }
            vtnName = vmNetInfo.VTNName;

            vbrName = this.CreateUniqueNameForVBridge(name, vmNetInfo.VTNName);

            VLANIDMap vLANIDMap = new VLANIDMap(txnMng,
                VtnHostName,
                TransactionManager.OpenMode.ReadMode);
            string vlanIdRange = vLANIDMap.GetVlanId(vmNetInfo.VMNetworkOriginalName, name);
            if (string.IsNullOrEmpty(vlanIdRange)) {
                ODLVSEMETW.EventWriteFoundNoVlanError(MethodBase.GetCurrentMethod().Name,
                    "No VLAN ID found.");
                throw new ItemNotFoundException("No VLAN ID found.");
            }
            long vlanId = this.SelectVlanId(vlanIdRange,
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo);
            if (vlanId == 0) {
                ODLVSEMETW.EventWriteFoundNoUnusedVlanError(MethodBase.GetCurrentMethod().Name,
                    "No unused VLAN ID found.");
                throw new ItemNotFoundException("No unused VLAN ID found.");
            }

            VMSubnet vmNetworkDef = CreateVbrVmNetworkDefinition(
                vMNetworkId,
                maxNumberOfPorts,
                ipSubnet,
                name,
                logicalNetworkDefinitionId,
                vbrName,
                vlanId);

            if (vmNetworkDef == null) {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Subnet.");
                throw new InvalidOperationException("Failed to create VM Subnet.");
            }
            Vbridge vBridge = new Vbridge(this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            Controller odl_ctr = new Controller(this.ConnectionString, this.Credential);
            if (odl_ctr.Get_status(Constants.CTR_NAME)) {
            vBridge.AddVbridge(vbrName, vmNetInfo.VTNName, vlanId);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", string.Empty);
            } else {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VBR controller status is down.");
                throw new InvalidOperationException("Failed to create VBR.");
            }

            var vmNet = vMNetworkConfig.VMNetwork.VmNetworks.Where(nwk =>
                nwk.Id == vMNetworkId).FirstOrDefault();

            Array.Resize(ref vmNet.VMSubnets, vmNet.VMSubnets.Length + 1);
            vmNet.VMSubnets[vmNet.VMSubnets.Length - 1] = vmNetworkDef;
            vmNetInfo.VMSubnetInfo.Add(new VMSubnetInfo {
                VBridgeName = vbrName,
                VMSubnetVlanId = vlanId,
                VMSubnetID = vmNetworkDef.Id,
                VMSubnetName = vmNetworkDef.Name,
                CreatedFrom = "SCVMM",
                VBridgeVlanId = vlanId
            });

            return vmNetworkDef;
        }
        /// <summary>
        /// Create an IP Address Pool and add it to the specified VM Subnet.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="name">Name of IP address pool.</param>
        /// <param name="description">Description for IP address pool.</param>
        /// <param name="subnet">IP address subnet.</param>
        /// <param name="addressStart">Starting address for IP address pool.</param>
        /// <param name="addressEnd">Ending address for IP address pool.</param>
        /// <param name="gatewayInfo">Network gateway info.</param>
        /// <param name="vmNetworkDefinitionId">VM Subnet ID.</param>
        /// <returns>Newly created ip address pool.</returns>
        public IPAddressPool CreateIpAddressPool(TransactionManager txnMng,
            string name,
            string description,
            string subnet,
            string addressStart,
            string addressEnd,
            NetworkGatewayInfo[] gatewayInfo,
            Guid vmNetworkDefinitionId)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"gatewayInfo\":" + JavaScriptSerializer.Serialize(gatewayInfo));
            json.Append("\"name\":\"" + name + "\"");
            json.Append("\"description\":\"" + description + "\"");
            json.Append("\"subnet\":\"" + subnet + "\"");
            json.Append("\"addressStart\":\"" + addressStart + "\"");
            json.Append("\"addressEnd\":\"" + addressEnd + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");
                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }
            if (string.IsNullOrEmpty(name)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");
                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }
            if (string.IsNullOrEmpty(subnet)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'subnet' is null or invalid.");
                throw new ArgumentException("The parameter 'subnet' is null or invalid.");
            }
            if (string.IsNullOrEmpty(addressStart)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'addressStart' is null or invalid.");
                throw new ArgumentException("The parameter 'addressStart' is null or invalid.");
            }
            if (string.IsNullOrEmpty(addressEnd)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'addressEnd' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'addressEnd' is null or invalid.");
            }
            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "VMNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            VMSubnet vmNetDef = null;
            foreach (var vmNet in vMNetworkConfig.VMNetwork.VmNetworks) {
                vmNetDef = vmNet.VMSubnets.FirstOrDefault(vmSubNet =>
                    vmSubNet.Id == vmNetworkDefinitionId);
                if (vmNetDef != null) {
                    break;
                }
            }

            if (vmNetDef == null) {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                        string.Format(CultureInfo.CurrentCulture,
                        "VM Subnet '{0}' not found.",
                        vmNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "VM Subnet '{0}' not found.",
                    vmNetworkDefinitionId.ToString("B")));
            }

            this.SyncVMSubnet(vmNetworkDefinitionId, vMNetworkConfig);

            IPAddressPool poolAdd = null;

            if (vmNetDef != null) {
                poolAdd = this.CreateIpAddressPool(name,
                    description,
                    subnet,
                    addressStart,
                    addressEnd,
                    gatewayInfo);

                if (poolAdd != null) {
                    AddressFamily addressFamily = AddressFamily.IPv4;
                    IPAddress address = null;
                    var parts = subnet.Split('/');
                    var parsingResult = IPAddress.TryParse(parts[0], out address);
                    if (parsingResult == false || address == null) {
                        ODLVSEMETW.EventWriteArgumentError(
                            MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                            MethodBase.GetCurrentMethod().Name,
                            "The parameter 'subnet' is null or invalid.");
                        throw new ArgumentException("The parameter 'subnet' is invalid.");
                    }
                    switch (address.AddressFamily) {
                        case System.Net.Sockets.AddressFamily.InterNetwork:
                            addressFamily = AddressFamily.IPv4;
                            break;
                        case System.Net.Sockets.AddressFamily.InterNetworkV6:
                            addressFamily = AddressFamily.IPv6;
                            break;
                        default:
                            ODLVSEMETW.EventWriteArgumentError(
                                MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                                MethodBase.GetCurrentMethod().Name,
                                "The parameter 'subnet' is null or invalid.");
                            throw new ArgumentException("The IP address family of subnet is invalid.");
                    }

                    IPSubnet ipsub = null;
                    if (vmNetDef.IPSubnets != null) {
                        ipsub = vmNetDef.IPSubnets.FirstOrDefault(x => x.AddressFamily == addressFamily);
                    } else {
                        vmNetDef.IPSubnets = new IPSubnet[0];
                    }
                    if (ipsub == null) {
                        IPSubnet ipSubnet = new IPSubnet();
                        ipSubnet.Id = Guid.NewGuid();
                        poolAdd.IPSubnetId = ipSubnet.Id;
                        ipSubnet.IPAddressPools = new IPAddressPool[] {
                        poolAdd};
                        ipSubnet.AddressFamily = addressFamily;
                        ipSubnet.LastModifiedTimeStamp = DateTime.Now;
                        ipSubnet.Subnet = subnet;
                        ipSubnet.SupportsDHCP = true;
                        List<IPSubnet> subnets = vmNetDef.IPSubnets.ToList();
                        subnets.Add(ipSubnet);
                        vmNetDef.IPSubnets = subnets.ToArray();
                    } else {
                        List<IPAddressPool> pools = ipsub.IPAddressPools.ToList();
                        pools.Add(poolAdd);
                        poolAdd.IPSubnetId = ipsub.Id;
                        ipsub.IPAddressPools = pools.ToArray();
                        ipsub.LastModifiedTimeStamp = DateTime.Now;
                    }
                    vmNetDef.LastModifiedTimeStamp = DateTime.Now;

                    string error = Validations.IsIPSubnetListValid(
                        vmNetDef.IPSubnets.ToList(), poolAdd.Id);
                    if (!string.IsNullOrEmpty(error)) {
                        ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                                MethodBase.GetCurrentMethod().Name,
                                error);
                        throw new ArgumentException(error);
                    }
                }
            }

            return poolAdd;
        }
        private void AcceptCallback(IAsyncResult ar)
        {
            if (_stop)
            {
                return;
            }
            var listener = (Socket)ar.AsyncState;

            try
            {
                var conn = listener.EndAccept(ar);

                var localPort = ((IPEndPoint)conn.LocalEndPoint).Port;

                if ((_authUser ?? string.Empty).Length == 0 && !IPSubnet.IsLan(conn) &&
                    !(_config.PortMapCache.ContainsKey(localPort) ||
                      _config.PortMapCache[localPort].type == PortMapType.Forward))
                {
                    conn.Shutdown(SocketShutdown.Both);
                    conn.Close();
                }
                else
                {
                    var      buf   = new byte[4096];
                    object[] state =
                    {
                        conn,
                        buf
                    };

                    if (!_config.PortMapCache.ContainsKey(localPort) || _config.PortMapCache[localPort].type != PortMapType.Forward)
                    {
                        conn.BeginReceive(buf, 0, buf.Length, 0, ReceiveCallback, state);
                    }
                    else
                    {
                        if (_services.Any(service => service.Handle(buf, 0, conn)))
                        {
                            return;
                        }
                        // no service found for this
                        // shouldn't happen
                        conn.Shutdown(SocketShutdown.Both);
                        conn.Close();
                    }
                }
            }
            catch (ObjectDisposedException)
            {
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                try
                {
                    listener.BeginAccept(AcceptCallback, listener);
                }
                catch (ObjectDisposedException)
                {
                    // do nothing
                }
                catch (Exception e)
                {
                    Logging.LogUsefulException(e);
                }
            }
        }
示例#20
0
        public override bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (socket.ProtocolType != ProtocolType.Tcp)
            {
                return(false);
            }
            try
            {
                var    request = Encoding.UTF8.GetString(firstPacket, 0, length);
                var    lines = request.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                bool   hostMatch = false, pathMatch = false;
                var    socksType = 0;
                string proxy     = null;
                foreach (var line in lines)
                {
                    var kv = line.Split(new[] { ':' }, 2);
                    if (kv.Length == 2)
                    {
                        if (kv[0] == "Host")
                        {
                            if (kv[1].Trim() == ((IPEndPoint)socket.LocalEndPoint).ToString())
                            {
                                hostMatch = true;
                            }
                        }
                    }
                    else if (kv.Length == 1)
                    {
                        if (!IPSubnet.IsLocal(socket) || line.IndexOf($@"auth={_config.localAuthPassword}", StringComparison.Ordinal) > 0)
                        {
                            if (line.IndexOf(" /pac?", StringComparison.Ordinal) > 0 && line.IndexOf("GET", StringComparison.Ordinal) == 0)
                            {
                                var url = line.Substring(line.IndexOf(" ", StringComparison.Ordinal) + 1);
                                url       = url.Substring(0, url.IndexOf(" ", StringComparison.Ordinal));
                                pathMatch = true;
                                var port_pos = url.IndexOf("port=", StringComparison.Ordinal);
                                if (port_pos > 0)
                                {
                                    var port = url.Substring(port_pos + 5);
                                    if (port.IndexOf("&", StringComparison.Ordinal) >= 0)
                                    {
                                        port = port.Substring(0, port.IndexOf("&", StringComparison.Ordinal));
                                    }

                                    var ip_pos = url.IndexOf("ip=", StringComparison.Ordinal);
                                    if (ip_pos > 0)
                                    {
                                        proxy = url.Substring(ip_pos + 3);
                                        if (proxy.IndexOf("&", StringComparison.Ordinal) >= 0)
                                        {
                                            proxy = proxy.Substring(0, proxy.IndexOf("&", StringComparison.Ordinal));
                                        }
                                        proxy += $@":{port};";
                                    }
                                    else
                                    {
                                        proxy = $@"127.0.0.1:{port};";
                                    }
                                }

                                if (url.IndexOf("type=socks4", StringComparison.Ordinal) > 0 || url.IndexOf("type=s4", StringComparison.Ordinal) > 0)
                                {
                                    socksType = 4;
                                }
                                if (url.IndexOf("type=socks5", StringComparison.Ordinal) > 0 || url.IndexOf("type=s5", StringComparison.Ordinal) > 0)
                                {
                                    socksType = 5;
                                }
                            }
                        }
                    }
                }
                if (hostMatch && pathMatch)
                {
                    SendResponse(socket, socksType, proxy);
                    return(true);
                }
                return(false);
            }
            catch (ArgumentException)
            {
                return(false);
            }
        }
示例#21
0
        /// <summary>
        /// Create an IP Address Pool and add it to the specified VM Subnet.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="name">Name of IP address pool.</param>
        /// <param name="description">Description for IP address pool.</param>
        /// <param name="subnet">IP address subnet.</param>
        /// <param name="addressStart">Starting address for IP address pool.</param>
        /// <param name="addressEnd">Ending address for IP address pool.</param>
        /// <param name="gatewayInfo">Network gateway info.</param>
        /// <param name="vmNetworkDefinitionId">VM Subnet ID.</param>
        /// <returns>Newly created ip address pool.</returns>
        public IPAddressPool CreateIpAddressPool(TransactionManager txnMng,
                                                 string name,
                                                 string description,
                                                 string subnet,
                                                 string addressStart,
                                                 string addressEnd,
                                                 NetworkGatewayInfo[] gatewayInfo,
                                                 Guid vmNetworkDefinitionId)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();

            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));

            json.Append(" \"gatewayInfo\":" + JavaScriptSerializer.Serialize(gatewayInfo));
            json.Append("\"name\":\"" + name + "\"");
            json.Append("\"description\":\"" + description + "\"");
            json.Append("\"subnet\":\"" + subnet + "\"");
            json.Append("\"addressStart\":\"" + addressStart + "\"");
            json.Append("\"addressEnd\":\"" + addressEnd + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                                              json.ToString());
            if (txnMng == null)
            {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'txnMng' is null or invalid.");
                throw new ArgumentException("The parameter 'txnMng' is null or invalid.");
            }
            if (string.IsNullOrEmpty(name))
            {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'name' is null or invalid.");
                throw new ArgumentException("The parameter 'name' is null or invalid.");
            }
            if (string.IsNullOrEmpty(subnet))
            {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'subnet' is null or invalid.");
                throw new ArgumentException("The parameter 'subnet' is null or invalid.");
            }
            if (string.IsNullOrEmpty(addressStart))
            {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'addressStart' is null or invalid.");
                throw new ArgumentException("The parameter 'addressStart' is null or invalid.");
            }
            if (string.IsNullOrEmpty(addressEnd))
            {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'addressEnd' is null or invalid.");
                throw new ArgumentException(
                          "The parameter 'addressEnd' is null or invalid.");
            }
            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal))
            {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);

            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Count == 0)
            {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                                  "VMNetwork.config {0}",
                                  configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                          string.Format(CultureInfo.CurrentCulture,
                                        "VMNetwork.config {0}",
                                        configFileIOErrorValidationMessage));
            }

            VMSubnet vmNetDef = null;

            foreach (var vmNet in vMNetworkConfig.VMNetwork.VmNetworks)
            {
                vmNetDef = vmNet.VMSubnets.FirstOrDefault(vmSubNet =>
                                                          vmSubNet.Id == vmNetworkDefinitionId);
                if (vmNetDef != null)
                {
                    break;
                }
            }

            if (vmNetDef == null)
            {
                ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                                  "VM Subnet '{0}' not found.",
                                  vmNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          "VM Subnet '{0}' not found.",
                                                          vmNetworkDefinitionId.ToString("B")));
            }

            this.SyncVMSubnet(vmNetworkDefinitionId, vMNetworkConfig);

            IPAddressPool poolAdd = null;

            if (vmNetDef != null)
            {
                poolAdd = this.CreateIpAddressPool(name,
                                                   description,
                                                   subnet,
                                                   addressStart,
                                                   addressEnd,
                                                   gatewayInfo);

                if (poolAdd != null)
                {
                    AddressFamily addressFamily = AddressFamily.IPv4;
                    IPAddress     address       = null;
                    var           parts         = subnet.Split('/');
                    var           parsingResult = IPAddress.TryParse(parts[0], out address);
                    if (parsingResult == false || address == null)
                    {
                        ODLVSEMETW.EventWriteArgumentError(
                            MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                            MethodBase.GetCurrentMethod().Name,
                            "The parameter 'subnet' is null or invalid.");
                        throw new ArgumentException("The parameter 'subnet' is invalid.");
                    }
                    switch (address.AddressFamily)
                    {
                    case System.Net.Sockets.AddressFamily.InterNetwork:
                        addressFamily = AddressFamily.IPv4;
                        break;

                    case System.Net.Sockets.AddressFamily.InterNetworkV6:
                        addressFamily = AddressFamily.IPv6;
                        break;

                    default:
                        ODLVSEMETW.EventWriteArgumentError(
                            MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                            MethodBase.GetCurrentMethod().Name,
                            "The parameter 'subnet' is null or invalid.");
                        throw new ArgumentException("The IP address family of subnet is invalid.");
                    }

                    IPSubnet ipsub = null;
                    if (vmNetDef.IPSubnets != null)
                    {
                        ipsub = vmNetDef.IPSubnets.FirstOrDefault(x => x.AddressFamily == addressFamily);
                    }
                    else
                    {
                        vmNetDef.IPSubnets = new IPSubnet[0];
                    }
                    if (ipsub == null)
                    {
                        IPSubnet ipSubnet = new IPSubnet();
                        ipSubnet.Id             = Guid.NewGuid();
                        poolAdd.IPSubnetId      = ipSubnet.Id;
                        ipSubnet.IPAddressPools = new IPAddressPool[] {
                            poolAdd
                        };
                        ipSubnet.AddressFamily         = addressFamily;
                        ipSubnet.LastModifiedTimeStamp = DateTime.Now;
                        ipSubnet.Subnet       = subnet;
                        ipSubnet.SupportsDHCP = true;
                        List <IPSubnet> subnets = vmNetDef.IPSubnets.ToList();
                        subnets.Add(ipSubnet);
                        vmNetDef.IPSubnets = subnets.ToArray();
                    }
                    else
                    {
                        List <IPAddressPool> pools = ipsub.IPAddressPools.ToList();
                        pools.Add(poolAdd);
                        poolAdd.IPSubnetId          = ipsub.Id;
                        ipsub.IPAddressPools        = pools.ToArray();
                        ipsub.LastModifiedTimeStamp = DateTime.Now;
                    }
                    vmNetDef.LastModifiedTimeStamp = DateTime.Now;

                    string error = Validations.IsIPSubnetListValid(
                        vmNetDef.IPSubnets.ToList(), poolAdd.Id);
                    if (!string.IsNullOrEmpty(error))
                    {
                        ODLVSEMETW.EventWriteValidateVMNetDefinitionError(
                            MethodBase.GetCurrentMethod().Name,
                            error);
                        throw new ArgumentException(error);
                    }
                }
            }

            return(poolAdd);
        }
        /// <summary>
        /// Create a new VM network with specified parameters using VTN on demand.
        /// </summary>
        /// <param name="txnMng">Transaction manager.</param>
        /// <param name="vMSubnetName">Name of VM Subnet to create.</param>
        /// <param name="vMNetworkName">Name of VM network to create.</param>
        /// <param name="maxNumberOfPorts">Maximum number of ports.</param>
        /// <param name="ipSubnets">IP pools to use.</param>
        /// <param name="logicalNetworkDefinitionId">ID of logical network definition
        /// to associate with.</param>
        /// <param name="connection">VSEM connection.</param>
        /// <param name="vtnName">VTN name.</param>
        /// <returns>VM network if successful, else null.</returns>
        public VMNetwork CreateVMNetwork(TransactionManager txnMng,
            string vMSubnetName,
            string vMNetworkName,
            long? maxNumberOfPorts,
            IPSubnet[] ipSubnets,
            Guid logicalNetworkDefinitionId,
            VSEMConnection connection,
            out string vtnName)
        {
            var JavaScriptSerializer = new JavaScriptSerializer();
            JavaScriptSerializer.MaxJsonLength = int.MaxValue;
            StringBuilder json = new StringBuilder("\"txnMng\":" + JavaScriptSerializer.Serialize(txnMng));
            json.Append(" \"ipSubnets\":" + JavaScriptSerializer.Serialize(ipSubnets));
            json.Append("\"maxNumberOfPorts\":\"" + maxNumberOfPorts + "\"");
            json.Append("\"vMNetworkName\":\"" + vMNetworkName + "\"");
            json.Append("\"vMSubnetName\":\"" + vMSubnetName + "\"");
            json.Append("\"logicalNetworkDefinitionId\":\"" + logicalNetworkDefinitionId + "\"");
            ODLVSEMETW.EventWriteStartLibrary(MethodBase.GetCurrentMethod().Name,
                json.ToString());
            if (txnMng == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'transaction' is null or invalid.");
                throw new ArgumentException("The parameter 'transaction' is null or invalid.");
            }

            if (string.IsNullOrEmpty(vMNetworkName)) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'vMNetworkName' is null or invalid.");
                throw new ArgumentException("The parameter 'vMNetworkName' is null or invalid.");
            }
            if (logicalNetworkDefinitionId == Guid.Empty) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
                throw new ArgumentException(
                    "The parameter 'logicalNetworkDefinitionId' is null or invalid.");
            }
            if (connection == null) {
                ODLVSEMETW.EventWriteArgumentError(
                    MethodBase.GetCurrentMethod().DeclaringType.Name.ToString(),
                    MethodBase.GetCurrentMethod().Name,
                    "The parameter 'connection' is null or invalid.");
                throw new ArgumentException("The parameter 'connection' is null or invalid.");
            }

            string VtnHostName = this.ConnectionString;

            if (VtnHostName.StartsWith(@"https://", StringComparison.Ordinal)) {
                VtnHostName = VtnHostName.Substring(8);
            }

            VtnHostName = VtnHostName.Split('.', ':').First();

            var vMNetworkConfig = new VMNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(vMNetworkConfig, TransactionManager.OpenMode.WriteMode);

            var LogicalNetworkConfig = new LogicalNetworkConfig(VtnHostName);
            txnMng.SetConfigManager(LogicalNetworkConfig, TransactionManager.OpenMode.ReadMode);
            if (LogicalNetworkConfig.LogicalNetworks.Count == 0) {
                ODLVSEMETW.EventWriteConfigManagerFileIOError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
                throw new InvalidOperationException(
                    string.Format(CultureInfo.CurrentCulture,
                    "LogicalNetwork.config {0}",
                    configFileIOErrorValidationMessage));
            }

            var logicalNetName = VSEMODLConstants.LOGICAL_NETWORK_NAME;
            logicalNetName += VtnHostName;
            var fabricNwDef = LogicalNetworkConfig.LogicalNetworks.First(
                log => log.Name.Equals(logicalNetName)).LogicalNetworkDefinitions.FirstOrDefault(
                fabnw => fabnw.Id == logicalNetworkDefinitionId);
            if (fabricNwDef == null) {
                ODLVSEMETW.EventWriteGetFabricNetworkDefinitionError(
                    MethodBase.GetCurrentMethod().Name,
                    string.Format(CultureInfo.CurrentCulture,
                    "Logical network definition '{0}' not found.",
                    logicalNetworkDefinitionId.ToString("B")));
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                     "Logical network definition '{0}' not found.",
                logicalNetworkDefinitionId.ToString("B")));
            }

            ODLVSEMETW.EventWriteReturnLibrary(string.Format(CultureInfo.CurrentCulture,
                "VSEMLogicalNetworkDefinition is retrieved by ID: {0}",
                logicalNetworkDefinitionId.ToString("B")),
                string.Empty);

            if (!fabricNwDef.SupportsVMNetworkProvisioning) {
                ODLVSEMETW.EventWriteSupportsVMNetworkProvisioningError(
                    "Logical network does not support VM network creation.",
                    string.Empty);
                throw new InvalidOperationException(
                    "Logical network does not support VM network creation.");
            }

            vtnName = this.CreateUniqueNameForVTN(vMNetworkName);

            Vtn vtn = new Vtn(this.ConnectionString, this.Credential);
            vtn.AddVtn(vtnName);

            ODLVSEMETW.EventWriteReturnODLLibrary(string.Format(CultureInfo.CurrentCulture,
                "VTN '{0}' is created",
                vtnName),
                string.Empty);

            VMNetwork vmNet = CreateVtnVmNetwork(vMNetworkName);
            vmNet.LogicalNetwork = fabricNwDef.LogicalNetworkId;
            if (vmNet == null) {
                ODLVSEMETW.EventWriteProcessFailedVMNetworkError(
                    MethodBase.GetCurrentMethod().Name,
                    "Failed to create VM Network.");
                throw new InvalidOperationException("Failed to create VM Network.");
            }
            ODLVSEMETW.EventWriteSuccessVmNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Network Successfully Created.");

            // Create the VM Subnet
            vMNetworkConfig.VMNetwork.VmNetworks.Add(vmNet);
            if (vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo == null) {
                vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo =
                    new List<VMNetworkInfo>();
            }

            vMNetworkConfig.VMNetwork.VMNetworkMappingInformation.VMNetworkInfo.Add(
                new VMNetworkInfo {
                    VMNetworkID = vmNet.Id,
                    VMNetworkName = vmNet.Name,
                    VTNName = vtnName,
                    VMSubnetInfo = new List<VMSubnetInfo>(),
                    CreatedFrom = "SCVMM",
                    VMNetworkOriginalName = vmNet.Name
                });

            var vsemvmnetworkDefinition = new VSEMVMSubnetManagement(
                this.ConnectionString, this.Credential);
            ODLVSEMETW.EventWriteCreateVMsubNetwork(MethodBase.GetCurrentMethod().Name,
                    "VM Sub Network creation process started.");
            string vbrName = string.Empty;
            VMSubnet vmNetworkDef =
                vsemvmnetworkDefinition.CreateVMNetworkDefinitionforVtn(
                txnMng,
                LogicalNetworkConfig,
                vMNetworkConfig,
                vMSubnetName,
                vmNet.Id,
                maxNumberOfPorts,
                ipSubnets,
                logicalNetworkDefinitionId,
                connection,
                out vtnName,
                out vbrName);

            Controller odl = new Controller(this.ConnectionString, this.Credential);
            odl.UpdateStartupConfiguration();
            string output = "\"vmNet\":" + JavaScriptSerializer.Serialize(vmNet);
            ODLVSEMETW.EventWriteReturnODLLibrary("Return from ODL Library.", output);

            ODLVSEMETW.EventWriteEndLibrary(MethodBase.GetCurrentMethod().Name,
                output);
            return vmNet;
        }
 /// <summary>
 /// Create IPSubnet instance.
 /// </summary>
 /// <returns>IPSubnet instance.</returns>
 private IPSubnet CreateDefaultIPSubnet()
 {
     var ipSubnet = new IPSubnet {
         AddressFamily = HNVODLConstants.IP_SUBNET.ADDRESS_FAMILY, Id = HNVODLConstants.IP_SUBNET.ID,
         IPAddressPools = null, LastModifiedTimeStamp = DateTime.Now, Subnet = HNVODLConstants.IP_SUBNET.SUBNET,
         SupportsDHCP = HNVODLConstants.IP_SUBNET.SUPPORTS_DHCP
     };
     return ipSubnet;
 }