TunnelCluster.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. const { EventEmitter } = require('events');
  2. const debug = require('debug')('localtunnel:client');
  3. const fs = require('fs');
  4. const net = require('net');
  5. const tls = require('tls');
  6. const HeaderHostTransformer = require('./HeaderHostTransformer');
  7. // manages groups of tunnels
  8. module.exports = class TunnelCluster extends EventEmitter {
  9. constructor(opts = {}) {
  10. super(opts);
  11. this.opts = opts;
  12. }
  13. open() {
  14. const opt = this.opts;
  15. // Prefer IP if returned by the server
  16. const remoteHostOrIp = opt.remote_ip || opt.remote_host;
  17. const remotePort = opt.remote_port;
  18. const localHost = opt.local_host || 'localhost';
  19. const localPort = opt.local_port;
  20. const localProtocol = opt.local_https ? 'https' : 'http';
  21. const allowInvalidCert = opt.allow_invalid_cert;
  22. debug(
  23. 'establishing tunnel %s://%s:%s <> %s:%s',
  24. localProtocol,
  25. localHost,
  26. localPort,
  27. remoteHostOrIp,
  28. remotePort
  29. );
  30. // connection to localtunnel server
  31. const remote = net.connect({
  32. host: remoteHostOrIp,
  33. port: remotePort,
  34. });
  35. remote.setKeepAlive(true);
  36. remote.on('error', err => {
  37. debug('got remote connection error', err.message);
  38. // emit connection refused errors immediately, because they
  39. // indicate that the tunnel can't be established.
  40. if (err.code === 'ECONNREFUSED') {
  41. this.emit(
  42. 'error',
  43. new Error(
  44. `connection refused: ${remoteHostOrIp}:${remotePort} (check your firewall settings)`
  45. )
  46. );
  47. }
  48. remote.end();
  49. });
  50. const connLocal = () => {
  51. if (remote.destroyed) {
  52. debug('remote destroyed');
  53. this.emit('dead');
  54. return;
  55. }
  56. debug('connecting locally to %s://%s:%d', localProtocol, localHost, localPort);
  57. remote.pause();
  58. if (allowInvalidCert) {
  59. debug('allowing invalid certificates');
  60. }
  61. const getLocalCertOpts = () =>
  62. allowInvalidCert
  63. ? { rejectUnauthorized: false }
  64. : {
  65. cert: fs.readFileSync(opt.local_cert),
  66. key: fs.readFileSync(opt.local_key),
  67. ca: opt.local_ca ? [fs.readFileSync(opt.local_ca)] : undefined,
  68. };
  69. // connection to local http server
  70. const local = opt.local_https
  71. ? tls.connect({ host: localHost, port: localPort, ...getLocalCertOpts() })
  72. : net.connect({ host: localHost, port: localPort });
  73. const remoteClose = () => {
  74. debug('remote close');
  75. this.emit('dead');
  76. local.end();
  77. };
  78. remote.once('close', remoteClose);
  79. // TODO some languages have single threaded servers which makes opening up
  80. // multiple local connections impossible. We need a smarter way to scale
  81. // and adjust for such instances to avoid beating on the door of the server
  82. local.once('error', err => {
  83. debug('local error %s', err.message);
  84. local.end();
  85. remote.removeListener('close', remoteClose);
  86. if (err.code !== 'ECONNREFUSED') {
  87. return remote.end();
  88. }
  89. // retrying connection to local server
  90. setTimeout(connLocal, 1000);
  91. });
  92. local.once('connect', () => {
  93. debug('connected locally');
  94. remote.resume();
  95. let stream = remote;
  96. // if user requested specific local host
  97. // then we use host header transform to replace the host header
  98. if (opt.local_host) {
  99. debug('transform Host header to %s', opt.local_host);
  100. stream = remote.pipe(new HeaderHostTransformer({ host: opt.local_host }));
  101. }
  102. stream.pipe(local).pipe(remote);
  103. // when local closes, also get a new remote
  104. local.once('close', hadError => {
  105. debug('local connection closed [%s]', hadError);
  106. });
  107. });
  108. };
  109. remote.on('data', data => {
  110. const match = data.toString().match(/^(\w+) (\S+)/);
  111. if (match) {
  112. this.emit('request', {
  113. method: match[1],
  114. path: match[2],
  115. });
  116. }
  117. });
  118. // tunnel is considered open when remote connects
  119. remote.once('connect', () => {
  120. this.emit('open', remote);
  121. connLocal();
  122. });
  123. }
  124. };