packet.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. // This file was modified by Oracle on June 1, 2021.
  2. // A comment describing some changes in the strict default SQL mode regarding
  3. // non-standard dates was introduced.
  4. // Modifications copyright (c) 2021, Oracle and/or its affiliates.
  5. 'use strict';
  6. const ErrorCodeToName = require('../constants/errors.js');
  7. const NativeBuffer = require('buffer').Buffer;
  8. const Long = require('long');
  9. const StringParser = require('../parsers/string.js');
  10. const Types = require('../constants/types.js');
  11. const INVALID_DATE = new Date(NaN);
  12. // this is nearly duplicate of previous function so generated code is not slower
  13. // due to "if (dateStrings)" branching
  14. const pad = '000000000000';
  15. function leftPad(num, value) {
  16. const s = value.toString();
  17. // if we don't need to pad
  18. if (s.length >= num) {
  19. return s;
  20. }
  21. return (pad + s).slice(-num);
  22. }
  23. // The whole reason parse* function below exist
  24. // is because String creation is relatively expensive (at least with V8), and if we have
  25. // a buffer with "12345" content ideally we would like to bypass intermediate
  26. // "12345" string creation and directly build 12345 number out of
  27. // <Buffer 31 32 33 34 35> data.
  28. // In my benchmarks the difference is ~25M 8-digit numbers per second vs
  29. // 4.5 M using Number(packet.readLengthCodedString())
  30. // not used when size is close to max precision as series of *10 accumulate error
  31. // and approximate result mihgt be diffreent from (approximate as well) Number(bigNumStringValue))
  32. // In the futire node version if speed difference is smaller parse* functions might be removed
  33. // don't consider them as Packet public API
  34. const minus = '-'.charCodeAt(0);
  35. const plus = '+'.charCodeAt(0);
  36. // TODO: handle E notation
  37. const dot = '.'.charCodeAt(0);
  38. const exponent = 'e'.charCodeAt(0);
  39. const exponentCapital = 'E'.charCodeAt(0);
  40. class Packet {
  41. constructor(id, buffer, start, end) {
  42. // hot path, enable checks when testing only
  43. // if (!Buffer.isBuffer(buffer) || typeof start == 'undefined' || typeof end == 'undefined')
  44. // throw new Error('invalid packet');
  45. this.sequenceId = id;
  46. this.numPackets = 1;
  47. this.buffer = buffer;
  48. this.start = start;
  49. this.offset = start + 4;
  50. this.end = end;
  51. }
  52. // ==============================
  53. // readers
  54. // ==============================
  55. reset() {
  56. this.offset = this.start + 4;
  57. }
  58. length() {
  59. return this.end - this.start;
  60. }
  61. slice() {
  62. return this.buffer.slice(this.start, this.end);
  63. }
  64. dump() {
  65. // eslint-disable-next-line no-console
  66. console.log(
  67. [this.buffer.asciiSlice(this.start, this.end)],
  68. this.buffer.slice(this.start, this.end),
  69. this.length(),
  70. this.sequenceId
  71. );
  72. }
  73. haveMoreData() {
  74. return this.end > this.offset;
  75. }
  76. skip(num) {
  77. this.offset += num;
  78. }
  79. readInt8() {
  80. return this.buffer[this.offset++];
  81. }
  82. readInt16() {
  83. this.offset += 2;
  84. return this.buffer.readUInt16LE(this.offset - 2);
  85. }
  86. readInt24() {
  87. return this.readInt16() + (this.readInt8() << 16);
  88. }
  89. readInt32() {
  90. this.offset += 4;
  91. return this.buffer.readUInt32LE(this.offset - 4);
  92. }
  93. readSInt8() {
  94. return this.buffer.readInt8(this.offset++);
  95. }
  96. readSInt16() {
  97. this.offset += 2;
  98. return this.buffer.readInt16LE(this.offset - 2);
  99. }
  100. readSInt32() {
  101. this.offset += 4;
  102. return this.buffer.readInt32LE(this.offset - 4);
  103. }
  104. readInt64JSNumber() {
  105. const word0 = this.readInt32();
  106. const word1 = this.readInt32();
  107. const l = new Long(word0, word1, true);
  108. return l.toNumber();
  109. }
  110. readSInt64JSNumber() {
  111. const word0 = this.readInt32();
  112. const word1 = this.readInt32();
  113. if (!(word1 & 0x80000000)) {
  114. return word0 + 0x100000000 * word1;
  115. }
  116. const l = new Long(word0, word1, false);
  117. return l.toNumber();
  118. }
  119. readInt64String() {
  120. const word0 = this.readInt32();
  121. const word1 = this.readInt32();
  122. const res = new Long(word0, word1, true);
  123. return res.toString();
  124. }
  125. readSInt64String() {
  126. const word0 = this.readInt32();
  127. const word1 = this.readInt32();
  128. const res = new Long(word0, word1, false);
  129. return res.toString();
  130. }
  131. readInt64() {
  132. const word0 = this.readInt32();
  133. const word1 = this.readInt32();
  134. let res = new Long(word0, word1, true);
  135. const resNumber = res.toNumber();
  136. const resString = res.toString();
  137. res = resNumber.toString() === resString ? resNumber : resString;
  138. return res;
  139. }
  140. readSInt64() {
  141. const word0 = this.readInt32();
  142. const word1 = this.readInt32();
  143. let res = new Long(word0, word1, false);
  144. const resNumber = res.toNumber();
  145. const resString = res.toString();
  146. res = resNumber.toString() === resString ? resNumber : resString;
  147. return res;
  148. }
  149. isEOF() {
  150. return this.buffer[this.offset] === 0xfe && this.length() < 13;
  151. }
  152. eofStatusFlags() {
  153. return this.buffer.readInt16LE(this.offset + 3);
  154. }
  155. eofWarningCount() {
  156. return this.buffer.readInt16LE(this.offset + 1);
  157. }
  158. readLengthCodedNumber(bigNumberStrings, signed) {
  159. const byte1 = this.buffer[this.offset++];
  160. if (byte1 < 251) {
  161. return byte1;
  162. }
  163. return this.readLengthCodedNumberExt(byte1, bigNumberStrings, signed);
  164. }
  165. readLengthCodedNumberSigned(bigNumberStrings) {
  166. return this.readLengthCodedNumber(bigNumberStrings, true);
  167. }
  168. readLengthCodedNumberExt(tag, bigNumberStrings, signed) {
  169. let word0, word1;
  170. let res;
  171. if (tag === 0xfb) {
  172. return null;
  173. }
  174. if (tag === 0xfc) {
  175. return this.readInt8() + (this.readInt8() << 8);
  176. }
  177. if (tag === 0xfd) {
  178. return this.readInt8() + (this.readInt8() << 8) + (this.readInt8() << 16);
  179. }
  180. if (tag === 0xfe) {
  181. // TODO: check version
  182. // Up to MySQL 3.22, 0xfe was followed by a 4-byte integer.
  183. word0 = this.readInt32();
  184. word1 = this.readInt32();
  185. if (word1 === 0) {
  186. return word0; // don't convert to float if possible
  187. }
  188. if (word1 < 2097152) {
  189. // max exact float point int, 2^52 / 2^32
  190. return word1 * 0x100000000 + word0;
  191. }
  192. res = new Long(word0, word1, !signed); // Long need unsigned
  193. const resNumber = res.toNumber();
  194. const resString = res.toString();
  195. res = resNumber.toString() === resString ? resNumber : resString;
  196. return bigNumberStrings ? resString : res;
  197. }
  198. // eslint-disable-next-line no-console
  199. console.trace();
  200. throw new Error(`Should not reach here: ${tag}`);
  201. }
  202. readFloat() {
  203. const res = this.buffer.readFloatLE(this.offset);
  204. this.offset += 4;
  205. return res;
  206. }
  207. readDouble() {
  208. const res = this.buffer.readDoubleLE(this.offset);
  209. this.offset += 8;
  210. return res;
  211. }
  212. readBuffer(len) {
  213. if (typeof len === 'undefined') {
  214. len = this.end - this.offset;
  215. }
  216. this.offset += len;
  217. return this.buffer.slice(this.offset - len, this.offset);
  218. }
  219. // DATE, DATETIME and TIMESTAMP
  220. readDateTime(timezone) {
  221. if (!timezone || timezone === 'Z' || timezone === 'local') {
  222. const length = this.readInt8();
  223. if (length === 0xfb) {
  224. return null;
  225. }
  226. let y = 0;
  227. let m = 0;
  228. let d = 0;
  229. let H = 0;
  230. let M = 0;
  231. let S = 0;
  232. let ms = 0;
  233. if (length > 3) {
  234. y = this.readInt16();
  235. m = this.readInt8();
  236. d = this.readInt8();
  237. }
  238. if (length > 6) {
  239. H = this.readInt8();
  240. M = this.readInt8();
  241. S = this.readInt8();
  242. }
  243. if (length > 10) {
  244. ms = this.readInt32() / 1000;
  245. }
  246. // NO_ZERO_DATE mode and NO_ZERO_IN_DATE mode are part of the strict
  247. // default SQL mode used by MySQL 8.0. This means that non-standard
  248. // dates like '0000-00-00' become NULL. For older versions and other
  249. // possible MySQL flavours we still need to account for the
  250. // non-standard behaviour.
  251. if (y + m + d + H + M + S + ms === 0) {
  252. return INVALID_DATE;
  253. }
  254. if (timezone === 'Z') {
  255. return new Date(Date.UTC(y, m - 1, d, H, M, S, ms));
  256. }
  257. return new Date(y, m - 1, d, H, M, S, ms);
  258. }
  259. let str = this.readDateTimeString(6, 'T', null);
  260. if (str.length === 10) {
  261. str += 'T00:00:00';
  262. }
  263. return new Date(str + timezone);
  264. }
  265. readDateTimeString(decimals, timeSep, columnType) {
  266. const length = this.readInt8();
  267. let y = 0;
  268. let m = 0;
  269. let d = 0;
  270. let H = 0;
  271. let M = 0;
  272. let S = 0;
  273. let ms = 0;
  274. let str;
  275. if (length > 3) {
  276. y = this.readInt16();
  277. m = this.readInt8();
  278. d = this.readInt8();
  279. str = [leftPad(4, y), leftPad(2, m), leftPad(2, d)].join('-');
  280. }
  281. if (length > 6) {
  282. H = this.readInt8();
  283. M = this.readInt8();
  284. S = this.readInt8();
  285. str += `${timeSep || ' '}${[
  286. leftPad(2, H),
  287. leftPad(2, M),
  288. leftPad(2, S)
  289. ].join(':')}`;
  290. } else if (columnType === Types.DATETIME) {
  291. str += ' 00:00:00';
  292. }
  293. if (length > 10) {
  294. ms = this.readInt32();
  295. str += '.';
  296. if (decimals) {
  297. ms = leftPad(6, ms);
  298. if (ms.length > decimals) {
  299. ms = ms.substring(0, decimals); // rounding is done at the MySQL side, only 0 are here
  300. }
  301. }
  302. str += ms;
  303. }
  304. return str;
  305. }
  306. // TIME - value as a string, Can be negative
  307. readTimeString(convertTtoMs) {
  308. const length = this.readInt8();
  309. if (length === 0) {
  310. return '00:00:00';
  311. }
  312. const sign = this.readInt8() ? -1 : 1; // 'isNegative' flag byte
  313. let d = 0;
  314. let H = 0;
  315. let M = 0;
  316. let S = 0;
  317. let ms = 0;
  318. if (length > 6) {
  319. d = this.readInt32();
  320. H = this.readInt8();
  321. M = this.readInt8();
  322. S = this.readInt8();
  323. }
  324. if (length > 10) {
  325. ms = this.readInt32();
  326. }
  327. if (convertTtoMs) {
  328. H += d * 24;
  329. M += H * 60;
  330. S += M * 60;
  331. ms += S * 1000;
  332. ms *= sign;
  333. return ms;
  334. }
  335. // Format follows mySQL TIME format ([-][h]hh:mm:ss[.u[u[u[u[u[u]]]]]])
  336. // For positive times below 24 hours, this makes it equal to ISO 8601 times
  337. return (
  338. (sign === -1 ? '-' : '') +
  339. [leftPad(2, d * 24 + H), leftPad(2, M), leftPad(2, S)].join(':') +
  340. (ms ? `.${ms}`.replace(/0+$/, '') : '')
  341. );
  342. }
  343. readLengthCodedString(encoding) {
  344. const len = this.readLengthCodedNumber();
  345. // TODO: check manually first byte here to avoid polymorphic return type?
  346. if (len === null) {
  347. return null;
  348. }
  349. this.offset += len;
  350. // TODO: Use characterSetCode to get proper encoding
  351. // https://github.com/sidorares/node-mysql2/pull/374
  352. return StringParser.decode(
  353. this.buffer,
  354. encoding,
  355. this.offset - len,
  356. this.offset
  357. );
  358. }
  359. readLengthCodedBuffer() {
  360. const len = this.readLengthCodedNumber();
  361. if (len === null) {
  362. return null;
  363. }
  364. return this.readBuffer(len);
  365. }
  366. readNullTerminatedString(encoding) {
  367. const start = this.offset;
  368. let end = this.offset;
  369. while (this.buffer[end]) {
  370. end = end + 1; // TODO: handle OOB check
  371. }
  372. this.offset = end + 1;
  373. return StringParser.decode(this.buffer, encoding, start, end);
  374. }
  375. // TODO reuse?
  376. readString(len, encoding) {
  377. if (typeof len === 'string' && typeof encoding === 'undefined') {
  378. encoding = len;
  379. len = undefined;
  380. }
  381. if (typeof len === 'undefined') {
  382. len = this.end - this.offset;
  383. }
  384. this.offset += len;
  385. return StringParser.decode(
  386. this.buffer,
  387. encoding,
  388. this.offset - len,
  389. this.offset
  390. );
  391. }
  392. parseInt(len, supportBigNumbers) {
  393. if (len === null) {
  394. return null;
  395. }
  396. if (len >= 14 && !supportBigNumbers) {
  397. const s = this.buffer.toString('ascii', this.offset, this.offset + len);
  398. this.offset += len;
  399. return Number(s);
  400. }
  401. let result = 0;
  402. const start = this.offset;
  403. const end = this.offset + len;
  404. let sign = 1;
  405. if (len === 0) {
  406. return 0; // TODO: assert? exception?
  407. }
  408. if (this.buffer[this.offset] === minus) {
  409. this.offset++;
  410. sign = -1;
  411. }
  412. // max precise int is 9007199254740992
  413. let str;
  414. const numDigits = end - this.offset;
  415. if (supportBigNumbers) {
  416. if (numDigits >= 15) {
  417. str = this.readString(end - this.offset, 'binary');
  418. result = parseInt(str, 10);
  419. if (result.toString() === str) {
  420. return sign * result;
  421. }
  422. return sign === -1 ? `-${str}` : str;
  423. }
  424. if (numDigits > 16) {
  425. str = this.readString(end - this.offset);
  426. return sign === -1 ? `-${str}` : str;
  427. }
  428. }
  429. if (this.buffer[this.offset] === plus) {
  430. this.offset++; // just ignore
  431. }
  432. while (this.offset < end) {
  433. result *= 10;
  434. result += this.buffer[this.offset] - 48;
  435. this.offset++;
  436. }
  437. const num = result * sign;
  438. if (!supportBigNumbers) {
  439. return num;
  440. }
  441. str = this.buffer.toString('ascii', start, end);
  442. if (num.toString() === str) {
  443. return num;
  444. }
  445. return str;
  446. }
  447. // note that if value of inputNumberAsString is bigger than MAX_SAFE_INTEGER
  448. // ( or smaller than MIN_SAFE_INTEGER ) the parseIntNoBigCheck result might be
  449. // different from what you would get from Number(inputNumberAsString)
  450. // String(parseIntNoBigCheck) <> String(Number(inputNumberAsString)) <> inputNumberAsString
  451. parseIntNoBigCheck(len) {
  452. if (len === null) {
  453. return null;
  454. }
  455. let result = 0;
  456. const end = this.offset + len;
  457. let sign = 1;
  458. if (len === 0) {
  459. return 0; // TODO: assert? exception?
  460. }
  461. if (this.buffer[this.offset] === minus) {
  462. this.offset++;
  463. sign = -1;
  464. }
  465. if (this.buffer[this.offset] === plus) {
  466. this.offset++; // just ignore
  467. }
  468. while (this.offset < end) {
  469. result *= 10;
  470. result += this.buffer[this.offset] - 48;
  471. this.offset++;
  472. }
  473. return result * sign;
  474. }
  475. // copy-paste from https://github.com/mysqljs/mysql/blob/master/lib/protocol/Parser.js
  476. parseGeometryValue() {
  477. const buffer = this.readLengthCodedBuffer();
  478. let offset = 4;
  479. if (buffer === null || !buffer.length) {
  480. return null;
  481. }
  482. function parseGeometry() {
  483. let x, y, i, j, numPoints, line;
  484. let result = null;
  485. const byteOrder = buffer.readUInt8(offset);
  486. offset += 1;
  487. const wkbType = byteOrder
  488. ? buffer.readUInt32LE(offset)
  489. : buffer.readUInt32BE(offset);
  490. offset += 4;
  491. switch (wkbType) {
  492. case 1: // WKBPoint
  493. x = byteOrder
  494. ? buffer.readDoubleLE(offset)
  495. : buffer.readDoubleBE(offset);
  496. offset += 8;
  497. y = byteOrder
  498. ? buffer.readDoubleLE(offset)
  499. : buffer.readDoubleBE(offset);
  500. offset += 8;
  501. result = { x: x, y: y };
  502. break;
  503. case 2: // WKBLineString
  504. numPoints = byteOrder
  505. ? buffer.readUInt32LE(offset)
  506. : buffer.readUInt32BE(offset);
  507. offset += 4;
  508. result = [];
  509. for (i = numPoints; i > 0; i--) {
  510. x = byteOrder
  511. ? buffer.readDoubleLE(offset)
  512. : buffer.readDoubleBE(offset);
  513. offset += 8;
  514. y = byteOrder
  515. ? buffer.readDoubleLE(offset)
  516. : buffer.readDoubleBE(offset);
  517. offset += 8;
  518. result.push({ x: x, y: y });
  519. }
  520. break;
  521. case 3: // WKBPolygon
  522. // eslint-disable-next-line no-case-declarations
  523. const numRings = byteOrder
  524. ? buffer.readUInt32LE(offset)
  525. : buffer.readUInt32BE(offset);
  526. offset += 4;
  527. result = [];
  528. for (i = numRings; i > 0; i--) {
  529. numPoints = byteOrder
  530. ? buffer.readUInt32LE(offset)
  531. : buffer.readUInt32BE(offset);
  532. offset += 4;
  533. line = [];
  534. for (j = numPoints; j > 0; j--) {
  535. x = byteOrder
  536. ? buffer.readDoubleLE(offset)
  537. : buffer.readDoubleBE(offset);
  538. offset += 8;
  539. y = byteOrder
  540. ? buffer.readDoubleLE(offset)
  541. : buffer.readDoubleBE(offset);
  542. offset += 8;
  543. line.push({ x: x, y: y });
  544. }
  545. result.push(line);
  546. }
  547. break;
  548. case 4: // WKBMultiPoint
  549. case 5: // WKBMultiLineString
  550. case 6: // WKBMultiPolygon
  551. case 7: // WKBGeometryCollection
  552. // eslint-disable-next-line no-case-declarations
  553. const num = byteOrder
  554. ? buffer.readUInt32LE(offset)
  555. : buffer.readUInt32BE(offset);
  556. offset += 4;
  557. result = [];
  558. for (i = num; i > 0; i--) {
  559. result.push(parseGeometry());
  560. }
  561. break;
  562. }
  563. return result;
  564. }
  565. return parseGeometry();
  566. }
  567. parseVector() {
  568. const bufLen = this.readLengthCodedNumber();
  569. const vectorEnd = this.offset + bufLen;
  570. const result = [];
  571. while (this.offset < vectorEnd && this.offset < this.end) {
  572. result.push(this.readFloat());
  573. }
  574. return result;
  575. }
  576. parseDate(timezone) {
  577. const strLen = this.readLengthCodedNumber();
  578. if (strLen === null) {
  579. return null;
  580. }
  581. if (strLen !== 10) {
  582. // we expect only YYYY-MM-DD here.
  583. // if for some reason it's not the case return invalid date
  584. return new Date(NaN);
  585. }
  586. const y = this.parseInt(4);
  587. this.offset++; // -
  588. const m = this.parseInt(2);
  589. this.offset++; // -
  590. const d = this.parseInt(2);
  591. if (!timezone || timezone === 'local') {
  592. return new Date(y, m - 1, d);
  593. }
  594. if (timezone === 'Z') {
  595. return new Date(Date.UTC(y, m - 1, d));
  596. }
  597. return new Date(
  598. `${leftPad(4, y)}-${leftPad(2, m)}-${leftPad(2, d)}T00:00:00${timezone}`
  599. );
  600. }
  601. parseDateTime(timezone) {
  602. const str = this.readLengthCodedString('binary');
  603. if (str === null) {
  604. return null;
  605. }
  606. if (!timezone || timezone === 'local') {
  607. return new Date(str);
  608. }
  609. return new Date(`${str}${timezone}`);
  610. }
  611. parseFloat(len) {
  612. if (len === null) {
  613. return null;
  614. }
  615. let result = 0;
  616. const end = this.offset + len;
  617. let factor = 1;
  618. let pastDot = false;
  619. let charCode = 0;
  620. if (len === 0) {
  621. return 0; // TODO: assert? exception?
  622. }
  623. if (this.buffer[this.offset] === minus) {
  624. this.offset++;
  625. factor = -1;
  626. }
  627. if (this.buffer[this.offset] === plus) {
  628. this.offset++; // just ignore
  629. }
  630. while (this.offset < end) {
  631. charCode = this.buffer[this.offset];
  632. if (charCode === dot) {
  633. pastDot = true;
  634. this.offset++;
  635. } else if (charCode === exponent || charCode === exponentCapital) {
  636. this.offset++;
  637. const exponentValue = this.parseInt(end - this.offset);
  638. return (result / factor) * Math.pow(10, exponentValue);
  639. } else {
  640. result *= 10;
  641. result += this.buffer[this.offset] - 48;
  642. this.offset++;
  643. if (pastDot) {
  644. factor = factor * 10;
  645. }
  646. }
  647. }
  648. return result / factor;
  649. }
  650. parseLengthCodedIntNoBigCheck() {
  651. return this.parseIntNoBigCheck(this.readLengthCodedNumber());
  652. }
  653. parseLengthCodedInt(supportBigNumbers) {
  654. return this.parseInt(this.readLengthCodedNumber(), supportBigNumbers);
  655. }
  656. parseLengthCodedIntString() {
  657. return this.readLengthCodedString('binary');
  658. }
  659. parseLengthCodedFloat() {
  660. return this.parseFloat(this.readLengthCodedNumber());
  661. }
  662. peekByte() {
  663. return this.buffer[this.offset];
  664. }
  665. // OxFE is often used as "Alt" flag - not ok, not error.
  666. // For example, it's first byte of AuthSwitchRequest
  667. isAlt() {
  668. return this.peekByte() === 0xfe;
  669. }
  670. isError() {
  671. return this.peekByte() === 0xff;
  672. }
  673. asError(encoding) {
  674. this.reset();
  675. this.readInt8(); // fieldCount
  676. const errorCode = this.readInt16();
  677. let sqlState = '';
  678. if (this.buffer[this.offset] === 0x23) {
  679. this.skip(1);
  680. sqlState = this.readBuffer(5).toString();
  681. }
  682. const message = this.readString(undefined, encoding);
  683. const err = new Error(message);
  684. err.code = ErrorCodeToName[errorCode];
  685. err.errno = errorCode;
  686. err.sqlState = sqlState;
  687. err.sqlMessage = message;
  688. return err;
  689. }
  690. writeInt32(n) {
  691. this.buffer.writeUInt32LE(n, this.offset);
  692. this.offset += 4;
  693. }
  694. writeInt24(n) {
  695. this.writeInt8(n & 0xff);
  696. this.writeInt16(n >> 8);
  697. }
  698. writeInt16(n) {
  699. this.buffer.writeUInt16LE(n, this.offset);
  700. this.offset += 2;
  701. }
  702. writeInt8(n) {
  703. this.buffer.writeUInt8(n, this.offset);
  704. this.offset++;
  705. }
  706. writeDouble(n) {
  707. this.buffer.writeDoubleLE(n, this.offset);
  708. this.offset += 8;
  709. }
  710. writeBuffer(b) {
  711. b.copy(this.buffer, this.offset);
  712. this.offset += b.length;
  713. }
  714. writeNull() {
  715. this.buffer[this.offset] = 0xfb;
  716. this.offset++;
  717. }
  718. // TODO: refactor following three?
  719. writeNullTerminatedString(s, encoding) {
  720. const buf = StringParser.encode(s, encoding);
  721. this.buffer.length && buf.copy(this.buffer, this.offset);
  722. this.offset += buf.length;
  723. this.writeInt8(0);
  724. }
  725. writeString(s, encoding) {
  726. if (s === null) {
  727. this.writeInt8(0xfb);
  728. return;
  729. }
  730. if (s.length === 0) {
  731. return;
  732. }
  733. // const bytes = Buffer.byteLength(s, 'utf8');
  734. // this.buffer.write(s, this.offset, bytes, 'utf8');
  735. // this.offset += bytes;
  736. const buf = StringParser.encode(s, encoding);
  737. this.buffer.length && buf.copy(this.buffer, this.offset);
  738. this.offset += buf.length;
  739. }
  740. writeLengthCodedString(s, encoding) {
  741. const buf = StringParser.encode(s, encoding);
  742. this.writeLengthCodedNumber(buf.length);
  743. this.buffer.length && buf.copy(this.buffer, this.offset);
  744. this.offset += buf.length;
  745. }
  746. writeLengthCodedBuffer(b) {
  747. this.writeLengthCodedNumber(b.length);
  748. b.copy(this.buffer, this.offset);
  749. this.offset += b.length;
  750. }
  751. writeLengthCodedNumber(n) {
  752. if (n < 0xfb) {
  753. return this.writeInt8(n);
  754. }
  755. if (n < 0xffff) {
  756. this.writeInt8(0xfc);
  757. return this.writeInt16(n);
  758. }
  759. if (n < 0xffffff) {
  760. this.writeInt8(0xfd);
  761. return this.writeInt24(n);
  762. }
  763. if (n === null) {
  764. return this.writeInt8(0xfb);
  765. }
  766. // TODO: check that n is out of int precision
  767. this.writeInt8(0xfe);
  768. this.buffer.writeUInt32LE(n, this.offset);
  769. this.offset += 4;
  770. this.buffer.writeUInt32LE(n >> 32, this.offset);
  771. this.offset += 4;
  772. return this.offset;
  773. }
  774. writeDate(d, timezone) {
  775. this.buffer.writeUInt8(11, this.offset);
  776. if (!timezone || timezone === 'local') {
  777. this.buffer.writeUInt16LE(d.getFullYear(), this.offset + 1);
  778. this.buffer.writeUInt8(d.getMonth() + 1, this.offset + 3);
  779. this.buffer.writeUInt8(d.getDate(), this.offset + 4);
  780. this.buffer.writeUInt8(d.getHours(), this.offset + 5);
  781. this.buffer.writeUInt8(d.getMinutes(), this.offset + 6);
  782. this.buffer.writeUInt8(d.getSeconds(), this.offset + 7);
  783. this.buffer.writeUInt32LE(d.getMilliseconds() * 1000, this.offset + 8);
  784. } else {
  785. if (timezone !== 'Z') {
  786. const offset =
  787. (timezone[0] === '-' ? -1 : 1) *
  788. (parseInt(timezone.substring(1, 3), 10) * 60 +
  789. parseInt(timezone.substring(4), 10));
  790. if (offset !== 0) {
  791. d = new Date(d.getTime() + 60000 * offset);
  792. }
  793. }
  794. this.buffer.writeUInt16LE(d.getUTCFullYear(), this.offset + 1);
  795. this.buffer.writeUInt8(d.getUTCMonth() + 1, this.offset + 3);
  796. this.buffer.writeUInt8(d.getUTCDate(), this.offset + 4);
  797. this.buffer.writeUInt8(d.getUTCHours(), this.offset + 5);
  798. this.buffer.writeUInt8(d.getUTCMinutes(), this.offset + 6);
  799. this.buffer.writeUInt8(d.getUTCSeconds(), this.offset + 7);
  800. this.buffer.writeUInt32LE(d.getUTCMilliseconds() * 1000, this.offset + 8);
  801. }
  802. this.offset += 12;
  803. }
  804. writeHeader(sequenceId) {
  805. const offset = this.offset;
  806. this.offset = 0;
  807. this.writeInt24(this.buffer.length - 4);
  808. this.writeInt8(sequenceId);
  809. this.offset = offset;
  810. }
  811. clone() {
  812. return new Packet(this.sequenceId, this.buffer, this.start, this.end);
  813. }
  814. type() {
  815. if (this.isEOF()) {
  816. return 'EOF';
  817. }
  818. if (this.isError()) {
  819. return 'Error';
  820. }
  821. if (this.buffer[this.offset] === 0) {
  822. return 'maybeOK'; // could be other packet types as well
  823. }
  824. return '';
  825. }
  826. static lengthCodedNumberLength(n) {
  827. if (n < 0xfb) {
  828. return 1;
  829. }
  830. if (n < 0xffff) {
  831. return 3;
  832. }
  833. if (n < 0xffffff) {
  834. return 5;
  835. }
  836. return 9;
  837. }
  838. static lengthCodedStringLength(str, encoding) {
  839. const buf = StringParser.encode(str, encoding);
  840. const slen = buf.length;
  841. return Packet.lengthCodedNumberLength(slen) + slen;
  842. }
  843. static MockBuffer() {
  844. const noop = function () { };
  845. const res = Buffer.alloc(0);
  846. for (const op in NativeBuffer.prototype) {
  847. if (typeof res[op] === 'function') {
  848. res[op] = noop;
  849. }
  850. }
  851. return res;
  852. }
  853. }
  854. module.exports = Packet;