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.

99 lines
2.2 KiB

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