Пример #1
0
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return;                       // socket closed
            }
            FleckLog.Debug(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            ListenForClients();

            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => HandlerFactory.BuildHandler(
                    r,
                    s => connection.OnMessage(s),
                    connection.Close,
                    b => connection.OnBinary(b),
                    b => connection.OnPing(b),
                    b => connection.OnPong(b)
                    ),
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s)
                );

            if (IsSecure)
            {
                FleckLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(
                    Certificate,
                    EnabledSslProtocols,
                    connection.StartReceiving,
                    e => FleckLog.Warn("Failed to Authenticate", e)
                    );
            }
            else
            {
                connection.StartReceiving();
            }
        }
Пример #2
0
        private void HandleReadError(Exception e)
        {
            if (e is AggregateException)
            {
                var agg = e as AggregateException;
                HandleReadError(agg.InnerException);
                return;
            }

            if (e is ObjectDisposedException)
            {
                FleckLog.Debug("Swallowing ObjectDisposedException", e);
                return;
            }

            OnError(e);

            if (e is HandshakeException)
            {
                FleckLog.Debug("Error while reading", e);
            }
            else if (e is WebSocketException)
            {
                FleckLog.Debug("Error while reading", e);
                Close(((WebSocketException)e).StatusCode);
            }
            else if (e is SubProtocolNegotiationFailureException)
            {
                FleckLog.Debug(e.Message);
                Close(WebSocketStatusCodes.ProtocolError);
            }
            else if (e is IOException)
            {
                FleckLog.Debug("Error while reading", e);
                Close(WebSocketStatusCodes.AbnormalClosure);
            }
            else
            {
                FleckLog.Error("Application Error", e);
                Close(WebSocketStatusCodes.InternalServerError);
            }
        }
 private Task SendBytes(byte[] bytes, Action callback = null)
 {
     return(Socket.Send(bytes, () =>
     {
         FleckLog.Trace("Sent " + bytes.Length + " bytes");
         callback?.Invoke();
     },
                        e =>
     {
         if (e is IOException)
         {
             FleckLog.Error("Failed to send. Disconnecting.", e);
         }
         else
         {
             FleckLog.Error("Failed to send. Disconnecting.", e);
         }
         CloseSocket();
     }));
 }
Пример #4
0
 private void ListenForClients()
 {
     ListenerSocket.Accept(OnClientConnect, e => {
         FleckLog.Error("Listener socket is closed", e);
         if (RestartAfterListenError)
         {
             try
             {
                 ListenerSocket.Dispose();
                 var socket     = new Socket(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
                 ListenerSocket = new SocketWrapper(socket);
                 Start(_config);
             }
             catch (Exception ex)
             {
                 FleckLog.Error("Listener could not be restarted", ex);
             }
         }
     });
 }
Пример #5
0
 private void ListenForClients()
 {
     ListenerSocket.Accept(OnClientConnect, e =>
     {
         FleckLog.Error("Listener socket is closed", e);
         FleckLog.Info("Listener socket restarting");
         try
         {
             ListenerSocket.Dispose();
             var socket     = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
             ListenerSocket = new SocketWrapper(socket);
             Start(_config);
             FleckLog.Info("Listener socket restarted");
         }
         catch (Exception ex)
         {
             FleckLog.Error("Listener could not be restarted", ex);
         }
     });
 }
Пример #6
0
        private void SendBytes(MemoryBuffer bytes, Action <WebSocketConnection, bool> callback = null)
        {
            try
            {
                // TODO: this allocates for the delegate - could probably avoid that with QueuedStream
                Socket.Stream.BeginWrite(bytes.Data, 0, bytes.Length, result =>
                {
                    var instance = (WebSocketConnection)result.AsyncState;
                    var success  = false;

                    try
                    {
                        instance.Socket.Stream.EndWrite(result);
                        FleckLog.Debug($"Sent {bytes.Length} bytes");

                        success = true;
                    }
                    catch (Exception e)
                    {
                        instance.HandleWriteError(e);
                    }
                    finally
                    {
                        bytes.Dispose();
                    }

                    try
                    {
                        callback?.Invoke(instance, success);
                    }
                    catch (Exception e)
                    {
                        instance.OnError(e);
                    }
                }, this);
            }
            catch (Exception e)
            {
                HandleWriteError(e);
            }
        }
Пример #7
0
        private Task Send <T>(T message, Func <T, byte[]> createFrame)
        {
            if (Handler == null)
            {
                throw new InvalidOperationException("Cannot send before handshake");
            }

            if (!IsAvailable)
            {
                const string errorMessage = "Data sent while closing or after close. Ignoring.";
                FleckLog.Warn(errorMessage);

                var taskForException = new TaskCompletionSource <object>();
                taskForException.SetException(new ConnectionNotAvailableException(errorMessage));
                return(taskForException.Task);
            }

            var bytes = createFrame(message);

            return(SendBytes(bytes));
        }
Пример #8
0
        private void OnClientConnect(ISocket clientSocket)
        {
            FleckLog.Debug(String.Format("Policy-Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            ListenForClients();

            var connection = new SocketConnection(clientSocket);

            connection.OnMessage = (message) =>
            {
                if (_regex.IsMatch(message))
                {
                    connection.Send(_policy, "policy", connection.Close);
                }
                else
                {
                    FleckLog.Info("Policy-Server invalid request: " + message);
                    connection.Close();
                }
            };
            connection.StartReceiving();
        }
Пример #9
0
        private void ListenForClients()
        {
            ManualResetEvent acceptDone = new ManualResetEvent(false);
            bool             running    = true;

            Task client_task = new Task(() =>
            {
                while (running)
                {
                    acceptDone.Reset();

                    var task = ListenerSocket.Accept(
                        s =>
                    {
                        running = (s != null);
                        acceptDone.Set();
                        OnClientConnect(s);
                    },
                        e =>
                    {
                        FleckLog.Error("Error while listening for new clients", e);
                        if (RestartAfterListenError)
                        {
                            TryRestart();
                        }
                        running = false; acceptDone.Set();
                    }
                        );

                    task.ContinueWith((t) => FleckLog.Warn("Error during client connect", t.Exception),
                                      TaskContinuationOptions.OnlyOnFaulted);

                    acceptDone.WaitOne();
                }
            });

            client_task.Start();
        }
Пример #10
0
 private void SendBytes(byte[] bytes, Action callback = null)
 {
     Socket.Send(bytes, () =>
     {
         FleckLog.Debug("Sent " + bytes.Length + " bytes");
         if (callback != null)
         {
             callback();
         }
     },
                 e =>
     {
         if (e is IOException)
         {
             FleckLog.Debug("Failed to send. Disconnecting.", e);
         }
         else
         {
             FleckLog.Info("Failed to send. Disconnecting.", e);
         }
         CloseSocket();
     });
 }
Пример #11
0
        public SocketConnection(ISocket socket)
        {
            Socket = socket;

            OnOpen    = () => { };
            OnClose   = () => { };
            OnMessage = (x) => { };
            OnError   = (x) => { };

            // default read handler
            OnRead = (data, readBytes) =>
            {
                OnMessage(Encoding.UTF8.GetString(readBytes.ToArray <byte>()));
            };

            // default read error handler
            OnReadError = (e) =>
            {
                FleckLog.Error("Error while reading", e);
                OnError(e);
                Close();
            };
        }
        public void Start(Action <IWebSocketConnection> config)
        {
            var ipLocal = new IPEndPoint(_locationIP, Port);

            ListenerSocket.Bind(ipLocal);
            ListenerSocket.Listen(1000);
            Port = ((IPEndPoint)ListenerSocket.LocalEndPoint).Port;
            if (_scheme == "wss")
            {
                if (Certificate == null)
                {
                    FleckLog.Error("Scheme cannot be 'wss' without a Certificate");
                    return;
                }

                if (EnabledSslProtocols == SslProtocols.None)
                {
                    EnabledSslProtocols = SslProtocols.Tls;
                    FleckLog.Trace("Using default TLS 1.0 security protocol.");
                }
            }
            ListenForClients();
            _config = config;
        }
Пример #13
0
 private void ListenForClients()
 {
     ListenerSocket.Accept(OnClientConnect, e => FleckLog.Error("Listener socket is closed", e));
 }
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return;                                   // socket closed
            }
            FleckLog.Trace($"Client connected from {clientSocket.RemoteIpAddress}:{clientSocket.RemotePort}");
            ListenForClients();

            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => HandlerFactory.BuildHandler(r,
                                                 s => connection.OnMessage(s),
                                                 connection.Close,
                                                 b => connection.OnBinary(b),
                                                 b => connection.OnPing(b),
                                                 b => connection.OnPong(b)),
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            if (IsSecure)
            {
                FleckLog.Debug("Attempting to secure connection...");
                clientSocket.Authenticate(Certificate, EnabledSslProtocols, connection.StartReceiving, e => FleckLog.Error($"Cannot secure the connection: {e.Message}", e));
            }
            else
            {
                connection.StartReceiving();
            }
        }
Пример #15
0
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return;                       // socket closed
            }
            // experimental removed by wmp
            //FleckLog.Debug(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            //Console.WriteLine(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));

            string rep = string.Empty;

            bool failed = false;

            try {
                rep = clientSocket.RemoteIpAddress;
                Console.WriteLine("Connecting: " + rep);
            }
            catch {
                Console.WriteLine("Started but IP not available.");
                failed = true;
            }

            //ListenForClients();

            if (failed)
            {
                try{ clientSocket.Close(); }catch {}
                try{ clientSocket.Stream.Close(); }catch {}
                try{ clientSocket.Dispose(); }catch {}

                return;
            }


            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => HandlerFactory.BuildHandler(r,
                                                 s => connection.OnMessage(s),
                                                 connection.Close,
                                                 b => connection.OnBinary(b),
                                                 b => connection.OnPing(b),
                                                 b => connection.OnPong(b)),
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            if (IsSecure)
            {
                FleckLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(Certificate,
                              EnabledSslProtocols,
                              () =>
                {
                    Console.WriteLine("Authenticated {0}", rep);
                    Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthSuccess);
                    connection.StartReceiving();
                }
                              , e =>
                {
                    FleckLog.Warn("Failed to Authenticate " + rep, e);
                    // here we could add connection.Close() ! wmp
                    Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthFailure);
                    connection.Close();
                });
            }
            else
            {
                Server.Firewall.Update(rep, Server.Firewall.UpdateEntry.AuthSuccess);

                connection.StartReceiving();
            }
        }
Пример #16
0
        private void OnClientConnect(ISocket clientSocket)
        {
            FleckLog.Debug(String.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            ListenForClients();

            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => HandlerFactory.BuildHandler(r,
                                                 s => connection.OnMessage(s),
                                                 connection.Close,
                                                 b => connection.OnBinary(b),
                                                 b => connection.OnPing(b),
                                                 b => connection.OnPong(b)),
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            // Determine whether this is a ws or wss connection
            try
            {
                // Wait up to 5 seconds for the first handshake byte
                // (Only peek, so it's still in the buffer for the actual handshake handler)
                byte[] buffer = new byte[1];
                clientSocket.Socket.ReceiveTimeout = 5000;
                int BytesRead = clientSocket.Socket.Receive(buffer, 1, SocketFlags.Peek);
                clientSocket.Socket.ReceiveTimeout = 0;
                if (BytesRead == 1)
                {
                    if ((buffer[0] == 0x16) || (buffer[0] == 0x80))
                    {
                        // wss connection, ensure we have a certificate
                        if (IsSecure)
                        {
                            FleckLog.Info("Accepting wss:// Connection");
                            clientSocket
                            .Authenticate(Certificate,
                                          connection.StartReceiving,
                                          e =>
                            {
                                FleckLog.Warn("Failed to Authenticate", e);
                                connection.Close();
                            });
                        }
                        else
                        {
                            FleckLog.Warn("Rejecting wss:// connection (no certificate)");
                            connection.Close();
                        }
                    }
                    else
                    {
                        // ws connection
                        FleckLog.Info("Accepting ws:// Connection");
                        connection.StartReceiving();
                    }
                }
                else
                {
                    connection.Close();
                }
            }
            catch (Exception ex)
            {
                FleckLog.Error("Unable to read handshake byte from client", ex);
                connection.Close();
            }
        }