Ejemplo n.º 1
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));

            if (IsSecure)
            {
                FleckLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(Certificate,
                              connection.StartReceiving,
                              e => FleckLog.Warn("Failed to Authenticate", e));
            }
            else
            {
                connection.StartReceiving();
            }
        }
Ejemplo n.º 2
0
        private void Read(List <byte> data, byte[] buffer)
        {
            if (!IsAvailable)
            {
                return;
            }

            Socket.Receive(buffer, r =>
            {
                if (r <= 0)
                {
                    FleckLog.Debug("0 bytes read. Closing.");
                    CloseSocket();
                    return;
                }
                FleckLog.Debug(r + " bytes read");
                var readBytes = buffer.Take(r);
                if (Handler != null)
                {
                    Handler.Receive(readBytes);
                }
                else
                {
                    data.AddRange(readBytes);
                    CreateHandler(data);
                }

                Read(data, buffer);
            },
                           HandleReadError);
        }
Ejemplo n.º 3
0
        public void Start(Action <IWebSocketConnection> config)
        {
            var ipLocal = new IPEndPoint(_locationIP, Port);

            ListenerSocket.Bind(ipLocal);
            ListenerSocket.Listen(100);
            Port = ((IPEndPoint)ListenerSocket.LocalEndPoint).Port;
            FleckLog.Info(string.Format("Server started at {0} (actual port {1})", Location, 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.Debug("Using default TLS 1.0 security protocol.");
                }
            }
            ListenForClients();
            _config = config;
        }
Ejemplo n.º 4
0
        private void HandleReadError(Exception e)
        {
            if (e is AggregateException)
            {
                var agg = e as AggregateException;
                HandleReadError(agg.InnerException);
                return;
            }
            else 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
            {
                FleckLog.Error("Application Error", e);
                Close(WebSocketStatusCodes.InternalServerError);
            }
        }
Ejemplo n.º 5
0
        private void HandleWriteError(Exception e)
        {
            if (e is IOException)
            {
                FleckLog.Debug("Failed to send. Disconnecting.", e);
            }
            else
            {
                FleckLog.Info("Failed to send. Disconnecting.", e);
            }

            CloseSocket();
        }
Ejemplo n.º 6
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);
                CloseSocket();
                return;
            }

            OnError(e);

            if (e is HandshakeException)
            {
                FleckLog.Debug("Error while reading", e);
                // why no close here?? TL
                //Close(WebSocketStatusCodes.ProtocolError);
                CloseSocket();
            }
            else if (e is WebSocketException)
            {
                FleckLog.Debug("Error while reading", e);
                //Close(((WebSocketException)e).StatusCode);
                CloseSocket();
            }
            else if (e is SubProtocolNegotiationFailureException)
            {
                FleckLog.Debug(e.Message);
                CloseSocket();
                //Close(WebSocketStatusCodes.ProtocolError);
            }
            else if (e is IOException)
            {
                FleckLog.Debug("Error while reading", e);
                CloseSocket();
                //Close(WebSocketStatusCodes.AbnormalClosure);
            }
            else
            {
                FleckLog.Error("Application Error", e);
                CloseSocket();
                //Close(WebSocketStatusCodes.InternalServerError);
            }
        }
Ejemplo n.º 7
0
        private void Read(List <byte> data, byte[] buffer)
        {
            if (!IsAvailable)
            {
                return;
            }

            var body = Encoding.UTF8.GetString(buffer);

            if (body.StartsWith("<policy-file-request/>"))
            {
                FleckLog.Debug("Reveived Flash Policy File Request");

                var    policyFile = @"<?xml version=""1.0""?><!DOCTYPE cross-domain-policy SYSTEM ""http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd""><cross-domain-policy><allow-access-from domain=""*"" to-ports=""*""/></cross-domain-policy>";
                byte[] bytes      = new System.Text.UTF8Encoding().GetBytes(policyFile);

                Socket.Stream.Write(bytes, 0, bytes.Length);
                Socket.Stream.WriteByte(0);
                Socket.Stream.WriteByte(13);

                FleckLog.Debug("Flash Policy File Sent");

                return;
            }

            Socket.Receive(buffer, r =>
            {
                if (r <= 0)
                {
                    FleckLog.Debug("0 bytes read. Closing.");
                    CloseSocket();
                    return;
                }
                FleckLog.Debug(r + " bytes read");
                var readBytes = buffer.Take(r);
                if (Handler != null)
                {
                    Handler.Receive(readBytes);
                }
                else
                {
                    data.AddRange(readBytes);
                    CreateHandler(data);
                }

                Read(data, buffer);
            },
                           HandleReadError);
        }
Ejemplo n.º 8
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);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("Swallowing ObjectDisposedException: {0}", e), "white");
                return;
            }

            OnError(e);

            if (e is HandshakeException)
            {
                FleckLog.Debug("Error while reading", e);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("Error while reading: {0}", e), "white");
            }
            else if (e is WebSocketException)
            {
                FleckLog.Debug("Error while reading", e);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("Error while reading: {0}", e), "white");
                Close(((WebSocketException)e).StatusCode);
            }
            else if (e is SubProtocolNegotiationFailureException)
            {
                FleckLog.Debug(e.Message);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("e.Message: {0}", e.Message), "white");
                Close(WebSocketStatusCodes.ProtocolError);
            }
            else if (e is IOException)
            {
                FleckLog.Debug("Error while reading", e);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("Error while reading: {0}", e), "white");
                Close(WebSocketStatusCodes.AbnormalClosure);
            }
            else
            {
                FleckLog.Error("Application Error", e);
                Log.Insert(DateTime.Now, "WebSocketConnection.cs", string.Format("Application error: {0}", e), "white");
                Close(WebSocketStatusCodes.InternalServerError);
            }
        }
Ejemplo n.º 9
0
 private void SendBytes(byte[] bytes, Action callback = null)
 {
     Socket.Send(bytes, () =>
     {
         FleckLog.Debug("Sent " + bytes.Length + " bytes");
         if (callback != null)
         {
             callback();
         }
     },
                 e =>
     {
         FleckLog.Info("Failed to send. Disconnecting.", e);
         CloseSocket();
     });
 }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
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();
        }
Ejemplo n.º 12
0
 private Task SendBytes(byte[] bytes, Action callback = null)
 {
     return(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();
     }));
 }
Ejemplo n.º 13
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();
            }
        }
Ejemplo n.º 14
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();
            }
        }