Skip to content

Commit

Permalink
fix issue, if something is listening on 127.0.0.1 it was still possible
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
greggman committed Jan 30, 2024
1 parent 489054d commit 75c72b7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
10 changes: 2 additions & 8 deletions lib/get-free-port.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -26,7 +20,7 @@ async function getFreePort(port) {

server.listen({
port,
host: "0.0.0.0",
host,
exclusive: true,
});
});
Expand Down
6 changes: 5 additions & 1 deletion lib/servez.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,11 +236,15 @@ class Servez extends EventEmitter {
res.status(404).send(`<pre>ERROR 404: No such path ${req.path}</pre>`);
}

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);
Expand Down
8 changes: 8 additions & 0 deletions test/tests/servez-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 75c72b7

Please sign in to comment.