diff --git a/README.md b/README.md index d60f3f8..f0ac0da 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,7 @@ A minimal Websockets Server in Python with no external dependencies. * Multiple clients * No dependencies -Notice that this implementation does not support the more advanced features -like multithreading etc. The project is focused mainly on making it easy to run a -websocket server for prototyping, testing or for making a GUI for your application. +Notice this project is focused mainly on making it easy to run a websocket server for prototyping, testing or for making a GUI for your application. Thus not all possible features of Websockets are supported. Installation @@ -79,9 +77,12 @@ The WebsocketServer can be initialized with the below parameters. | `set_fn_message_received()` | Sets a callback function that will be called when a `client` sends a message | function | None | | `send_message()` | Sends a `message` to a specific `client`. The message is a simple string. | client, message | None | | `send_message_to_all()` | Sends a `message` to **all** connected clients. The message is a simple string. | message | None | -| `shutdown_gracefully()` | Shutdown server by sending a websocket CLOSE handshake to all connected clients. | None | None | -| `shutdown_abruptly()` | Shutdown server without sending any websocket CLOSE handshake. | None | None | - +| `disconnect_clients_gracefully()` | Disconnect all connected clients by sending a websocket CLOSE handshake. | Optional: status, reason | None | +| `disconnect_clients_abruptly()` | Disconnect all connected clients. Clients won't be aware until they try to send some data. | None | None | +| `shutdown_gracefully()` | Disconnect clients with a CLOSE handshake and shutdown server. | Optional: status, reason | None | +| `shutdown_abruptly()` | Disconnect clients and shutdown server with no handshake. | None | None | +| `deny_new_connections()` | Close connection for new clients. | Optional: status, reason | None | +| `allow_new_connections()` | Allows back connection for new clients. | | None | ### Callback functions diff --git a/releases.txt b/releases.txt index f143b39..2fda06c 100644 --- a/releases.txt +++ b/releases.txt @@ -18,3 +18,17 @@ 0.6.0 - Change order of params 'host' and 'port' - Add host attribute to server + +0.6.1 +- Sending data is now thread-safe + +0.6.2 +- Add API for disconnecting clients + +0.6.3 +- Remove deprecation warnings + +0.6.4 +- Add deny_new_connections & allow_new_connections +- Fix disconnect_clients_gracefully to now take params +- Fix shutdown_gracefully unused param diff --git a/server.py b/server.py index f0587c6..210c884 100644 --- a/server.py +++ b/server.py @@ -19,7 +19,7 @@ def message_received(client, server, message): PORT=9001 -server = WebsocketServer(PORT) +server = WebsocketServer(port = PORT) server.set_fn_new_client(new_client) server.set_fn_client_left(client_left) server.set_fn_message_received(message_received) diff --git a/setup.py b/setup.py index e345f7e..684b88d 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ from distutils.command.install import install -VERSION = '0.6.0' +VERSION = '0.6.4' def get_tag_version(): diff --git a/tests/test_server.py b/tests/test_server.py index 447d823..d03ce08 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -115,3 +115,45 @@ def test_client_closes_gracefully(self, session): assert not server.clients with pytest.raises(BrokenPipeError): old_client_handler.connection.send(b"test") + + def test_disconnect_clients_abruptly(self, session): + client, server = session + assert client.connected + assert server.clients + server.disconnect_clients_abruptly() + assert not server.clients + + # Client won't be aware until trying to write more data + with pytest.raises(BrokenPipeError): + for i in range(3): + client.send("test") + sleep(0.2) + + def test_disconnect_clients_gracefully(self, session): + client, server = session + assert client.connected + assert server.clients + server.disconnect_clients_gracefully() + assert not server.clients + + # Client won't be aware until trying to write more data + with pytest.raises(BrokenPipeError): + for i in range(3): + client.send("test") + sleep(0.2) + + def test_deny_new_connections(self, threaded_server): + url = "ws://{}:{}".format(*threaded_server.server_address) + server = threaded_server + server.deny_new_connections(status=1013, reason=b"Please try re-connecting later") + + conn = websocket.create_connection(url) + try: + conn.send("test") + except websocket.WebSocketProtocolException as e: + assert 'Invalid close opcode' in e.args[0] + assert not server.clients + + server.allow_new_connections() + conn = websocket.create_connection(url) + conn.send("test") diff --git a/websocket_server/websocket_server.py b/websocket_server/websocket_server.py index 1bed1e8..c954c34 100644 --- a/websocket_server/websocket_server.py +++ b/websocket_server/websocket_server.py @@ -80,12 +80,24 @@ def send_message(self, client, msg): def send_message_to_all(self, msg): self._multicast(msg) + def deny_new_connections(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): + self._deny_new_connections(status, reason) + + def allow_new_connections(self): + self._allow_new_connections() + def shutdown_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): - self._shutdown_gracefully(status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON) + self._shutdown_gracefully(status, reason) def shutdown_abruptly(self): self._shutdown_abruptly() + def disconnect_clients_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): + self._disconnect_clients_gracefully(status, reason) + + def disconnect_clients_abruptly(self): + self._disconnect_clients_abruptly() + class WebsocketServer(ThreadingMixIn, TCPServer, API): """ @@ -125,6 +137,8 @@ def __init__(self, host='127.0.0.1', port=0, loglevel=logging.WARNING, key=None, self.id_counter = 0 self.thread = None + self._deny_clients = False + def _run_forever(self, threaded): cls_name = self.__class__.__name__ try: @@ -155,6 +169,13 @@ def _pong_received_(self, handler, msg): pass def _new_client_(self, handler): + if self._deny_clients: + status = self._deny_clients["status"] + reason = self._deny_clients["reason"] + handler.send_close(status, reason) + self._terminate_client_handler(handler) + return + self.id_counter += 1 client = { 'id': self.id_counter, @@ -182,26 +203,24 @@ def handler_to_client(self, handler): if client['handler'] == handler: return client + def _terminate_client_handler(self, handler): + handler.keep_alive = False + handler.finish() + handler.connection.close() + def _terminate_client_handlers(self): """ Ensures request handler for each client is terminated correctly """ for client in self.clients: - client["handler"].keep_alive = False - client["handler"].finish() - client["handler"].connection.close() + self._terminate_client_handler(client["handler"]) def _shutdown_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): """ Send a CLOSE handshake to all connected clients before terminating server """ self.keep_alive = False - - # Send CLOSE to clients - for client in self.clients: - client["handler"].send_close(CLOSE_STATUS_NORMAL, reason) - - self._terminate_client_handlers() + self._disconnect_clients_gracefully(status, reason) self.server_close() self.shutdown() @@ -210,20 +229,49 @@ def _shutdown_abruptly(self): Terminate server without sending a CLOSE handshake """ self.keep_alive = False - self._terminate_client_handlers() + self._disconnect_clients_abruptly() self.server_close() self.shutdown() + def _disconnect_clients_gracefully(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): + """ + Terminate clients gracefully without shutting down the server + """ + for client in self.clients: + client["handler"].send_close(status, reason) + self._terminate_client_handlers() + + def _disconnect_clients_abruptly(self): + """ + Terminate clients abruptly (no CLOSE handshake) without shutting down the server + """ + self._terminate_client_handlers() + + def _deny_new_connections(self, status, reason): + self._deny_clients = { + "status": status, + "reason": reason, + } + + def _allow_new_connections(self): + self._deny_clients = False + class WebSocketHandler(StreamRequestHandler): def __init__(self, socket, addr, server): self.server = server + assert not hasattr(self, "_send_lock"), "_send_lock already exists" + self._send_lock = threading.Lock() if server.key and server.cert: try: - socket = ssl.wrap_socket(socket, server_side=True, certfile=server.cert, keyfile=server.key) - except: # Not sure which exception it throws if the key/cert isn't found - logger.warn("SSL not available (are the paths {} and {} correct for the key and cert?)".format(server.key, server.cert)) + ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + ssl_context.load_cert_chain(certfile=server.cert, keyfile=server.key) + socket = ssl_context.wrap_socket(socket, server_side=True) + except FileNotFoundError: + logger.warning("SSL key or certificate file not found. Please check the paths for the key and cert.") + except ssl.SSLError as e: + logger.warning(f"SSL error occurred: {e}") StreamRequestHandler.__init__(self, socket, addr, server) def setup(self): @@ -264,14 +312,14 @@ def read_next_message(self): self.keep_alive = 0 return if not masked: - logger.warn("Client must always be masked.") + logger.warning("Client must always be masked.") self.keep_alive = 0 return if opcode == OPCODE_CONTINUATION: - logger.warn("Continuation frames are not supported.") + logger.warning("Continuation frames are not supported.") return elif opcode == OPCODE_BINARY: - logger.warn("Binary frames are not supported.") + logger.warning("Binary frames are not supported.") return elif opcode == OPCODE_TEXT: opcode_handler = self.server._message_received_ @@ -280,7 +328,7 @@ def read_next_message(self): elif opcode == OPCODE_PONG: opcode_handler = self.server._pong_received_ else: - logger.warn("Unknown opcode %#x." % opcode) + logger.warning("Unknown opcode %#x." % opcode) self.keep_alive = 0 return @@ -321,7 +369,8 @@ def send_close(self, status=CLOSE_STATUS_NORMAL, reason=DEFAULT_CLOSE_REASON): # Send CLOSE with status & reason header.append(FIN | OPCODE_CLOSE_CONN) header.append(payload_length) - self.request.send(header + payload) + with self._send_lock: + self.request.send(header + payload) def send_text(self, message, opcode=OPCODE_TEXT): """ @@ -364,7 +413,8 @@ def send_text(self, message, opcode=OPCODE_TEXT): raise Exception("Message is too big. Consider breaking it into chunks.") return - self.request.send(header + payload) + with self._send_lock: + self.request.send(header + payload) def read_http_headers(self): headers = {} @@ -397,7 +447,8 @@ def handshake(self): return response = self.make_handshake_response(key) - self.handshake_done = self.request.send(response.encode()) + with self._send_lock: + self.handshake_done = self.request.send(response.encode()) self.valid_client = True self.server._new_client_(self)