Example #1
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));
        }
Example #2
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();
        }
Example #3
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()));
            Log.Insert(DateTime.Now, "WebSocketServer.cs", string.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()), "white");
            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();
            }
        }
Example #4
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();
            }
        }
Example #5
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();
            }
        }