Пример #1
0
        /// <summary>
        /// Ends the host connection phase and negotiates the proxied connection
        /// </summary>
        private void EndConnectToIPAddress(IAsyncResult res)
        {
            try
            {
                socket.EndConnect(res);
                if (destinationSsl)
                {
                    socket.AuthenticateAsClient(destinationServer);
                }
            }
            catch (Exception sockex)
            {
                OnConnectionFailed("Can't connect to server: {0}", sockex);
                return;
            }

            if (parent.Connections.LocalInternalIP == null)
            {
                parent.Connections.LocalInternalIP = ((IPEndPoint)socket.LocalEndPoint).Address;
            }

            if (parent.ServerSettings.ProxySetting == ProxyType.None)
            {
                OnConnectionComplete();
                return;
            }


            if (parent.ServerSettings.ProxySetting == ProxyType.Socks5)
            {
                Socks5AuthType auth = GetSocks5AuthMethod();
                if (auth == Socks5AuthType.AuthMethodRejected)
                {
                    socket.Close();
                    OnConnectionFailed("SOCKS5 authentication mechanism unsupported");
                    return;
                }
                else if (auth != Socks5AuthType.None)
                {
                    if (SendSocks5Authentication() == false)
                    {
                        socket.Close();
                        OnConnectionFailed("SOCK5 authentication failed, bad username/password");
                        return;
                    }
                }

                if (SendSocks5ConnectRequest() == false)
                {
                    socket.Close();
                    OnConnectionFailed("SOCKS5 connect failed, proxy server failure");
                    return;
                }
            }

            // Done!
            OnConnectionComplete();
        }
Пример #2
0
        protected override void ConnectionTimedOut(object data)
        {
            if (socket != null)
            {
                socket.Close();
            }
            if (_listener != null)
            {
                _listener.Close();
            }

            OnDirectConnectFailed("Connection timed out");
        }
Пример #3
0
        /// <summary>
        /// Disconnects from the OSCAR server
        /// </summary>
        /// <param name="error"><c>true</c> if the disconnection is resulting from an error, <c>false</c> otherwise</param>
        /// <returns><c>true</c> if the disconnection succeeded without error,
        /// <c>false</c> otherwise</returns>
        public bool DisconnectFromServer(bool error)
        {
            isDisconnecting = true;

            try
            {
                if (socket != null)
                {
                    socket.Blocking = false;
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                parent.Connections.DeregisterConnection(this, error);
                isConnecting = false;
                keepAliveTimer.Change(Timeout.Infinite, Timeout.Infinite);
                StopTimeoutPeriod();
            }
            return(true);
        }
Пример #4
0
        public void Close()
        {
            IsConnected = false;
            if (client == null)
            {
                return;
            }
            if (DisconnectEvent != null)
            {
                DisconnectEvent();
            }
#if WINDOWS_UWP
            client.Dispose();
#else
            client.Close();
#endif
        }
Пример #5
0
        /// <summary>
        /// Releases the unmanaged resources used by the NetworkStream and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
#if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81
            _outputStream?.Dispose();
            _outputStream = null;
            _inputStream?.Dispose();
            _outputStream = null;
            _socket?.Dispose();
            _socket = null;
#elif __ANDROID__
            _socket?.Close();
            _socket?.Dispose();
            _socket = null;
#endif

            base.Dispose(disposing);
        }
Пример #6
0
        //------------------------------------------------------------------------------------------------------------------------
        SimpleActionResult _sockConnection(string RemoteHost, int RemotePort)
        {
            //declares
            bool   isSecured   = false;
            string sslProtocol = "";
            var    result      = new SimpleActionResult()
            {
                IsSuccessful = false,
                Message      = "",
            };

            lock (this)
            {
                //create socket
#if NETFX
                _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#elif UNIVERSAL
                _sock = new StreamSocket();
#endif

                //Try to connect
                try
                {
                    //attemp connection
#if NETFX
                    _sock.Connect(RemoteHost, RemotePort);
#elif UNIVERSAL
                    SocketSetup?.Invoke(this, _sock);
                    _sock.Control.KeepAlive = true;
                    _sock.ConnectAsync(new Windows.Networking.HostName(RemoteHost), RemotePort.ToStringInvariant(), SocketProtectionLevel.PlainSocket).AsTask().Wait();
#endif
                }
                catch (Exception ex)
                {
                    DebugEx.TraceError(ex, "Connection Error");
                    result.Message = ex.Message;
                    try { Close("Connection Error"); } catch { }
                    return(result);
                }


                //create network stream
#if NETFX
                //Stream _netstream = new BufferedStream(new NetworkStream(_sock, true));
                Stream _netstream = new NetworkStream(_sock, true);
#endif

                //Wrap with a secure stream?
                if (Secure)
                {
#if NETFX
                    //create ssl stream
                    var sslstream = new SslStream(_netstream, false);
#endif
                    //decide on certifacte server name
                    var remCertHostName = !string.IsNullOrWhiteSpace(CertificateServerName) ? CertificateServerName : RemoteHost;

                    try
                    {
#if NETFX
                        //collect certificates
                        var certs = Yodiwo.Tools.Certificates.CollectCertificates();
                        if (CustomCertificates != null)
                        {
                            foreach (var c in CustomCertificates)
                            {
                                certs.Add(c);
                            }
                        }

                        //try authenticate
                        sslstream.AuthenticateAsClient(remCertHostName,
                                                       certs,
                                                       System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12,
                                                       true
                                                       );


                        //checks
                        if (!sslstream.IsAuthenticated)
                        {
                            DebugEx.Assert("Not authenticated");
                            throw new Exception("Not authenticated");
                        }
                        if (!sslstream.IsEncrypted)
                        {
                            DebugEx.Assert("No encryption");
                            throw new Exception("Not encryption");
                        }

                        //get info
                        isSecured   = true;
                        sslProtocol = sslstream.SslProtocol.ToStringInvariant();

                        //use this stream from now on
                        _netstream = sslstream;
#elif UNIVERSAL
                        _sock.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new Windows.Networking.HostName(remCertHostName)).AsTask().Wait();
                        var _isSecured = _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls10 ||
                                         _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls11 ||
                                         _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls12;
                        if (!_isSecured)
                        {
                            throw new Exception("Connection not secured (" + _sock.Information.ProtectionLevel + ")");
                        }
#endif
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceError(ex, "Certificate not accepted, " + ex.Message);
                        result.Message = "Certificate not accepted, " + ex.Message;
                        if (ex.InnerException != null)
                        {
                            result.Message += "  (inner msg=" + ex.InnerException.Message + ")";
                        }
                        try { Close("Certificate not accepted, " + ex.Message); } catch { }
#if NETFX
                        try { _netstream?.Close(); _netstream?.Dispose(); } catch { }
                        try { sslstream?.Close(); sslstream?.Dispose(); } catch { }
                        try { _sock?.Close(); } catch { }
#endif
                        try { _sock?.Dispose(); } catch { }
                        return(result);
                    }
                }


                //write packers
#if NETFX
                var _nodelay = _sock.NoDelay;
                _sock.NoDelay = true; //Disable the Nagle Algorithm
                _netstream.WriteByte((byte)this.SupportedChannelSerializationModes);
                _netstream.WriteByte((byte)this.PreferredChannelSerializationModes);
                _sock.NoDelay = _nodelay; //Restore (default:enable) the Nagle Algorithm
#elif UNIVERSAL
                {
                    var wStream = _sock.OutputStream.AsStreamForWrite();
                    wStream.WriteByte((byte)this.SupportedChannelSerializationModes);
                    wStream.WriteByte((byte)this.PreferredChannelSerializationModes);
                    wStream.Flush();
                }
#endif

                //read final packer
                var packerType = ChannelSerializationMode.Unkown;
#if NETFX
                packerType = (ChannelSerializationMode)_netstream.ReadByte();
#elif UNIVERSAL
                packerType = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
#endif
                if (!this.SupportedChannelSerializationModes.HasFlag(packerType))
                {
                    DebugEx.Assert("Invalid ChannelSerializationMode. Server uses  " + packerType);
                    result.Message = "Invalid ChannelSerializationMode. Server uses  " + packerType;
                    try { Close("Invalid ChannelSerializationMode. Server uses  " + packerType); } catch { }
#if NETFX
                    try { _netstream?.Close(); _netstream?.Dispose(); } catch { }
                    try { _sock?.Close(); } catch { }
#endif
                    try { _sock?.Dispose(); } catch { }
                    return(result);
                }
                //select serialization mode
                _ChannelSerializationMode = packerType;

                //setup info
                try
                {
#if NETFX
                    this.LocalHost  = _sock.LocalEndPoint.GetIPAddress().ToString();
                    this.RemotePort = _sock.LocalEndPoint.GetPort().ToStringInvariant();
#elif UNIVERSAL
                    this.LocalHost  = _sock.Information.LocalAddress.ToString();
                    this.RemotePort = _sock.Information.LocalPort;
#endif
                }
                catch { }

                //setup info
                this.RemoteHost = RemoteHost;
                this.RemotePort = RemotePort.ToStringInvariant();

                //log
                DebugEx.TraceLog("YPClient (socks) new connection to " + RemoteHost + ":" + RemotePort + " (Secure=" + isSecured + ",SSL=" + sslProtocol + ")");

                //create stream
#if NETFX
                SetupStream(_netstream);
#elif UNIVERSAL
                SetupStream();
#endif
                result.IsSuccessful = true;
                return(result);
            }
        }
Пример #7
0
        private void ConnectCallback(IAsyncResult result)
#endif
        {
            //We can get here is the connection fails and the monotor thread
            // calls close. We should just do nothing at this point
#if __WINDOWS__
            if (client == null || !connected)
            {
                return;
            }

            if (stopped)
            {
                if (connected)
                {
                    client.Dispose();
                }
                return;
            }
#else
            if ((client != null && !client.Connected))
            {
                return;
            }

            if (stopped)
            {
                if (client.Connected)
                {
                    client.Close();
                }
                return;
            }

            clientStream = GSTlsClient.WrapStream(client.GetStream(), remotehost);
#endif

            //Each time a tcp connection is established we re-authenticate
            try {
                LoginCommand loginCmd = new LoginCommand(session.ConnectToken);

                Send(loginCmd);

                Packet p = PooledObjects.PacketPool.Pop();

                PositionStream rss = PooledObjects.PositionStreamPool.Pop();
#if __WINDOWS__
                rss.Wrap(client.InputStream.AsStreamForRead());
#else
                rss.Wrap(clientStream);
#endif

                int bytesRead = 0;

                while ((bytesRead = read(rss, p)) != 0)
                {
                    OnPacketReceived(p, bytesRead);
                    PooledObjects.PacketPool.Push(p);
                    p = PooledObjects.PacketPool.Pop();
                }

                PooledObjects.PacketPool.Push(p);
                PooledObjects.PositionStreamPool.Push(rss);
            }
#if __WINDOWS__
            /*catch (AggregateException exception)
             * {
             *  foreach (Exception ex in exception.InnerExceptions)
             *  {
             *      System.Diagnostics.Debug.WriteLine(ex);
             *  }
             * }*/
#endif
            catch (Exception e)
            {
                if (session != null && !stopped)
                {
                    session.ConnectState = GameSparksRT.ConnectState.Disconnected;
                    session.Log("ReliableConnection", GameSparksRT.LogLevel.DEBUG, e.Message);
                    try{
                        session.OnReady(false);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
            }
        }