packet.js 25 KB

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