From 355fa955334979670ad4a485541cce504e5af4f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Tue, 17 Sep 2019 19:37:22 +0200 Subject: [PATCH] server: Add a config option to set the SSO helper listening port. --- contrib/matrix_sso_helper | 40 ++++++++++++++++++++++++++++++++++++--- matrix/server.py | 15 +++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/contrib/matrix_sso_helper b/contrib/matrix_sso_helper index 0e85293..fa85295 100755 --- a/contrib/matrix_sso_helper +++ b/contrib/matrix_sso_helper @@ -15,6 +15,7 @@ import asyncio +import argparse import socket import json from random import choice @@ -49,16 +50,20 @@ async def get_token(request): } # Send the token to weechat. - print(json.dumps(message)) + to_weechat(message) # Initiate a shutdown. shutdown_task = asyncio.ensure_future(shutdown()) # Respond to the browser. return web.Response(text="Continuing in Weechat.") -def bind_socket(): +def bind_socket(port=None): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + if port is not None and port != 0: + sock.bind(("localhost", port)) + return sock + while True: port = choice(port_range) @@ -81,9 +86,38 @@ async def wait_for_shutdown_task(_): def main(): + parser = argparse.ArgumentParser( + description="Start a web server that waits for a SSO token to be " + "passed with a GET request" + ) + parser.add_argument( + "-p", "--port", + help=("the port that the web server will be listening on, if 0 a " + "random port should be chosen" + ), + type=int, + default=0 + ) + + args = parser.parse_args() + app = web.Application() app.add_routes([web.get('/', get_token)]) - sock = bind_socket() + + if not 0 <= args.port <= 65535: + raise ValueError("Port needs to be 0-65535") + + try: + sock = bind_socket(args.port) + except OSError as e: + message = { + "type": "error", + "message": str(e), + "code": e.errno + } + to_weechat(message) + return + host, port = sock.getsockname() message = { diff --git a/matrix/server.py b/matrix/server.py index 57bd4dc..02581f9 100644 --- a/matrix/server.py +++ b/matrix/server.py @@ -208,6 +208,15 @@ class ServerConfig(ConfigSection): "10", ("Delay (in seconds) before trying to reconnect to server"), ), + Option( + "sso_helper_listening_port", + "integer", + "", + 0, + 65535, + "0", + ("The port that the SSO helpers web server should listen on"), + ), ] section = W.config_search_section(config_ptr, "server") @@ -251,6 +260,10 @@ class ServerConfig(ConfigSection): password = ConfigSection.option_property( "password", "string", evaluate=True ) + sso_helper_listening_port = ConfigSection.option_property( + "sso_helper_listening_port", + "integer" + ) def free(self): W.config_section_free_options(self._ptr) @@ -807,6 +820,8 @@ class MatrixServer(object): process_args = { "buffer_flush": "1", + "arg1": "--port", + "arg2": str(self.config.sso_helper_listening_port) } self.sso_hook = W.hook_process_hashtable(