diff --git a/marznode/marznode.py b/marznode/marznode.py index 60cb476..b71fb01 100644 --- a/marznode/marznode.py +++ b/marznode/marznode.py @@ -11,6 +11,7 @@ from marznode.service import MarzService from marznode.storage import MemoryStorage from marznode.utils.ssl import generate_keypair, create_secure_context +from marznode.utils.network import find_free_port from marznode.xray.base import XrayCore from marznode.xray.config import XrayConfig from marznode.xray_api import XrayAPI @@ -35,11 +36,13 @@ async def main(): config.SSL_KEY_FILE, trusted=config.SSL_CLIENT_CERT_FILE) + xray_api_port = find_free_port() + storage = MemoryStorage() - xray_config = XrayConfig(config.XRAY_CONFIG_PATH, storage) + xray_config = XrayConfig(config.XRAY_CONFIG_PATH, storage, api_port=xray_api_port) xray = XrayCore(config.XRAY_EXECUTABLE_PATH, config.XRAY_ASSETS_PATH) await xray.start(xray_config) - xray_api = XrayAPI("127.0.0.1", 8080) + xray_api = XrayAPI("127.0.0.1", xray_api_port) server = Server([MarzService(xray_api, storage, xray), Health()]) with graceful_exit([server]): diff --git a/marznode/service/service.py b/marznode/service/service.py index ca10068..c46f691 100644 --- a/marznode/service/service.py +++ b/marznode/service/service.py @@ -9,6 +9,7 @@ from grpclib.server import Stream from marznode.storage import BaseStorage +from marznode.utils.network import find_free_port from marznode.xray_api import XrayAPI from marznode.xray_api.exceptions import EmailExistsError, EmailNotFoundError from marznode.xray_api.types.account import accounts_map @@ -18,6 +19,7 @@ from .. import config from ..xray.base import XrayCore from ..xray.config import XrayConfig +from ..xray_api import XrayAPI logger = logging.getLogger(__name__) @@ -148,7 +150,8 @@ async def FetchXrayConfig(self, stream: Stream[Empty, XrayConfig_pb2]) -> None: async def RestartXray(self, stream: Stream[XrayConfig_pb2, InboundsResponse]) -> None: message = await stream.recv_message() - xconfig = XrayConfig(message.configuration, storage=self.storage) + api_port = find_free_port() + xconfig = XrayConfig(message.configuration, storage=self.storage, api_port=api_port) await self.storage.flush_users() await self.xray.restart(xconfig) stored_inbounds = await self.storage.list_inbounds() @@ -156,3 +159,4 @@ async def RestartXray(self, stream: Stream[XrayConfig_pb2, InboundsResponse]) -> await stream.send_message(InboundsResponse(inbounds=inbounds)) with open(config.XRAY_CONFIG_PATH, 'w') as f: f.write(message.configuration) + self.api = XrayAPI("127.0.0.1", api_port) diff --git a/marznode/utils/network.py b/marznode/utils/network.py new file mode 100644 index 0000000..0686529 --- /dev/null +++ b/marznode/utils/network.py @@ -0,0 +1,11 @@ +import socket + + +def find_free_port(): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + + return port +