rewrite-packet.js 16 KB

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