You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.3 KiB

  1. /*!
  2. * ws: a node.js websocket client
  3. * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Returns a Buffer from a "ff 00 ff"-type hex string.
  8. */
  9. getBufferFromHexString = function(byteStr) {
  10. var bytes = byteStr.split(' ');
  11. var buf = new Buffer(bytes.length);
  12. for (var i = 0; i < bytes.length; ++i) {
  13. buf[i] = parseInt(bytes[i], 16);
  14. }
  15. return buf;
  16. }
  17. /**
  18. * Returns a hex string from a Buffer.
  19. */
  20. getHexStringFromBuffer = function(data) {
  21. var s = '';
  22. for (var i = 0; i < data.length; ++i) {
  23. s += padl(data[i].toString(16), 2, '0') + ' ';
  24. }
  25. return s.trim();
  26. }
  27. /**
  28. * Splits a buffer in two parts.
  29. */
  30. splitBuffer = function(buffer) {
  31. var b1 = new Buffer(Math.ceil(buffer.length / 2));
  32. buffer.copy(b1, 0, 0, b1.length);
  33. var b2 = new Buffer(Math.floor(buffer.length / 2));
  34. buffer.copy(b2, 0, b1.length, b1.length + b2.length);
  35. return [b1, b2];
  36. }
  37. /**
  38. * Performs hybi07+ type masking on a hex string or buffer.
  39. */
  40. mask = function(buf, maskString) {
  41. if (typeof buf == 'string') buf = new Buffer(buf);
  42. var mask = getBufferFromHexString(maskString || '34 83 a8 68');
  43. for (var i = 0; i < buf.length; ++i) {
  44. buf[i] ^= mask[i % 4];
  45. }
  46. return buf;
  47. }
  48. /**
  49. * Returns a hex string representing the length of a message
  50. */
  51. getHybiLengthAsHexString = function(len, masked) {
  52. if (len < 126) {
  53. var buf = new Buffer(1);
  54. buf[0] = (masked ? 0x80 : 0) | len;
  55. }
  56. else if (len < 65536) {
  57. var buf = new Buffer(3);
  58. buf[0] = (masked ? 0x80 : 0) | 126;
  59. getBufferFromHexString(pack(4, len)).copy(buf, 1);
  60. }
  61. else {
  62. var buf = new Buffer(9);
  63. buf[0] = (masked ? 0x80 : 0) | 127;
  64. getBufferFromHexString(pack(16, len)).copy(buf, 1);
  65. }
  66. return getHexStringFromBuffer(buf);
  67. }
  68. /**
  69. * Unpacks a Buffer into a number.
  70. */
  71. unpack = function(buffer) {
  72. var n = 0;
  73. for (var i = 0; i < buffer.length; ++i) {
  74. n = (i == 0) ? buffer[i] : (n * 256) + buffer[i];
  75. }
  76. return n;
  77. }
  78. /**
  79. * Returns a hex string, representing a specific byte count 'length', from a number.
  80. */
  81. pack = function(length, number) {
  82. return padl(number.toString(16), length, '0').replace(/([0-9a-f][0-9a-f])/gi, '$1 ').trim();
  83. }
  84. /**
  85. * Left pads the string 's' to a total length of 'n' with char 'c'.
  86. */
  87. padl = function(s, n, c) {
  88. return new Array(1 + n - s.length).join(c) + s;
  89. }