wsproxy.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // A WebSocket to TCP socket proxy
  2. // Copyright 2010 Joel Martin
  3. // Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
  4. var net = require('net'),
  5. sys = require('sys'),
  6. crypto = require('crypto'),
  7. source_arg, source_host, source_port,
  8. target_arg, target_host, target_port;
  9. // md5 calculation borrowed from Socket.IO (MIT license)
  10. function gen_md5(headers, k3) {
  11. var k1 = headers['sec-websocket-key1'],
  12. k2 = headers['sec-websocket-key2'],
  13. md5 = crypto.createHash('md5');
  14. [k1, k2].forEach(function(k){
  15. var n = parseInt(k.replace(/[^\d]/g, '')),
  16. spaces = k.replace(/[^ ]/g, '').length;
  17. if (spaces === 0 || n % spaces !== 0){
  18. return false;
  19. }
  20. n /= spaces;
  21. md5.update(String.fromCharCode(
  22. n >> 24 & 0xFF,
  23. n >> 16 & 0xFF,
  24. n >> 8 & 0xFF,
  25. n & 0xFF));
  26. });
  27. md5.update(k3.toString('binary'));
  28. return md5.digest('binary');
  29. }
  30. function encode(buf) {
  31. return String.fromCharCode(0) +
  32. buf.toString('base64', 0) +
  33. String.fromCharCode(255);
  34. }
  35. function decode(data) {
  36. var i, len = 0, strs, retstrs = [],
  37. buf = new Buffer(data.length),
  38. str = data.toString('binary', 1, data.length-1);
  39. if (str.indexOf('\xff') > -1) {
  40. // We've gotten multiple frames at once
  41. strs = str.split('\xff\x00')
  42. for (i = 0; i < strs.length; i++) {
  43. len = buf.write(strs[i], 0, 'base64');
  44. retstrs.push(buf.toString('binary', 0, len));
  45. }
  46. return retstrs.join("");
  47. } else {
  48. len = buf.write(str, 0, 'base64');
  49. return buf.toString('binary', 0, len);
  50. }
  51. }
  52. var server = net.createServer(function (client) {
  53. var handshake = "", headers = {}, header,
  54. version, path, k1, k2, k3, target = null;
  55. function cleanup() {
  56. client.end();
  57. if (target) {
  58. target.end();
  59. target = null;
  60. }
  61. }
  62. function do_handshake(data) {
  63. var i, idx, dlen = data.length, lines, location, rheaders,
  64. sec_hdr;
  65. //sys.log("received handshake data: " + data);
  66. handshake += data.toString('utf8');
  67. if ((data[dlen-12] != 13) ||
  68. (data[dlen-11] != 10) ||
  69. (data[dlen-10] != 13) ||
  70. (data[dlen-9] != 10)) {
  71. //sys.log("Got partial handshake");
  72. return;
  73. }
  74. //sys.log("Got whole handshake");
  75. if (handshake.indexOf('GET ') != 0) {
  76. sys.error("Got invalid handshake");
  77. client.end();
  78. return;
  79. }
  80. lines = handshake.split('\r\n');
  81. path = lines[0].split(' ')[1];
  82. //sys.log("path: " + path);
  83. k3 = data.slice(dlen-8, dlen);
  84. for (i = 1; i < lines.length; i++) {
  85. //sys.log("lines[i]: " + lines[i]);
  86. if (lines[i].length == 0) { break; }
  87. idx = lines[i].indexOf(': ');
  88. if (idx < 0) {
  89. sys.error("Got invalid handshake header");
  90. client.end();
  91. return;
  92. }
  93. header = lines[i].slice(0, idx).toLowerCase();
  94. headers[header] = lines[i].slice(idx+2);
  95. }
  96. //console.dir(headers);
  97. //sys.log("k3: " + k3 + ", k3.length: " + k3.length);
  98. if (headers.upgrade !== 'WebSocket') {
  99. sys.error("Upgrade header is not 'WebSocket'");
  100. client.end();
  101. return;
  102. }
  103. location = (headers.origin.substr(0, 5) == 'https' ? 'wss' : 'ws')
  104. + '://' + headers.host + path;
  105. //sys.log("location: " + location);
  106. if ('sec-websocket-key1' in headers) {
  107. version = 76;
  108. sec_hdr = "Sec-";
  109. } else {
  110. version = 75;
  111. sec_hdr = "";
  112. }
  113. sys.log("using protocol version " + version);
  114. rheaders = [
  115. 'HTTP/1.1 101 WebSocket Protocol Handshake',
  116. 'Upgrade: WebSocket',
  117. 'Connection: Upgrade',
  118. sec_hdr + 'WebSocket-Origin: ' + headers.origin,
  119. sec_hdr + 'WebSocket-Location: ' + location
  120. ];
  121. if ('sec-websocket-protocol' in headers) {
  122. rheaders.push('Sec-WebSocket-Protocol: ' + headers['sec-websocket-protocol']);
  123. }
  124. rheaders.push('');
  125. if (version === 76) {
  126. rheaders.push(gen_md5(headers, k3));
  127. }
  128. // Switch listener to normal data path
  129. client.on('data', client_data);
  130. //client.setEncoding('utf8');
  131. client.removeListener('data', do_handshake);
  132. // Do not delay writes
  133. client.setNoDelay(true);
  134. // Send the handshake response
  135. try {
  136. //sys.log("response: " + rheaders.join('\r\n'));
  137. client.write(rheaders.join('\r\n'), 'binary');
  138. } catch(e) {
  139. sys.error("Failed to send handshake response");
  140. client.end();
  141. return;
  142. }
  143. // Create a connection to the target
  144. target = net.createConnection(target_port, target_host);
  145. target.on('data', target_data);
  146. target.on('end', function () {
  147. sys.log("received target end");
  148. cleanup();
  149. });
  150. target.on('error', function (exc) {
  151. sys.log("received target error: " + exc);
  152. cleanup();
  153. });
  154. }
  155. function client_data(data) {
  156. var ret;
  157. //sys.log("received client data: " + data);
  158. //sys.log(" decoded: " + decode(data));
  159. try {
  160. ret = target.write(decode(data), 'binary');
  161. if (! ret) {
  162. sys.log("target write returned false");
  163. }
  164. } catch(e) {
  165. sys.log("fatal error writing to target");
  166. cleanup();
  167. }
  168. }
  169. function target_data(data) {
  170. //sys.log("received target data: " + data);
  171. //sys.log(" encoded: " + encode(data));
  172. try {
  173. client.write(encode(data), 'binary');
  174. } catch(e) {
  175. sys.log("fatal error writing to client");
  176. cleanup();
  177. }
  178. }
  179. client.on('connect', function () {
  180. sys.log("Got client connection");
  181. });
  182. client.on('data', do_handshake);
  183. client.on('end', function () {
  184. sys.log("recieved client end");
  185. cleanup();
  186. });
  187. client.on('error', function (exc) {
  188. sys.log("recieved client error: " + exc);
  189. cleanup();
  190. });
  191. });
  192. // parse source and target into parts
  193. source_arg = process.argv[2];
  194. target_arg = process.argv[3];
  195. try {
  196. var idx;
  197. idx = source_arg.indexOf(":");
  198. if (idx >= 0) {
  199. source_host = source_arg.slice(0, idx);
  200. source_port = parseInt(source_arg.slice(idx+1), 10);
  201. } else {
  202. source_host = "";
  203. source_port = parseInt(source_arg, 10);
  204. }
  205. idx = target_arg.indexOf(":");
  206. if (idx < 0) {
  207. throw("target must be host:port");
  208. }
  209. target_host = target_arg.slice(0, idx);
  210. target_port = parseInt(target_arg.slice(idx+1), 10);
  211. if (isNaN(source_port) || isNaN(target_port)) {
  212. throw("illegal port");
  213. }
  214. } catch(e) {
  215. console.error("wsproxy.py [source_addr:]source_port target_addr:target_port");
  216. process.exit(2);
  217. }
  218. sys.log("source: " + source_host + ":" + source_port);
  219. sys.log("target: " + target_host + ":" + target_port);
  220. server.listen(source_port, source_host);