From 757d628bc84c729e1ca5e103a714b8fc6b44c5f9 Mon Sep 17 00:00:00 2001 From: Owen Date: Fri, 21 Feb 2025 12:52:24 -0500 Subject: [PATCH] Handle port correctly --- install/fs/config.yml | 5 ++++ server/lib/config.ts | 2 ++ server/routers/newt/handleGetConfigMessage.ts | 24 ++++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/install/fs/config.yml b/install/fs/config.yml index 8e4411e7..cf9e6464 100644 --- a/install/fs/config.yml +++ b/install/fs/config.yml @@ -32,6 +32,11 @@ gerbil: site_block_size: 30 subnet_group: 100.89.137.0/20 +wg_site: + start_port: 51820 + block_size: 24 + subnet_group: 100.89.137.0/20 + rate_limits: global: window_minutes: 1 diff --git a/server/lib/config.ts b/server/lib/config.ts index fc1c0531..f607fe0d 100644 --- a/server/lib/config.ts +++ b/server/lib/config.ts @@ -12,6 +12,7 @@ import { } from "@server/lib/consts"; import { passwordSchema } from "@server/auth/passwordSchema"; import stoi from "./stoi"; +import { start } from "repl"; const portSchema = z.number().positive().gt(0).lte(65535); const hostnameSchema = z @@ -112,6 +113,7 @@ const configSchema = z.object({ wg_site: z.object({ block_size: z.number().positive().gt(0), subnet_group: z.string(), + start_port: portSchema }), rate_limits: z.object({ global: z.object({ diff --git a/server/routers/newt/handleGetConfigMessage.ts b/server/routers/newt/handleGetConfigMessage.ts index 4f03bdd8..6d8cb8c8 100644 --- a/server/routers/newt/handleGetConfigMessage.ts +++ b/server/routers/newt/handleGetConfigMessage.ts @@ -41,7 +41,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => { return; } - const { publicKey, endpoint, listenPort } = message.data as Input; + const { publicKey, endpoint } = message.data as Input; const siteId = newt.siteId; @@ -58,6 +58,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => { let site: Site | undefined; if (!site) { const address = await getNextAvailableSubnet(); + const listenPort = await getNextAvailablePort(); // create a new exit node const [updateRes] = await db @@ -146,3 +147,24 @@ async function getNextAvailableSubnet(): Promise { subnet.split("/")[1]; return subnet; } + +async function getNextAvailablePort(): Promise { + // Get all existing ports from exitNodes table + const existingPorts = await db.select({ + listenPort: sites.listenPort, + }).from(sites); + + // Find the first available port between 1024 and 65535 + let nextPort = config.getRawConfig().wg_site.start_port; + for (const port of existingPorts) { + if (port.listenPort && port.listenPort > nextPort) { + break; + } + nextPort++; + if (nextPort > 65535) { + throw new Error('No available ports remaining in space'); + } + } + + return nextPort; +}