示例#1
0
 /// <summary>
 /// Write Configuration data in XML format to the XML Text Writer.
 /// </summary>
 /// <param name="writer">XML Text Writer</param>
 public override void WriteXmlConfig(XmlTextWriter writer)
 {
     writer.WriteStartElement("Hl7PeerToPeerConfiguration");
     writer.WriteStartElement("FromActor");
     writer.WriteStartElement("ActorName");
     writer.WriteElementString("ActorType", ActorTypes.Type(FromActorName.Type));
     writer.WriteElementString("ActorId", FromActorName.Id);
     writer.WriteEndElement();
     writer.WriteElementString("AeTitle", FromActorAeTitle);
     writer.WriteEndElement();
     writer.WriteStartElement("ToActor");
     writer.WriteStartElement("ActorName");
     writer.WriteElementString("ActorType", ActorTypes.Type(ToActorName.Type));
     writer.WriteElementString("ActorId", ToActorName.Id);
     writer.WriteEndElement();
     writer.WriteElementString("AeTitle", ToActorAeTitle);
     writer.WriteElementString("IpAddress", ToActorIpAddress);
     writer.WriteEndElement();
     writer.WriteElementString("PortNumber", PortNumber.ToString());
     writer.WriteElementString("MessageDelimiters", MessageDelimiters.ToString());
     writer.WriteElementString("SecureConnection", SecureConnection.ToString());
     writer.WriteElementString("AutoValidate", AutoValidate.ToString());
     writer.WriteElementString("ActorOption1", ActorOption1);
     writer.WriteElementString("ActorOption2", ActorOption2);
     writer.WriteElementString("ActorOption3", ActorOption3);
     writer.WriteElementString("SessionId", _sessionId.ToString());
     writer.WriteEndElement();
 }
示例#2
0
        /// <summary>
        /// Initialise a secure communications connection.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response InitialiseSecureConnection(LoginRequest request)
        {
            // Decrypt the password
            var cp = new CspParameters();

            cp.KeyContainerName = "CruiseControl.NET Server";
            var provider     = new RSACryptoServiceProvider(cp);
            var originalKey  = request.FindCredential(LoginRequest.UserNameCredential).Value;
            var decryptedKey = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalKey), false));
            var originalIv  = request.FindCredential(LoginRequest.PasswordCredential).Value;
            var decryptedIv = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalIv), false));

            // Generate the connection details
            var connection = new SecureConnection
            {
                Expiry = DateTime.Now.AddMinutes(15),
                IV     = Convert.FromBase64String(decryptedIv),
                Key    = Convert.FromBase64String(decryptedKey)
            };

            connections[request.SourceName] = connection;

            // Generate a response
            var response = new Response(request);

            response.Result = ResponseResult.Success;
            return(response);
        }
示例#3
0
 public AuthForm()
 {
     InitializeComponent();
     secure = new SecureConnection();
     secure.OnConnectionEstablished += new SecureConnection.ConnectionEstablishedHandler(secure_OnConnectionEstablished);
     secure.OnResponseReceived      += new SecureConnection.ResponseReceivedHandler(secure_OnResponseReceived);
     secure.SetServerURL("https://gozaltech.org/auth/");
     secure.EstablishSecureConnectionAsync();
     btnLogin.Enabled = false;
 }
示例#4
0
    public async Task IncrementTest()
    {
        var caseList = new List <(byte[] value, byte[] actual)>
        {
            (new byte[] { 0x00, 0x00 }, new byte[] { 0x01, 0x00 }),
            (new byte[] { 0xff, 0x00 }, new byte[] { 0x00, 0x01 }),
            (new byte[] { 0xff, 0xff }, new byte[] { 0x00, 0x00 })
        };

        foreach (var(value, actual) in caseList)
        {
            var result = value;
            SecureConnection.Increment(result);

            Assert.Equal(result, actual);
        }
    }
示例#5
0
    private edit_Item_Dropdown_Chooser getFilter(XmlNode node)
    {
        edit_Item_Dropdown_Chooser filter = new edit_Item_Dropdown_Chooser();

        filter.ConnStr      = getChild(node, "conn", "ConnStr1");
        filter.ConnStr      = SecureConnection.GetCnxString(filter.ConnStr);
        filter.ID           = node.Attributes["id"].Value;
        filter.Label        = node.Attributes["label"].Value;
        filter.Width        = node.Attributes["width"].Value;
        filter.Type         = Edit_Item_Type.Dropdown_Chooser;
        filter.Field        = node.SelectSingleNode(".//field").InnerText;
        filter.FieldType    = node.SelectSingleNode(".//fieldtype").InnerText;
        filter.FieldList    = node.SelectSingleNode(".//fieldlist").InnerText;
        filter.FilterField  = node.SelectSingleNode(".//filterField").InnerText;
        filter.SQL          = node.SelectSingleNode(".//sql").InnerText;
        filter.ErrorNoInput = getChild(node, "error_no_input", "");
        return(filter);
    }
示例#6
0
        /// <summary>
        /// Log in through armorgames
        /// </summary>
        /// <param name="config">The config</param>
        /// <returns>The established client if valid; otherwise null</returns>
        public Client LogIn(Config config)
        {
            string loginCookie = GetArmorgamesLoginCookie();

            if (loginCookie == null)
            {
                return(null);
            }

            ArmorgamesFlashvars flashVars = GetFlashvars(loginCookie);

            if (flashVars == null)
            {
                return(null);
            }

            FluidClient guestClient = new FluidClient(new GuestAuth());

            if (!guestClient.LogIn())
            {
                return(null);
            }

            SecureConnection secureConnection = guestClient.GetSecureConnection();

            if (secureConnection == null)
            {
                return(null);
            }

            secureConnection.SendAuth(flashVars.UserId, flashVars.AuthToken);
            AuthEvent armorGamesAuth = secureConnection.WaitForServerEvent <AuthEvent>();

            if (armorGamesAuth.IsAuthenitcated())
            {
                return(PlayerIO.Connect(config.GameID, "secure", armorGamesAuth.UserID, armorGamesAuth.AuthToken, "armorgames"));
            }
            else
            {
                return(null);
            }
        }
示例#7
0
            private static Stream OpenStream(HttpWebRequest req)
            {
                Socket sock = OpenSocket(req);

                if (req.isSecured)
                {
#if CONFIG_SSL
                    SecureConnection secured = new SecureConnection();
                    /*TODO: suspected memory hold for SecureConnection */
                    Stream retval = secured.OpenStream(sock);
                    return(retval);
#else
                    throw new NotSupportedException(S._("NotSupp_SSL"));
#endif
                }
                else
                {
                    return(new NetworkStream(sock, true));
                }
            }
示例#8
0
    private view_Item_Dropdown_Filter getFilter(XmlNode node)
    {
        string id    = node.Attributes["id"].Value;    //.SelectSingleNode(".//id").InnerText;
        string label = node.Attributes["label"].Value; //.SelectSingleNode(".//label").InnerText;
        string type  = node.Attributes["type"].Value;  //.SelectSingleNode(".//type").InnerText;

        view_Item_Dropdown_Filter filter = new view_Item_Dropdown_Filter();

        filter.ConnStr = node.SelectSingleNode(".//conn") == null?VatLid.DAL.getConnectionString1() : node.SelectSingleNode(".//conn").InnerText;

        filter.ConnStr = SecureConnection.GetCnxString(filter.ConnStr);
        filter.ID      = id;
        filter.Label   = label;
        filter.Type    = type;
        if (type != "3") //<!-- filter, type = 3: Filter info load from list of different kind of filter. Ex: {Canceled,IsPause=1};{Free,IsPause=0 AND NextCharge>0};{==All status==,} -->
        {
            filter.FieldList   = node.SelectSingleNode(".//fieldlist").InnerText;
            filter.FilterField = node.SelectSingleNode(".//filterField").InnerText;
        }
        filter.SQL = node.SelectSingleNode(".//sql").InnerText;
        return(filter);
    }
示例#9
0
 /// <summary>
 /// Write Configuration data in XML format to the XML Text Writer.
 /// </summary>
 /// <param name="writer">XML Text Writer</param>
 public override void WriteXmlConfig(XmlTextWriter writer)
 {
     writer.WriteStartElement("DicomPeerToPeerConfiguration");
     writer.WriteStartElement("FromActor");
     writer.WriteStartElement("ActorName");
     writer.WriteElementString("ActorType", ActorTypes.Type(FromActorName.Type));
     writer.WriteElementString("ActorId", FromActorName.Id);
     writer.WriteEndElement();
     writer.WriteElementString("AeTitle", FromActorAeTitle);
     writer.WriteEndElement();
     writer.WriteStartElement("ToActor");
     writer.WriteStartElement("ActorName");
     writer.WriteElementString("ActorType", ActorTypes.Type(ToActorName.Type));
     writer.WriteElementString("ActorId", ToActorName.Id);
     writer.WriteEndElement();
     writer.WriteElementString("AeTitle", ToActorAeTitle);
     writer.WriteElementString("IpAddress", ToActorIpAddress);
     writer.WriteEndElement();
     writer.WriteElementString("PortNumber", PortNumber.ToString());
     writer.WriteElementString("SecureConnection", SecureConnection.ToString());
     writer.WriteElementString("AutoValidate", AutoValidate.ToString());
     writer.WriteElementString("ActorOption1", ActorOption1);
     writer.WriteElementString("ActorOption2", ActorOption2);
     writer.WriteElementString("ActorOption3", ActorOption3);
     writer.WriteElementString("SessionId", _sessionId.ToString());
     writer.WriteElementString("SourceDataDirectory", _sourceDataDirectory);
     writer.WriteElementString("StoreDataDirectory", _storeDataDirectory);
     writer.WriteElementString("StoreData", _storeData.ToString());
     writer.WriteStartElement("DefinitionFiles");
     foreach (System.String defintionFilename in _definitionFiles)
     {
         writer.WriteElementString("DefinitionFile", defintionFilename);
     }
     writer.WriteEndElement();
     writer.WriteEndElement();
 }
        /// <summary>
        /// Initialise a secure communications connection.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response InitialiseSecureConnection(LoginRequest request)
        {
            // Decrypt the password
            var cp = new CspParameters();
            cp.KeyContainerName = "CruiseControl.NET Server";
            var provider = new RSACryptoServiceProvider(cp);
            var originalKey = request.FindCredential(LoginRequest.UserNameCredential).Value;
            var decryptedKey = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalKey), false));
            var originalIv = request.FindCredential(LoginRequest.PasswordCredential).Value;
            var decryptedIv = UTF8Encoding.UTF8.GetString(
                provider.Decrypt(Convert.FromBase64String(originalIv), false));

            // Generate the connection details
            var connection = new SecureConnection
            {
                Expiry = DateTime.Now.AddMinutes(15),
                IV = Convert.FromBase64String(decryptedIv),
                Key = Convert.FromBase64String(decryptedKey)
            };
            connections[request.SourceName] = connection;

            // Generate a response
            var response = new Response(request);
            response.Result = ResponseResult.Success;
            return response;
        }
示例#11
0
    private void travelXML(XmlNode doc)
    {
        listItems = new ArrayList();
        foreach (XmlNode value in doc.SelectNodes(".//text"))
        {
            string type = value.Attributes["type"].Value;

            edit_Item_TextInput textinput = new edit_Item_TextInput();
            textinput.ID           = value.Attributes["id"].Value;
            textinput.Label        = value.Attributes["label"].Value;
            textinput.Width        = value.Attributes["width"].Value;
            textinput.Field        = value.SelectSingleNode(".//field").InnerText;
            textinput.FieldType    = value.SelectSingleNode(".//fieldtype").InnerText;
            textinput.Validate     = value.SelectSingleNode(".//validate").InnerText;
            textinput.ErrorNoInput = getChild(value, "error_no_input", "");
            if (type == "2") // text area
            {
                textinput.Type   = Edit_Item_Type.TextArea;
                textinput.Height = value.SelectSingleNode(".//height").InnerText;
            }
            else
            {
                textinput.Type = Edit_Item_Type.TextBox;
            }

            listItems.Add(textinput);
        }

        //foreach (XmlNode value in doc.SelectNodes(".//check"))
        //{
        //    string type = value.Attributes["type"].Value;

        //    edit_Item_CheckBox textinput = new edit_Item_CheckBox();
        //    textinput.ID = value.Attributes["id"].Value;
        //    textinput.Label = value.Attributes["label"].Value;
        //    textinput.Width = value.Attributes["width"].Value;
        //    textinput.Field = value.SelectSingleNode(".//field").InnerText;
        //    textinput.FieldType = value.SelectSingleNode(".//fieldtype").InnerText;
        //    textinput.ErrorNoInput = getChild(value, "error_no_input", "");

        //    textinput.Type = Edit_Item_Type.TextBox;

        //    listItems.Add(textinput);
        //}


        foreach (XmlNode value in doc.SelectNodes(".//file"))
        {
            edit_Item_FileInput fileinput = new edit_Item_FileInput();
            fileinput.ID           = value.Attributes["id"].Value;
            fileinput.Label        = value.Attributes["label"].Value;
            fileinput.Width        = value.Attributes["width"].Value;
            fileinput.Field        = value.SelectSingleNode(".//field").InnerText;
            fileinput.FieldType    = value.SelectSingleNode(".//fieldtype").InnerText;
            fileinput.Extention    = value.SelectSingleNode(".//extension").InnerText;
            fileinput.StorePath    = ConfigurationSettings.AppSettings[value.SelectSingleNode(".//storepath").InnerText];
            fileinput.MaxSize      = Int32.Parse(getChild(value, "maxsize", "10204000"));
            fileinput.ErrorNoInput = getChild(value, "error_no_input", "");
            fileinput.CurrentValue = "";

            listItems.Add(fileinput);
        }
        foreach (XmlNode value in doc.SelectNodes(".//filter"))
        {
            edit_Item_Dropdown_Chooser filter = getFilter(value);
            listItems.Add(filter);

            XmlNode n = value.SelectSingleNode(".//filter_sub");
            if (n != null)
            {
                edit_Item_Dropdown_Chooser sub = getFilter(n);
                sub.Type     = Edit_Item_Type.Dropdown_Chooser_2;
                filter.Child = sub;
                listItems.Add(sub);
            }
        }
        foreach (XmlNode value in doc.SelectNodes(".//action"))
        {
            string type = value.Attributes["type"].Value;

            edit_Item_ButtonAction action = new edit_Item_ButtonAction();
            action.ConnStr = getChild(value, "conn", "ConnStr1");
            action.ConnStr = SecureConnection.GetCnxString(action.ConnStr);
            action.ID      = value.Attributes["id"].Value;
            action.Label   = value.Attributes["label"].Value;
            if (type == "1")
            {
                action.Type = Edit_Item_Type.AddAction;
            }
            else
            {
                action.Type = Edit_Item_Type.EditAction;
            }
            action.Procedure = value.SelectSingleNode(".//procedure").InnerText;
            action.BackLink  = getChild(value, "backlink", "");

            listItems.Add(action);
        }
    }
示例#12
0
        public Connection CreateConnection(string uri, BandwidthLimit bandwidthLimit)
        {
            List <IDisposable> garbages = new List <IDisposable>();

            try
            {
                Connection connection = null;

                if (connection == null)
                {
                    // Overlay network
                    var cap = this.OnCreateCapEvent(uri);
                    if (cap == null)
                    {
                        goto End;
                    }

                    garbages.Add(cap);

                    connection = new BaseConnection(cap, bandwidthLimit, _maxReceiveCount, _bufferManager);
                    garbages.Add(connection);

                    End :;
                }

                if (connection == null)
                {
                    ConnectionFilter connectionFilter = null;

                    lock (this.ThisLock)
                    {
                        foreach (var filter in this.Filters)
                        {
                            if (filter.UriCondition.IsMatch(uri))
                            {
                                if (filter.ConnectionType != ConnectionType.None)
                                {
                                    connectionFilter = filter.Clone();
                                }

                                break;
                            }
                        }
                    }

                    if (connectionFilter == null)
                    {
                        return(null);
                    }

                    string scheme = null;
                    string host   = null;
                    int    port   = -1;

                    {
                        var match = _regex.Match(uri);

                        if (match.Success)
                        {
                            scheme = match.Groups[1].Value;
                            host   = match.Groups[2].Value;
                            port   = int.Parse(match.Groups[3].Value);
                        }
                        else
                        {
                            var match2 = _regex2.Match(uri);

                            if (match2.Success)
                            {
                                scheme = match2.Groups[1].Value;
                                host   = match2.Groups[2].Value;
                                port   = 4050;
                            }
                        }
                    }

                    if (host == null)
                    {
                        return(null);
                    }

                    IList <KeyValuePair <string, string> > options = null;

                    if (!string.IsNullOrWhiteSpace(connectionFilter.Option))
                    {
                        options = ClientManager.Decode(connectionFilter.Option).OfType <KeyValuePair <string, string> >().ToList();
                    }

                    if (connectionFilter.ConnectionType == ConnectionType.Tcp)
                    {
                        var ipAddress = ClientManager.GetIpAddress(host);
                        if (ipAddress == null)
                        {
                            return(null);
                        }

                        host = ipAddress.ToString();
                        uri  = string.Format("{0}:{1}:{2}", scheme, host, port);

                        if (!this.OnCheckUriEvent(uri))
                        {
                            return(null);
                        }

#if !DEBUG
                        // Check
                        {
                            Uri url = new Uri(string.Format("{0}://{1}:{2}", scheme, host, port));

                            if (url.HostNameType == UriHostNameType.IPv4)
                            {
                                if (IPAddress.Any.ToString() == ipAddress.ToString() ||
                                    IPAddress.Loopback.ToString() == ipAddress.ToString() ||
                                    IPAddress.Broadcast.ToString() == ipAddress.ToString())
                                {
                                    return(null);
                                }
                                if (CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("10.0.0.0").GetAddressBytes()) >= 0 &&
                                    CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("10.255.255.255").GetAddressBytes()) <= 0)
                                {
                                    return(null);
                                }
                                if (CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("172.16.0.0").GetAddressBytes()) >= 0 &&
                                    CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("172.31.255.255").GetAddressBytes()) <= 0)
                                {
                                    return(null);
                                }
                                if (CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("127.0.0.0").GetAddressBytes()) >= 0 &&
                                    CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("127.255.255.255").GetAddressBytes()) <= 0)
                                {
                                    return(null);
                                }
                                if (CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("192.168.0.0").GetAddressBytes()) >= 0 &&
                                    CollectionUtilities.Compare(ipAddress.GetAddressBytes(), IPAddress.Parse("192.168.255.255").GetAddressBytes()) <= 0)
                                {
                                    return(null);
                                }
                            }
                            else if (url.HostNameType == UriHostNameType.IPv6)
                            {
                                if (IPAddress.IPv6Any.ToString() == ipAddress.ToString() ||
                                    IPAddress.IPv6Loopback.ToString() == ipAddress.ToString() ||
                                    IPAddress.IPv6None.ToString() == ipAddress.ToString())
                                {
                                    return(null);
                                }
                                if (ipAddress.ToString().ToLower().StartsWith("fe80:"))
                                {
                                    return(null);
                                }
                            }
                        }
#endif

                        var socket = ClientManager.Connect(new IPEndPoint(ipAddress, port), new TimeSpan(0, 0, 10));
                        garbages.Add(socket);

                        var cap = new SocketCap(socket);
                        garbages.Add(cap);

                        connection = new BaseConnection(cap, bandwidthLimit, _maxReceiveCount, _bufferManager);
                        garbages.Add(connection);
                    }
                    else
                    {
                        if (!this.OnCheckUriEvent(uri))
                        {
                            return(null);
                        }

                        string proxyScheme = null;
                        string proxyHost   = null;
                        int    proxyPort   = -1;

                        {
                            var match = _regex.Match(connectionFilter.ProxyUri);

                            if (match.Success)
                            {
                                proxyScheme = match.Groups[1].Value;
                                proxyHost   = match.Groups[2].Value;
                                proxyPort   = int.Parse(match.Groups[3].Value);
                            }
                            else
                            {
                                var match2 = _regex2.Match(connectionFilter.ProxyUri);

                                if (match2.Success)
                                {
                                    proxyScheme = match2.Groups[1].Value;
                                    proxyHost   = match2.Groups[2].Value;

                                    if (connectionFilter.ConnectionType == ConnectionType.Socks4Proxy ||
                                        connectionFilter.ConnectionType == ConnectionType.Socks4aProxy ||
                                        connectionFilter.ConnectionType == ConnectionType.Socks5Proxy)
                                    {
                                        proxyPort = 1080;
                                    }
                                    else if (connectionFilter.ConnectionType == ConnectionType.HttpProxy)
                                    {
                                        proxyPort = 80;
                                    }
                                }
                            }
                        }

                        if (proxyHost == null)
                        {
                            return(null);
                        }

                        if (connectionFilter.ConnectionType == ConnectionType.Socks4Proxy ||
                            connectionFilter.ConnectionType == ConnectionType.Socks4aProxy ||
                            connectionFilter.ConnectionType == ConnectionType.Socks5Proxy ||
                            connectionFilter.ConnectionType == ConnectionType.HttpProxy)
                        {
                            var socket = ClientManager.Connect(new IPEndPoint(ClientManager.GetIpAddress(proxyHost), proxyPort), new TimeSpan(0, 0, 10));
                            garbages.Add(socket);

                            ProxyClientBase proxy = null;

                            if (connectionFilter.ConnectionType == ConnectionType.Socks4Proxy)
                            {
                                var user = (options != null) ? options.Where(n => n.Key.ToLower().StartsWith("user")).Select(n => n.Value).FirstOrDefault() : null;
                                proxy = new Socks4ProxyClient(socket, user, host, port);
                            }
                            else if (connectionFilter.ConnectionType == ConnectionType.Socks4aProxy)
                            {
                                var user = (options != null) ? options.Where(n => n.Key.ToLower().StartsWith("user")).Select(n => n.Value).FirstOrDefault() : null;
                                proxy = new Socks4aProxyClient(socket, user, host, port);
                            }
                            else if (connectionFilter.ConnectionType == ConnectionType.Socks5Proxy)
                            {
                                var user = (options != null) ? options.Where(n => n.Key.ToLower().StartsWith("user")).Select(n => n.Value).FirstOrDefault() : null;
                                var pass = (options != null) ? options.Where(n => n.Key.ToLower().StartsWith("pass")).Select(n => n.Value).FirstOrDefault() : null;
                                proxy = new Socks5ProxyClient(socket, user, pass, host, port);
                            }
                            else if (connectionFilter.ConnectionType == ConnectionType.HttpProxy)
                            {
                                proxy = new HttpProxyClient(socket, host, port);
                            }

                            var cap = new SocketCap(proxy.Create(new TimeSpan(0, 0, 30)));
                            garbages.Add(cap);

                            connection = new BaseConnection(cap, bandwidthLimit, _maxReceiveCount, _bufferManager);
                            garbages.Add(connection);
                        }
                    }
                }

                if (connection == null)
                {
                    return(null);
                }

                var secureConnection = new SecureConnection(SecureConnectionVersion.Version3, SecureConnectionType.Connect, connection, null, _bufferManager);
                garbages.Add(secureConnection);

                secureConnection.Connect(new TimeSpan(0, 0, 30));

                var compressConnection = new CompressConnection(secureConnection, _maxReceiveCount, _bufferManager);
                garbages.Add(compressConnection);

                compressConnection.Connect(new TimeSpan(0, 0, 10));

                return(compressConnection);
            }
            catch (Exception)
            {
                foreach (var item in garbages)
                {
                    item.Dispose();
                }
            }

            return(null);
        }
示例#13
0
        public Connection AcceptConnection(out string uri, BandwidthLimit bandwidthLimit)
        {
            uri = null;
            List <IDisposable> garbages = new List <IDisposable>();

            try
            {
                Connection connection = null;

                foreach (var type in (new int[] { 0, 1 }).Randomize())
                {
                    if (this.State == ManagerState.Stop)
                    {
                        return(null);
                    }

                    if (type == 0)
                    {
                        lock (this.ThisLock)
                        {
                            foreach (var item in _tcpListeners)
                            {
                                if (item.Value.Pending())
                                {
                                    var socket = item.Value.AcceptTcpClient().Client;
                                    garbages.Add(socket);

                                    {
                                        var remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;

                                        uri = string.Format("tcp:{0}:{1}", remoteEndPoint.Address, remoteEndPoint.Port);
                                    }

                                    if (!this.OnCheckUriEvent(uri))
                                    {
                                        _blockedCount.Increment();

                                        continue;
                                    }

                                    var cap = new SocketCap(socket);
                                    garbages.Add(cap);

                                    connection = new BaseConnection(cap, bandwidthLimit, _maxReceiveCount, _bufferManager);
                                    garbages.Add(connection);
                                }
                            }
                        }
                    }
                    else if (type == 1)
                    {
                        // Overlay network
                        var cap = this.OnAcceptCapEvent(out uri);
                        if (cap == null)
                        {
                            continue;
                        }

                        garbages.Add(cap);

                        connection = new BaseConnection(cap, bandwidthLimit, _maxReceiveCount, _bufferManager);
                        garbages.Add(connection);
                    }

                    if (connection != null)
                    {
                        break;
                    }
                }

                if (connection == null)
                {
                    return(null);
                }

                var secureConnection = new SecureConnection(SecureConnectionVersion.Version3, SecureConnectionType.Accept, connection, null, _bufferManager);
                garbages.Add(secureConnection);

                secureConnection.Connect(new TimeSpan(0, 0, 30));

                var compressConnection = new CompressConnection(secureConnection, _maxReceiveCount, _bufferManager);
                garbages.Add(compressConnection);

                compressConnection.Connect(new TimeSpan(0, 0, 10));

                return(compressConnection);
            }
            catch (Exception)
            {
                foreach (var item in garbages)
                {
                    item.Dispose();
                }
            }

            return(null);
        }
		private static Stream OpenStream(HttpWebRequest req)
		{
			Socket sock=OpenSocket(req);
			if(req.isSecured)
			{
#if CONFIG_SSL
				SecureConnection secured=new SecureConnection();
				/*TODO: suspected memory hold for SecureConnection */
				Stream retval=secured.OpenStream(sock);
				return retval;
#else
				throw new NotSupportedException(S._("NotSupp_SSL"));
#endif
			}
			else
			{
				return new NetworkStream(sock,true);
			}
		}
        public void Test_SecureConnection()
        {
            for (int i = 0; i < 32; i++)
            {
                TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 60000));
                listener.Start();
                var listenerAcceptSocket = listener.BeginAcceptSocket(null, null);

                TcpClient client = new TcpClient();
                client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 60000));

                var server = listener.EndAcceptSocket(listenerAcceptSocket);
                listener.Stop();

                DigitalSignature clientDigitalSignature = null;
                DigitalSignature serverDigitalSignature = null;

                if (_random.Next(0, 100) < 50)
                {
                    clientDigitalSignature = new DigitalSignature("NickName1", DigitalSignatureAlgorithm.EcDsaP521_Sha256);
                }

                if (_random.Next(0, 100) < 50)
                {
                    serverDigitalSignature = new DigitalSignature("NickName2", DigitalSignatureAlgorithm.EcDsaP521_Sha256);
                }

                SecureConnectionVersion clientVersion;
                SecureConnectionVersion serverVersion;

                {
                    clientVersion = SecureConnectionVersion.Version3;
                    serverVersion = SecureConnectionVersion.Version3;
                }

                {
                    //SecureConnectionVersion clientVersion = 0;
                    //SecureConnectionVersion serverVersion = 0;

                    //for (; ; )
                    //{
                    //    switch (_random.Next(0, 3))
                    //    {
                    //        case 0:
                    //            clientVersion = SecureConnectionVersion.Version2;
                    //            break;
                    //        case 1:
                    //            clientVersion = SecureConnectionVersion.Version3;
                    //            break;
                    //        case 2:
                    //            clientVersion = SecureConnectionVersion.Version2 | SecureConnectionVersion.Version3;
                    //            break;
                    //    }

                    //    switch (_random.Next(0, 3))
                    //    {
                    //        case 0:
                    //            serverVersion = SecureConnectionVersion.Version2;
                    //            break;
                    //        case 1:
                    //            serverVersion = SecureConnectionVersion.Version3;
                    //            break;
                    //        case 2:
                    //            serverVersion = SecureConnectionVersion.Version2 | SecureConnectionVersion.Version3;
                    //            break;
                    //    }

                    //    if ((clientVersion & serverVersion) != 0) break;
                    //}
                }

                //var TcpClient = new BaseConnection(client.Client, Test_Library_Net_Connection.MaxReceiveCount, _bufferManager);
                using (var secureClient = new SecureConnection(clientVersion, SecureConnectionType.Connect, new BaseConnection(new SocketCap(client.Client), null, Test_Library_Net_Connection.MaxReceiveCount, _bufferManager), clientDigitalSignature, _bufferManager))
                    using (var secureServer = new SecureConnection(serverVersion, SecureConnectionType.Accept, new BaseConnection(new SocketCap(server), null, Test_Library_Net_Connection.MaxReceiveCount, _bufferManager), serverDigitalSignature, _bufferManager))
                    {
                        try
                        {
                            var clientConnectTask = secureClient.ConnectAsync(new TimeSpan(0, 0, 20));
                            var serverConnectTask = secureServer.ConnectAsync(new TimeSpan(0, 0, 20));

                            Task.WaitAll(clientConnectTask, serverConnectTask);

                            if (clientDigitalSignature != null)
                            {
                                if (secureServer.Certificate.ToString() != clientDigitalSignature.ToString())
                                {
                                    throw new Exception();
                                }
                            }

                            if (serverDigitalSignature != null)
                            {
                                if (secureClient.Certificate.ToString() != serverDigitalSignature.ToString())
                                {
                                    throw new Exception();
                                }
                            }

                            using (MemoryStream stream = new MemoryStream())
                            {
                                var buffer = new byte[1024 * 8];
                                _random.NextBytes(buffer);

                                stream.Write(buffer, 0, buffer.Length);
                                stream.Seek(0, SeekOrigin.Begin);

                                var clientSendTask    = secureClient.SendAsync(stream, new TimeSpan(0, 0, 20));
                                var serverReceiveTask = secureServer.ReceiveAsync(new TimeSpan(0, 0, 20));

                                Task.WaitAll(clientConnectTask, serverReceiveTask);

                                using (var returnStream = serverReceiveTask.Result)
                                {
                                    var buff2 = new byte[(int)returnStream.Length];
                                    returnStream.Read(buff2, 0, buff2.Length);

                                    Assert.IsTrue(CollectionUtilities.Equals(buffer, buff2), "SecureConnection #1");
                                }
                            }

                            using (MemoryStream stream = new MemoryStream())
                            {
                                var buffer = new byte[1024 * 8];
                                _random.NextBytes(buffer);

                                stream.Write(buffer, 0, buffer.Length);
                                stream.Seek(0, SeekOrigin.Begin);

                                var serverSendTask    = secureServer.SendAsync(stream, new TimeSpan(0, 0, 20));
                                var clientReceiveTask = secureClient.ReceiveAsync(new TimeSpan(0, 0, 20));

                                Task.WaitAll(serverSendTask, clientReceiveTask);

                                using (var returnStream = clientReceiveTask.Result)
                                {
                                    var buff2 = new byte[(int)returnStream.Length];
                                    returnStream.Read(buff2, 0, buff2.Length);

                                    Assert.IsTrue(CollectionUtilities.Equals(buffer, buff2), "SecureConnection #2");
                                }
                            }
                        }
                        catch (AggregateException e)
                        {
                            Assert.IsTrue(e.InnerException.GetType() == typeof(ConnectionException) &&
                                          (clientVersion & serverVersion) == 0, "SecureConnection #Version test");
                        }
                    }

                client.Close();
                server.Close();
            }
        }