Skip to content

Instantly share code, notes, and snippets.

@Warr1024
Last active July 24, 2024 23:01
Show Gist options
  • Save Warr1024/a93e5ade411d674ed0a51a73f7f5eaed to your computer and use it in GitHub Desktop.
Save Warr1024/a93e5ade411d674ed0a51a73f7f5eaed to your computer and use it in GitHub Desktop.
/*
Copyright 2019-2024 Aaron Suen <warr1024@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";
const process = require("process");
const dgram = require("dgram");
// Command line args:
let [listenport, fwdport, fwdaddr, mindelay, maxdelay] = process.argv.slice(2);
// It will listen on <listenport> and act as a reverse proxy for the UDP service
// at <fwdaddr>:<fwdport>. All packets will be delayed by a uniformly
// distributed random value between <mindelay> and <maxdelay> in milleseconds.
// Defaults:
listenport = Number(listenport) || 30001;
fwdport = Number(fwdport) || 30000;
fwdaddr = fwdaddr || "127.0.0.1";
mindelay = Number(mindelay) || 400;
maxdelay = Number(maxdelay) || mindelay * 1.25;
console.log(
`${listenport}->${fwdaddr}:${fwdport} min ${mindelay} max ${maxdelay}`
);
function delaysend(sock, msg, toport, toaddr, fromport, fromaddr) {
const delay = Math.floor(Math.random() * (maxdelay - mindelay) + mindelay);
setTimeout(() => sock.send(msg, toport, toaddr), delay);
}
const server = dgram.createSocket("udp4");
server.on("error", (e) => {
throw e;
});
server.on("listening", () => `listening on ${listenport}`);
server.bind(listenport);
const fwds = {};
server.on("message", (msg, info) => {
const { address, port } = info;
const key = `${address}:${port}`;
let sock = fwds[key];
if (!sock) {
fwds[key] = sock = dgram.createSocket("udp4");
sock.on("error", (e) => {
throw e;
});
server.on("listening", () =>
console.log(
`new connection from ${address}:${port} relaying via port ${
sock.address().port
}`
)
);
sock.on("message", (m) =>
delaysend(server, m, port, address, fwdport, fwdaddr)
);
}
delaysend(sock, msg, fwdport, fwdaddr, port, address);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment