/// <summary> /// Handle the initiation of a client connection request /// </summary> protected override IClient <Request, Response> CreateClient(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { var stream = args.Client.Stream; var address = args.Client.Address; try { Logger.WriteLine("ProtocolBuffers: client requesting connection (" + address + ")", Logger.Severity.Debug); var request = Utils.ReadMessage <ConnectionRequest> (stream); if (request == null) { return(null); } if (request.Type != Type.Rpc) { var name = request.Type.ToString().ToLower(); WriteErrorConnectionResponse(Status.WrongType, "Connection request was for the " + name + " server, but this is the rpc server. " + "Did you connect to the wrong port number?", stream); } else { return(new RPCClient(request.ClientName, args.Client)); } } catch (InvalidProtocolBufferException e) { WriteErrorConnectionResponse(Status.MalformedMessage, e.Message, stream); } args.Request.Deny(); Logger.WriteLine("ProtocolBuffers: client connection denied (" + address + ")", Logger.Severity.Error); return(null); }
public void OnClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs eventArgs) { // Not open, so open the dialog if (!Visible) { Logger.WriteLine("Asking player to allow/deny connection attempt..."); args = eventArgs; Open(); return; } // Already open for a different request, so ignore if (Visible && args.Client != eventArgs.Client) { return; } // Open, and we have a decision (must be the correct client at this point), to close the dialog if (Visible && !args.Request.StillPending) { if (args.Request.ShouldAllow) { eventArgs.Request.Allow(); } else { eventArgs.Request.Deny(); } Close(); } }
public void WrongConnectionType() { var responseStream = new MemoryStream(); var connectionMessage = TestingTools.CreateConnectionRequest(Type.Rpc, clientId.ToByteArray()); var stream = new TestStream(new MemoryStream(connectionMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); TestingTools.CheckConnectionResponse(responseStream.ToArray(), 120, Status.WrongType, "Connection request was for the rpc server, but this is the stream server. " + "Did you connect to the wrong port number?", 0); }
public void DefaultBehaviour () { var attempt = new ClientRequestingConnectionEventArgs<byte,byte> (null); Assert.IsFalse (attempt.Request.ShouldDeny); Assert.IsFalse (attempt.Request.ShouldAllow); Assert.IsTrue (attempt.Request.StillPending); }
public void ValidConnectionMessage() { var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(TestingTools.CreateConnectionRequest(Type.Stream, clientId.ToByteArray())), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsTrue(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(1, server.Clients.Count()); Assert.AreEqual(clientId, server.Clients.First().Guid); TestingTools.CheckConnectionResponse(responseStream.ToArray(), 19, Status.Ok, string.Empty, 16); }
static string CheckInvalidConnectionRequest(byte[] request) { var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(request), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new KRPC.Server.WebSockets.RPCServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(0, server.Clients.Count()); return(Encoding.ASCII.GetString(responseStream.ToArray())); }
public void InvalidConnectionMessageIdentifier() { var connectionMessage = TestingTools.CreateConnectionRequest(Type.Stream, "123456".ToBytes()); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(connectionMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); TestingTools.CheckConnectionResponse(responseStream.ToArray(), 40, Status.MalformedMessage, "Client identifier must be 16 bytes.", 0); }
public void ValidHelloMessage () { var responseStream = new MemoryStream (); var stream = new TestStream (new MemoryStream (helloMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock<IServer<byte,byte>> (); var byteServer = mockByteServer.Object; var byteClient = new TestClient (stream); var server = new RPCServer (byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow (); server.Start (); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs<byte,byte> (byteClient); mockByteServer.Raise (m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsTrue (eventArgs.Request.ShouldAllow); Assert.IsFalse (eventArgs.Request.ShouldDeny); server.Update (); Assert.AreEqual (1, server.Clients.Count ()); Assert.AreEqual ("Jebediah Kerman!!!", server.Clients.First ().Name); byte[] bytes = responseStream.ToArray (); byte[] responseBytes = byteClient.Guid.ToByteArray (); Assert.IsTrue (responseBytes.SequenceEqual (bytes)); }
public void ValidHelloMessage() { var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(helloMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new RPCServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsTrue(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(1, server.Clients.Count()); Assert.AreEqual("Jebediah Kerman!!!", server.Clients.First().Name); byte[] bytes = responseStream.ToArray(); byte[] responseBytes = byteClient.Guid.ToByteArray(); Assert.IsTrue(responseBytes.SequenceEqual(bytes)); }
public void ShortHelloMessageName() { var shortHelloMessage = new byte[8 + 31]; Array.Copy(helloMessage, shortHelloMessage, shortHelloMessage.Length); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(shortHelloMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new RPCServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); Assert.AreEqual(0, responseStream.Length); }
public void ShortConnectionMessageHeader() { var connectionMessage = new byte[5]; Array.Copy(TestingTools.CreateConnectionRequest(Type.Rpc), connectionMessage, connectionMessage.Length); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(connectionMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new KRPC.Server.SerialIO.RPCServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); Assert.AreEqual(responseStream.ToArray().Length, 0); }
public void NoConnectionMessage() { var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); Assert.AreEqual(responseStream.ToArray().Length, 0); }
public void InvalidHelloMessageHeader () { var responseStream = new MemoryStream (); helloMessage [4] = 0x42; var stream = new TestStream (new MemoryStream (helloMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock<IServer<byte,byte>> (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock<IClient<byte,byte>> (); mockByteClient.Setup (x => x.Stream).Returns (stream); var byteClient = mockByteClient.Object; var server = new StreamServer (byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow (); server.Start (); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs<byte,byte> (byteClient); mockByteServer.Raise (m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse (eventArgs.Request.ShouldAllow); Assert.IsTrue (eventArgs.Request.ShouldDeny); Assert.AreEqual (0, responseStream.Length); }
public void Update() { try { if (client == null && pendingClient == null && port.IsOpen && port.BytesToRead > 0) { Logger.WriteLine( "SerialIO.Server[" + Address + "]: client requesting connection", Logger.Severity.Debug); pendingClient = new ByteClient(port); } } catch (IOException) { Stop(); } catch (TimeoutException) { Stop(); } catch (ObjectDisposedException) { Stop(); } if (client == null && pendingClient != null) { // Trigger OnClientRequestingConnection events to verify the connection var args = new ClientRequestingConnectionEventArgs <byte, byte> (pendingClient); EventHandlerExtensions.Invoke(OnClientRequestingConnection, this, args); // Deny the connection if (args.Request.ShouldDeny) { Logger.WriteLine( "SerialIO.Server[" + Address + "]: client connection denied", Logger.Severity.Debug); DisconnectClient(pendingClient, true); pendingClient = null; } // Allow the connection else if (args.Request.ShouldAllow) { client = pendingClient; pendingClient = null; Logger.WriteLine( "SerialIO.Server[" + Address + "]: " + "client connection accepted", Logger.Severity.Debug); EventHandlerExtensions.Invoke(OnClientConnected, this, new ClientConnectedEventArgs <byte, byte> (client)); } // Still pending, will either be denied or allowed on a subsequent called to Update else { Logger.WriteLine( "SerialIO.Server[" + Address + "]: " + "client connection still pending", Logger.Severity.Debug); } } else if (client != null && !client.Connected) { DisconnectClient(client); client = null; } }
public void DefaultBehaviour() { var attempt = new ClientRequestingConnectionEventArgs <byte, byte> (null); Assert.IsFalse(attempt.Request.ShouldDeny); Assert.IsFalse(attempt.Request.ShouldAllow); Assert.IsTrue(attempt.Request.StillPending); }
/// <summary> /// When a client requests a connection, and is successful, send the ok message /// </summary> public override void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { base.HandleClientRequestingConnection(sender, args); if (args.Request.ShouldAllow) { args.Client.Stream.Write(okMessage); } }
/// <summary> /// When a client requests a connection, check and parse the hello message /// (which should consist of a header and a client name) /// </summary> protected override IClient<Request,Response> CreateClient (object sender, ClientRequestingConnectionEventArgs<byte,byte> args) { string clientName = CheckHelloMessage (args.Client); if (clientName != null) return new RPCClient (clientName, args.Client); else args.Request.Deny (); return null; }
public void AllowAndDeny () { var attempt = new ClientRequestingConnectionEventArgs<byte,byte> (null); attempt.Request.Allow (); attempt.Request.Deny (); Assert.IsTrue (attempt.Request.ShouldDeny); Assert.IsFalse (attempt.Request.ShouldAllow); Assert.IsFalse (attempt.Request.StillPending); }
public void AllowAndDeny() { var attempt = new ClientRequestingConnectionEventArgs <byte, byte> (null); attempt.Request.Allow(); attempt.Request.Deny(); Assert.IsTrue(attempt.Request.ShouldDeny); Assert.IsFalse(attempt.Request.ShouldAllow); Assert.IsFalse(attempt.Request.StillPending); }
/// <summary> /// When a client requests a connection, check the hello message /// </summary> protected override IClient<NoMessage,StreamMessage> CreateClient (object sender, ClientRequestingConnectionEventArgs<byte,byte> args) { var guid = CheckHelloMessage (args.Client); if (guid != Guid.Empty) return new StreamClient (guid, args.Client); else args.Request.Deny (); return null; }
/// <summary> /// When a client requests a connection, check and parse the hello message (which should /// consist of a header and a client name), then trigger RPCServer.OnClientRequestingConnection /// to get response of delegates /// </summary> public virtual void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { Logger.WriteLine("Message.RPCServer: handling client connection request", Logger.Severity.Debug); if (!pendingClients.ContainsKey(args.Client)) { // A new client connection attempt. Try to create the client. var client = CreateClient(sender, args); // Check if creating the client denied the connection attempt if (args.Request.ShouldDeny) { return; } // Check if a client was created - if not, retry again later if (client == null) { return; } // Add the client to the pending connections pendingClients [args.Client] = client; } // Client is in pending clients and passed hello message verification. // Invoke connection request events. var handler = OnClientRequestingConnection; if (handler != null) { var client = pendingClients [args.Client]; var subArgs = new ClientRequestingConnectionEventArgs <Request, Response> (client); handler(this, subArgs); if (subArgs.Request.ShouldAllow) { args.Request.Allow(); clients [args.Client] = client; Logger.WriteLine("Message.RPCServer: client connection allowed", Logger.Severity.Debug); } else if (subArgs.Request.ShouldDeny) { args.Request.Deny(); Logger.WriteLine("Message.RPCServer: client connection denied", Logger.Severity.Debug); } else { Logger.WriteLine("Message.RPCServer: client connection still pending", Logger.Severity.Debug); } } else { // No events configured, so allow the connection args.Request.Allow(); clients [args.Client] = pendingClients [args.Client]; Logger.WriteLine("Message.RPCServer: client connection allowed", Logger.Severity.Debug); pendingClients.Remove(args.Client); } }
/// <summary> /// Send an upgrade response to the client on successful connection. /// </summary> public override void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { base.HandleClientRequestingConnection(sender, args); if (args.Request.ShouldAllow) { args.Client.Stream.Write(ConnectionRequest.WriteResponse(clientKeys [args.Client])); } if (args.Request.ShouldDeny && clientKeys.ContainsKey(args.Client)) { clientKeys.Remove(args.Client); } }
/// <summary> /// Send an upgrade response to the client on successful connection. /// </summary> public override void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { base.HandleClientRequestingConnection(sender, args); if (args.Request.ShouldAllow) { args.Client.Stream.Write(ConnectionRequest.WriteResponse(clientKeys [args.Client])); Logger.WriteLine("WebSockets: client connection accepted (" + args.Client.Address + ")"); } if (args.Request.ShouldDeny && clientKeys.ContainsKey(args.Client)) { clientKeys.Remove(args.Client); } }
/// <summary> /// When a client requests a connection, check the hello message, /// then trigger RPCServer.OnClientRequestingConnection to get response of delegates /// </summary> public virtual void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { if (!pendingClients.ContainsKey(args.Client)) { var client = CreateClient(sender, args); if (args.Request.ShouldDeny) { return; } if (client == null) { return; } pendingClients [args.Client] = client; } // Client is in pending clients and passed hello message verification. // Invoke connection request events. var handler = OnClientRequestingConnection; if (handler != null) { var client = pendingClients [args.Client]; var address = client.Address; var subArgs = new ClientRequestingConnectionEventArgs <NoMessage, StreamUpdate> (client); handler(this, subArgs); if (subArgs.Request.ShouldAllow) { args.Request.Allow(); clients [args.Client] = client; Logger.WriteLine("StreamServer: client connection allowed (" + address + ")", Logger.Severity.Debug); } else if (subArgs.Request.ShouldDeny) { args.Request.Deny(); Logger.WriteLine("StreamServer: client connection denied (" + address + ")", Logger.Severity.Debug); } else { pendingClients.Remove(args.Client); Logger.WriteLine("StreamServer: client connection still pending (" + address + ")", Logger.Severity.Debug); } } else { args.Request.Allow(); clients [args.Client] = pendingClients [args.Client]; pendingClients.Remove(args.Client); Logger.WriteLine("StreamServer: client connection allowed (" + args.Client.Address + ")", Logger.Severity.Debug); } }
/// <summary> /// When a client requests a connection, check and parse the hello message /// (which should consist of a header and a client name) /// </summary> protected override IClient <Request, Response> CreateClient(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { string clientName = CheckHelloMessage(args.Client); if (clientName != null) { return(new RPCClient(clientName, args.Client)); } else { args.Request.Deny(); } return(null); }
public void Update() { // Remove disconnected clients for (int i = clients.Count - 1; i >= 0; i--) { var client = clients [i]; if (!client.Connected) { clients.RemoveAt(i); DisconnectClient(client); } } // Process pending clients lock (pendingClientsLock) { if (pendingClients.Count > 0) { var stillPendingClients = new List <TCPClient> (); foreach (var client in pendingClients) { // Trigger OnClientRequestingConnection events to verify the connection var args = new ClientRequestingConnectionEventArgs <byte, byte> (client); EventHandlerExtensions.Invoke(OnClientRequestingConnection, this, args); // Deny the connection if (args.Request.ShouldDeny) { Logger.WriteLine("TCPServer: client connection denied (" + client.Address + ")", Logger.Severity.Debug); DisconnectClient(client, true); } // Allow the connection else if (args.Request.ShouldAllow) { Logger.WriteLine("TCPServer: client connection accepted (" + client.Address + ")", Logger.Severity.Debug); clients.Add(client); EventHandlerExtensions.Invoke(OnClientConnected, this, new ClientConnectedEventArgs <byte, byte> (client)); } // Still pending, will either be denied or allowed on a subsequent called to Update else { Logger.WriteLine("TCPServer: client connection still pending (" + client.Address + ")", Logger.Severity.Debug); stillPendingClients.Add(client); } } pendingClients = stillPendingClients; } } }
/// <summary> /// When a client requests a connection, process the connection request /// </summary> protected override IClient <Request, Response> CreateClient(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { var client = args.Client; var address = client.Address; try { Logger.WriteLine( "SerialIO: client requesting connection on " + address, Logger.Severity.Debug); bool timeout; var request = ProtocolBuffers.Utils.ReadMessage <MultiplexedRequest> (client, out timeout); if (timeout) { WriteErrorConnectionResponse(client, Status.Timeout, "Connection request message not received after waiting 3 seconds"); args.Request.Deny(); Logger.WriteLine("SerialIO: client connection timed out on " + address, Logger.Severity.Error); return(null); } if (request == null) { return(null); } var connectionRequest = request.ConnectionRequest; if (connectionRequest == null) { WriteErrorConnectionResponse( client, Status.MalformedMessage, "Expected a ConnectionRequest message"); } if (connectionRequest.Type != Type.Rpc) { var name = connectionRequest.Type.ToString().ToLower(); WriteErrorConnectionResponse( client, Status.WrongType, "Connection request was for a " + name + " server, " + "but this is an rpc server."); } else { return(new RPCClient(connectionRequest.ClientName, client, Server)); } } catch (InvalidProtocolBufferException e) { WriteErrorConnectionResponse(client, Status.MalformedMessage, e.Message); } catch (TimeoutException e) { WriteErrorConnectionResponse(client, Status.Timeout, e.Message); } args.Request.Deny(); Logger.WriteLine( "SerialIO: client connection denied on " + address, Logger.Severity.Error); return(null); }
/// <summary> /// Handle a client connection request /// </summary> public override void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { base.HandleClientRequestingConnection(sender, args); var client = args.Client; if (args.Request.ShouldAllow) { Utils.WriteConnectionResponse(client); Logger.WriteLine("ProtocolBuffers: client connection accepted (" + args.Client.Address + ")"); } else if (args.Request.ShouldDeny) { client.Stream.Close(); } }
public void ValidConnectionRequest() { var clientGuid = new Guid("1234567890abcdef1234567890abcdef".ToBytes()); var clientGuidBase64 = Convert.ToBase64String(clientGuid.ToByteArray()); var request = Encoding.ASCII.GetBytes( "GET /?id=" + clientGuidBase64 + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n" ); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(request), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsTrue(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(1, server.Clients.Count()); Assert.AreEqual(clientGuid, server.Clients.First().Guid); var response = Encoding.ASCII.GetString(responseStream.ToArray()); Assert.AreEqual( "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n", response ); }
/// <summary> /// Handle a client connection request /// </summary> public override void HandleClientRequestingConnection(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { base.HandleClientRequestingConnection(sender, args); if (args.Request.ShouldAllow) { var client = args.Client; var response = new ConnectionResponse(); response.Status = Status.Ok; response.ClientIdentifier = ByteString.CopyFrom(client.Guid.ToByteArray()); Utils.WriteMessage(client.Stream, response); } else if (args.Request.ShouldDeny) { args.Client.Stream.Close(); } }
/// <summary> /// When a client requests a connection, process the websockets HTTP request /// </summary> protected override IClient <Request, Response> CreateClient(object sender, ClientRequestingConnectionEventArgs <byte, byte> args) { var address = args.Client.Address; Logger.WriteLine("WebSockets: client requesting connection (" + address + ")", Logger.Severity.Debug); var request = ConnectionRequest.ReadRequest(args); if (args.Request.ShouldDeny) { Logger.WriteLine("WebSockets: client connection denied (" + address + ")", Logger.Severity.Error); return(null); } var clientName = GetClientName(request); clientKeys [args.Client] = request.Headers ["sec-websocket-key"].Single(); return(new RPCClient(clientName, args.Client, shouldEcho)); }
public void InvalidConnectionRequestNoGuid() { var ascii = Encoding.ASCII; var request = ascii.GetBytes( "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n" ); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(request), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(0, server.Clients.Count()); var response = ascii.GetString(responseStream.ToArray()); Assert.AreEqual( "HTTP/1.1 400 Bad Request\r\n\r\n", response ); }
static void CheckValidConnectionRequest(string request, string name) { var ascii = Encoding.ASCII; var requestBytes = ascii.GetBytes(request); var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(requestBytes), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> >(); var byteServer = mockByteServer.Object; var byteClient = new TestClient(stream); var server = new KRPC.Server.WebSockets.RPCServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte>(byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsTrue(eventArgs.Request.ShouldAllow); Assert.IsFalse(eventArgs.Request.ShouldDeny); server.Update(); Assert.AreEqual(1, server.Clients.Count()); Assert.AreEqual(name, server.Clients.First().Name); var response = ascii.GetString(responseStream.ToArray()); Assert.AreEqual( "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n", response ); }
public void OnClientRequestingConnection (object sender, ClientRequestingConnectionEventArgs eventArgs) { // Not open, so open the dialog if (!Visible) { Logger.WriteLine ("Asking player to allow/deny connection attempt..."); args = eventArgs; Open (); return; } // Already open for a different request, so ignore if (Visible && args.Client != eventArgs.Client) return; // Open, and we have a decision (must be the correct client at this point), to close the dialog if (Visible && !args.Request.StillPending) { if (args.Request.ShouldAllow) eventArgs.Request.Allow (); else eventArgs.Request.Deny (); Close (); } }
public void InvalidConnectionMessageHeader() { var connectionMessage = TestingTools.CreateConnectionRequest(Type.Stream, clientId.ToByteArray()); connectionMessage [2] ^= 0x42; connectionMessage [3] ^= 0x42; connectionMessage [4] ^= 0x42; connectionMessage [5] ^= 0x42; var responseStream = new MemoryStream(); var stream = new TestStream(new MemoryStream(connectionMessage), responseStream); // Create mock byte server and client var mockByteServer = new Mock <IServer <byte, byte> > (); var byteServer = mockByteServer.Object; var mockByteClient = new Mock <IClient <byte, byte> > (); mockByteClient.Setup(x => x.Stream).Returns(stream); var byteClient = mockByteClient.Object; var server = new StreamServer(byteServer); server.OnClientRequestingConnection += (sender, e) => e.Request.Allow(); server.Start(); // Fire a client connection event var eventArgs = new ClientRequestingConnectionEventArgs <byte, byte> (byteClient); mockByteServer.Raise(m => m.OnClientRequestingConnection += null, eventArgs); Assert.IsFalse(eventArgs.Request.ShouldAllow); Assert.IsTrue(eventArgs.Request.ShouldDeny); TestingTools.CheckConnectionResponse(responseStream.ToArray(), 209, Status.MalformedMessage, "While parsing a protocol message, the input ended unexpectedly in the middle of a field. " + "This could mean either that the input has been truncated or that an embedded message misreported its own length.", 0); }
/// <summary> /// Read a websockets connection request. If the request is invalid, /// writes the approprate HTTP response and denies the connection attempt. /// </summary> public static Request ReadRequest(ClientRequestingConnectionEventArgs <byte, byte> args) { var stream = args.Client.Stream; try { var buffer = new byte [BUFFER_SIZE]; var count = stream.Read(buffer, 0); var request = Request.FromBytes(buffer, 0, count); CheckValid(request); Logger.WriteLine("WebSockets: received valid connection request", Logger.Severity.Debug); return(request); } catch (HandshakeException e) { Logger.WriteLine("WebSockets handshake failed: " + e.Response, Logger.Severity.Error); args.Request.Deny(); stream.Write(e.Response.ToBytes()); return(null); } catch (MalformedRequestException e) { // TODO: wait for timeout seconds to see if the request was truncated Logger.WriteLine("Malformed WebSockets connection request: " + e.Message, Logger.Severity.Error); args.Request.Deny(); stream.Write(Response.CreateBadRequest().ToBytes()); return(null); } }
protected override void Closed() { args = null; }
protected override void Closed () { args = null; }
/// <summary> /// When a client requests a connection, and is successful, send the ok message /// </summary> public override void HandleClientRequestingConnection (object sender, ClientRequestingConnectionEventArgs<byte,byte> args) { base.HandleClientRequestingConnection (sender, args); if (args.Request.ShouldAllow) args.Client.Stream.Write (okMessage); }