private void FireOnSent(BaseSocketConnection connection, byte[] buffer, bool sentByServer)
 {
     if (connection.Active)
     {
         FSocketService.OnSent(new MessageEventArgs(connection, buffer, sentByServer));
     }
 }
 internal override void BeginSendTo(BaseSocketConnection connection, byte[] buffer)
 {
     if (!Disposed)
     {
         BeginSend(connection, buffer, true);
     }
 }
Esempio n. 3
0
        public byte[] GetRawBufferWithTail(BaseSocketConnection connection, int index, int delimiterSize)
        {
            //----- Get Raw Buffer with Tail!
            byte[] result        = null;
            int    messageLength = 0;
            int    clearLength   = index + delimiterSize;

            if (connection.DelimiterType == DelimiterType.dtMessageTailIncludeOnReceive)
            {
                messageLength = index + delimiterSize;
            }
            else
            {
                messageLength = index;
            }

            result = new byte[messageLength];
            Buffer.BlockCopy(FPacketBuffer, 0, result, 0, messageLength);

            //----- Adjust Packet Buffer!
            byte[] packetBuffer = new byte[FPacketBuffer.Length - clearLength];
            Buffer.BlockCopy(FPacketBuffer, clearLength, packetBuffer, 0, packetBuffer.Length);

            FPacketBuffer = packetBuffer;
            FPacketOffSet = FPacketOffSet - clearLength;

            return(result);
        }
 internal void FireOnConnected(BaseSocketConnection connection)
 {
     if (connection.Active)
     {
         FSocketService.OnConnected(new ConnectionEventArgs(connection));
     }
 }
 internal void FireOnException(BaseSocketConnection connection, Exception ex, bool forceEvent)
 {
     if (forceEvent || connection.Active)
     {
         FSocketService.OnException(new ExceptionEventArgs(connection, ex));
     }
 }
        /// <summary>
        /// Begin disconnect the connection
        /// </summary>
        internal void BeginDisconnect(BaseSocketConnection connection)
        {
            if (!Disposed)
            {
                ConnectionEventArgs e = new ConnectionEventArgs(connection);

                if (connection.Active)
                {
                    try
                    {
                        if ((Environment.OSVersion.Version.Major == 5) &&
                            (Environment.OSVersion.Version.Minor >= 1))
                        {
                            //----- NT5 / WinXP and later!
                            connection.Socket.BeginDisconnect(false, new AsyncCallback(BeginDisconnectCallback), e);
                        }
                        else
                        {
                            //----- NT5 / Win2000!
                            ThreadPool.QueueUserWorkItem(new WaitCallback(BeginDisconnectCallbackProcessing), e);
                        }
                    }
                    catch (Exception ex)
                    {
                        FireOnException(connection, ex);
                    }
                }
                else
                {
                    RemoveSocketConnection(connection);
                    DisposeAndNullConnection(ref connection);
                }
            }
        }
Esempio n. 7
0
        internal void Reconnect(bool resetAttempts, BaseSocketConnection connection, Exception ex)
        {
            if (!Disposed)
            {
                if (resetAttempts)
                {
                    FReconnectAttempted = 0;
                }

                if (FReconnectAttempts > 0)
                {
                    if (FReconnectAttempted < FReconnectAttempts)
                    {
                        Host.RemoveSocketConnection(connection);
                        Host.DisposeAndNullConnection(ref connection);

                        FReconnectTimer.Change(FReconnectAttemptInterval, FReconnectAttemptInterval);
                    }
                    else
                    {
                        Host.FireOnException(connection, new ReconnectAttemptsException("Max reconnect attempts reached"), true);
                    }
                }
                else
                {
                    if ((connection != null) && (ex != null))
                    {
                        Host.FireOnException(connection, ex, true);
                    }
                }
            }
        }
 internal void DisposeAndNullConnection(ref BaseSocketConnection connection)
 {
     if (connection != null)
     {
         connection.Dispose();
         connection = null;
     }
 }
        /// <summary>
        /// Connect callback!
        /// </summary>
        /// <param name="ar"></param>
        internal void BeginConnectCallbackAsync(object sender, SocketAsyncEventArgs e)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection = null;
                SocketConnector      connector  = null;
                Exception            exception  = null;

                if (e.SocketError == SocketError.Success)
                {
                    try
                    {
                        connector = (SocketConnector)e.UserToken;

                        connection = new ClientSocketConnection(Host, connector, connector.Socket);

                        //----- Adjust buffer size!
                        connector.Socket.ReceiveBufferSize = Host.SocketBufferSize;
                        connector.Socket.SendBufferSize    = Host.SocketBufferSize;

                        //----- Initialize!
                        Host.AddSocketConnection(connection);
                        connection.Active = true;

                        Host.InitializeConnection(connection);
                    }
                    catch (Exception ex)
                    {
                        exception = ex;

                        if (connection != null)
                        {
                            Host.DisposeConnection(connection);
                            Host.RemoveSocketConnection(connection);

                            connection = null;
                        }
                    }
                }
                else
                {
                    exception = new SocketException((int)e.SocketError);
                }

                if (exception != null)
                {
                    FReconnectAttempted++;
                    ReconnectConnection(false, exception);
                }
            }

            e.UserToken = null;
            e.Dispose();
            e = null;
        }
Esempio n. 10
0
        internal override BaseSocketConnection GetConnectionById(long connectionId)
        {
            BaseSocketConnection result = null;

            if (!Disposed)
            {
                result = GetSocketConnectionById(connectionId);
            }

            return(result);
        }
        private void BeginDisconnectCallbackProcessing(object state)
        {
            if (!Disposed)
            {
                bool calledByBeginDisconnect = false;

                IAsyncResult         ar         = null;
                BaseSocketConnection connection = null;
                ConnectionEventArgs  e          = null;

                try
                {
                    if (state is ConnectionEventArgs)
                    {
                        //----- NT5 / Win2000!
                        e = (ConnectionEventArgs)state;
                        calledByBeginDisconnect = false;
                    }
                    else
                    {
                        //----- NT5 / WinXP and later!
                        ar = (IAsyncResult)state;
                        e  = (ConnectionEventArgs)ar.AsyncState;
                        calledByBeginDisconnect = true;
                    }

                    connection = (BaseSocketConnection)e.Connection;

                    if (connection.Active)
                    {
                        if (calledByBeginDisconnect)
                        {
                            connection.Socket.EndDisconnect(ar);
                        }

                        lock (connection.SyncActive)
                        {
                            connection.Active = false;
                            connection.Socket.Close();
                        }

                        FireOnDisconnected(e);
                    }

                    RemoveSocketConnection(connection);
                    DisposeAndNullConnection(ref connection);
                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }
            }
        }
Esempio n. 12
0
        protected override void InitializeConnection(object state)
        {
            BaseSocketConnection connection = (BaseSocketConnection)state;

            if (FProxyInfo != null)
            {
                InitializeProxy(connection);
            }
            else
            {
                base.InitializeConnection(connection);
            }
        }
        /// <summary>
        /// Begin send the data.
        /// </summary>
        internal void BeginSend(BaseSocketConnection connection, byte[] buffer, bool sentByServer)
        {
            if (!Disposed)
            {
                try
                {
                    if (connection.Active)
                    {
                        if (buffer.Length > FMessageBufferSize)
                        {
                            throw new MessageLengthException("Message length is greater than Host maximum message length.");
                        }

                        connection.LastAction = DateTime.Now;

                        MessageBuffer writeMessage = MessageBuffer.GetPacketMessage(connection, buffer);
                        writeMessage.SentByServer = sentByServer;

                        lock (connection.WriteQueue)
                        {
                            if (connection.WriteQueueHasItems)
                            {
                                //----- If the connection is sending, enqueue the message!
                                connection.WriteQueue.Enqueue(writeMessage);
                            }
                            else
                            {
                                //----- If the connection is not sending, send the message!
                                connection.WriteQueueHasItems = true;

                                if (connection.Stream != null)
                                {
                                    //----- Ssl!
                                    connection.Stream.BeginWrite(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, new AsyncCallback(BeginSendCallback), new CallbackData(connection, writeMessage));
                                }
                                else
                                {
                                    //----- Socket!
                                    connection.Socket.BeginSend(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginSendCallback), new CallbackData(connection, writeMessage));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }
            }
        }
Esempio n. 14
0
        private void SslAuthenticateCallback(IAsyncResult ar)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection = null;
                SslStream            stream     = null;
                bool completed = false;

                try
                {
                    AuthenticateCallbackData callbackData = (AuthenticateCallbackData)ar.AsyncState;

                    connection = callbackData.Connection;
                    stream     = callbackData.Stream;

                    if (connection.Active)
                    {
                        if (callbackData.HostType == HostType.htClient)
                        {
                            stream.EndAuthenticateAsClient(ar);
                        }
                        else
                        {
                            stream.EndAuthenticateAsServer(ar);
                        }

                        if ((stream.IsSigned && stream.IsEncrypted))
                        {
                            completed = true;
                        }

                        callbackData      = null;
                        connection.Stream = stream;

                        if (!completed)
                        {
                            throw new SSLAuthenticationException("Ssl authenticate is not signed or not encrypted.");
                        }

                        FHost.FireOnConnected(connection);
                    }
                }
                catch (Exception ex)
                {
                    FHost.FireOnException(connection, ex);
                }
            }
        }
        internal void AddSocketConnection(BaseSocketConnection socketConnection)
        {
            if (!Disposed)
            {
                FSocketConnectionsSync.AcquireWriterLock(Timeout.Infinite);

                try
                {
                    FSocketConnections.Add(socketConnection.ConnectionId, socketConnection);
                }
                finally
                {
                    FSocketConnectionsSync.ReleaseWriterLock();
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes the connection with encryption.
        /// </summary>
        /// <param name="connection"></param>
        protected virtual void InitializeConnection(object state)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection = (BaseSocketConnection)state;

                if (FCryptoService != null)
                {
                    InitializeCryptService(connection);
                }
                else
                {
                    //----- No encryption!
                    FHost.FireOnConnected(connection);
                }
            }
        }
Esempio n. 17
0
        private void InitializeProxyReceiveCallback(IAsyncResult ar)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection   = null;
                MessageBuffer        readMessage  = null;
                CallbackData         callbackData = null;

                try
                {
                    callbackData = (CallbackData)ar.AsyncState;
                    connection   = callbackData.Connection;
                    readMessage  = callbackData.Buffer;

                    if (connection.Active)
                    {
                        int readBytes = connection.Socket.EndReceive(ar);

                        if (readBytes > 0)
                        {
                            FProxyInfo.GetProxyResponseStatus(readMessage.PacketBuffer);

                            readMessage  = null;
                            callbackData = null;

                            if (FProxyInfo.Completed)
                            {
                                base.InitializeConnection(connection);
                            }
                            else
                            {
                                InitializeProxy(connection);
                            }
                        }
                        else
                        {
                            throw new ProxyAuthenticationException(0, "Proxy connection aborted.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Host.FireOnException(connection, ex);
                }
            }
        }
        private void BeginReadCallbackProcessing(object state)
        {
            if (!Disposed)
            {
                IAsyncResult ar = (IAsyncResult)state;

                BaseSocketConnection connection = null;

                try
                {
                    CallbackData callbackData = (CallbackData)ar.AsyncState;

                    connection = callbackData.Connection;

                    if (connection.Active)
                    {
                        int readBytes = 0;

                        if (connection.Stream != null)
                        {
                            //----- Ssl!
                            readBytes = connection.Stream.EndRead(ar);
                        }
                        else
                        {
                            //----- Socket!
                            readBytes = connection.Socket.EndReceive(ar);
                        }

                        if (readBytes > 0)
                        {
                            ReadBytesFromConnection(callbackData, readBytes);
                        }
                        else
                        {
                            //----- Is has no data to read then the connection has been terminated!
                            connection.BeginDisconnect();
                        }
                    }
                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }
            }
        }
Esempio n. 19
0
        public static byte[] GetPacketBuffer(BaseSocketConnection connection, byte[] buffer, ref int bufferSize)
        {
            byte[] result = null;
            buffer = CryptUtils.EncryptData(connection, buffer);

            switch (connection.DelimiterType)
            {
            case DelimiterType.dtNone:

                //----- No Delimiter!
                bufferSize = buffer.Length;

                result = connection.BaseHost.BufferManager.TakeBuffer(bufferSize);
                Buffer.BlockCopy(buffer, 0, result, 0, buffer.Length);


                break;

            case DelimiterType.dtMessageTailExcludeOnReceive:
            case DelimiterType.dtMessageTailIncludeOnReceive:

                if (connection.Delimiter?.Length > 0)
                {
                    //----- Need delimiter!
                    bufferSize = buffer.Length + connection.Delimiter.Length;

                    result = connection.BaseHost.BufferManager.TakeBuffer(bufferSize);
                    Buffer.BlockCopy(buffer, 0, result, 0, buffer.Length);
                    Buffer.BlockCopy(connection.Delimiter, 0, result, buffer.Length, connection.Delimiter.Length);
                }
                else
                {
                    bufferSize = buffer.Length;

                    result = connection.BaseHost.BufferManager.TakeBuffer(bufferSize);
                    Buffer.BlockCopy(buffer, 0, result, 0, buffer.Length);
                }

                break;
            }

            return(result);
        }
Esempio n. 20
0
 protected void InitializeProxy(BaseSocketConnection connection)
 {
     if (!Disposed)
     {
         try
         {
             if (connection.Active)
             {
                 MessageBuffer mb = new MessageBuffer(0);
                 mb.PacketBuffer = FProxyInfo.GetProxyRequestData(FRemoteEndPoint);
                 connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxySendCallback), new CallbackData(connection, mb));
             }
         }
         catch (Exception ex)
         {
             Host.FireOnException(connection, ex);
         }
     }
 }
        internal BaseSocketConnection GetSocketConnectionById(long connectionId)
        {
            BaseSocketConnection item = null;

            if (!Disposed)
            {
                FSocketConnectionsSync.AcquireReaderLock(Timeout.Infinite);

                try
                {
                    item = FSocketConnections[connectionId];
                }
                finally
                {
                    FSocketConnectionsSync.ReleaseReaderLock();
                }
            }

            return(item);
        }
        /// <summary>
        /// Receive data from connetion.
        /// </summary>
        internal void BeginReceive(BaseSocketConnection connection)
        {
            if (!Disposed)
            {
                try
                {
                    if (connection.Active)
                    {
                        lock (connection.SyncReadCount)
                        {
                            if (connection.ReadCanEnqueue)
                            {
                                if (connection.ReadCount == 0)
                                {
                                    //----- if the connection is not receiving, start the receive!
                                    MessageBuffer readMessage = new MessageBuffer(FSocketBufferSize);

                                    if (connection.Stream != null)
                                    {
                                        //----- Ssl!
                                        connection.Stream.BeginRead(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }
                                    else
                                    {
                                        //----- Socket!
                                        connection.Socket.BeginReceive(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }
                                }

                                //----- Increase the read count!
                                connection.ReadCount++;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }
            }
        }
Esempio n. 23
0
        private void InitializeProxySendCallback(IAsyncResult ar)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection   = null;
                MessageBuffer        writeMessage = null;
                CallbackData         callbackData = null;

                try
                {
                    callbackData = (CallbackData)ar.AsyncState;
                    connection   = callbackData.Connection;
                    writeMessage = callbackData.Buffer;

                    if (connection.Active)
                    {
                        //----- Socket!
                        int writeBytes = connection.Socket.EndSend(ar);

                        if (writeBytes < writeMessage.PacketRemaining)
                        {
                            //----- Continue to send until all bytes are sent!
                            writeMessage.PacketOffSet += writeBytes;
                            connection.Socket.BeginSend(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxySendCallback), callbackData);
                        }
                        else
                        {
                            writeMessage = null;
                            callbackData = null;

                            MessageBuffer readMessage = new MessageBuffer(4096);
                            connection.Socket.BeginReceive(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxyReceiveCallback), new CallbackData(connection, readMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Host.FireOnException(connection, ex);
                }
            }
        }
        internal BaseSocketConnection[] GetSocketConnections()
        {
            BaseSocketConnection[] items = null;

            if (!Disposed)
            {
                FSocketConnectionsSync.AcquireReaderLock(Timeout.Infinite);

                try
                {
                    items = new BaseSocketConnection[FSocketConnections.Count];
                    FSocketConnections.Values.CopyTo(items, 0);
                }
                finally
                {
                    FSocketConnectionsSync.ReleaseReaderLock();
                }
            }

            return(items);
        }
Esempio n. 25
0
        /// <summary>
        /// Connect callback!
        /// </summary>
        /// <param name="ar"></param>
        internal void BeginConnectCallback(IAsyncResult ar)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection = null;
                SocketConnector      connector  = null;

                try
                {
                    connector  = (SocketConnector)ar.AsyncState;
                    connection = new ClientSocketConnection(Host, connector, connector.Socket);

                    connector.Socket.EndConnect(ar);

                    //----- Adjust buffer size!
                    connector.Socket.ReceiveBufferSize = Host.SocketBufferSize;
                    connector.Socket.SendBufferSize    = Host.SocketBufferSize;

                    connection.Active = true;

                    //----- Initialize!
                    Host.AddSocketConnection(connection);
                    InitializeConnection(connection);
                }
                catch (Exception ex)
                {
                    if (ex is SocketException)
                    {
                        FReconnectAttempted++;
                        Reconnect(false, connection, ex);
                    }
                    else
                    {
                        Host.FireOnException(connection, ex);
                    }
                }
            }
        }
        private void FireOnReceived(BaseSocketConnection connection, byte[] buffer, bool readCanEnqueue)
        {
            if (connection.Active)
            {
                if (!readCanEnqueue)
                {
                    lock (connection.SyncReadCount)
                    {
                        connection.ReadCanEnqueue = false;
                    }
                }

                FSocketService.OnReceived(new MessageEventArgs(connection, buffer, false));

                if (!readCanEnqueue)
                {
                    lock (connection.SyncReadCount)
                    {
                        connection.ReadCanEnqueue = true;
                    }
                }
            }
        }
Esempio n. 27
0
        public static byte[] GetRawBufferWithTail(BaseSocketConnection connection, SocketAsyncEventArgs e, int position, int delimiterSize)
        {
            //----- Get Raw Buffer with Tail!
            byte[] result = null;

            if (connection.DelimiterType == DelimiterType.dtMessageTailIncludeOnReceive)
            {
                result = new byte[position - e.Offset + 1];
            }
            else
            {
                result = new byte[position - e.Offset + 1 - delimiterSize];
            }

            Buffer.BlockCopy(e.Buffer, e.Offset, result, 0, result.Length);

            for (int i = 0; i < delimiterSize; i++)
            {
                e.Buffer[position - i] = 0;
            }

            return(result);
        }
        internal void RemoveSocketConnection(BaseSocketConnection socketConnection)
        {
            if (!Disposed)
            {
                if (socketConnection != null)
                {
                    FSocketConnectionsSync.AcquireWriterLock(Timeout.Infinite);

                    try
                    {
                        FSocketConnections.Remove(socketConnection.ConnectionId);
                    }
                    finally
                    {
                        FSocketConnectionsSync.ReleaseWriterLock();

                        if (FSocketConnections.Count <= 0)
                        {
                            FWaitConnectionsDisposing.Set();
                        }
                    }
                }
            }
        }
        internal BaseSocketConnection[] GetSocketConnections()
        {

            BaseSocketConnection[] items = null;

            if (!Disposed)
            {

                FSocketConnectionsSync.AcquireReaderLock(Timeout.Infinite);

                try
                {
                    items = new BaseSocketConnection[FSocketConnections.Count];
                    FSocketConnections.Values.CopyTo(items, 0);
                }
                finally
                {
                    FSocketConnectionsSync.ReleaseReaderLock();
                }

            }

            return items;

        }
        internal void FireOnConnected(BaseSocketConnection connection)
        {

            if (connection.Active)
            {
                FSocketService.OnConnected(new ConnectionEventArgs(connection));
            }

        }
        protected void InitializeCryptService(BaseSocketConnection connection)
        { 

          //----- None!
          if (connection.EncryptType == EncryptType.etNone || connection.EncryptType == EncryptType.etBase64)
          {
              FHost.FireOnConnected(connection);
          }

          //----- Symmetric!
          if (connection.EncryptType == EncryptType.etRijndael || connection.EncryptType == EncryptType.etTripleDES)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get RSA provider!
                  RSACryptoServiceProvider serverPublicKey;
                  RSACryptoServiceProvider clientPrivateKey = new RSACryptoServiceProvider();
                  byte[] signMessage;

                  FCryptoService.OnSymmetricAuthenticate(connection, out serverPublicKey, out signMessage);

                  //----- Generates symmetric algoritm!
                  SymmetricAlgorithm sa = CryptUtils.CreateSymmetricAlgoritm(connection.EncryptType);
                  sa.GenerateIV();
                  sa.GenerateKey();

                  //----- Adjust connection cryptors!
                  connection.Encryptor = sa.CreateEncryptor();
                  connection.Decryptor = sa.CreateDecryptor();

                  //----- Create authenticate structure!
                  AuthMessage am = new AuthMessage();
                  am.SessionIV = serverPublicKey.Encrypt(sa.IV, false);
                  am.SessionKey = serverPublicKey.Encrypt(sa.Key, false);
                  am.SourceKey = CryptUtils.EncryptDataForAuthenticate(sa, Encoding.UTF8.GetBytes(clientPrivateKey.ToXmlString(false)), PaddingMode.ISO10126);

                  //----- Sign message with am.SourceKey, am.SessionKey and signMessage!
                  //----- Need to use PaddingMode.PKCS7 in sign!
                  MemoryStream m = new MemoryStream();
                  m.Write(am.SourceKey, 0, am.SourceKey.Length);
                  m.Write(am.SessionKey, 0, am.SessionKey.Length);
                  m.Write(signMessage, 0, signMessage.Length);
                  
                  am.Sign = clientPrivateKey.SignData(CryptUtils.EncryptDataForAuthenticate(sa, m.ToArray(), PaddingMode.PKCS7), new SHA1CryptoServiceProvider());

                  //----- Serialize authentication message!
                  XmlSerializer xml = new XmlSerializer(typeof(AuthMessage));
                  m.SetLength(0);
                  xml.Serialize(m, am);

                  //----- Send structure!
                  MessageBuffer mb = new MessageBuffer(0);
                  mb.PacketBuffer = Encoding.GetEncoding(1252).GetBytes(Convert.ToBase64String(m.ToArray()));
                  connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionSendCallback), new CallbackData(connection, mb));

                  m.Close();
                  am.SessionIV.Initialize();
                  am.SessionKey.Initialize();
                  serverPublicKey.Clear();
                  clientPrivateKey.Clear();

              }
              else
              {

                  //----- Create empty authenticate structure!
                  MessageBuffer mb = new MessageBuffer(8192);

                  //----- Start receive structure!
                  connection.Socket.BeginReceive(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionReceiveCallback), new CallbackData(connection, mb));

              }

          }

          //----- Asymmetric!
          if (connection.EncryptType == EncryptType.etSSL)
          {

              if (FHost.HostType == HostType.htClient)
              {

                  //----- Get SSL items!
                  X509Certificate2Collection certs = null;
                  string serverName = null;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificateCallback)); 

                  if (certs == null)
                  {
                      ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
                  }
                  else
                  {
                      ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));

                  }

              }
              else
              {

                  //----- Get SSL items!
                  X509Certificate2 cert = null;
                  bool clientAuthenticate = false;
                  bool checkRevocation = true;

                  FCryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);

                  //----- Authneticate SSL!
                  SslStream ssl = new SslStream(new NetworkStream(connection.Socket));
                  ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));

              }

          }

        }
Esempio n. 32
0
        protected void InitializeProxy(BaseSocketConnection connection)
        {

          if (!Disposed)
          {

            try
            {

              if (connection.Active)
              {

                MessageBuffer mb = new MessageBuffer(0);
                mb.PacketBuffer = FProxyInfo.GetProxyRequestData(FRemoteEndPoint);
                connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeProxySendCallback), new CallbackData(connection, mb));
              }

            }
            catch (Exception ex)
            {
              Host.FireOnException(connection, ex);
            }

          }

        }
Esempio n. 33
0
        /// <summary>
        /// Encrypts the data.
        /// </summary>
        /// <param name="connection">
        /// Connection information.
        /// </param>
        /// <param name="buffer">
        /// Data to be encrypted.
        /// </param>
        /// <param name="signOnly">
        /// Indicates is encrypt method only uses symmetric algoritm.
        /// </param>
        public static byte[] EncryptData(BaseSocketConnection connection, byte[] buffer)
        {
            byte[] result = null;

            if (
                (connection.EncryptType == EncryptType.etSSL && connection.CompressionType == CompressionType.ctNone) ||
                (connection.EncryptType == EncryptType.etNone && connection.CompressionType == CompressionType.ctNone)
                )
            {
                result = buffer;
            }
            else
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    CryptoStream cs = null;
                    GZipStream   gs = null;

                    switch (connection.EncryptType)
                    {
                    case EncryptType.etNone:
                    case EncryptType.etSSL:
                    {
                        break;
                    }

                    case EncryptType.etBase64:
                    {
                        cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
                        break;
                    }

                    default:
                    {
                        cs = new CryptoStream(ms, connection.Encryptor, CryptoStreamMode.Write);
                        break;
                    }
                    }

                    switch (connection.CompressionType)
                    {
                    case CompressionType.ctGZIP:
                    {
                        if (cs != null)
                        {
                            gs = new GZipStream(cs, CompressionMode.Compress, true);
                        }
                        else
                        {
                            gs = new GZipStream(ms, CompressionMode.Compress, true);
                        }

                        break;
                    }
                    }

                    if (gs != null)
                    {
                        gs.Write(buffer, 0, buffer.Length);
                        gs.Flush();
                        gs.Close();
                    }
                    else
                    {
                        cs.Write(buffer, 0, buffer.Length);
                    }

                    if (cs != null)
                    {
                        cs.FlushFinalBlock();
                        cs.Close();
                    }

                    result = ms.ToArray();
                }
            }

            return(result);
        }
        internal void RemoveSocketConnection(BaseSocketConnection socketConnection)
        {

          if (!Disposed)
          {

              if (socketConnection != null)
              {


                  FSocketConnectionsSync.AcquireWriterLock(Timeout.Infinite);

                  try
                  {

                      FSocketConnections.Remove(socketConnection.ConnectionId);

                  }
                  finally
                  {
                      FSocketConnectionsSync.ReleaseWriterLock();

                      if (FSocketConnections.Count <= 0)
                      {
                          FWaitConnectionsDisposing.Set();
                      }

                  }

              }

        }

        }
        /// <summary>
        /// Receive data from connetion.
        /// </summary>
        internal void BeginReceive(BaseSocketConnection connection)
        {

            if (!Disposed)
            {

                try
                {

                    if (connection.Active)
                    {

                        lock (connection.SyncReadCount)
                        {

                            if (connection.ReadCanEnqueue)
                            {

                                if (connection.ReadCount == 0)
                                {

                                    //----- if the connection is not receiving, start the receive!
                                    MessageBuffer readMessage = new MessageBuffer(FSocketBufferSize);

                                    if (connection.Stream != null)
                                    {
                                        //----- Ssl!
                                        connection.Stream.BeginRead(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }
                                    else
                                    {
                                        //----- Socket!
                                        connection.Socket.BeginReceive(readMessage.PacketBuffer, readMessage.PacketOffSet, readMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginReadCallback), new CallbackData(connection, readMessage));
                                    }

                                }

                                //----- Increase the read count!
                                connection.ReadCount++;

                            }

                        }

                    }

                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }

            }

        }
 internal void FireOnException(BaseSocketConnection connection, Exception ex)
 {
   FireOnException(connection, ex, false);
 }
Esempio n. 37
0
 public CallbackData(BaseSocketConnection connection, MessageBuffer buffer)
 {
     FConnection = connection;
     FBuffer = buffer;
 }
        /// <summary>
        /// Begin disconnect the connection
        /// </summary>
        internal void BeginDisconnect(BaseSocketConnection connection)
        {

            if (!Disposed)
            {

              ConnectionEventArgs e = new ConnectionEventArgs(connection);

              if (connection.Active)
              {

                try
                {

                  if ((Environment.OSVersion.Version.Major == 5)
                      && (Environment.OSVersion.Version.Minor >= 1))
                  {

                    //----- NT5 / WinXP and later!
                    connection.Socket.BeginDisconnect(false, new AsyncCallback(BeginDisconnectCallback), e);

                  }
                  else
                  {

                    //----- NT5 / Win2000!
                    ThreadPool.QueueUserWorkItem(new WaitCallback(BeginDisconnectCallbackProcessing), e);
                    
                  }

                }
                catch (Exception ex)
                {
                  FireOnException(connection, ex);
                }

              }
              else
              {

                RemoveSocketConnection(connection);
                DisposeAndNullConnection(ref connection);

              }

            }

        }
        internal void DisposeAndNullConnection(ref BaseSocketConnection connection)
        {

          if (connection != null)
          {
            connection.Dispose();
            connection = null;
          }

        }
Esempio n. 40
0
        internal void Reconnect(bool resetAttempts, BaseSocketConnection connection, Exception ex)
        {

          if (!Disposed)
          {

              if (resetAttempts)
              {
                FReconnectAttempted = 0;
              }

              if (FReconnectAttempts > 0)
              {

                if (FReconnectAttempted < FReconnectAttempts)
                {

                  Host.RemoveSocketConnection(connection);
                  Host.DisposeAndNullConnection(ref connection);

                  FReconnectTimer.Change(FReconnectAttemptInterval, FReconnectAttemptInterval);

                }
                else
                {
                  Host.FireOnException(connection, new ReconnectAttemptsException("Max reconnect attempts reached"), true);
                }

              }
              else
              {
                
                if ( (connection != null) && (ex != null) )
                {
                  Host.FireOnException(connection, ex, true);
                }

              }

           }

        }
Esempio n. 41
0
        /// <summary>
        /// Encrypts the data.
        /// </summary>
        /// <param name="connection">
        /// Connection information.
        /// </param>
        /// <param name="buffer">
        /// Data to be encrypted.
        /// </param>
        /// <param name="signOnly">
        /// Indicates is encrypt method only uses symmetric algoritm.
        /// </param>
        public static byte[] EncryptData(BaseSocketConnection connection, byte[] buffer)
        {

            byte[] result = null;

            if (
                 (connection.EncryptType == EncryptType.etSSL && connection.CompressionType == CompressionType.ctNone) ||
                 (connection.EncryptType == EncryptType.etNone && connection.CompressionType == CompressionType.ctNone)
                )
            {
                result = buffer;
            }
            else
            {

                using(MemoryStream ms = new MemoryStream())
                {

                    CryptoStream cs = null;
                    GZipStream gs = null;

                    switch (connection.EncryptType)
                    {

                        case EncryptType.etNone:
                        case EncryptType.etSSL:
                            {
                                break;
                            }

                        case EncryptType.etBase64:
                            {
                                cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
                                break;
                            }

                        default:
                            {
                                cs = new CryptoStream(ms, connection.Encryptor, CryptoStreamMode.Write);
                                break;
                            }
                    }

                    switch (connection.CompressionType)
                    {

                        case CompressionType.ctGZIP:
                            {

                                if (cs != null)
                                {
                                    gs = new GZipStream(cs, CompressionMode.Compress, true);
                                }
                                else
                                {
                                    gs = new GZipStream(ms, CompressionMode.Compress, true);
                                }

                                break;
                            }

                    }

                    if (gs != null)
                    {
                        gs.Write(buffer, 0, buffer.Length);
                        gs.Flush();
                        gs.Close();
                    }
                    else
                    {
                        cs.Write(buffer, 0, buffer.Length);
                    }

                    if (cs != null)
                    {
                        cs.FlushFinalBlock();
                        cs.Close();
                    }

                    result = ms.ToArray();

                }

            }

            return result;

        }
        /// <summary>
        /// Begin send the data.
        /// </summary>
        internal void BeginSend(BaseSocketConnection connection, byte[] buffer, bool sentByServer)
        {

            if (!Disposed)
            {

                try
                {

                    if (connection.Active)
                    {

                        if (buffer.Length > FMessageBufferSize) 
                        {
                            throw new MessageLengthException("Message length is greater than Host maximum message length.");
                        }

                        connection.LastAction = DateTime.Now;

                        MessageBuffer writeMessage = MessageBuffer.GetPacketMessage(connection, buffer);
                        writeMessage.SentByServer = sentByServer;

                        lock (connection.WriteQueue)
                        {

                            if (connection.WriteQueueHasItems)
                            {
                                //----- If the connection is sending, enqueue the message!
                                connection.WriteQueue.Enqueue(writeMessage);
                            }
                            else
                            {

                                //----- If the connection is not sending, send the message!
                                connection.WriteQueueHasItems = true;

                                if (connection.Stream != null)
                                {
                                    //----- Ssl!
                                    connection.Stream.BeginWrite(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, new AsyncCallback(BeginSendCallback), new CallbackData(connection, writeMessage));
                                }
                                else
                                {
                                    //----- Socket!
                                    connection.Socket.BeginSend(writeMessage.PacketBuffer, writeMessage.PacketOffSet, writeMessage.PacketRemaining, SocketFlags.None, new AsyncCallback(BeginSendCallback), new CallbackData(connection, writeMessage));
                                }

                            }

                        }

                    }

                }
                catch (Exception ex)
                {
                    FireOnException(connection, ex);
                }

            }

        }
        internal void AddSocketConnection(BaseSocketConnection socketConnection)
        {

            if (!Disposed)
            {

                FSocketConnectionsSync.AcquireWriterLock(Timeout.Infinite);

                try
                {
                    FSocketConnections.Add(socketConnection.ConnectionId, socketConnection);
                }
                finally
                {
                    FSocketConnectionsSync.ReleaseWriterLock();
                }

            }

        }
Esempio n. 44
0
        /// <summary>
        /// Decrypts the data.
        /// </summary>
        /// <param name="connection">
        /// Connection information.
        /// </param>
        /// <param name="buffer">
        /// Data to be encrypted.
        /// </param>
        /// <param name="maxBufferSize">
        /// Max buffer size accepted.
        /// </param>
        public static byte[] DecryptData(BaseSocketConnection connection, byte[] buffer, int maxBufferSize)
        {

            byte[] result = null;

            if (
                 (connection.EncryptType == EncryptType.etSSL && connection.CompressionType == CompressionType.ctNone) ||
                 (connection.EncryptType == EncryptType.etNone && connection.CompressionType == CompressionType.ctNone)
                )
            {
                result = buffer;
            }
            else
            {

                MemoryStream ms = new MemoryStream(buffer);
                CryptoStream cs = null;
                GZipStream gs = null;

                switch (connection.EncryptType)
                {

                    case EncryptType.etNone:
                    case EncryptType.etSSL:
                        {
                            break;
                        }

                    case EncryptType.etBase64:
                        {
                            cs = new CryptoStream(ms, new FromBase64Transform(), CryptoStreamMode.Read);
                            break;
                        }

                    default:
                        {
                            cs = new CryptoStream(ms, connection.Decryptor, CryptoStreamMode.Read);
                            break;
                        }
                }

                switch (connection.CompressionType)
                {

                    case CompressionType.ctGZIP:
                        {

                            if (cs != null)
                            {
                                gs = new GZipStream(cs, CompressionMode.Decompress, true);
                            }
                            else
                            {
                                gs = new GZipStream(ms, CompressionMode.Decompress, true);
                            }

                            break;
                        }

                }

                BinaryReader b = null;

                if (gs != null)
                {
                    b = new BinaryReader(gs);
                }
                else
                {
                    b = new BinaryReader(cs);
                }

                result = b.ReadBytes(maxBufferSize);

                b.Close();

            }

            return result;

        }
 internal abstract void BeginSendTo(BaseSocketConnection connectionTo, byte[] buffer);
Esempio n. 46
0
 internal override void BeginSendTo(BaseSocketConnection connectionTo, byte[] buffer) { }
        internal void FireOnException(BaseSocketConnection connection, Exception ex, bool forceEvent)
        {
            
          if (forceEvent || connection.Active)
          {
            FSocketService.OnException(new ExceptionEventArgs(connection, ex));
          }

        }
        private void FireOnReceived(BaseSocketConnection connection, byte[] buffer, bool readCanEnqueue)
        {

            if (connection.Active)
            {

                if (!readCanEnqueue)
                {

                    lock (connection.SyncReadCount)
                    {
                        connection.ReadCanEnqueue = false;
                    }

                }

                FSocketService.OnReceived(new MessageEventArgs(connection, buffer, false));

                if (!readCanEnqueue)
                {

                    lock (connection.SyncReadCount)
                    {
                        connection.ReadCanEnqueue = true;
                    }

                }

            }

        }
 public AuthenticateCallbackData(BaseSocketConnection connection, SslStream stream, HostType hostType)
 {
     FConnection = connection;
     FStream = stream;
     FHostType = hostType;
 }
        private void FireOnSent(BaseSocketConnection connection, byte[] buffer, bool sentByServer)
        {
            
            if (connection.Active)
            {
                FSocketService.OnSent(new MessageEventArgs(connection, buffer, sentByServer));
            }

        }
Esempio n. 51
0
        /// <summary>
        /// Decrypts the data.
        /// </summary>
        /// <param name="connection">
        /// Connection information.
        /// </param>
        /// <param name="buffer">
        /// Data to be encrypted.
        /// </param>
        /// <param name="maxBufferSize">
        /// Max buffer size accepted.
        /// </param>
        public static byte[] DecryptData(BaseSocketConnection connection, byte[] buffer, int maxBufferSize)
        {
            byte[] result = null;

            if (
                (connection.EncryptType == EncryptType.etSSL && connection.CompressionType == CompressionType.ctNone) ||
                (connection.EncryptType == EncryptType.etNone && connection.CompressionType == CompressionType.ctNone)
                )
            {
                result = buffer;
            }
            else
            {
                MemoryStream ms = new MemoryStream(buffer);
                CryptoStream cs = null;
                GZipStream   gs = null;

                switch (connection.EncryptType)
                {
                case EncryptType.etNone:
                case EncryptType.etSSL:
                {
                    break;
                }

                case EncryptType.etBase64:
                {
                    cs = new CryptoStream(ms, new FromBase64Transform(), CryptoStreamMode.Read);
                    break;
                }

                default:
                {
                    cs = new CryptoStream(ms, connection.Decryptor, CryptoStreamMode.Read);
                    break;
                }
                }

                switch (connection.CompressionType)
                {
                case CompressionType.ctGZIP:
                {
                    if (cs != null)
                    {
                        gs = new GZipStream(cs, CompressionMode.Decompress, true);
                    }
                    else
                    {
                        gs = new GZipStream(ms, CompressionMode.Decompress, true);
                    }

                    break;
                }
                }

                BinaryReader b = null;

                if (gs != null)
                {
                    b = new BinaryReader(gs);
                }
                else
                {
                    b = new BinaryReader(cs);
                }

                result = b.ReadBytes(maxBufferSize);

                b.Close();
            }

            return(result);
        }
Esempio n. 52
0
        internal override void BeginSendTo(BaseSocketConnection connection, byte[] buffer)
        {

            if (!Disposed)
            {
                BeginSend(connection, buffer, true);
            }

        }