uws.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. 'use strict';
  2. const http = require('http');
  3. const EventEmitter = require('events');
  4. const EE_ERROR = 'Registering more than one listener to a WebSocket is not supported.';
  5. const DEFAULT_PAYLOAD_LIMIT = 16777216;
  6. function noop() {}
  7. function abortConnection(socket, code, name) {
  8. socket.end('HTTP/1.1 ' + code + ' ' + name + '\r\n\r\n');
  9. }
  10. function emitConnection(ws) {
  11. this.emit('connection', ws);
  12. }
  13. function onServerMessage(message, webSocket) {
  14. webSocket.internalOnMessage(message);
  15. }
  16. const native = (() => {
  17. try {
  18. try {
  19. return process.binding('uws_builtin');
  20. } catch (e) {
  21. return require(`./uws_${process.platform}_${process.versions.modules}`);
  22. }
  23. } catch (e) {
  24. const version = process.version.substring(1).split('.').map(function(n) {
  25. return parseInt(n);
  26. });
  27. const lessThanSixFour = version[0] < 6 || (version[0] === 6 && version[1] < 4);
  28. if (process.platform === 'win32' && lessThanSixFour) {
  29. throw new Error('µWebSockets requires Node.js 6.4.0 or greater on Windows.');
  30. } else {
  31. throw new Error('Compilation of µWebSockets has failed and there is no pre-compiled binary ' +
  32. 'available for your system. Please install a supported C++11 compiler and reinstall the module \'uws\'.');
  33. }
  34. }
  35. })();
  36. native.setNoop(noop);
  37. var _upgradeReq = null;
  38. const clientGroup = native.client.group.create(0, DEFAULT_PAYLOAD_LIMIT);
  39. native.client.group.onConnection(clientGroup, (external) => {
  40. const webSocket = native.getUserData(external);
  41. webSocket.external = external;
  42. webSocket.internalOnOpen();
  43. });
  44. native.client.group.onMessage(clientGroup, (message, webSocket) => {
  45. webSocket.internalOnMessage(message);
  46. });
  47. native.client.group.onDisconnection(clientGroup, (external, code, message, webSocket) => {
  48. webSocket.external = null;
  49. process.nextTick(() => {
  50. webSocket.internalOnClose(code, message);
  51. });
  52. native.clearUserData(external);
  53. });
  54. native.client.group.onPing(clientGroup, (message, webSocket) => {
  55. webSocket.onping(message);
  56. });
  57. native.client.group.onPong(clientGroup, (message, webSocket) => {
  58. webSocket.onpong(message);
  59. });
  60. native.client.group.onError(clientGroup, (webSocket) => {
  61. process.nextTick(() => {
  62. webSocket.internalOnError({
  63. message: 'uWs client connection error',
  64. stack: 'uWs client connection error'
  65. });
  66. });
  67. });
  68. class WebSocket {
  69. constructor(external) {
  70. this.external = external;
  71. this.internalOnMessage = noop;
  72. this.internalOnClose = noop;
  73. this.onping = noop;
  74. this.onpong = noop;
  75. }
  76. get upgradeReq() {
  77. return _upgradeReq;
  78. }
  79. set onmessage(f) {
  80. if (f) {
  81. this.internalOnMessage = (message) => {
  82. f({data: message});
  83. };
  84. } else {
  85. this.internalOnMessage = noop;
  86. }
  87. }
  88. set onopen(f) {
  89. if (f) {
  90. this.internalOnOpen = f;
  91. } else {
  92. this.internalOnOpen = noop;
  93. }
  94. }
  95. set onclose(f) {
  96. if (f) {
  97. this.internalOnClose = (code, message) => {
  98. f({code: code, reason: message});
  99. };
  100. } else {
  101. this.internalOnClose = noop;
  102. }
  103. }
  104. set onerror(f) {
  105. if (f && this instanceof WebSocketClient) {
  106. this.internalOnError = f;
  107. } else {
  108. this.internalOnError = noop;
  109. }
  110. }
  111. emit(eventName, arg1, arg2) {
  112. if (eventName === 'message') {
  113. this.internalOnMessage(arg1);
  114. } else if (eventName === 'close') {
  115. this.internalOnClose(arg1, arg2);
  116. } else if (eventName === 'ping') {
  117. this.onping(arg1);
  118. } else if (eventName === 'pong') {
  119. this.onpong(arg1);
  120. }
  121. return this;
  122. }
  123. on(eventName, f) {
  124. if (eventName === 'message') {
  125. if (this.internalOnMessage !== noop) {
  126. throw Error(EE_ERROR);
  127. }
  128. this.internalOnMessage = f;
  129. } else if (eventName === 'close') {
  130. if (this.internalOnClose !== noop) {
  131. throw Error(EE_ERROR);
  132. }
  133. this.internalOnClose = f;
  134. } else if (eventName === 'ping') {
  135. if (this.onping !== noop) {
  136. throw Error(EE_ERROR);
  137. }
  138. this.onping = f;
  139. } else if (eventName === 'pong') {
  140. if (this.onpong !== noop) {
  141. throw Error(EE_ERROR);
  142. }
  143. this.onpong = f;
  144. } else if (eventName === 'open') {
  145. if (this.internalOnOpen !== noop) {
  146. throw Error(EE_ERROR);
  147. }
  148. this.internalOnOpen = f;
  149. } else if (eventName === 'error' && this instanceof WebSocketClient) {
  150. if (this.internalOnError !== noop) {
  151. throw Error(EE_ERROR);
  152. }
  153. this.internalOnError = f;
  154. }
  155. return this;
  156. }
  157. once(eventName, f) {
  158. if (eventName === 'message') {
  159. if (this.internalOnMessage !== noop) {
  160. throw Error(EE_ERROR);
  161. }
  162. this.internalOnMessage = (message) => {
  163. this.internalOnMessage = noop;
  164. f(message);
  165. };
  166. } else if (eventName === 'close') {
  167. if (this.internalOnClose !== noop) {
  168. throw Error(EE_ERROR);
  169. }
  170. this.internalOnClose = (code, message) => {
  171. this.internalOnClose = noop;
  172. f(code, message);
  173. };
  174. } else if (eventName === 'ping') {
  175. if (this.onping !== noop) {
  176. throw Error(EE_ERROR);
  177. }
  178. this.onping = () => {
  179. this.onping = noop;
  180. f();
  181. };
  182. } else if (eventName === 'pong') {
  183. if (this.onpong !== noop) {
  184. throw Error(EE_ERROR);
  185. }
  186. this.onpong = () => {
  187. this.onpong = noop;
  188. f();
  189. };
  190. }
  191. return this;
  192. }
  193. removeAllListeners(eventName) {
  194. if (!eventName || eventName === 'message') {
  195. this.internalOnMessage = noop;
  196. }
  197. if (!eventName || eventName === 'close') {
  198. this.internalOnClose = noop;
  199. }
  200. if (!eventName || eventName === 'ping') {
  201. this.onping = noop;
  202. }
  203. if (!eventName || eventName === 'pong') {
  204. this.onpong = noop;
  205. }
  206. return this;
  207. }
  208. removeListener(eventName, cb) {
  209. if (eventName === 'message' && this.internalOnMessage === cb) {
  210. this.internalOnMessage = noop;
  211. } else if (eventName === 'close' && this.internalOnClose === cb) {
  212. this.internalOnClose = noop;
  213. } else if (eventName === 'ping' && this.onping === cb) {
  214. this.onping = noop;
  215. } else if (eventName === 'pong' && this.onpong === cb) {
  216. this.onpong = noop;
  217. }
  218. return this;
  219. }
  220. get OPEN() {
  221. return WebSocketClient.OPEN;
  222. }
  223. get CLOSED() {
  224. return WebSocketClient.CLOSED;
  225. }
  226. get readyState() {
  227. return this.external ? WebSocketClient.OPEN : WebSocketClient.CLOSED;
  228. }
  229. get _socket() {
  230. const address = this.external ? native.getAddress(this.external) : new Array(3);
  231. return {
  232. remotePort: address[0],
  233. remoteAddress: address[1],
  234. remoteFamily: address[2]
  235. };
  236. }
  237. // from here down, functions are not common between client and server
  238. ping(message, options, dontFailWhenClosed) {
  239. if (this.external) {
  240. native.server.send(this.external, message, WebSocketClient.OPCODE_PING);
  241. }
  242. }
  243. terminate() {
  244. if (this.external) {
  245. native.server.terminate(this.external);
  246. this.external = null;
  247. }
  248. }
  249. send(message, options, cb) {
  250. if (this.external) {
  251. if (typeof options === 'function') {
  252. cb = options;
  253. options = null;
  254. }
  255. const binary = options && options.binary || typeof message !== 'string';
  256. native.server.send(this.external, message, binary ? WebSocketClient.OPCODE_BINARY : WebSocketClient.OPCODE_TEXT, cb ? (() => {
  257. process.nextTick(cb);
  258. }) : undefined);
  259. } else if (cb) {
  260. cb(new Error('not opened'));
  261. }
  262. }
  263. close(code, data) {
  264. if (this.external) {
  265. native.server.close(this.external, code, data);
  266. this.external = null;
  267. }
  268. }
  269. }
  270. class WebSocketClient extends WebSocket {
  271. constructor(uri) {
  272. super(null);
  273. this.internalOnOpen = noop;
  274. this.internalOnError = noop;
  275. native.connect(clientGroup, uri, this);
  276. }
  277. ping(message, options, dontFailWhenClosed) {
  278. if (this.external) {
  279. native.client.send(this.external, message, WebSocketClient.OPCODE_PING);
  280. }
  281. }
  282. terminate() {
  283. if (this.external) {
  284. native.client.terminate(this.external);
  285. this.external = null;
  286. }
  287. }
  288. send(message, options, cb) {
  289. if (this.external) {
  290. if (typeof options === 'function') {
  291. cb = options;
  292. options = null;
  293. }
  294. const binary = options && options.binary || typeof message !== 'string';
  295. native.client.send(this.external, message, binary ? WebSocketClient.OPCODE_BINARY : WebSocketClient.OPCODE_TEXT, cb ? (() => {
  296. process.nextTick(cb);
  297. }) : undefined);
  298. } else if (cb) {
  299. cb(new Error('not opened'));
  300. }
  301. }
  302. close(code, data) {
  303. if (this.external) {
  304. native.client.close(this.external, code, data);
  305. this.external = null;
  306. }
  307. }
  308. }
  309. class Server extends EventEmitter {
  310. constructor(options, callback) {
  311. super();
  312. if (!options) {
  313. throw new TypeError('missing options');
  314. }
  315. if (options.port === undefined && !options.server && !options.noServer) {
  316. throw new TypeError('invalid options');
  317. }
  318. var nativeOptions = WebSocketClient.PERMESSAGE_DEFLATE;
  319. if (options.perMessageDeflate !== undefined) {
  320. if (options.perMessageDeflate === false) {
  321. nativeOptions = 0;
  322. }
  323. }
  324. this.serverGroup = native.server.group.create(nativeOptions, options.maxPayload === undefined ? DEFAULT_PAYLOAD_LIMIT : options.maxPayload);
  325. // can these be made private?
  326. this._upgradeCallback = noop;
  327. this._upgradeListener = null;
  328. this._noDelay = options.noDelay === undefined ? true : options.noDelay;
  329. this._lastUpgradeListener = true;
  330. this._passedHttpServer = options.server;
  331. if (!options.noServer) {
  332. this.httpServer = options.server ? options.server : http.createServer((request, response) => {
  333. // todo: default HTTP response
  334. response.end();
  335. });
  336. if (options.path && (!options.path.length || options.path[0] !== '/')) {
  337. options.path = '/' + options.path;
  338. }
  339. this.httpServer.on('upgrade', this._upgradeListener = ((request, socket, head) => {
  340. if (!options.path || options.path == request.url.split('?')[0].split('#')[0]) {
  341. if (options.verifyClient) {
  342. const info = {
  343. origin: request.headers.origin,
  344. secure: request.connection.authorized !== undefined || request.connection.encrypted !== undefined,
  345. req: request
  346. };
  347. if (options.verifyClient.length === 2) {
  348. options.verifyClient(info, (result, code, name) => {
  349. if (result) {
  350. this.handleUpgrade(request, socket, head, emitConnection);
  351. } else {
  352. abortConnection(socket, code, name);
  353. }
  354. });
  355. } else {
  356. if (options.verifyClient(info)) {
  357. this.handleUpgrade(request, socket, head, emitConnection);
  358. } else {
  359. abortConnection(socket, 400, 'Client verification failed');
  360. }
  361. }
  362. } else {
  363. this.handleUpgrade(request, socket, head, emitConnection);
  364. }
  365. } else {
  366. if (this._lastUpgradeListener) {
  367. abortConnection(socket, 400, 'URL not supported');
  368. }
  369. }
  370. }));
  371. this.httpServer.on('newListener', (eventName, listener) => {
  372. if (eventName === 'upgrade') {
  373. this._lastUpgradeListener = false;
  374. }
  375. });
  376. this.httpServer.on('error', (err) => {
  377. this.emit('error', err);
  378. });
  379. }
  380. native.server.group.onDisconnection(this.serverGroup, (external, code, message, webSocket) => {
  381. webSocket.external = null;
  382. process.nextTick(() => {
  383. webSocket.internalOnClose(code, message);
  384. });
  385. native.clearUserData(external);
  386. });
  387. native.server.group.onMessage(this.serverGroup, onServerMessage);
  388. native.server.group.onPing(this.serverGroup, (message, webSocket) => {
  389. webSocket.onping(message);
  390. });
  391. native.server.group.onPong(this.serverGroup, (message, webSocket) => {
  392. webSocket.onpong(message);
  393. });
  394. native.server.group.onConnection(this.serverGroup, (external) => {
  395. const webSocket = new WebSocket(external);
  396. native.setUserData(external, webSocket);
  397. this._upgradeCallback(webSocket);
  398. _upgradeReq = null;
  399. });
  400. if (options.port !== undefined) {
  401. if (options.host) {
  402. this.httpServer.listen(options.port, options.host, () => {
  403. this.emit('listening');
  404. callback && callback();
  405. });
  406. } else {
  407. this.httpServer.listen(options.port, () => {
  408. this.emit('listening');
  409. callback && callback();
  410. });
  411. }
  412. }
  413. }
  414. handleUpgrade(request, socket, upgradeHead, callback) {
  415. if (socket._isNative) {
  416. if (this.serverGroup) {
  417. _upgradeReq = request;
  418. this._upgradeCallback = callback ? callback : noop;
  419. native.upgrade(this.serverGroup, socket.external, secKey, request.headers['sec-websocket-extensions'], request.headers['sec-websocket-protocol']);
  420. }
  421. } else {
  422. const secKey = request.headers['sec-websocket-key'];
  423. const socketHandle = socket.ssl ? socket._parent._handle : socket._handle;
  424. const sslState = socket.ssl ? socket.ssl._external : null;
  425. if (socketHandle && secKey && secKey.length == 24) {
  426. socket.setNoDelay(this._noDelay);
  427. const ticket = native.transfer(socketHandle.fd === -1 ? socketHandle : socketHandle.fd, sslState);
  428. socket.on('close', (error) => {
  429. if (this.serverGroup) {
  430. _upgradeReq = request;
  431. this._upgradeCallback = callback ? callback : noop;
  432. native.upgrade(this.serverGroup, ticket, secKey, request.headers['sec-websocket-extensions'], request.headers['sec-websocket-protocol']);
  433. }
  434. });
  435. }
  436. socket.destroy();
  437. }
  438. }
  439. broadcast(message, options) {
  440. if (this.serverGroup) {
  441. native.server.group.broadcast(this.serverGroup, message, options && options.binary || false);
  442. }
  443. }
  444. startAutoPing(interval, userMessage) {
  445. if (this.serverGroup) {
  446. native.server.group.startAutoPing(this.serverGroup, interval, userMessage);
  447. }
  448. }
  449. close(cb) {
  450. if (this._upgradeListener && this.httpServer) {
  451. this.httpServer.removeListener('upgrade', this._upgradeListener);
  452. if (!this._passedHttpServer) {
  453. this.httpServer.close();
  454. }
  455. }
  456. if (this.serverGroup) {
  457. native.server.group.close(this.serverGroup);
  458. this.serverGroup = null;
  459. }
  460. if (typeof cb === 'function') {
  461. // compatibility hack, 15 seconds timeout
  462. setTimeout(cb, 20000);
  463. }
  464. }
  465. get clients() {
  466. if (this.serverGroup) {
  467. return {
  468. length: native.server.group.getSize(this.serverGroup),
  469. forEach: ((cb) => {native.server.group.forEach(this.serverGroup, cb)})
  470. };
  471. }
  472. }
  473. }
  474. WebSocketClient.PERMESSAGE_DEFLATE = 1;
  475. WebSocketClient.SERVER_NO_CONTEXT_TAKEOVER = 2;
  476. WebSocketClient.CLIENT_NO_CONTEXT_TAKEOVER = 4;
  477. WebSocketClient.OPCODE_TEXT = 1;
  478. WebSocketClient.OPCODE_BINARY = 2;
  479. WebSocketClient.OPCODE_PING = 9;
  480. WebSocketClient.OPEN = 1;
  481. WebSocketClient.CLOSED = 0;
  482. WebSocketClient.Server = Server;
  483. WebSocketClient.http = native.httpServer;
  484. WebSocketClient.native = native;
  485. module.exports = WebSocketClient;