throttleproxy.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env node
  2. var net = require('net');
  3. var opts = require('commander');
  4. var Throttle = require('../src/throttle.js').Throttle;
  5. function parseAddr(addr) {
  6. var result = /^(([^:]*):)?(\d+)$/.exec(addr);
  7. if (!result)
  8. return null;
  9. return {
  10. host: result[2],
  11. port: result[3]
  12. };
  13. }
  14. function parseInteger(s) {
  15. if (!/^\d+$/.test(s))
  16. return undefined;
  17. return parseInt(s, 10);
  18. }
  19. function runProxy(localAddr, remoteAddr, downRate, upRate) {
  20. var server = net.createServer(function(local) {
  21. var remote = net.createConnection(remoteAddr);
  22. var localThrottle = new Throttle({rate: upRate});
  23. var remoteThrottle = new Throttle({rate: downRate});
  24. local.pipe(localThrottle).pipe(remote);
  25. local.on('error', function() {
  26. remote.destroy();
  27. local.destroy();
  28. });
  29. remote.pipe(remoteThrottle).pipe(local);
  30. remote.on('error', function() {
  31. local.destroy();
  32. remote.destroy();
  33. });
  34. });
  35. server.listen(localAddr.port, localAddr.host);
  36. }
  37. function main() {
  38. var localAddr, remoteAddr, downRate, upRate;
  39. opts
  40. .option('-l, --localaddr <addr>', 'local address, default 0.0.0.0:8080')
  41. .option('-r, --remoteaddr <addr>', 'remote address, default localhost:80')
  42. .option('-d, --downstream <bps>', 'downstream bandwidth', parseInteger)
  43. .option('-u, --upstream <bps>', 'upstream bandwidth, default equal to downstream', parseInteger)
  44. .parse(process.argv);
  45. if (opts.localaddr !== undefined) {
  46. localAddr = parseAddr(opts.localaddr);
  47. if (!localAddr)
  48. opts.help();
  49. } else
  50. localAddr = {host: undefined, port: 8080};
  51. if (opts.remoteaddr !== undefined) {
  52. remoteAddr = parseAddr(opts.remoteaddr);
  53. if (!remoteAddr)
  54. opts.help();
  55. } else
  56. remoteAddr = {host: undefined, port: 80};
  57. if (opts.downstream === undefined)
  58. opts.help();
  59. downRate = opts.downstream;
  60. if (opts.upstream !== undefined)
  61. upRate = opts.upstream;
  62. else
  63. upRate = downRate;
  64. runProxy(localAddr, remoteAddr, downRate, upRate);
  65. }
  66. main();