packet-output-stream.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. 'use strict';
  2. const Iconv = require('iconv-lite');
  3. const Utils = require('../misc/utils');
  4. const QUOTE = 0x27;
  5. const DBL_QUOTE = 0x22;
  6. const ZERO_BYTE = 0x00;
  7. const SLASH = 0x5c;
  8. //increase by level to avoid buffer copy.
  9. const SMALL_BUFFER_SIZE = 1024;
  10. const MEDIUM_BUFFER_SIZE = 16384; //16k
  11. const LARGE_BUFFER_SIZE = 131072; //128k
  12. const BIG_BUFFER_SIZE = 1048576; //1M
  13. const MAX_BUFFER_SIZE = 16777219; //16M + 4
  14. const CHARS_GLOBAL_REGEXP = /[\0\"\'\\\b\n\r\t\u001A]/g; // eslint-disable-line no-control-regex
  15. /**
  16. * MySQL packet builder.
  17. *
  18. * @param opts options
  19. * @param info connection info
  20. * @constructor
  21. */
  22. class PacketOutputStream {
  23. constructor(opts, info) {
  24. this.opts = opts;
  25. this.info = info;
  26. this.pos = 4;
  27. this.buf = Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  28. this.changeEncoding(this.opts.collation);
  29. this.changeDebug(this.opts.logPackets, this.opts.debug);
  30. this.opts.on('collation', this.changeEncoding.bind(this));
  31. this.opts.on('debug', this.changeDebug.bind(this));
  32. }
  33. changeEncoding(collation) {
  34. this.encoding = collation.charset;
  35. if (this.encoding === 'utf8') {
  36. this.writeString = this.writeDefaultBufferString;
  37. this.writeStringEscapeQuote = this.writeUtf8StringEscapeQuote;
  38. } else if (Buffer.isEncoding(this.encoding)) {
  39. this.writeString = this.writeDefaultBufferString;
  40. this.writeStringEscapeQuote = this.writeDefaultStringEscapeQuote;
  41. } else {
  42. this.writeString = this.writeDefaultIconvString;
  43. this.writeStringEscapeQuote = this.writeDefaultStringEscapeQuote;
  44. }
  45. }
  46. changeDebug(logPackets, debug) {
  47. this.logPackets = logPackets;
  48. this.debug = debug;
  49. this.flushBuffer =
  50. this.logPackets || this.debug ? this.flushBufferDebug : this.flushBufferBasic;
  51. }
  52. setStream(stream) {
  53. this.stream = stream;
  54. }
  55. growBuffer(len) {
  56. let newCapacity;
  57. if (len + this.pos < MEDIUM_BUFFER_SIZE) {
  58. newCapacity = MEDIUM_BUFFER_SIZE;
  59. } else if (len + this.pos < LARGE_BUFFER_SIZE) {
  60. newCapacity = LARGE_BUFFER_SIZE;
  61. } else if (len + this.pos < BIG_BUFFER_SIZE) {
  62. newCapacity = BIG_BUFFER_SIZE;
  63. } else newCapacity = MAX_BUFFER_SIZE;
  64. let newBuf = Buffer.allocUnsafe(newCapacity);
  65. this.buf.copy(newBuf, 0, 0, this.pos);
  66. this.buf = newBuf;
  67. }
  68. startPacket(cmd) {
  69. this.cmd = cmd;
  70. this.pos = 4;
  71. }
  72. writeInt8(value) {
  73. if (this.pos + 1 >= this.buf.length) {
  74. if (this.pos >= MAX_BUFFER_SIZE) {
  75. //buffer is more than a Packet, must flushBuffer()
  76. this.flushBuffer(false, 1);
  77. } else this.growBuffer(1);
  78. }
  79. this.buf[this.pos++] = value;
  80. }
  81. writeInt16(value) {
  82. if (this.pos + 2 >= this.buf.length) {
  83. let b = Buffer.allocUnsafe(2);
  84. b.writeUInt16LE(value, 0);
  85. this.writeBuffer(b, 0, 2);
  86. return;
  87. }
  88. this.buf[this.pos] = value;
  89. this.buf[this.pos + 1] = value >> 8;
  90. this.pos += 2;
  91. }
  92. writeInt16AtPos(initPos) {
  93. this.buf[initPos] = this.pos - initPos - 2;
  94. this.buf[initPos + 1] = (this.pos - initPos - 2) >> 8;
  95. }
  96. writeInt32(value) {
  97. if (this.pos + 4 >= this.buf.length) {
  98. //not enough space remaining
  99. let arr = Buffer.allocUnsafe(4);
  100. arr.writeInt32LE(value, 0);
  101. this.writeBuffer(arr, 0, 4);
  102. return;
  103. }
  104. this.buf[this.pos] = value;
  105. this.buf[this.pos + 1] = value >> 8;
  106. this.buf[this.pos + 2] = value >> 16;
  107. this.buf[this.pos + 3] = value >> 24;
  108. this.pos += 4;
  109. }
  110. writeLengthCoded(len) {
  111. //length encoded can be null(0xfb) or bigger than 65k, but only if using binary protocol
  112. //so not implemented for now
  113. if (len < 0xfb) {
  114. this.writeInt8(len);
  115. return;
  116. }
  117. //max length is len < 0xffff
  118. this.writeInt8(0xfc);
  119. this.writeInt16(len);
  120. }
  121. writeBuffer(arr, off, len) {
  122. if (len > this.buf.length - this.pos) {
  123. if (this.buf.length !== MAX_BUFFER_SIZE) {
  124. this.growBuffer(len);
  125. }
  126. //max buffer size
  127. if (len > this.buf.length - this.pos) {
  128. //not enough space in buffer, will stream :
  129. // fill buffer and flush until all data are snd
  130. let remainingLen = len;
  131. while (true) {
  132. //filling buffer
  133. let lenToFillBuffer = Math.min(MAX_BUFFER_SIZE - this.pos, remainingLen);
  134. arr.copy(this.buf, this.pos, off, off + lenToFillBuffer);
  135. remainingLen -= lenToFillBuffer;
  136. off += lenToFillBuffer;
  137. this.pos += lenToFillBuffer;
  138. if (remainingLen === 0) return;
  139. this.flushBuffer(false, remainingLen);
  140. }
  141. }
  142. }
  143. arr.copy(this.buf, this.pos, off, off + len);
  144. this.pos += len;
  145. }
  146. /**
  147. * Write ascii string to socket (no escaping)
  148. *
  149. * @param str string
  150. */
  151. writeStringAscii(str) {
  152. let len = str.length;
  153. //not enough space remaining
  154. if (len >= this.buf.length - this.pos) {
  155. let strBuf = Buffer.from(str, 'ascii');
  156. this.writeBuffer(strBuf, 0, strBuf.length);
  157. return;
  158. }
  159. for (let off = 0; off < len; ) {
  160. this.buf[this.pos++] = str.charCodeAt(off++);
  161. }
  162. }
  163. writeUtf8StringEscapeQuote(str) {
  164. const charsLength = str.length;
  165. //not enough space remaining
  166. if (charsLength * 3 + 2 >= this.buf.length - this.pos) {
  167. const arr = Buffer.from(str, 'utf8');
  168. this.writeInt8(QUOTE);
  169. this.writeBufferEscape(arr);
  170. this.writeInt8(QUOTE);
  171. return;
  172. }
  173. //create UTF-8 byte array
  174. //since javascript char are internally using UTF-16 using surrogate's pattern, 4 bytes unicode characters will
  175. //represent 2 characters : example "\uD83C\uDFA4" = 🎤 unicode 8 "no microphones"
  176. //so max size is 3 * charLength
  177. //(escape characters are 1 byte encoded, so length might only be 2 when escaped)
  178. // + 2 for the quotes for text protocol
  179. let charsOffset = 0;
  180. let currChar;
  181. this.buf[this.pos++] = QUOTE;
  182. //quick loop if only ASCII chars for faster escape
  183. for (
  184. ;
  185. charsOffset < charsLength && (currChar = str.charCodeAt(charsOffset)) < 0x80;
  186. charsOffset++
  187. ) {
  188. if (
  189. currChar === SLASH ||
  190. currChar === QUOTE ||
  191. currChar === ZERO_BYTE ||
  192. currChar === DBL_QUOTE
  193. ) {
  194. this.buf[this.pos++] = SLASH;
  195. }
  196. this.buf[this.pos++] = currChar;
  197. }
  198. //if quick loop not finished
  199. while (charsOffset < charsLength) {
  200. currChar = str.charCodeAt(charsOffset++);
  201. if (currChar < 0x80) {
  202. if (
  203. currChar === SLASH ||
  204. currChar === QUOTE ||
  205. currChar === ZERO_BYTE ||
  206. currChar === DBL_QUOTE
  207. ) {
  208. this.buf[this.pos++] = SLASH;
  209. }
  210. this.buf[this.pos++] = currChar;
  211. } else if (currChar < 0x800) {
  212. this.buf[this.pos++] = 0xc0 | (currChar >> 6);
  213. this.buf[this.pos++] = 0x80 | (currChar & 0x3f);
  214. } else if (currChar >= 0xd800 && currChar < 0xe000) {
  215. //reserved for surrogate - see https://en.wikipedia.org/wiki/UTF-16
  216. if (currChar < 0xdc00) {
  217. //is high surrogate
  218. if (charsOffset + 1 > charsLength) {
  219. this.buf[this.pos++] = 0x3f;
  220. } else {
  221. const nextChar = str.charCodeAt(charsOffset);
  222. if (nextChar >= 0xdc00 && nextChar < 0xe000) {
  223. //is low surrogate
  224. const surrogatePairs =
  225. (currChar << 10) + nextChar + (0x010000 - (0xd800 << 10) - 0xdc00);
  226. this.buf[this.pos++] = 0xf0 | (surrogatePairs >> 18);
  227. this.buf[this.pos++] = 0x80 | ((surrogatePairs >> 12) & 0x3f);
  228. this.buf[this.pos++] = 0x80 | ((surrogatePairs >> 6) & 0x3f);
  229. this.buf[this.pos++] = 0x80 | (surrogatePairs & 0x3f);
  230. charsOffset++;
  231. } else {
  232. //must have low surrogate
  233. this.buf[this.pos++] = 0x3f;
  234. }
  235. }
  236. } else {
  237. //low surrogate without high surrogate before
  238. this.buf[this.pos++] = 0x3f;
  239. }
  240. } else {
  241. this.buf[this.pos++] = 0xe0 | (currChar >> 12);
  242. this.buf[this.pos++] = 0x80 | ((currChar >> 6) & 0x3f);
  243. this.buf[this.pos++] = 0x80 | (currChar & 0x3f);
  244. }
  245. }
  246. this.buf[this.pos++] = QUOTE;
  247. }
  248. writeDefaultBufferString(str) {
  249. //javascript use UCS-2 or UTF-16 string internal representation
  250. //that means that string to byte will be a maximum of * 3
  251. // (4 bytes utf-8 are represented on 2 UTF-16 characters)
  252. if (str.length * 3 < this.buf.length - this.pos) {
  253. this.pos += this.buf.write(str, this.pos, this.encoding);
  254. return;
  255. }
  256. //checking real length
  257. let byteLength = Buffer.byteLength(str, this.encoding);
  258. if (byteLength > this.buf.length - this.pos) {
  259. if (this.buf.length < MAX_BUFFER_SIZE) {
  260. this.growBuffer(byteLength);
  261. }
  262. if (byteLength > this.buf.length - this.pos) {
  263. //not enough space in buffer, will stream :
  264. let strBuf = Buffer.from(str, this.encoding);
  265. this.writeBuffer(strBuf, 0, strBuf.length);
  266. return;
  267. }
  268. }
  269. this.pos += this.buf.write(str, this.pos, this.encoding);
  270. }
  271. writeDefaultIconvString(str) {
  272. let buf = Iconv.encode(str, this.encoding);
  273. this.writeBuffer(buf, 0, buf.length);
  274. }
  275. /**
  276. * Parameters need to be properly escaped :
  277. * following characters are to be escaped by "\" :
  278. * - \0
  279. * - \\
  280. * - \'
  281. * - \"
  282. * regex split part of string writing part, and escaping special char.
  283. * Those chars are <= 7f meaning that this will work even with multi-byte encoding
  284. *
  285. * @param str string to escape.
  286. */
  287. writeDefaultStringEscapeQuote(str) {
  288. this.writeInt8(QUOTE);
  289. let match;
  290. let lastIndex = 0;
  291. while ((match = CHARS_GLOBAL_REGEXP.exec(str)) !== null) {
  292. this.writeString(str.slice(lastIndex, match.index));
  293. this.writeInt8(SLASH);
  294. this.writeInt8(match[0].charCodeAt(0));
  295. lastIndex = CHARS_GLOBAL_REGEXP.lastIndex;
  296. }
  297. if (lastIndex === 0) {
  298. // Nothing was escaped
  299. this.writeString(str);
  300. this.writeInt8(QUOTE);
  301. return;
  302. }
  303. if (lastIndex < str.length) {
  304. this.writeString(str.slice(lastIndex));
  305. }
  306. this.writeInt8(QUOTE);
  307. }
  308. writeBufferEscape(val) {
  309. let valLen = val.length;
  310. if (valLen * 2 > this.buf.length - this.pos) {
  311. //makes buffer bigger (up to 16M)
  312. if (this.buf.length !== MAX_BUFFER_SIZE) this.growBuffer(valLen * 2);
  313. //data may still be bigger than buffer.
  314. //must flush buffer when full (and reset position to 4)
  315. if (valLen * 2 > this.buf.length - this.pos) {
  316. //not enough space in buffer, will fill buffer
  317. for (let i = 0; i < valLen; i++) {
  318. switch (val[i]) {
  319. case QUOTE:
  320. case SLASH:
  321. case DBL_QUOTE:
  322. case ZERO_BYTE:
  323. if (this.pos >= this.buf.length) this.flushBuffer(false, (valLen - i) * 2);
  324. this.buf[this.pos++] = SLASH; //add escape slash
  325. }
  326. if (this.pos >= this.buf.length) this.flushBuffer(false, (valLen - i) * 2);
  327. this.buf[this.pos++] = val[i];
  328. }
  329. return;
  330. }
  331. }
  332. //sure to have enough place to use buffer directly
  333. for (let i = 0; i < valLen; i++) {
  334. switch (val[i]) {
  335. case QUOTE:
  336. case SLASH:
  337. case DBL_QUOTE:
  338. case ZERO_BYTE:
  339. this.buf[this.pos++] = SLASH; //add escape slash
  340. }
  341. this.buf[this.pos++] = val[i];
  342. }
  343. }
  344. /**
  345. * Indicate if buffer contain any data.
  346. * @returns {boolean}
  347. */
  348. isEmpty() {
  349. return this.pos <= 4;
  350. }
  351. /**
  352. * Flush the internal buffer.
  353. */
  354. flushBufferDebug(commandEnd, remainingLen) {
  355. this.buf[0] = this.pos - 4;
  356. this.buf[1] = (this.pos - 4) >>> 8;
  357. this.buf[2] = (this.pos - 4) >>> 16;
  358. this.buf[3] = ++this.cmd.sequenceNo;
  359. this.stream.writeBuf(this.buf.slice(0, this.pos), this.cmd);
  360. const packet = Utils.log(this.opts, this.buf, 0, this.pos);
  361. if (this.opts.logPackets) {
  362. this.info.addPacket(
  363. '==> conn:' +
  364. (this.info.threadId ? this.info.threadId : -1) +
  365. ' ' +
  366. this.cmd.constructor.name +
  367. '(0,' +
  368. this.pos +
  369. ')\n' +
  370. packet
  371. );
  372. }
  373. if (this.opts.debug) {
  374. console.log(
  375. '==> conn:%d %s\n%s',
  376. this.info.threadId ? this.info.threadId : -1,
  377. this.cmd.constructor.name + '(0,' + this.pos + ')',
  378. Utils.log(this.opts, this.buf, 0, this.pos)
  379. );
  380. }
  381. if (commandEnd) {
  382. //if last packet fill the max size, must send an empty com to indicate that command end.
  383. if (this.pos === MAX_BUFFER_SIZE) {
  384. this.writeEmptyPacket();
  385. } else {
  386. this.stream.flush(true, this.cmd);
  387. this.buf = Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  388. }
  389. } else {
  390. this.buf = allocateBuffer(remainingLen + 4);
  391. this.pos = 4;
  392. }
  393. }
  394. flushBufferBasic(commandEnd, remainingLen) {
  395. this.buf[0] = this.pos - 4;
  396. this.buf[1] = (this.pos - 4) >>> 8;
  397. this.buf[2] = (this.pos - 4) >>> 16;
  398. this.buf[3] = ++this.cmd.sequenceNo;
  399. this.stream.writeBuf(this.buf.slice(0, this.pos), this.cmd);
  400. if (commandEnd) {
  401. //if last packet fill the max size, must send an empty com to indicate that command end.
  402. if (this.pos === MAX_BUFFER_SIZE) {
  403. this.writeEmptyPacket();
  404. } else {
  405. this.stream.flush(true, this.cmd);
  406. this.buf = Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  407. }
  408. } else {
  409. this.buf = allocateBuffer(remainingLen + 4);
  410. this.pos = 4;
  411. }
  412. }
  413. writeEmptyPacket() {
  414. const emptyBuf = Buffer.from([0x00, 0x00, 0x00, ++this.cmd.sequenceNo]);
  415. if (this.opts.logPackets || this.opts.debug) {
  416. const packet = Utils.log(this.opts, emptyBuf, 0, 4);
  417. if (this.opts.logPackets) {
  418. this.info.addPacket(
  419. '==> conn:' +
  420. (this.info.threadId ? this.info.threadId : -1) +
  421. ' ' +
  422. this.cmd.constructor.name +
  423. '(0,4)\n' +
  424. packet
  425. );
  426. }
  427. if (this.opts.debug) {
  428. console.log(
  429. '==> conn:%d %s\n%s',
  430. this.info.threadId ? this.info.threadId : -1,
  431. this.cmd.constructor.name + '(0,4)',
  432. packet
  433. );
  434. }
  435. }
  436. this.stream.writeBuf(emptyBuf, this.cmd);
  437. this.stream.flush(true, this.cmd);
  438. }
  439. }
  440. function allocateBuffer(len) {
  441. if (len < SMALL_BUFFER_SIZE) {
  442. return Buffer.allocUnsafe(SMALL_BUFFER_SIZE);
  443. } else if (len < MEDIUM_BUFFER_SIZE) {
  444. return Buffer.allocUnsafe(MEDIUM_BUFFER_SIZE);
  445. } else if (len < LARGE_BUFFER_SIZE) {
  446. return Buffer.allocUnsafe(LARGE_BUFFER_SIZE);
  447. } else if (len < BIG_BUFFER_SIZE) {
  448. return Buffer.allocUnsafe(BIG_BUFFER_SIZE);
  449. }
  450. return Buffer.allocUnsafe(MAX_BUFFER_SIZE);
  451. }
  452. module.exports = PacketOutputStream;