From 75c72b7b3779816bbf65d12cc1269a3de9749b78 Mon Sep 17 00:00:00 2001 From: Gregg Tavares Date: Mon, 29 Jan 2024 17:56:24 -0800 Subject: [PATCH] fix issue, if something is listening on 127.0.0.1 it was still possible to start servez on 0.0.0.0 on the same port. That seems wrong, so servez now checks both 0.0.0.0 and 127.0.0.1 for an open port. --- lib/get-free-port.js | 10 ++-------- lib/servez.js | 6 +++++- test/tests/servez-test.js | 8 ++++++++ 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/lib/get-free-port.js b/lib/get-free-port.js index 7d73e4a..ebc26ef 100644 --- a/lib/get-free-port.js +++ b/lib/get-free-port.js @@ -3,21 +3,15 @@ const { Server } = require('net'); // This works by trying to listen on a port. // If connecting works then the port is good to use. // If not the port is busy, try another -async function getFreePort(port) { +function getFreePort(port, host) { return new Promise((resolve, reject) => { const server = new Server(); -// const timeout = () => { -// resolve(port); -// socket.destroy(); -// }; const next = () => { server.close(); resolve(getFreePort(++port)); }; -// setTimeout(timeout, 1000); -// server.on("timeout", timeout); server.on("listening", () => { server.close(); resolve(port); @@ -26,7 +20,7 @@ async function getFreePort(port) { server.listen({ port, - host: "0.0.0.0", + host, exclusive: true, }); }); diff --git a/lib/servez.js b/lib/servez.js index a4b96ff..518218d 100644 --- a/lib/servez.js +++ b/lib/servez.js @@ -236,11 +236,15 @@ class Servez extends EventEmitter { res.status(404).send(`
ERROR 404: No such path ${req.path}
`); } + async function getFreePortForLocalAndPublic(port) { + return await getFreePort(await getFreePort(port, '0.0.0.0'), '127.0.0.1'); + } + app.use(nonErrorLocalErrorHandler); app.use(localErrorHandler); (async () => { - const port = await getFreePort(settings.port); + const port = await getFreePortForLocalAndPublic(settings.port); if (!settings.scan && port !== settings.port) { const msg = `ERROR: port $${port} in use`; errorFiltered(Servez.MsgType.Error, msg); diff --git a/test/tests/servez-test.js b/test/tests/servez-test.js index 80a1237..beb0675 100644 --- a/test/tests/servez-test.js +++ b/test/tests/servez-test.js @@ -75,6 +75,14 @@ describe('servez-lib', () => { server2.servez.close(); }); + it('scans for port if only 127.0.0.1 is in use', async() => { + const server1 = await makeServer({local: true}); + const server2 = await makeServer(); + assert.notStrictEqual(server1.baseUrl, server2.baseUrl); + server1.servez.close(); + server2.servez.close(); + }); + it('does not scan for port when scan false', async() => { const server1 = await makeServer(); let threw = false;