index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const net = require('net');
  2. const server = net.createServer();
  3. server.on('connection', (clientToProxySocket) => {
  4. console.log('Client Connected To Proxy');
  5. // We need only the data once, the starting packet
  6. clientToProxySocket.once('data', (data) => {
  7. // If you want to see the packet uncomment below
  8. // console.log(data.toString());
  9. let isTLSConnection = data.toString().indexOf('CONNECT') !== -1;
  10. // By Default port is 80
  11. let serverPort = 80;
  12. let serverAddress;
  13. if (isTLSConnection) {
  14. // Port changed if connection is TLS
  15. serverPort = data.toString()
  16. .split('CONNECT ')[1].split(' ')[0].split(':')[1];;
  17. serverAddress = data.toString()
  18. .split('CONNECT ')[1].split(' ')[0].split(':')[0];
  19. } else {
  20. serverAddress = data.toString().split('Host: ')[1].split('\r\n')[0];
  21. }
  22. console.log(serverAddress);
  23. let proxyToServerSocket = net.createConnection({
  24. host: serverAddress,
  25. port: serverPort
  26. }, () => {
  27. console.log('PROXY TO SERVER SET UP');
  28. if (isTLSConnection) {
  29. clientToProxySocket.write('HTTP/1.1 200 OK\r\n\n');
  30. } else {
  31. proxyToServerSocket.write(data);
  32. }
  33. clientToProxySocket.pipe(proxyToServerSocket);
  34. proxyToServerSocket.pipe(clientToProxySocket);
  35. proxyToServerSocket.on('error', (err) => {
  36. console.log('PROXY TO SERVER ERROR');
  37. console.log(err);
  38. });
  39. });
  40. clientToProxySocket.on('error', err => {
  41. console.log('CLIENT TO PROXY ERROR');
  42. console.log(err);
  43. });
  44. });
  45. });
  46. server.on('error', (err) => {
  47. console.log('SERVER ERROR');
  48. console.log(err);
  49. throw err;
  50. });
  51. server.on('close', () => {
  52. console.log('Client Disconnected');
  53. });
  54. server.listen(8124, () => {
  55. console.log('Server runnig at http://localhost:' + 8124);
  56. });