Backend half

This commit is contained in:
2025-07-11 19:56:28 +02:00
parent fa868e7c1d
commit 8600fa7c1d
19426 changed files with 3750448 additions and 8108 deletions
+677
View File
@@ -0,0 +1,677 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2025 MariaDB Corporation Ab
'use strict';
const Parser = require('./parser');
const Errors = require('../misc/errors');
const BinaryEncoder = require('./encoder/binary-encoder');
const FieldType = require('../const/field-type');
const OkPacket = require('./class/ok-packet');
const Capabilities = require('../const/capabilities');
const ServerStatus = require('../const/server-status');
// GeoJSON types supported by MariaDB
const GEOJSON_TYPES = [
'Point',
'LineString',
'Polygon',
'MultiPoint',
'MultiLineString',
'MultiPolygon',
'GeometryCollection'
];
/**
* Protocol COM_STMT_BULK_EXECUTE implementation
* Provides efficient batch operations for MariaDB servers >= 10.2.7
*
* @see https://mariadb.com/kb/en/library/com_stmt_bulk_execute/
*/
class BatchBulk extends Parser {
constructor(resolve, reject, connOpts, prepare, cmdParam) {
super(resolve, reject, connOpts, cmdParam);
this.cmdOpts = cmdParam.opts;
this.binary = true;
this.prepare = prepare;
this.canSkipMeta = true;
this.bulkPacketNo = 0;
this.sending = false;
this.firstError = null;
}
/**
* Initiates the batch operation
*
* @param {Object} out - Output writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection information
*/
start(out, opts, info) {
this.info = info;
this.values = this.initialValues;
// Batch operations don't support timeouts
if (this.cmdOpts && this.cmdOpts.timeout) {
return this.handleTimeoutError(info);
}
this.onPacketReceive = this.readResponsePacket;
// Process named placeholders if needed
if (this.opts.namedPlaceholders && this.prepare._placeHolderIndex) {
this.processNamedPlaceholders();
}
// Validate parameters before proceeding
if (!this.validateParameters(info)) return;
// Send the bulk execute command
this.sendComStmtBulkExecute(out, opts, info);
}
/**
* Handle timeout error case
* @param {Object} info - Connection information
* @private
*/
handleTimeoutError(info) {
this.bulkPacketNo = 1;
this.sending = false;
return this.sendCancelled('Cannot use timeout for Batch statement', Errors.ER_TIMEOUT_NOT_SUPPORTED);
}
/**
* Process named placeholders to positional parameters
* @private
*/
processNamedPlaceholders() {
this.values = [];
if (!this.initialValues) return;
const placeHolderIndex = this.prepare._placeHolderIndex;
const paramCount = this.prepare.parameterCount;
for (let r = 0; r < this.initialValues.length; r++) {
const val = this.initialValues[r];
const newRow = new Array(paramCount);
for (let i = 0; i < placeHolderIndex.length; i++) {
newRow[i] = val[placeHolderIndex[i]];
}
this.values[r] = newRow;
}
}
/**
* Determine parameter header types based on value types
*
* @param {Array} value - Parameter values
* @param {Number} parameterCount - Number of parameters
* @returns {Array} Array of parameter header types
*/
parameterHeaderFromValue(value, parameterCount) {
const parameterHeaderType = new Array(parameterCount);
for (let i = 0; i < parameterCount; i++) {
const val = value[i];
if (val == null) {
parameterHeaderType[i] = FieldType.VAR_STRING;
continue;
}
const type = typeof val;
switch (type) {
case 'boolean':
parameterHeaderType[i] = FieldType.TINY;
break;
case 'bigint':
parameterHeaderType[i] = val >= 2n ** 63n ? FieldType.NEWDECIMAL : FieldType.BIGINT;
break;
case 'number':
if (Number.isInteger(val) && val >= -2147483648 && val < 2147483647) {
parameterHeaderType[i] = FieldType.INT;
} else {
parameterHeaderType[i] = FieldType.DOUBLE;
}
break;
case 'string':
parameterHeaderType[i] = FieldType.VAR_STRING;
break;
case 'object':
parameterHeaderType[i] = this.getObjectFieldType(val);
break;
default:
parameterHeaderType[i] = FieldType.BLOB;
}
}
return parameterHeaderType;
}
/**
* Determine field type for object values
*
* @param {Object} val - Object value
* @returns {Number} Field type constant
* @private
*/
getObjectFieldType(val) {
if (Object.prototype.toString.call(val) === '[object Date]') {
return FieldType.DATETIME;
}
if (Buffer.isBuffer(val)) {
return FieldType.BLOB;
}
if (typeof val.toSqlString === 'function') {
return FieldType.VAR_STRING;
}
if (val.type != null && GEOJSON_TYPES.includes(val.type)) {
return FieldType.BLOB;
}
return FieldType.VAR_STRING;
}
/**
* Check if current value has same header as set in initial BULK header
*
* @param {Array} parameterHeaderType - Current header types
* @param {Array} value - Current values
* @param {Number} parameterCount - Number of parameters
* @returns {Boolean} True if headers are identical
*/
checkSameHeader(parameterHeaderType, value, parameterCount) {
for (let i = 0; i < parameterCount; i++) {
const val = value[i];
if (val == null) continue;
const type = typeof val;
switch (type) {
case 'boolean':
if (parameterHeaderType[i] !== FieldType.TINY) return false;
break;
case 'bigint':
if (val >= 2n ** 63n) {
if (parameterHeaderType[i] !== FieldType.VAR_STRING) return false;
} else {
if (parameterHeaderType[i] !== FieldType.BIGINT) return false;
}
break;
case 'number':
if (Number.isInteger(val) && val >= -2147483648 && val < 2147483647) {
if (parameterHeaderType[i] !== FieldType.INT) return false;
} else {
if (parameterHeaderType[i] !== FieldType.DOUBLE) return false;
}
break;
case 'string':
if (parameterHeaderType[i] !== FieldType.VAR_STRING) return false;
break;
case 'object':
if (!this.checkObjectHeaderType(val, parameterHeaderType[i])) {
return false;
}
break;
default:
if (parameterHeaderType[i] !== FieldType.BLOB) return false;
}
}
return true;
}
/**
* Check if object value matches expected header type
*
* @param {Object} val - Object value
* @param {Number} headerType - Expected header type
* @returns {Boolean} True if types match
* @private
*/
checkObjectHeaderType(val, headerType) {
if (Object.prototype.toString.call(val) === '[object Date]') {
return headerType === FieldType.TIMESTAMP;
}
if (Buffer.isBuffer(val)) {
return headerType === FieldType.BLOB;
}
if (typeof val.toSqlString === 'function') {
return headerType === FieldType.VAR_STRING;
}
if (val.type != null && GEOJSON_TYPES.includes(val.type)) {
return headerType === FieldType.BLOB;
}
return headerType === FieldType.VAR_STRING;
}
/**
* Send a COM_STMT_BULK_EXECUTE command
*
* @param {Object} out - Output packet writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection information
*/
sendComStmtBulkExecute(out, opts, info) {
if (opts.logger.query) {
opts.logger.query(`BULK: (${this.prepare.id}) sql: ${opts.logParam ? this.displaySql() : this.sql}`);
}
const parameterCount = this.prepare.parameterCount;
this.rowIdx = 0;
this.vals = this.values[this.rowIdx++];
let parameterHeaderType = this.parameterHeaderFromValue(this.vals, parameterCount);
let lastCmdData = null;
this.bulkPacketNo = 0;
this.sending = true;
// Main processing loop for batching parameters
main_loop: while (true) {
this.bulkPacketNo++;
out.startPacket(this);
out.writeInt8(0xfa); // COM_STMT_BULK_EXECUTE
out.writeInt32(this.prepare.id); // Statement id
// Set flags: SEND_TYPES_TO_SERVER + SEND_UNIT_RESULTS if possible
this.useUnitResult = (info.clientCapabilities & Capabilities.BULK_UNIT_RESULTS) > 0;
out.writeInt16(this.useUnitResult ? 192 : 128);
// Write parameter header types
for (let i = 0; i < parameterCount; i++) {
out.writeInt16(parameterHeaderType[i]);
}
// Handle leftover data from previous packet
if (lastCmdData != null) {
const err = out.checkMaxAllowedLength(lastCmdData.length, info);
if (err) {
this.sending = false;
this.throwError(err, info);
return;
}
out.writeBuffer(lastCmdData, 0, lastCmdData.length);
out.mark();
lastCmdData = null;
if (this.rowIdx >= this.values.length) {
break;
}
this.vals = this.values[this.rowIdx++];
}
parameter_loop: while (true) {
// Write each parameter value
for (let i = 0; i < parameterCount; i++) {
const param = this.vals[i];
if (param != null) {
// Special handling for GeoJSON
if (param.type != null && GEOJSON_TYPES.includes(param.type)) {
this.writeGeoJSONParam(out, param, info);
} else {
out.writeInt8(0x00); // value follows
BinaryEncoder.writeParam(out, param, this.opts, info);
}
} else {
out.writeInt8(0x01); // value is null
}
}
// Buffer management for packet boundaries
if (out.isMarked() && (out.hasDataAfterMark() || out.bufIsAfterMaxPacketLength())) {
// Packet length was ok at last mark, but won't be with new data
out.flushBufferStopAtMark();
out.mark();
lastCmdData = out.resetMark();
break;
}
out.mark();
if (out.hasDataAfterMark()) {
// Flush has been done
lastCmdData = out.resetMark();
break;
}
if (this.rowIdx >= this.values.length) {
break main_loop;
}
this.vals = this.values[this.rowIdx++];
// Check if parameter types have changed
if (!this.checkSameHeader(parameterHeaderType, this.vals, parameterCount)) {
out.flush();
// Reset header type for new packet
parameterHeaderType = this.parameterHeaderFromValue(this.vals, parameterCount);
break parameter_loop;
}
}
}
out.flush();
this.sending = false;
this.emit('send_end');
}
/**
* Write GeoJSON parameter to output buffer
*
* @param {Object} out - Output buffer
* @param {Object} param - GeoJSON parameter
* @param {Object} info - connection info data
* @private
*/
writeGeoJSONParam(out, param, info) {
const geoBuff = BinaryEncoder.getBufferFromGeometryValue(param);
if (geoBuff == null) {
out.writeInt8(0x01); // value is null
} else {
out.writeInt8(0x00); // value follows
const paramBuff = Buffer.concat([
Buffer.from([0, 0, 0, 0]), // SRID
geoBuff // WKB
]);
BinaryEncoder.writeParam(out, paramBuff, this.opts, info);
}
}
/**
* Format SQL with parameters for logging
*
* @returns {String} Formatted SQL string
*/
displaySql() {
if (this.sql.length > this.opts.debugLen) {
return this.sql.substring(0, this.opts.debugLen) + '...';
}
let sqlMsg = this.sql + ' - parameters:[';
for (let i = 0; i < this.initialValues.length; i++) {
if (i !== 0) sqlMsg += ',';
let param = this.initialValues[i];
sqlMsg = Parser.logParameters(this.opts, sqlMsg, param);
if (sqlMsg.length > this.opts.debugLen) {
return sqlMsg.substring(0, this.opts.debugLen) + '...';
}
}
sqlMsg += ']';
return sqlMsg;
}
/**
* Process successful query execution
*
* @param {Object} initVal - Query result
*/
success(initVal) {
this.bulkPacketNo--;
if (!this.sending && this.bulkPacketNo === 0) {
this.packet = null;
if (this.firstError) {
this.resolve = null;
this.onPacketReceive = null;
this._columns = null;
this._rows = null;
process.nextTick(this.reject, this.firstError);
this.reject = null;
this.emit('end', this.firstError);
} else {
this.processResults();
}
return;
}
if (!this.firstError) {
this._responseIndex++;
this.onPacketReceive = this.readResponsePacket;
}
}
/**
* Process successful results based on result type
* @private
*/
processResults() {
if (this._rows[0] && this._rows[0][0] && this._rows[0][0]['Affected_rows'] !== undefined) {
this.processUnitResults();
} else if (
this._rows[0].affectedRows !== undefined &&
!(this.opts.fullResult === undefined || this.opts.fullResult === true)
) {
this.processAggregatedResults();
} else {
this.processRowResults();
}
this._columns = null;
this._rows = null;
}
/**
* Process unit results (for bulk operations with unit results)
* @private
*/
processUnitResults() {
if (this.opts.fullResult === undefined || this.opts.fullResult === true) {
const rs = [];
this._rows.forEach((row) => {
row.forEach((unitRow) => {
rs.push(new OkPacket(Number(unitRow['Affected_rows']), BigInt(unitRow['Id']), 0));
});
});
this.successEnd(this.opts.metaAsArray ? [rs, []] : rs);
} else {
let totalAffectedRows = 0;
this._rows.forEach((row) => {
row.forEach((unitRow) => {
totalAffectedRows += Number(unitRow['Affected_rows']);
});
});
const rs = new OkPacket(totalAffectedRows, BigInt(this._rows[0][0]['Id']), 0);
this.successEnd(this.opts.metaAsArray ? [rs, []] : rs);
}
}
/**
* Process aggregated results (for non-fullResult mode)
* @private
*/
processAggregatedResults() {
let totalAffectedRows = 0;
this._rows.forEach((row) => {
totalAffectedRows += row.affectedRows;
});
const rs = new OkPacket(totalAffectedRows, this._rows[0].insertId, this._rows[this._rows.length - 1].warningStatus);
this.successEnd(this.opts.metaAsArray ? [rs, []] : rs);
}
/**
* Process row results (for SELECT queries)
* @private
*/
processRowResults() {
if (this._rows.length === 1) {
this.successEnd(this.opts.metaAsArray ? [this._rows[0], this._columns] : this._rows[0]);
return;
}
if (this.opts.metaAsArray) {
if (this.useUnitResult) {
const rs = [];
this._rows.forEach((row, i) => {
if (i % 2 === 0) rs.push(...row);
});
this.successEnd([rs, this.prepare.columns]);
} else {
const rs = [];
this._rows.forEach((row) => {
rs.push(...row);
});
this.successEnd([rs, this._columns]);
}
} else {
if (this.useUnitResult) {
const rs = [];
this._rows.forEach((row, i) => {
if (i % 2 === 0) rs.push(...row);
});
Object.defineProperty(rs, 'meta', {
value: this._columns,
writable: true,
enumerable: this.opts.metaEnumerable
});
this.successEnd(rs);
} else {
if (this._rows.length === 1) {
this.successEnd(this._rows[0]);
} else {
const rs = [];
if (Array.isArray(this._rows[0])) {
this._rows.forEach((row) => {
rs.push(...row);
});
} else rs.push(...this._rows);
Object.defineProperty(rs, 'meta', {
value: this._columns,
writable: true,
enumerable: this.opts.metaEnumerable
});
this.successEnd(rs);
}
}
}
}
/**
* Handle OK packet success
*
* @param {Object} okPacket - OK packet
* @param {Object} info - Connection information
*/
okPacketSuccess(okPacket, info) {
this._rows.push(okPacket);
if (info.status & ServerStatus.MORE_RESULTS_EXISTS) {
this._responseIndex++;
return (this.onPacketReceive = this.readResponsePacket);
}
if (this.opts.metaAsArray) {
if (!this._meta) {
this._meta = new Array(this._responseIndex);
}
this._meta[this._responseIndex] = null;
this.success([this._rows, this._meta]);
} else {
this.success(this._rows);
}
}
/**
* Handle errors during query execution
*
* @param {Error} err - Error object
* @param {Object} info - Connection information
*/
throwError(err, info) {
this.bulkPacketNo--;
if (!this.firstError) {
if (err.fatal) {
this.bulkPacketNo = 0;
}
if (this.cmdParam.stack) {
err = Errors.createError(
err.message,
err.errno,
info,
err.sqlState,
this.sql,
err.fatal,
this.cmdParam.stack,
false
);
}
this.firstError = err;
}
if (!this.sending && this.bulkPacketNo === 0) {
this.resolve = null;
this.emit('send_end');
process.nextTick(this.reject, this.firstError);
this.reject = null;
this.onPacketReceive = null;
this.emit('end', this.firstError);
} else {
this.onPacketReceive = this.readResponsePacket;
}
}
/**
* Validate that parameters exist and are defined
*
* @param {Object} info - Connection information
* @returns {Boolean} Returns false if any error occurs
*/
validateParameters(info) {
const nbParameter = this.prepare.parameterCount;
for (let r = 0; r < this.values.length; r++) {
if (!Array.isArray(this.values[r])) {
this.values[r] = [this.values[r]];
}
if (this.values[r].length < nbParameter) {
this.emit('send_end');
this.throwNewError(
`Expect ${nbParameter} parameters, but at index ${r}, parameters only contains ${this.values[r].length}\n ${
this.opts.logParam ? this.displaySql() : this.sql
}`,
false,
info,
'HY000',
Errors.ER_PARAMETER_UNDEFINED
);
return false;
}
}
return true;
}
}
module.exports = BatchBulk;
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
// noinspection JSBitwiseOperatorUsage
'use strict';
const Iconv = require('iconv-lite');
const Capabilities = require('../const/capabilities');
const Ed25519PasswordAuth = require('./handshake/auth/ed25519-password-auth');
const NativePasswordAuth = require('./handshake/auth/native-password-auth');
const Collations = require('../const/collations');
const Authentication = require('./handshake/authentication');
/**
* send a COM_CHANGE_USER: resets the connection and re-authenticates with the given credentials
* see https://mariadb.com/kb/en/library/com_change_user/
*/
class ChangeUser extends Authentication {
constructor(cmdParam, connOpts, resolve, reject, getSocket) {
super(cmdParam, resolve, reject, () => {}, getSocket);
this.configAssign(connOpts, cmdParam.opts);
}
start(out, opts, info) {
if (opts.logger.query) opts.logger.query(`CHANGE USER to '${this.opts.user || ''}'`);
let authToken;
const pwd = Array.isArray(this.opts.password) ? this.opts.password[0] : this.opts.password;
switch (info.defaultPluginName) {
case 'mysql_native_password':
case '':
authToken = NativePasswordAuth.encryptSha1Password(pwd, info.seed);
break;
case 'client_ed25519':
authToken = Ed25519PasswordAuth.encryptPassword(pwd, info.seed);
break;
default:
authToken = Buffer.alloc(0);
break;
}
out.startPacket(this);
out.writeInt8(0x11);
out.writeString(this.opts.user || '');
out.writeInt8(0);
if (info.serverCapabilities & Capabilities.SECURE_CONNECTION) {
out.writeInt8(authToken.length);
out.writeBuffer(authToken, 0, authToken.length);
} else {
out.writeBuffer(authToken, 0, authToken.length);
out.writeInt8(0);
}
if (info.clientCapabilities & Capabilities.CONNECT_WITH_DB) {
out.writeString(this.opts.database);
out.writeInt8(0);
info.database = this.opts.database;
}
// handle default collation.
if (this.opts.collation) {
// collation has been set using charset.
// If server use same charset, use server collation.
if (!this.opts.charset || info.collation.charset !== this.opts.collation.charset) {
info.collation = this.opts.collation;
}
} else {
// if not utf8mb4 and no configuration, force to use UTF8MB4_UNICODE_CI
if (info.collation.charset !== 'utf8' || info.collation.maxLength === 3) {
info.collation = Collations.fromIndex(224);
}
}
out.writeInt16(info.collation.index);
if (info.clientCapabilities & Capabilities.PLUGIN_AUTH) {
out.writeString(info.defaultPluginName);
out.writeInt8(0);
}
if (info.clientCapabilities & Capabilities.CONNECT_ATTRS) {
out.writeInt8(0xfc);
let initPos = out.pos; //save position, assuming connection attributes length will be less than 2 bytes length
out.writeInt16(0);
const encoding = info.collation.charset;
writeAttribute(out, '_client_name', encoding);
writeAttribute(out, 'MariaDB connector/Node', encoding);
let packageJson = require('../../package.json');
writeAttribute(out, '_client_version', encoding);
writeAttribute(out, packageJson.version, encoding);
writeAttribute(out, '_node_version', encoding);
writeAttribute(out, process.versions.node, encoding);
if (opts.connectAttributes !== true) {
let attrNames = Object.keys(this.opts.connectAttributes);
for (let k = 0; k < attrNames.length; ++k) {
writeAttribute(out, attrNames[k], encoding);
writeAttribute(out, this.opts.connectAttributes[attrNames[k]], encoding);
}
}
//write end size
out.writeInt16AtPos(initPos);
}
out.flush();
this.plugin.onPacketReceive = this.handshakeResult.bind(this);
}
/**
* Assign global configuration option used by result-set to current query option.
* a little faster than Object.assign() since doest copy all information
*
* @param connOpts connection global configuration
* @param cmdOpts current options
*/
configAssign(connOpts, cmdOpts) {
if (!cmdOpts) {
this.opts = connOpts;
return;
}
this.opts = cmdOpts ? Object.assign({}, connOpts, cmdOpts) : connOpts;
if (cmdOpts.charset && typeof cmdOpts.charset === 'string') {
this.opts.collation = Collations.fromCharset(cmdOpts.charset.toLowerCase());
if (this.opts.collation === undefined) {
this.opts.collation = Collations.fromName(cmdOpts.charset.toUpperCase());
if (this.opts.collation !== undefined) {
this.opts.logger.warning(
"warning: please use option 'collation' " +
"in replacement of 'charset' when using a collation name ('" +
cmdOpts.charset +
"')\n" +
"(collation looks like 'UTF8MB4_UNICODE_CI', charset like 'utf8')."
);
}
}
if (this.opts.collation === undefined) throw new RangeError("Unknown charset '" + cmdOpts.charset + "'");
} else if (cmdOpts.collation && typeof cmdOpts.collation === 'string') {
const initial = cmdOpts.collation;
this.opts.collation = Collations.fromName(initial.toUpperCase());
if (this.opts.collation === undefined) throw new RangeError("Unknown collation '" + initial + "'");
} else {
this.opts.collation = Collations.fromIndex(cmdOpts.charsetNumber) || connOpts.collation;
}
connOpts.password = cmdOpts.password;
}
}
function writeAttribute(out, val, encoding) {
let param = Buffer.isEncoding(encoding) ? Buffer.from(val, encoding) : Iconv.encode(val, encoding);
out.writeLengthCoded(param.length);
out.writeBuffer(param, 0, param.length);
}
module.exports = ChangeUser;
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
/**
* Ok_Packet
* see https://mariadb.com/kb/en/ok_packet/
*/
class OkPacket {
constructor(affectedRows, insertId, warningStatus) {
this.affectedRows = affectedRows;
this.insertId = insertId;
this.warningStatus = warningStatus;
}
}
module.exports = OkPacket;
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const PrepareWrapper = require('./prepare-wrapper');
/**
* Prepare cache wrapper
* see https://mariadb.com/kb/en/com_stmt_prepare/#com_stmt_prepare_ok
*/
class PrepareCacheWrapper {
#use = 0;
#cached;
#prepare;
constructor(prepare) {
this.#prepare = prepare;
this.#cached = true;
}
incrementUse() {
this.#use += 1;
return new PrepareWrapper(this, this.#prepare);
}
unCache() {
this.#cached = false;
if (this.#use === 0) {
this.#prepare.close();
}
}
decrementUse() {
this.#use -= 1;
if (this.#use === 0 && !this.#cached) {
this.#prepare.close();
}
}
toString() {
return 'Prepare{use:' + this.#use + ',cached:' + this.#cached + '}';
}
}
module.exports = PrepareCacheWrapper;
@@ -0,0 +1,141 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Errors = require('../../misc/errors');
const ExecuteStream = require('../execute-stream');
const Parser = require('../parser');
/**
* Prepare result
* see https://mariadb.com/kb/en/com_stmt_prepare/#com_stmt_prepare_ok
*/
class PrepareResultPacket {
#conn;
constructor(statementId, parameterCount, columns, database, sql, placeHolderIndex, conn) {
this.id = statementId;
this.parameterCount = parameterCount;
this.columns = columns;
this.database = database;
this.query = sql;
this.closed = false;
this._placeHolderIndex = placeHolderIndex;
this.#conn = conn;
}
get conn() {
return this.#conn;
}
execute(values, opts, cb, stack) {
let _opts = opts,
_cb = cb;
if (typeof _opts === 'function') {
_cb = _opts;
_opts = undefined;
}
if (this.isClose()) {
let sql = this.query;
if (this.conn.opts.logParam) {
if (this.query.length > this.conn.opts.debugLen) {
sql = this.query.substring(0, this.conn.opts.debugLen) + '...';
} else {
let sqlMsg = this.query + ' - parameters:';
sql = Parser.logParameters(this.conn.opts, sqlMsg, values);
}
}
const error = Errors.createError(
`Execute fails, prepare command as already been closed`,
Errors.ER_PREPARE_CLOSED,
null,
'22000',
sql
);
if (!_cb) {
return Promise.reject(error);
} else {
_cb(error);
return;
}
}
const cmdParam = {
sql: this.query,
values: values,
opts: _opts,
callback: _cb
};
if (stack) cmdParam.stack = stack;
const conn = this.conn;
const promise = new Promise((resolve, reject) => conn.executePromise.call(conn, cmdParam, this, resolve, reject));
if (!_cb) {
return promise;
} else {
promise
.then((res) => {
if (_cb) _cb(null, res, null);
})
.catch(_cb || function (err) {});
}
}
executeStream(values, opts, cb, stack) {
let _opts = opts,
_cb = cb;
if (typeof _opts === 'function') {
_cb = _opts;
_opts = undefined;
}
if (this.isClose()) {
const error = Errors.createError(
`Execute fails, prepare command as already been closed`,
Errors.ER_PREPARE_CLOSED,
null,
'22000',
this.query
);
if (!_cb) {
throw error;
} else {
_cb(error);
return;
}
}
const cmdParam = {
sql: this.query,
values: values,
opts: _opts,
callback: _cb
};
if (stack) cmdParam.stack = stack;
const cmd = new ExecuteStream(cmdParam, this.conn.opts, this, this.conn.socket);
if (this.conn.opts.logger.error) cmd.on('error', this.conn.opts.logger.error);
this.conn.addCommand(cmd, true);
return cmd.inStream;
}
isClose() {
return this.closed;
}
close() {
if (!this.closed) {
this.closed = true;
this.#conn.emit('close_prepare', this);
}
}
toString() {
return 'Prepare{closed:' + this.closed + '}';
}
}
module.exports = PrepareResultPacket;
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
/**
* Prepare result wrapper
* This permit to ensure that cache can be close only one time cache.
*/
class PrepareWrapper {
#closed = false;
#cacheWrapper;
#prepare;
#conn;
constructor(cacheWrapper, prepare) {
this.#cacheWrapper = cacheWrapper;
this.#prepare = prepare;
this.#conn = prepare.conn;
this.execute = this.#prepare.execute;
this.executeStream = this.#prepare.executeStream;
}
get conn() {
return this.#conn;
}
get id() {
return this.#prepare.id;
}
get parameterCount() {
return this.#prepare.parameterCount;
}
get _placeHolderIndex() {
return this.#prepare._placeHolderIndex;
}
get columns() {
return this.#prepare.columns;
}
set columns(columns) {
this.#prepare.columns = columns;
}
get database() {
return this.#prepare.database;
}
get query() {
return this.#prepare.query;
}
isClose() {
return this.#closed;
}
close() {
if (!this.#closed) {
this.#closed = true;
this.#cacheWrapper.decrementUse();
}
}
toString() {
return 'PrepareWrapper{closed:' + this.#closed + ',cache:' + this.#cacheWrapper + '}';
}
}
module.exports = PrepareWrapper;
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Command = require('./command');
/**
* Close prepared statement
* see https://mariadb.com/kb/en/3-binary-protocol-prepared-statements-com_stmt_close/
*/
class ClosePrepare extends Command {
constructor(cmdParam, resolve, reject, prepare) {
super(cmdParam, resolve, reject);
this.prepare = prepare;
}
start(out, opts, info) {
if (opts.logger.query) opts.logger.query(`CLOSE PREPARE: (${this.prepare.id}) ${this.prepare.query}`);
const closeCmd = new Uint8Array([
5,
0,
0,
0,
0x19,
this.prepare.id,
this.prepare.id >> 8,
this.prepare.id >> 16,
this.prepare.id >> 24
]);
out.fastFlush(this, closeCmd);
this.onPacketReceive = null;
this.emit('send_end');
this.emit('end');
}
}
module.exports = ClosePrepare;
+200
View File
@@ -0,0 +1,200 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Collations = require('../const/collations.js');
const FieldType = require('../const/field-type');
const FieldDetails = require('../const/field-detail');
const Capabilities = require('../const/capabilities');
// noinspection JSBitwiseOperatorUsage
/**
* Column definition
* see https://mariadb.com/kb/en/library/resultset/#column-definition-packet
*/
class ColumnDef {
#stringParser;
constructor(packet, info, skipName) {
this.#stringParser = skipName ? new StringParser(packet) : new StringParserWithName(packet);
if (info.clientCapabilities & Capabilities.MARIADB_CLIENT_EXTENDED_METADATA) {
const len = packet.readUnsignedLength();
if (len > 0) {
const subPacket = packet.subPacketLengthEncoded(len);
while (subPacket.remaining()) {
switch (subPacket.readUInt8()) {
case 0:
this.dataTypeName = subPacket.readAsciiStringLengthEncoded();
break;
case 1:
this.dataTypeFormat = subPacket.readAsciiStringLengthEncoded();
break;
default:
subPacket.skip(subPacket.readUnsignedLength());
break;
}
}
}
}
packet.skip(1); // length of fixed fields
this.collation = Collations.fromIndex(packet.readUInt16());
this.columnLength = packet.readUInt32();
this.columnType = packet.readUInt8();
this.flags = packet.readUInt16();
this.scale = packet.readUInt8();
this.type = FieldType.TYPES[this.columnType];
}
__getDefaultGeomVal() {
if (this.dataTypeName) {
switch (this.dataTypeName) {
case 'point':
return { type: 'Point' };
case 'linestring':
return { type: 'LineString' };
case 'polygon':
return { type: 'Polygon' };
case 'multipoint':
return { type: 'MultiPoint' };
case 'multilinestring':
return { type: 'MultiLineString' };
case 'multipolygon':
return { type: 'MultiPolygon' };
default:
return { type: this.dataTypeName };
}
}
return null;
}
db() {
return this.#stringParser.db();
}
schema() {
return this.#stringParser.schema();
}
table() {
return this.#stringParser.table();
}
orgTable() {
return this.#stringParser.orgTable();
}
name() {
return this.#stringParser.name();
}
orgName() {
return this.#stringParser.orgName();
}
signed() {
return (this.flags & FieldDetails.UNSIGNED) === 0;
}
isSet() {
return (this.flags & FieldDetails.SET) !== 0;
}
}
/**
* String parser.
* This object permits avoiding listing all private information to a metadata object.
*/
class BaseStringParser {
constructor(encoding, readFct, saveBuf, initialPos) {
this.buf = saveBuf;
this.encoding = encoding;
this.readString = readFct;
this.initialPos = initialPos;
}
_readIdentifier(skip) {
let pos = this.initialPos;
while (skip-- > 0) {
const type = this.buf[pos++];
pos += type < 0xfb ? type : 2 + this.buf[pos] + this.buf[pos + 1] * 2 ** 8;
}
const type = this.buf[pos++];
const len = type < 0xfb ? type : this.buf[pos++] + this.buf[pos++] * 2 ** 8;
return this.readString(this.encoding, this.buf, pos, len);
}
name() {
return this._readIdentifier(3);
}
db() {
let pos = this.initialPos;
return this.readString(this.encoding, this.buf, pos + 1, this.buf[pos]);
}
schema() {
return this.db();
}
table() {
let pos = this.initialPos + 1 + this.buf[this.initialPos];
const type = this.buf[pos++];
const len = type < 0xfb ? type : this.buf[pos++] + this.buf[pos++] * 2 ** 8;
return this.readString(this.encoding, this.buf, pos, len);
}
orgTable() {
return this._readIdentifier(2);
}
orgName() {
return this._readIdentifier(4);
}
}
class StringParser extends BaseStringParser {
constructor(packet) {
packet.skip(packet.readUInt8()); //catalog
const initPos = packet.pos;
packet.skip(packet.readUInt8()); //schema
packet.skip(packet.readMetadataLength()); //table alias
packet.skip(packet.readUInt8()); //table
packet.skip(packet.readMetadataLength()); //column alias
packet.skip(packet.readUInt8()); //column
super(packet.encoding, packet.constructor.readString, packet.buf, initPos);
}
}
/**
* String parser.
* This object permits to avoid listing all private information to metadata object.
*/
class StringParserWithName extends BaseStringParser {
colName;
constructor(packet) {
packet.skip(packet.readUInt8()); //catalog
const initPos = packet.pos;
packet.skip(packet.readUInt8()); //schema
packet.skip(packet.readMetadataLength()); //table alias
packet.skip(packet.readUInt8()); //table
const colName = packet.readStringLengthEncoded(); //column alias
packet.skip(packet.readUInt8()); //column
super(packet.encoding, packet.constructor.readString, packet.buf, initPos);
this.colName = colName;
}
name() {
return this.colName;
}
}
module.exports = ColumnDef;
+134
View File
@@ -0,0 +1,134 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const EventEmitter = require('events');
const Errors = require('../misc/errors');
/**
* Default command interface.
*/
class Command extends EventEmitter {
constructor(cmdParam, resolve, reject) {
super();
this.cmdParam = cmdParam;
this.sequenceNo = -1;
this.compressSequenceNo = -1;
this.resolve = resolve;
this.reject = reject;
this.sending = false;
this.unexpectedError = this.throwUnexpectedError.bind(this);
}
displaySql() {
return null;
}
/**
* Throw an unexpected error.
* server exchange will still be read to keep connection in a good state, but promise will be rejected.
*
* @param msg message
* @param fatal is error fatal for connection
* @param info current server state information
* @param sqlState error sqlState
* @param errno error number
*/
throwUnexpectedError(msg, fatal, info, sqlState, errno) {
const err = Errors.createError(
msg,
errno,
info,
sqlState,
this.opts && this.opts.logParam ? this.displaySql() : this.sql,
fatal,
this.cmdParam ? this.cmdParam.stack : null,
false
);
if (this.reject) {
process.nextTick(this.reject, err);
this.resolve = null;
this.reject = null;
}
return err;
}
/**
* Create and throw new Error from error information
* only first called throwing an error or successfully end will be executed.
*
* @param msg message
* @param fatal is error fatal for connection
* @param info current server state information
* @param sqlState error sqlState
* @param errno error number
*/
throwNewError(msg, fatal, info, sqlState, errno) {
this.onPacketReceive = null;
const err = this.throwUnexpectedError(msg, fatal, info, sqlState, errno);
this.emit('end');
return err;
}
/**
* When command cannot be sent due to error.
* (this is only on start command)
*
* @param msg error message
* @param errno error number
* @param info connection information
*/
sendCancelled(msg, errno, info) {
const err = Errors.createError(msg, errno, info, 'HY000', this.opts.logParam ? this.displaySql() : this.sql);
this.emit('send_end');
this.throwError(err, info);
}
/**
* Throw Error
* only first called throwing an error or successfully end will be executed.
*
* @param err error to be thrown
* @param info current server state information
*/
throwError(err, info) {
this.onPacketReceive = null;
if (this.reject) {
if (this.cmdParam && this.cmdParam.stack) {
err = Errors.createError(
err.text ? err.text : err.message,
err.errno,
info,
err.sqlState,
err.sql,
err.fatal,
this.cmdParam.stack,
false
);
}
this.resolve = null;
process.nextTick(this.reject, err);
this.reject = null;
}
this.emit('end', err);
}
/**
* Successfully end command.
* only first called throwing an error or successfully end will be executed.
*
* @param val return value.
*/
successEnd(val) {
this.onPacketReceive = null;
if (this.resolve) {
this.reject = null;
process.nextTick(this.resolve, val);
this.resolve = null;
}
this.emit('end');
}
}
module.exports = Command;
@@ -0,0 +1,282 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const FieldType = require('../../const/field-type');
const Errors = require('../../misc/errors');
module.exports.newRow = function (packet, columns) {
packet.skip(1); // skip 0x00 header.
const len = ~~((columns.length + 9) / 8);
const nullBitMap = new Array(len);
for (let i = 0; i < len; i++) nullBitMap[i] = packet.readUInt8();
return nullBitMap;
};
module.exports.castWrapper = function (column, packet, opts, nullBitmap, index) {
column.string = () => (isNullBitmap(index, nullBitmap) ? null : packet.readStringLengthEncoded());
column.buffer = () => (isNullBitmap(index, nullBitmap) ? null : packet.readBufferLengthEncoded());
column.float = () => (isNullBitmap(index, nullBitmap) ? null : packet.readFloat());
column.tiny = () =>
isNullBitmap(index, nullBitmap) ? null : column.signed() ? packet.readInt8() : packet.readUInt8();
column.short = () =>
isNullBitmap(index, nullBitmap) ? null : column.signed() ? packet.readInt16() : packet.readUInt16();
column.int = () => (isNullBitmap(index, nullBitmap) ? null : packet.readInt32());
column.long = () => (isNullBitmap(index, nullBitmap) ? null : packet.readBigInt64());
column.decimal = () => (isNullBitmap(index, nullBitmap) ? null : packet.readDecimalLengthEncoded());
column.date = () => (isNullBitmap(index, nullBitmap) ? null : packet.readBinaryDate(opts));
column.datetime = () => (isNullBitmap(index, nullBitmap) ? null : packet.readBinaryDateTime());
column.geometry = () => {
let defaultVal = null;
if (column.dataTypeName) {
switch (column.dataTypeName) {
case 'point':
defaultVal = { type: 'Point' };
break;
case 'linestring':
defaultVal = { type: 'LineString' };
break;
case 'polygon':
defaultVal = { type: 'Polygon' };
break;
case 'multipoint':
defaultVal = { type: 'MultiPoint' };
break;
case 'multilinestring':
defaultVal = { type: 'MultiLineString' };
break;
case 'multipolygon':
defaultVal = { type: 'MultiPolygon' };
break;
default:
defaultVal = { type: column.dataTypeName };
break;
}
}
if (isNullBitmap(index, nullBitmap)) {
return defaultVal;
}
return packet.readGeometry(defaultVal);
};
};
module.exports.parser = function (col, opts) {
// set reader function read(col, packet, index, nullBitmap, opts, throwUnexpectedError)
// this permit for multi-row result-set to avoid resolving type parsing each data.
// return constant parser (function not depending on column info other than type)
const defaultParser = col.signed()
? DEFAULT_SIGNED_PARSER_TYPE[col.columnType]
: DEFAULT_UNSIGNED_PARSER_TYPE[col.columnType];
if (defaultParser) return defaultParser;
// parser depending on column info
switch (col.columnType) {
case FieldType.BIGINT:
if (col.signed()) {
return opts.bigIntAsNumber || opts.supportBigNumbers ? readBigintAsIntBinarySigned : readBigintBinarySigned;
}
return opts.bigIntAsNumber || opts.supportBigNumbers ? readBigintAsIntBinaryUnsigned : readBigintBinaryUnsigned;
case FieldType.DATETIME:
case FieldType.TIMESTAMP:
return opts.dateStrings ? readTimestampStringBinary.bind(null, col.scale) : readTimestampBinary;
case FieldType.DECIMAL:
case FieldType.NEWDECIMAL:
return col.scale === 0 ? readDecimalAsIntBinary : readDecimalBinary;
case FieldType.GEOMETRY:
let defaultVal = col.__getDefaultGeomVal();
return readGeometryBinary.bind(null, defaultVal);
case FieldType.BIT:
if (col.columnLength === 1 && opts.bitOneIsBoolean) {
return readBitBinaryBoolean;
}
return readBinaryBuffer;
case FieldType.JSON:
return opts.jsonStrings ? readStringBinary : readJsonBinary;
default:
if (col.dataTypeFormat && col.dataTypeFormat === 'json' && opts.autoJsonMap) {
return readJsonBinary;
}
if (col.collation.index === 63) {
return readBinaryBuffer;
}
if (col.isSet()) {
return readBinarySet;
}
return readStringBinary;
}
};
const isNullBitmap = (index, nullBitmap) => {
return (nullBitmap[~~((index + 2) / 8)] & (1 << (index + 2) % 8)) > 0;
};
const readTinyBinarySigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readInt8();
const readTinyBinaryUnsigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readUInt8();
const readShortBinarySigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readInt16();
const readShortBinaryUnsigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readUInt16();
const readMediumBinarySigned = (packet, opts, throwUnexpectedError, nullBitmap, index) => {
if (isNullBitmap(index, nullBitmap)) {
return null;
}
const result = packet.readInt24();
packet.skip(1); // MEDIUMINT is encoded on 4 bytes in exchanges !
return result;
};
const readMediumBinaryUnsigned = (packet, opts, throwUnexpectedError, nullBitmap, index) => {
if (isNullBitmap(index, nullBitmap)) {
return null;
}
const result = packet.readUInt24();
packet.skip(1); // MEDIUMINT is encoded on 4 bytes in exchanges !
return result;
};
const readIntBinarySigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readInt32();
const readIntBinaryUnsigned = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readUInt32();
const readFloatBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readFloat();
const readDoubleBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readDouble();
const readBigintBinaryUnsigned = function (packet, opts, throwUnexpectedError, nullBitmap, index) {
if (isNullBitmap(index, nullBitmap)) return null;
return packet.readBigUInt64();
};
const readBigintBinarySigned = function (packet, opts, throwUnexpectedError, nullBitmap, index) {
if (isNullBitmap(index, nullBitmap)) return null;
return packet.readBigInt64();
};
const readBigintAsIntBinaryUnsigned = function (packet, opts, throwUnexpectedError, nullBitmap, index) {
if (isNullBitmap(index, nullBitmap)) return null;
const val = packet.readBigUInt64();
if (opts.bigIntAsNumber && opts.checkNumberRange && !Number.isSafeInteger(Number(val))) {
return throwUnexpectedError(
`value ${val} can't safely be converted to number`,
false,
null,
'42000',
Errors.ER_PARSING_PRECISION
);
}
if (opts.supportBigNumbers && (opts.bigNumberStrings || !Number.isSafeInteger(Number(val)))) {
return val.toString();
}
return Number(val);
};
const readBigintAsIntBinarySigned = function (packet, opts, throwUnexpectedError, nullBitmap, index) {
if (isNullBitmap(index, nullBitmap)) return null;
const val = packet.readBigInt64();
if (opts.bigIntAsNumber && opts.checkNumberRange && !Number.isSafeInteger(Number(val))) {
return throwUnexpectedError(
`value ${val} can't safely be converted to number`,
false,
null,
'42000',
Errors.ER_PARSING_PRECISION
);
}
if (opts.supportBigNumbers && (opts.bigNumberStrings || !Number.isSafeInteger(Number(val)))) {
return val.toString();
}
return Number(val);
};
const readGeometryBinary = (defaultVal, packet, opts, throwUnexpectedError, nullBitmap, index) => {
if (isNullBitmap(index, nullBitmap)) {
return defaultVal;
}
return packet.readGeometry(defaultVal);
};
const readDateBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBinaryDate(opts);
const readTimestampBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBinaryDateTime();
const readTimestampStringBinary = (scale, packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBinaryDateTimeAsString(scale);
const readTimeBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBinaryTime();
const readDecimalAsIntBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) => {
//checkNumberRange additional check is only done when
// resulting value is an integer
if (isNullBitmap(index, nullBitmap)) return null;
const valDec = packet.readDecimalLengthEncoded();
if (valDec != null && (opts.decimalAsNumber || opts.supportBigNumbers)) {
if (opts.decimalAsNumber && opts.checkNumberRange && !Number.isSafeInteger(Number(valDec))) {
return throwUnexpectedError(
`value ${valDec} can't safely be converted to number`,
false,
null,
'42000',
Errors.ER_PARSING_PRECISION
);
}
if (opts.supportBigNumbers && (opts.bigNumberStrings || !Number.isSafeInteger(Number(valDec)))) {
return valDec;
}
return Number(valDec);
}
return valDec;
};
const readDecimalBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) => {
if (isNullBitmap(index, nullBitmap)) return null;
const valDec = packet.readDecimalLengthEncoded();
if (valDec != null && (opts.decimalAsNumber || opts.supportBigNumbers)) {
const numberValue = Number(valDec);
if (
opts.supportBigNumbers &&
(opts.bigNumberStrings || (Number.isInteger(numberValue) && !Number.isSafeInteger(numberValue)))
) {
return valDec;
}
return numberValue;
}
return valDec;
};
const readJsonBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : JSON.parse(packet.readStringLengthEncoded());
const readBitBinaryBoolean = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBufferLengthEncoded()[0] === 1;
const readBinaryBuffer = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readBufferLengthEncoded();
const readBinarySet = (packet, opts, throwUnexpectedError, nullBitmap, index) => {
if (isNullBitmap(index, nullBitmap)) return null;
const string = packet.readStringLengthEncoded();
return string == null ? null : string === '' ? [] : string.split(',');
};
const readStringBinary = (packet, opts, throwUnexpectedError, nullBitmap, index) =>
isNullBitmap(index, nullBitmap) ? null : packet.readStringLengthEncoded();
const DEFAULT_SIGNED_PARSER_TYPE = Array(256);
DEFAULT_SIGNED_PARSER_TYPE[FieldType.TINY] = readTinyBinarySigned;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.YEAR] = readShortBinarySigned;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.SHORT] = readShortBinarySigned;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.INT24] = readMediumBinarySigned;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.INT] = readIntBinarySigned;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.FLOAT] = readFloatBinary;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.DOUBLE] = readDoubleBinary;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.DATE] = readDateBinary;
DEFAULT_SIGNED_PARSER_TYPE[FieldType.TIME] = readTimeBinary;
const DEFAULT_UNSIGNED_PARSER_TYPE = Array(256);
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.TINY] = readTinyBinaryUnsigned;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.YEAR] = readShortBinaryUnsigned;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.SHORT] = readShortBinaryUnsigned;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.INT24] = readMediumBinaryUnsigned;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.INT] = readIntBinaryUnsigned;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.FLOAT] = readFloatBinary;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.DOUBLE] = readDoubleBinary;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.DATE] = readDateBinary;
DEFAULT_UNSIGNED_PARSER_TYPE[FieldType.TIME] = readTimeBinary;
@@ -0,0 +1,210 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const FieldType = require('../../const/field-type');
const Errors = require('../../misc/errors');
module.exports.parser = function (col, opts) {
// Fast path: For most types, we can directly return the default parser
// This avoids the cost of the switch statement for common types
const defaultParser = DEFAULT_PARSER_TYPE[col.columnType];
if (defaultParser) return defaultParser;
// Parser depending on column info
switch (col.columnType) {
case FieldType.DECIMAL:
case FieldType.NEWDECIMAL:
return col.scale === 0 ? readDecimalAsIntLengthCoded : readDecimalLengthCoded;
case FieldType.BIGINT:
if (opts.bigIntAsNumber || opts.supportBigNumbers) return readBigIntAsNumberLengthCoded;
return readBigIntLengthCoded;
case FieldType.GEOMETRY:
const defaultVal = col.__getDefaultGeomVal();
return function (packet, opts, throwUnexpectedError) {
return packet.readGeometry(defaultVal);
};
case FieldType.BIT:
if (col.columnLength === 1 && opts.bitOneIsBoolean) {
return readBitAsBoolean;
}
return readBufferLengthEncoded;
case FieldType.JSON:
return opts.jsonStrings ? readStringLengthEncoded : readJson;
default:
if (col.dataTypeFormat === 'json' && opts.autoJsonMap) {
return readJson;
}
if (col.collation.index === 63) {
return readBufferLengthEncoded;
}
if (col.isSet()) {
return readSet;
}
return readStringLengthEncoded;
}
};
module.exports.castWrapper = function (column, packet, opts, nullBitmap, index) {
const p = packet;
column.string = () => p.readStringLengthEncoded();
column.buffer = () => p.readBufferLengthEncoded();
column.float = () => p.readFloatLengthCoded();
column.tiny = column.short = column.int = () => p.readIntLengthEncoded();
column.long = () => p.readBigIntLengthEncoded();
column.decimal = () => p.readDecimalLengthEncoded();
column.date = () => p.readDate(opts);
column.datetime = () => p.readDateTime();
// Only define geometry method if needed (likely less common)
// Inline the geometry switch case for better performance
column.geometry = () => {
let defaultVal = null;
if (column.dataTypeName) {
// Use object lookup instead of switch for better performance
const geoTypes = {
point: { type: 'Point' },
linestring: { type: 'LineString' },
polygon: { type: 'Polygon' },
multipoint: { type: 'MultiPoint' },
multilinestring: { type: 'MultiLineString' },
multipolygon: { type: 'MultiPolygon' }
};
defaultVal = geoTypes[column.dataTypeName] || { type: column.dataTypeName };
}
return p.readGeometry(defaultVal);
};
};
const readIntLengthEncoded = (packet, opts, throwUnexpectedError) => packet.readIntLengthEncoded();
const readStringLengthEncoded = (packet, opts, throwUnexpectedError) => packet.readStringLengthEncoded();
const readFloatLengthCoded = (packet, opts, throwUnexpectedError) => packet.readFloatLengthCoded();
const readBigIntLengthCoded = (packet, opts, throwUnexpectedError) => packet.readBigIntLengthEncoded();
const readAsciiStringLengthEncoded = (packet, opts, throwUnexpectedError) => packet.readAsciiStringLengthEncoded();
const readBitAsBoolean = (packet, opts, throwUnexpectedError) => {
const val = packet.readBufferLengthEncoded();
return val == null ? null : val[0] === 1;
};
const readBufferLengthEncoded = (packet, opts, throwUnexpectedError) => packet.readBufferLengthEncoded();
const readJson = (packet, opts, throwUnexpectedError) => {
const jsonStr = packet.readStringLengthEncoded();
return jsonStr === null ? null : JSON.parse(jsonStr);
};
const readSet = (packet, opts, throwUnexpectedError) => {
const string = packet.readStringLengthEncoded();
return string == null ? null : string === '' ? [] : string.split(',');
};
const readDate = (packet, opts, throwUnexpectedError) =>
opts.dateStrings ? packet.readAsciiStringLengthEncoded() : packet.readDate();
const readTimestamp = (packet, opts, throwUnexpectedError) =>
opts.dateStrings ? packet.readAsciiStringLengthEncoded() : packet.readDateTime();
// Initialize the DEFAULT_PARSER_TYPE array with frequently used types
// Use a typed array for performance when accessing elements
const DEFAULT_PARSER_TYPE = new Array(256);
DEFAULT_PARSER_TYPE[FieldType.TINY] = readIntLengthEncoded;
DEFAULT_PARSER_TYPE[FieldType.SHORT] = readIntLengthEncoded;
DEFAULT_PARSER_TYPE[FieldType.INT] = readIntLengthEncoded;
DEFAULT_PARSER_TYPE[FieldType.INT24] = readIntLengthEncoded;
DEFAULT_PARSER_TYPE[FieldType.YEAR] = readIntLengthEncoded;
DEFAULT_PARSER_TYPE[FieldType.FLOAT] = readFloatLengthCoded;
DEFAULT_PARSER_TYPE[FieldType.DOUBLE] = readFloatLengthCoded;
DEFAULT_PARSER_TYPE[FieldType.DATE] = readDate;
DEFAULT_PARSER_TYPE[FieldType.DATETIME] = readTimestamp;
DEFAULT_PARSER_TYPE[FieldType.TIMESTAMP] = readTimestamp;
DEFAULT_PARSER_TYPE[FieldType.TIME] = readAsciiStringLengthEncoded;
const readBigIntAsNumberLengthCoded = (packet, opts, throwUnexpectedError) => {
const len = packet.readUnsignedLength();
if (len === null) return null;
// Fast path for small integers
if (len < 16) {
const val = packet._atoi(len);
// We know we're here because either bigIntAsNumber or supportBigNumbers is true
if (opts.supportBigNumbers && opts.bigNumberStrings) {
return `${val}`;
}
return val;
}
const val = packet.readBigIntFromLen(len);
if (opts.bigIntAsNumber && opts.checkNumberRange && !Number.isSafeInteger(Number(val))) {
return throwUnexpectedError(
`value ${val} can't safely be converted to number`,
false,
null,
'42000',
Errors.ER_PARSING_PRECISION
);
}
const numVal = Number(val);
if (opts.supportBigNumbers && (opts.bigNumberStrings || !Number.isSafeInteger(numVal))) {
return val.toString();
}
return numVal;
};
const readDecimalAsIntLengthCoded = (packet, opts, throwUnexpectedError) => {
const valDec = packet.readDecimalLengthEncoded();
if (valDec === null) return null;
// Only perform conversions if needed based on options
if (!(opts.decimalAsNumber || opts.supportBigNumbers)) return valDec;
// Convert once
const numValue = Number(valDec);
// Check number range if required
if (opts.decimalAsNumber && opts.checkNumberRange && !Number.isSafeInteger(numValue)) {
return throwUnexpectedError(
`value ${valDec} can't safely be converted to number`,
false,
null,
'42000',
Errors.ER_PARSING_PRECISION
);
}
// Return string representation for big numbers if needed
if (opts.supportBigNumbers && (opts.bigNumberStrings || !Number.isSafeInteger(numValue))) {
return valDec;
}
return numValue;
};
const readDecimalLengthCoded = (packet, opts, throwUnexpectedError) => {
const valDec = packet.readDecimalLengthEncoded();
if (valDec === null) return null;
// Only perform conversions if needed based on options
if (!(opts.decimalAsNumber || opts.supportBigNumbers)) return valDec;
const numberValue = Number(valDec);
// Handle big numbers specifically
if (
opts.supportBigNumbers &&
(opts.bigNumberStrings || (Number.isInteger(numberValue) && !Number.isSafeInteger(numberValue)))
) {
return valDec;
}
return numberValue;
};
@@ -0,0 +1,284 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
class BinaryEncoder {
/**
* Write (and escape) current parameter value to output writer
*
* @param out output writer
* @param value current parameter
* @param opts connection options
* @param info connection information
*/
static writeParam(out, value, opts, info) {
// GEOJSON are not checked, because change to null/Buffer on parameter validation
switch (typeof value) {
case 'boolean':
out.writeInt8(value ? 0x01 : 0x00);
break;
case 'bigint':
if (value >= 2n ** 63n) {
out.writeLengthEncodedString(value.toString());
} else {
out.writeBigInt(value);
}
break;
case 'number':
// additional verification, to permit query without type,
// like 'SELECT ?' returning same type of value
if (Number.isInteger(value) && value >= -2147483648 && value < 2147483647) {
out.writeInt32(value);
break;
}
out.writeDouble(value);
break;
case 'string':
out.writeLengthEncodedString(value);
break;
case 'object':
if (Object.prototype.toString.call(value) === '[object Date]') {
out.writeBinaryDate(value);
} else if (Buffer.isBuffer(value)) {
out.writeLengthEncodedBuffer(value);
} else if (typeof value.toSqlString === 'function') {
out.writeLengthEncodedString(String(value.toSqlString()));
} else {
out.writeLengthEncodedString(JSON.stringify(value));
}
break;
default:
out.writeLengthEncodedBuffer(value);
}
}
static getBufferFromGeometryValue(value, headerType) {
let geoBuff;
let pos;
let type;
if (!headerType) {
switch (value.type) {
case 'Point':
geoBuff = Buffer.allocUnsafe(21);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(1, 1); //wkbPoint
if (
value.coordinates &&
Array.isArray(value.coordinates) &&
value.coordinates.length >= 2 &&
!isNaN(value.coordinates[0]) &&
!isNaN(value.coordinates[1])
) {
geoBuff.writeDoubleLE(value.coordinates[0], 5); //X
geoBuff.writeDoubleLE(value.coordinates[1], 13); //Y
return geoBuff;
} else {
return null;
}
case 'LineString':
if (value.coordinates && Array.isArray(value.coordinates)) {
const pointNumber = value.coordinates.length;
geoBuff = Buffer.allocUnsafe(9 + 16 * pointNumber);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(2, 1); //wkbLineString
geoBuff.writeInt32LE(pointNumber, 5);
for (let i = 0; i < pointNumber; i++) {
if (
value.coordinates[i] &&
Array.isArray(value.coordinates[i]) &&
value.coordinates[i].length >= 2 &&
!isNaN(value.coordinates[i][0]) &&
!isNaN(value.coordinates[i][1])
) {
geoBuff.writeDoubleLE(value.coordinates[i][0], 9 + 16 * i); //X
geoBuff.writeDoubleLE(value.coordinates[i][1], 17 + 16 * i); //Y
} else {
return null;
}
}
return geoBuff;
} else {
return null;
}
case 'Polygon':
if (value.coordinates && Array.isArray(value.coordinates)) {
const numRings = value.coordinates.length;
let size = 0;
for (let i = 0; i < numRings; i++) {
size += 4 + 16 * value.coordinates[i].length;
}
geoBuff = Buffer.allocUnsafe(9 + size);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(3, 1); //wkbPolygon
geoBuff.writeInt32LE(numRings, 5);
pos = 9;
for (let i = 0; i < numRings; i++) {
const lineString = value.coordinates[i];
if (lineString && Array.isArray(lineString)) {
geoBuff.writeInt32LE(lineString.length, pos);
pos += 4;
for (let j = 0; j < lineString.length; j++) {
if (
lineString[j] &&
Array.isArray(lineString[j]) &&
lineString[j].length >= 2 &&
!isNaN(lineString[j][0]) &&
!isNaN(lineString[j][1])
) {
geoBuff.writeDoubleLE(lineString[j][0], pos); //X
geoBuff.writeDoubleLE(lineString[j][1], pos + 8); //Y
pos += 16;
} else {
return null;
}
}
}
}
return geoBuff;
} else {
return null;
}
case 'MultiPoint':
type = 'MultiPoint';
geoBuff = Buffer.allocUnsafe(9);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(4, 1); //wkbMultiPoint
break;
case 'MultiLineString':
type = 'MultiLineString';
geoBuff = Buffer.allocUnsafe(9);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(5, 1); //wkbMultiLineString
break;
case 'MultiPolygon':
type = 'MultiPolygon';
geoBuff = Buffer.allocUnsafe(9);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(6, 1); //wkbMultiPolygon
break;
case 'GeometryCollection':
geoBuff = Buffer.allocUnsafe(9);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(7, 1); //wkbGeometryCollection
if (value.geometries && Array.isArray(value.geometries)) {
const coordinateLength = value.geometries.length;
const subArrays = [geoBuff];
for (let i = 0; i < coordinateLength; i++) {
const tmpBuf = this.getBufferFromGeometryValue(value.geometries[i]);
if (tmpBuf === null) break;
subArrays.push(tmpBuf);
}
geoBuff.writeInt32LE(subArrays.length - 1, 5);
return Buffer.concat(subArrays);
} else {
geoBuff.writeInt32LE(0, 5);
return geoBuff;
}
default:
return null;
}
if (value.coordinates && Array.isArray(value.coordinates)) {
const coordinateLength = value.coordinates.length;
const subArrays = [geoBuff];
for (let i = 0; i < coordinateLength; i++) {
const tmpBuf = this.getBufferFromGeometryValue(value.coordinates[i], type);
if (tmpBuf === null) break;
subArrays.push(tmpBuf);
}
geoBuff.writeInt32LE(subArrays.length - 1, 5);
return Buffer.concat(subArrays);
} else {
geoBuff.writeInt32LE(0, 5);
return geoBuff;
}
} else {
switch (headerType) {
case 'MultiPoint':
if (value && Array.isArray(value) && value.length >= 2 && !isNaN(value[0]) && !isNaN(value[1])) {
geoBuff = Buffer.allocUnsafe(21);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(1, 1); //wkbPoint
geoBuff.writeDoubleLE(value[0], 5); //X
geoBuff.writeDoubleLE(value[1], 13); //Y
return geoBuff;
}
return null;
case 'MultiLineString':
if (value && Array.isArray(value)) {
const pointNumber = value.length;
geoBuff = Buffer.allocUnsafe(9 + 16 * pointNumber);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(2, 1); //wkbLineString
geoBuff.writeInt32LE(pointNumber, 5);
for (let i = 0; i < pointNumber; i++) {
if (
value[i] &&
Array.isArray(value[i]) &&
value[i].length >= 2 &&
!isNaN(value[i][0]) &&
!isNaN(value[i][1])
) {
geoBuff.writeDoubleLE(value[i][0], 9 + 16 * i); //X
geoBuff.writeDoubleLE(value[i][1], 17 + 16 * i); //Y
} else {
return null;
}
}
return geoBuff;
}
return null;
case 'MultiPolygon':
if (value && Array.isArray(value)) {
const numRings = value.length;
let size = 0;
for (let i = 0; i < numRings; i++) {
size += 4 + 16 * value[i].length;
}
geoBuff = Buffer.allocUnsafe(9 + size);
geoBuff.writeInt8(0x01, 0); //LITTLE ENDIAN
geoBuff.writeInt32LE(3, 1); //wkbPolygon
geoBuff.writeInt32LE(numRings, 5);
pos = 9;
for (let i = 0; i < numRings; i++) {
const lineString = value[i];
if (lineString && Array.isArray(lineString)) {
geoBuff.writeInt32LE(lineString.length, pos);
pos += 4;
for (let j = 0; j < lineString.length; j++) {
if (
lineString[j] &&
Array.isArray(lineString[j]) &&
lineString[j].length >= 2 &&
!isNaN(lineString[j][0]) &&
!isNaN(lineString[j][1])
) {
geoBuff.writeDoubleLE(lineString[j][0], pos); //X
geoBuff.writeDoubleLE(lineString[j][1], pos + 8); //Y
pos += 16;
} else {
return null;
}
}
}
}
return geoBuff;
}
return null;
}
return null;
}
}
}
module.exports = BinaryEncoder;
@@ -0,0 +1,311 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const QUOTE = 0x27;
// Cache common GeoJSON types
const GEO_TYPES = new Set([
'Point',
'LineString',
'Polygon',
'MultiPoint',
'MultiLineString',
'MultiPolygon',
'GeometryCollection'
]);
// Optimized function to pad numbers with leading zeros
const formatDigit = function (val, significantDigit) {
const str = `${val}`;
return str.length < significantDigit ? '0'.repeat(significantDigit - str.length) + str : str;
};
class TextEncoder {
/**
* Write (and escape) current parameter value to output writer
*
* @param out output writer
* @param value current parameter. Expected to be non-null
* @param opts connection options
* @param info connection information
*/
static writeParam(out, value, opts, info) {
switch (typeof value) {
case 'boolean':
out.writeStringAscii(value ? 'true' : 'false');
break;
case 'bigint':
case 'number':
out.writeStringAscii(`${value}`);
break;
case 'string':
out.writeStringEscapeQuote(value);
break;
case 'object':
if (Object.prototype.toString.call(value) === '[object Date]') {
out.writeStringAscii(TextEncoder.getLocalDate(value));
} else if (Buffer.isBuffer(value)) {
out.writeStringAscii("_BINARY '");
out.writeBufferEscape(value);
out.writeInt8(QUOTE);
} else if (typeof value.toSqlString === 'function') {
out.writeStringEscapeQuote(String(value.toSqlString()));
} else if (Array.isArray(value)) {
if (opts.arrayParenthesis) {
out.writeStringAscii('(');
}
for (let i = 0; i < value.length; i++) {
if (i !== 0) out.writeStringAscii(',');
if (value[i] == null) {
out.writeStringAscii('NULL');
} else TextEncoder.writeParam(out, value[i], opts, info);
}
if (opts.arrayParenthesis) {
out.writeStringAscii(')');
}
} else {
if (value.type != null && GEO_TYPES.has(value.type)) {
//GeoJSON format.
const isMariaDb = info.isMariaDB();
const prefix =
(isMariaDb && info.hasMinVersion(10, 1, 4)) || (!isMariaDb && info.hasMinVersion(5, 7, 6)) ? 'ST_' : '';
switch (value.type) {
case 'Point':
out.writeStringAscii(
prefix + "PointFromText('POINT(" + TextEncoder.geoPointToString(value.coordinates) + ")')"
);
break;
case 'LineString':
out.writeStringAscii(
prefix + "LineFromText('LINESTRING(" + TextEncoder.geoArrayPointToString(value.coordinates) + ")')"
);
break;
case 'Polygon':
out.writeStringAscii(
prefix +
"PolygonFromText('POLYGON(" +
TextEncoder.geoMultiArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiPoint':
out.writeStringAscii(
prefix +
"MULTIPOINTFROMTEXT('MULTIPOINT(" +
TextEncoder.geoArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiLineString':
out.writeStringAscii(
prefix +
"MLineFromText('MULTILINESTRING(" +
TextEncoder.geoMultiArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiPolygon':
out.writeStringAscii(
prefix +
"MPolyFromText('MULTIPOLYGON(" +
TextEncoder.geoMultiPolygonToString(value.coordinates) +
")')"
);
break;
case 'GeometryCollection':
out.writeStringAscii(
prefix +
"GeomCollFromText('GEOMETRYCOLLECTION(" +
TextEncoder.geometricCollectionToString(value.geometries) +
")')"
);
break;
}
} else if (String === value.constructor) {
out.writeStringEscapeQuote(value);
break;
} else {
if (opts.permitSetMultiParamEntries) {
let first = true;
for (const key in value) {
const val = value[key];
if (typeof val === 'function') continue;
if (first) {
first = false;
} else {
out.writeStringAscii(',');
}
out.writeString('`' + key + '`');
if (val == null) {
out.writeStringAscii('=NULL');
} else {
out.writeStringAscii('=');
TextEncoder.writeParam(out, val, opts, info);
}
}
if (first) out.writeStringEscapeQuote(JSON.stringify(value));
} else {
out.writeStringEscapeQuote(JSON.stringify(value));
}
}
}
break;
}
}
static geometricCollectionToString(geo) {
if (!geo) return '';
const len = geo.length;
let st = '';
for (let i = 0; i < len; i++) {
const item = geo[i];
//GeoJSON format.
if (i !== 0) st += ',';
switch (item.type) {
case 'Point':
st += `POINT(${TextEncoder.geoPointToString(item.coordinates)})`;
break;
case 'LineString':
st += `LINESTRING(${TextEncoder.geoArrayPointToString(item.coordinates)})`;
break;
case 'Polygon':
st += `POLYGON(${TextEncoder.geoMultiArrayPointToString(item.coordinates)})`;
break;
case 'MultiPoint':
st += `MULTIPOINT(${TextEncoder.geoArrayPointToString(item.coordinates)})`;
break;
case 'MultiLineString':
st += `MULTILINESTRING(${TextEncoder.geoMultiArrayPointToString(item.coordinates)})`;
break;
case 'MultiPolygon':
st += `MULTIPOLYGON(${TextEncoder.geoMultiPolygonToString(item.coordinates)})`;
break;
}
}
return st;
}
static geoMultiPolygonToString(coords) {
if (!coords) return '';
const len = coords.length;
if (len === 0) return '';
let st = '(';
for (let i = 0; i < len; i++) {
if (i !== 0) st += ',(';
st += TextEncoder.geoMultiArrayPointToString(coords[i]) + ')';
}
return st;
}
static geoMultiArrayPointToString(coords) {
if (!coords) return '';
const len = coords.length;
if (len === 0) return '';
let st = '(';
for (let i = 0; i < len; i++) {
if (i !== 0) st += ',(';
st += TextEncoder.geoArrayPointToString(coords[i]) + ')';
}
return st;
}
static geoArrayPointToString(coords) {
if (!coords) return '';
const len = coords.length;
if (len === 0) return '';
let st = '';
for (let i = 0; i < len; i++) {
if (i !== 0) st += ',';
st += TextEncoder.geoPointToString(coords[i]);
}
return st;
}
static geoPointToString(coords) {
if (!coords) return '';
const x = isNaN(coords[0]) ? '' : coords[0];
const y = isNaN(coords[1]) ? '' : coords[1];
return x + ' ' + y;
}
static getLocalDate(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const ms = date.getMilliseconds();
const d = "'" + year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
if (ms === 0) return d + "'";
return d + '.' + (ms < 10 ? '00' : ms < 100 ? '0' : '') + ms + "'";
}
static getFixedFormatDate(date) {
const year = date.getFullYear();
const mon = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const min = date.getMinutes();
const sec = date.getSeconds();
const ms = date.getMilliseconds();
let result =
"'" +
formatDigit(year, 4) +
'-' +
formatDigit(mon, 2) +
'-' +
formatDigit(day, 2) +
' ' +
formatDigit(hour, 2) +
':' +
formatDigit(min, 2) +
':' +
formatDigit(sec, 2);
if (ms > 0) {
result += '.' + formatDigit(ms, 3);
}
return result + "'";
}
}
module.exports = TextEncoder;
+61
View File
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Execute = require('./execute');
const { Readable } = require('stream');
/**
* Protocol COM_STMT_EXECUTE with streaming events.
* see : https://mariadb.com/kb/en/com_stmt_execute/
*/
class ExecuteStream extends Execute {
constructor(cmdParam, connOpts, prepare, socket) {
super(
() => {},
() => {},
connOpts,
cmdParam,
prepare
);
this.socket = socket;
this.inStream = new Readable({
objectMode: true,
read: () => {
this.socket.resume();
}
});
this.on('fields', function (meta) {
this.inStream.emit('fields', meta);
});
this.on('error', function (err) {
this.inStream.emit('error', err);
});
this.on('close', function (err) {
this.inStream.emit('error', err);
});
this.on('end', function (err) {
if (err) this.inStream.emit('error', err);
this.socket.resume();
this.inStream.push(null);
});
this.inStream.close = function () {
this.handleNewRows = () => {};
this.socket.resume();
}.bind(this);
}
handleNewRows(row) {
if (!this.inStream.push(row)) {
this.socket.pause();
}
}
}
module.exports = ExecuteStream;
+338
View File
@@ -0,0 +1,338 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Parser = require('./parser');
const Errors = require('../misc/errors');
const BinaryEncoder = require('./encoder/binary-encoder');
const FieldType = require('../const/field-type');
const Parse = require('../misc/parse');
/**
* Protocol COM_STMT_EXECUTE
* see : https://mariadb.com/kb/en/com_stmt_execute/
*/
class Execute extends Parser {
constructor(resolve, reject, connOpts, cmdParam, prepare) {
super(resolve, reject, connOpts, cmdParam);
this.binary = true;
this.prepare = prepare;
this.canSkipMeta = true;
}
/**
* Send COM_QUERY
*
* @param out output writer
* @param opts connection options
* @param info connection information
*/
start(out, opts, info) {
this.onPacketReceive = this.readResponsePacket;
this.values = [];
if (this.opts.namedPlaceholders) {
if (this.prepare) {
// using named placeholders, so change values accordingly
this.values = new Array(this.prepare.parameterCount);
this.placeHolderIndex = this.prepare._placeHolderIndex;
} else {
const res = Parse.searchPlaceholder(this.sql);
this.placeHolderIndex = res.placeHolderIndex;
this.values = new Array(this.placeHolderIndex.length);
}
if (this.initialValues) {
for (let i = 0; i < this.placeHolderIndex.length; i++) {
this.values[i] = this.initialValues[this.placeHolderIndex[i]];
}
}
} else {
if (this.initialValues)
this.values = Array.isArray(this.initialValues) ? this.initialValues : [this.initialValues];
}
this.parameterCount = this.prepare ? this.prepare.parameterCount : this.values.length;
if (!this.validateParameters(info)) return;
// fill parameter data type
this.parametersType = new Array(this.parameterCount);
let hasLongData = false; // send long data
let val;
for (let i = 0; i < this.parameterCount; i++) {
val = this.values[i];
// special check for GEOJSON that can be null even if object is not
if (
val &&
val.type != null &&
[
'Point',
'LineString',
'Polygon',
'MultiPoint',
'MultiLineString',
'MultiPolygon',
'GeometryCollection'
].includes(val.type)
) {
const geoBuff = BinaryEncoder.getBufferFromGeometryValue(val);
if (geoBuff == null) {
this.values[i] = null;
val = null;
} else {
this.values[i] = Buffer.concat([
Buffer.from([0, 0, 0, 0]), // SRID
geoBuff // WKB
]);
val = this.values[i];
}
}
if (val == null) {
this.parametersType[i] = NULL_PARAM_TYPE;
} else {
switch (typeof val) {
case 'boolean':
this.parametersType[i] = BOOLEAN_TYPE;
break;
case 'bigint':
if (val >= 2n ** 63n) {
this.parametersType[i] = BIG_BIGINT_TYPE;
} else {
this.parametersType[i] = BIGINT_TYPE;
}
break;
case 'number':
// additional verification, to permit query without type,
// like 'SELECT ?' returning same type of value
if (Number.isInteger(val) && val >= -2147483648 && val < 2147483647) {
this.parametersType[i] = INT_TYPE;
break;
}
this.parametersType[i] = DOUBLE_TYPE;
break;
case 'string':
this.parametersType[i] = STRING_TYPE;
break;
case 'object':
if (Object.prototype.toString.call(val) === '[object Date]') {
this.parametersType[i] = DATE_TYPE;
} else if (Buffer.isBuffer(val)) {
if (val.length < 16384 || !this.prepare) {
this.parametersType[i] = BLOB_TYPE;
} else {
this.parametersType[i] = LONGBLOB_TYPE;
hasLongData = true;
}
} else if (typeof val.toSqlString === 'function') {
this.parametersType[i] = STRING_FCT_TYPE;
} else if (typeof val.pipe === 'function' && typeof val.read === 'function') {
hasLongData = true;
this.parametersType[i] = STREAM_TYPE;
} else if (String === val.constructor) {
this.parametersType[i] = STRING_TOSTR_TYPE;
} else {
this.parametersType[i] = STRINGIFY_TYPE;
}
break;
}
}
}
// send long data using COM_STMT_SEND_LONG_DATA
this.longDataStep = false; // send long data
if (hasLongData) {
for (let i = 0; i < this.parameterCount; i++) {
if (this.parametersType[i].isLongData()) {
if (opts.logger.query)
opts.logger.query(
`EXECUTE: (${this.prepare ? this.prepare.id : -1}) sql: ${opts.logParam ? this.displaySql() : this.sql}`
);
if (!this.longDataStep) {
this.longDataStep = true;
this.registerStreamSendEvent(out, info);
this.currentParam = i;
}
this.sendComStmtLongData(out, info, this.values[i]);
return;
}
}
}
if (!this.longDataStep) {
// no stream parameter, so can send directly
if (opts.logger.query)
opts.logger.query(
`EXECUTE: (${this.prepare ? this.prepare.id : -1}) sql: ${opts.logParam ? this.displaySql() : this.sql}`
);
this.sendComStmtExecute(out, info);
}
}
/**
* Validate that parameters exists and are defined.
*
* @param info connection info
* @returns {boolean} return false if any error occur.
*/
validateParameters(info) {
//validate parameter size.
if (this.parameterCount > this.values.length) {
this.sendCancelled(
`Parameter at position ${this.values.length} is not set\\nsql: ${
this.opts.logParam ? this.displaySql() : this.sql
}`,
Errors.ER_MISSING_PARAMETER,
info
);
return false;
}
// validate placeholder
if (this.opts.namedPlaceholders && this.placeHolderIndex) {
for (let i = 0; i < this.parameterCount; i++) {
if (this.values[i] === undefined) {
let errMsg = `Parameter named ${this.placeHolderIndex[i]} is not set`;
if (this.placeHolderIndex.length < this.parameterCount) {
errMsg = `Command expect ${this.parameterCount} parameters, but found only ${this.placeHolderIndex.length} named parameters. You probably use question mark in place of named parameters`;
}
this.sendCancelled(errMsg, Errors.ER_PARAMETER_UNDEFINED, info);
return false;
}
}
}
return true;
}
sendComStmtLongData(out, info, value) {
out.startPacket(this);
out.writeInt8(0x18);
out.writeInt32(this.prepare.id);
out.writeInt16(this.currentParam);
if (Buffer.isBuffer(value)) {
out.writeBuffer(value, 0, value.length);
out.flush();
this.currentParam++;
return this.paramWritten();
}
this.sending = true;
// streaming
value.on('data', function (chunk) {
out.writeBuffer(chunk, 0, chunk.length);
});
value.on(
'end',
function () {
out.flush();
this.currentParam++;
this.paramWritten();
}.bind(this)
);
}
/**
* Send a COM_STMT_EXECUTE
* @param out
* @param info
*/
sendComStmtExecute(out, info) {
let nullCount = ~~((this.parameterCount + 7) / 8);
const nullBitsBuffer = Buffer.alloc(nullCount);
for (let i = 0; i < this.parameterCount; i++) {
if (this.values[i] == null) {
nullBitsBuffer[~~(i / 8)] |= 1 << i % 8;
}
}
out.startPacket(this);
out.writeInt8(0x17); // COM_STMT_EXECUTE
out.writeInt32(this.prepare ? this.prepare.id : -1); // Statement id
out.writeInt8(0); // no cursor flag
out.writeInt32(1); // 1 command
out.writeBuffer(nullBitsBuffer, 0, nullCount); // null buffer
out.writeInt8(1); // always send type to server
// send types
for (let i = 0; i < this.parameterCount; i++) {
out.writeInt8(this.parametersType[i].type);
out.writeInt8(0);
}
//********************************************
// send not null / not streaming values
//********************************************
for (let i = 0; i < this.parameterCount; i++) {
const parameterType = this.parametersType[i];
if (parameterType.encoder) parameterType.encoder(out, this.values[i]);
}
out.flush();
this.sending = false;
this.emit('send_end');
}
/**
* Define params events.
* Each parameter indicate that he is written to socket,
* emitting event so next stream parameter can be written.
*/
registerStreamSendEvent(out, info) {
// note : Implementation use recursive calls, but stack won't get near v8 max call stack size
//since event launched for stream parameter only
this.paramWritten = function () {
if (this.longDataStep) {
for (; this.currentParam < this.parameterCount; this.currentParam++) {
if (this.parametersType[this.currentParam].isLongData()) {
const value = this.values[this.currentParam];
this.sendComStmtLongData(out, info, value);
return;
}
}
this.longDataStep = false; // all streams have been send
}
if (!this.longDataStep) {
this.sendComStmtExecute(out, info);
}
}.bind(this);
}
}
class ParameterType {
constructor(type, encoder, pipe = false, isNull = false) {
this.pipe = pipe;
this.type = type;
this.encoder = encoder;
this.isNull = isNull;
}
isLongData() {
return this.encoder === null && !this.isNull;
}
}
const NULL_PARAM_TYPE = new ParameterType(FieldType.VAR_STRING, null, false, true);
const BOOLEAN_TYPE = new ParameterType(FieldType.TINY, (out, value) => out.writeInt8(value ? 0x01 : 0x00));
const BIG_BIGINT_TYPE = new ParameterType(FieldType.NEWDECIMAL, (out, value) =>
out.writeLengthEncodedString(value.toString())
);
const BIGINT_TYPE = new ParameterType(FieldType.BIGINT, (out, value) => out.writeBigInt(value));
const INT_TYPE = new ParameterType(FieldType.INT, (out, value) => out.writeInt32(value));
const DOUBLE_TYPE = new ParameterType(FieldType.DOUBLE, (out, value) => out.writeDouble(value));
const STRING_TYPE = new ParameterType(FieldType.VAR_STRING, (out, value) => out.writeLengthEncodedString(value));
const STRING_TOSTR_TYPE = new ParameterType(FieldType.VAR_STRING, (out, value) =>
out.writeLengthEncodedString(value.toString())
);
const DATE_TYPE = new ParameterType(FieldType.DATETIME, (out, value) => out.writeBinaryDate(value));
const BLOB_TYPE = new ParameterType(FieldType.BLOB, (out, value) => out.writeLengthEncodedBuffer(value));
const LONGBLOB_TYPE = new ParameterType(FieldType.BLOB, null);
const STRING_FCT_TYPE = new ParameterType(FieldType.VAR_STRING, (out, value) =>
out.writeLengthEncodedString(String(value.toSqlString()))
);
const STREAM_TYPE = new ParameterType(FieldType.BLOB, null, true);
const STRINGIFY_TYPE = new ParameterType(FieldType.VAR_STRING, (out, value) =>
out.writeLengthEncodedString(JSON.stringify(value))
);
module.exports = Execute;
@@ -0,0 +1,131 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
const PluginAuth = require('./plugin-auth');
const fs = require('fs');
const Errors = require('../../../misc/errors');
const Sha256PasswordAuth = require('./sha256-password-auth');
const State = {
INIT: 'INIT',
FAST_AUTH_RESULT: 'FAST_AUTH_RESULT',
REQUEST_SERVER_KEY: 'REQUEST_SERVER_KEY',
SEND_AUTH: 'SEND_AUTH'
};
/**
* Use caching Sha2 password authentication
*/
class CachingSha2PasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.multiAuthResolver = multiAuthResolver;
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
this.counter = 0;
this.state = State.INIT;
}
start(out, opts, info) {
this.exchange(this.pluginData, out, opts, info);
this.onPacketReceive = this.response;
}
exchange(packet, out, opts, info) {
switch (this.state) {
case State.INIT:
const truncatedSeed = this.pluginData.slice(0, this.pluginData.length - 1);
const encPwd = Sha256PasswordAuth.encryptSha256Password(opts.password, truncatedSeed);
out.startPacket(this);
if (encPwd.length > 0) {
out.writeBuffer(encPwd, 0, encPwd.length);
out.flushPacket();
} else {
out.writeEmptyPacket(true);
}
this.state = State.FAST_AUTH_RESULT;
return;
case State.FAST_AUTH_RESULT:
// length encoded numeric : 0x01 0x03/0x04
const fastAuthResult = packet[1];
switch (fastAuthResult) {
case 0x03:
// success authentication
// an OK_Packet will follow
return;
case 0x04:
if (opts.ssl) {
// using SSL, so sending password in clear
out.startPacket(this);
out.writeString(opts.password);
out.writeInt8(0);
out.flushPacket();
return;
}
// retrieve public key from configuration or from server
if (opts.cachingRsaPublicKey) {
try {
let key = opts.cachingRsaPublicKey;
if (!key.includes('-----BEGIN')) {
// rsaPublicKey contain path
key = fs.readFileSync(key, 'utf8');
}
this.publicKey = Sha256PasswordAuth.retrievePublicKey(key);
} catch (err) {
return this.throwError(err, info);
}
// send Sha256Password Packet
Sha256PasswordAuth.sendSha256PwdPacket(this, this.pluginData, this.publicKey, opts.password, out);
} else {
if (!opts.allowPublicKeyRetrieval) {
return this.throwError(
Errors.createFatalError(
'RSA public key is not available client side. Either set option `cachingRsaPublicKey` to indicate' +
' public key path, or allow public key retrieval with option `allowPublicKeyRetrieval`',
Errors.ER_CANNOT_RETRIEVE_RSA_KEY,
info
),
info
);
}
this.state = State.REQUEST_SERVER_KEY;
// ask caching public Key Retrieval
out.startPacket(this);
out.writeInt8(0x02);
out.flushPacket();
}
}
return;
case State.REQUEST_SERVER_KEY:
this.publicKey = Sha256PasswordAuth.retrievePublicKey(packet.toString(undefined, 1));
this.state = State.SEND_AUTH;
Sha256PasswordAuth.sendSha256PwdPacket(this, this.pluginData, this.publicKey, opts.password, out);
return;
}
}
response(packet, out, opts, info) {
const marker = packet.peek();
switch (marker) {
//*********************************************************************************************************
//* OK_Packet and Err_Packet ending packet
//*********************************************************************************************************
case 0x00:
case 0xff:
this.emit('send_end');
return this.multiAuthResolver(packet, out, opts, info);
default:
let promptData = packet.readBufferRemaining();
this.exchange(promptData, out, opts, info);
this.onPacketReceive = this.response;
}
}
}
module.exports = CachingSha2PasswordAuth;
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
const PluginAuth = require('./plugin-auth');
/**
* Send password in clear.
* (used only when SSL is active)
*/
class ClearPasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
this.counter = 0;
this.multiAuthResolver = multiAuthResolver;
}
start(out, opts, info) {
out.startPacket(this);
const pwd = opts.password;
if (pwd) {
if (Array.isArray(pwd)) {
out.writeString(pwd[this.counter++]);
} else {
out.writeString(pwd);
}
}
out.writeInt8(0);
out.flushPacket();
this.onPacketReceive = this.response;
}
response(packet, out, opts, info) {
const marker = packet.peek();
switch (marker) {
//*********************************************************************************************************
//* OK_Packet and Err_Packet ending packet
//*********************************************************************************************************
case 0x00:
case 0xff:
this.emit('send_end');
return this.multiAuthResolver(packet, out, opts, info);
default:
packet.readBuffer(); // prompt
out.startPacket(this);
out.writeString('password');
out.writeInt8(0);
out.flushPacket();
}
}
}
module.exports = ClearPasswordAuth;
@@ -0,0 +1,793 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const PluginAuth = require('./plugin-auth');
const Crypto = require('crypto');
/**
* Standard authentication plugin
*/
class Ed25519PasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
}
start(out, opts, info) {
//seed is ended with a null byte value.
const data = this.pluginData;
const sign = Ed25519PasswordAuth.encryptPassword(opts.password, data);
out.startPacket(this);
out.writeBuffer(sign, 0, sign.length);
out.flushPacket();
this.emit('send_end');
}
static encryptPassword(password, seed) {
if (!password) return Buffer.alloc(0);
let i, j;
let p = [gf(), gf(), gf(), gf()];
const signedMsg = Buffer.alloc(96);
const bytePwd = Buffer.from(password);
let hash = Crypto.createHash('sha512');
const d = hash.update(bytePwd).digest();
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
for (i = 0; i < 32; i++) signedMsg[64 + i] = seed[i];
for (i = 0; i < 32; i++) signedMsg[32 + i] = d[32 + i];
hash = Crypto.createHash('sha512');
const r = hash.update(signedMsg.subarray(32, 96)).digest();
reduce(r);
scalarbase(p, r);
pack(signedMsg, p);
p = [gf(), gf(), gf(), gf()];
scalarbase(p, d);
const tt = Buffer.alloc(32);
pack(tt, p);
for (i = 32; i < 64; i++) signedMsg[i] = tt[i - 32];
hash = Crypto.createHash('sha512');
const h = hash.update(signedMsg).digest();
reduce(h);
const x = new Float64Array(64);
for (i = 0; i < 64; i++) x[i] = 0;
for (i = 0; i < 32; i++) x[i] = r[i];
for (i = 0; i < 32; i++) {
for (j = 0; j < 32; j++) {
x[i + j] += h[i] * d[j];
}
}
modL(signedMsg.subarray(32), x);
return signedMsg.subarray(0, 64);
}
permitHash() {
return true;
}
hash(conf) {
let i;
let p = [gf(), gf(), gf(), gf()];
const signedMsg = Buffer.alloc(96);
const bytePwd = Buffer.from(conf.password);
let hash = Crypto.createHash('sha512');
const d = hash.update(bytePwd).digest();
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
for (i = 0; i < 32; i++) signedMsg[64 + i] = seed[i];
for (i = 0; i < 32; i++) signedMsg[32 + i] = d[32 + i];
hash = Crypto.createHash('sha512');
const r = hash.update(signedMsg.subarray(32, 96)).digest();
reduce(r);
scalarbase(p, r);
return r;
}
}
/*******************************************************
*
* This plugin uses the following public domain tweetnacl-js code by Dmitry Chestnykh
* (from https://github.com/dchest/tweetnacl-js/blob/master/nacl-fast.js).
* tweetnacl cannot be used directly (secret key mandatory size is 32 in nacl + implementation differ :
* second scalarbase use hash of secret key, not secret key).
*
*******************************************************/
const gf = function (init) {
const r = new Float64Array(16);
if (init) for (let i = 0; i < init.length; i++) r[i] = init[i];
return r;
};
const gf0 = gf(),
gf1 = gf([1]),
D2 = gf([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df,
0xd9dc, 0x2406
]),
X = gf([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e,
0x36d3, 0x2169
]),
Y = gf([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666
]);
const L = new Float64Array([
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0x10
]);
function reduce(r) {
const x = new Float64Array(64);
let i;
for (i = 0; i < 64; i++) x[i] = r[i];
for (i = 0; i < 64; i++) r[i] = 0;
modL(r, x);
}
function modL(r, x) {
let carry, i, j, k;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32, k = i - 12; j < k; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = (x[j] + 128) >> 8;
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; j++) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; j++) x[j] -= carry * L[j];
for (i = 0; i < 32; i++) {
x[i + 1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function scalarbase(p, s) {
const q = [gf(), gf(), gf(), gf()];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
M(q[3], X, Y);
scalarmult(p, q, s);
}
function set25519(r, a) {
for (let i = 0; i < 16; i++) r[i] = a[i] | 0;
}
function M(o, a, b) {
let v,
c,
t0 = 0,
t1 = 0,
t2 = 0,
t3 = 0,
t4 = 0,
t5 = 0,
t6 = 0,
t7 = 0,
t8 = 0,
t9 = 0,
t10 = 0,
t11 = 0,
t12 = 0,
t13 = 0,
t14 = 0,
t15 = 0,
t16 = 0,
t17 = 0,
t18 = 0,
t19 = 0,
t20 = 0,
t21 = 0,
t22 = 0,
t23 = 0,
t24 = 0,
t25 = 0,
t26 = 0,
t27 = 0,
t28 = 0,
t29 = 0,
t30 = 0;
const b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
// second car
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function scalarmult(p, q, s) {
let b, i;
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for (i = 255; i >= 0; --i) {
b = (s[(i / 8) | 0] >> (i & 7)) & 1;
cswap(p, q, b);
add(q, p);
add(p, p);
cswap(p, q, b);
}
}
function pack(r, p) {
const tx = gf(),
ty = gf(),
zi = gf();
inv25519(zi, p[2]);
M(tx, p[0], zi);
M(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function inv25519(o, i) {
const c = gf();
let a;
for (a = 0; a < 16; a++) c[a] = i[a];
for (a = 253; a >= 0; a--) {
S(c, c);
if (a !== 2 && a !== 4) M(c, c, i);
}
for (a = 0; a < 16; a++) o[a] = c[a];
}
function S(o, a) {
M(o, a, a);
}
function par25519(a) {
const d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function car25519(o) {
let i,
v,
c = 1;
for (i = 0; i < 16; i++) {
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function pack25519(o, n) {
let i, j, b;
const m = gf(),
t = gf();
for (i = 0; i < 16; i++) t[i] = n[i];
car25519(t);
car25519(t);
car25519(t);
for (j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (i = 0; i < 16; i++) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function cswap(p, q, b) {
for (let i = 0; i < 4; i++) {
sel25519(p[i], q[i], b);
}
}
function A(o, a, b) {
for (let i = 0; i < 16; i++) o[i] = a[i] + b[i];
}
function Z(o, a, b) {
for (let i = 0; i < 16; i++) o[i] = a[i] - b[i];
}
function add(p, q) {
const a = gf(),
b = gf(),
c = gf(),
d = gf(),
e = gf(),
f = gf(),
g = gf(),
h = gf(),
t = gf();
Z(a, p[1], p[0]);
Z(t, q[1], q[0]);
M(a, a, t);
A(b, p[0], p[1]);
A(t, q[0], q[1]);
M(b, b, t);
M(c, p[3], q[3]);
M(c, c, D2);
M(d, p[2], q[2]);
A(d, d, d);
Z(e, b, a);
Z(f, d, c);
A(g, d, c);
A(h, b, a);
M(p[0], e, f);
M(p[1], h, g);
M(p[2], g, f);
M(p[3], e, h);
}
function sel25519(p, q, b) {
const c = ~(b - 1);
let t;
for (let i = 0; i < 16; i++) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
module.exports = Ed25519PasswordAuth;
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
const PluginAuth = require('./plugin-auth');
const InitialHandshake = require('./initial-handshake');
const ClientCapabilities = require('../client-capabilities');
const Capabilities = require('../../../const/capabilities');
const SslRequest = require('../ssl-request');
const Errors = require('../../../misc/errors');
const NativePasswordAuth = require('./native-password-auth');
const os = require('os');
const Iconv = require('iconv-lite');
const Crypto = require('crypto');
const driverVersion = require('../../../../package.json').version;
/**
* Handshake response
*/
class Handshake extends PluginAuth {
constructor(auth, getSocket, multiAuthResolver, reject) {
super(null, multiAuthResolver, reject);
this.sequenceNo = 0;
this.compressSequenceNo = 0;
this.auth = auth;
this.getSocket = getSocket;
this.counter = 0;
this.onPacketReceive = this.parseHandshakeInit;
}
start(out, opts, info) {}
parseHandshakeInit(packet, out, opts, info) {
if (packet.peek() === 0xff) {
//in case that some host is not permit to connect server
const authErr = packet.readError(info);
authErr.fatal = true;
return this.throwError(authErr, info);
}
let handshake = new InitialHandshake(packet, info);
ClientCapabilities.init(opts, info);
this.pluginName = handshake.pluginName;
if (opts.ssl) {
if (info.serverCapabilities & Capabilities.SSL) {
info.clientCapabilities |= Capabilities.SSL;
SslRequest.send(this, out, info, opts);
this.auth._createSecureContext(info, () => {
// mark self-signed error only if was not explicitly forced
const secureSocket = this.getSocket();
info.selfSignedCertificate = !secureSocket.authorized;
info.tlsAuthorizationError = secureSocket.authorizationError;
const serverCert = secureSocket.getPeerCertificate(false);
info.tlsCert = serverCert;
info.tlsFingerprint = serverCert ? serverCert.fingerprint256.replace(/:/gi, '').toLowerCase() : null;
Handshake.send.call(this, this, out, opts, handshake.pluginName, info);
});
} else {
return this.throwNewError(
'Trying to connect with ssl, but ssl not enabled in the server',
true,
info,
'08S01',
Errors.ER_SERVER_SSL_DISABLED
);
}
} else {
Handshake.send(this, out, opts, handshake.pluginName, info);
}
this.onPacketReceive = this.auth.handshakeResult.bind(this.auth);
}
permitHash() {
return this.pluginName !== 'mysql_clear_password';
}
hash(conf) {
// mysql_native_password hash
let hash = Crypto.createHash('sha1');
let stage1 = hash.update(conf.password, 'utf8').digest();
hash = Crypto.createHash('sha1');
return hash.update(stage1).digest();
}
/**
* Send Handshake response packet
* see https://mariadb.com/kb/en/library/1-connecting-connecting/#handshake-response-packet
*
* @param cmd current handshake command
* @param out output writer
* @param opts connection options
* @param pluginName plugin name
* @param info connection information
*/
static send(cmd, out, opts, pluginName, info) {
out.startPacket(cmd);
info.defaultPluginName = pluginName;
const pwd = Array.isArray(opts.password) ? opts.password[0] : opts.password;
let authToken;
let authPlugin;
switch (pluginName) {
case 'mysql_clear_password':
authToken = Buffer.from(pwd);
authPlugin = 'mysql_clear_password';
break;
default:
authToken = NativePasswordAuth.encryptSha1Password(pwd, info.seed);
authPlugin = 'mysql_native_password';
break;
}
out.writeInt32(Number(info.clientCapabilities & BigInt(0xffffffff)));
out.writeInt32(1024 * 1024 * 1024); // max packet size
// if collation and id < 255, set it directly
// is not, additional command SET NAMES xx [COLLATE yy] will be issued
out.writeInt8(opts.collation && opts.collation.index <= 255 ? opts.collation.index : 224);
for (let i = 0; i < 19; i++) {
out.writeInt8(0);
}
out.writeInt32(Number(info.clientCapabilities >> 32n));
//null encoded user
out.writeString(opts.user || '');
out.writeInt8(0);
if (info.serverCapabilities & Capabilities.PLUGIN_AUTH_LENENC_CLIENT_DATA) {
out.writeLengthCoded(authToken.length);
out.writeBuffer(authToken, 0, authToken.length);
} else if (info.serverCapabilities & Capabilities.SECURE_CONNECTION) {
out.writeInt8(authToken.length);
out.writeBuffer(authToken, 0, authToken.length);
} else {
out.writeBuffer(authToken, 0, authToken.length);
out.writeInt8(0);
}
if (info.clientCapabilities & Capabilities.CONNECT_WITH_DB) {
out.writeString(opts.database);
out.writeInt8(0);
info.database = opts.database;
}
if (info.clientCapabilities & Capabilities.PLUGIN_AUTH) {
out.writeString(authPlugin);
out.writeInt8(0);
}
if (info.clientCapabilities & Capabilities.CONNECT_ATTRS) {
out.writeInt8(0xfc);
let initPos = out.pos; //save position, assuming connection attributes length will be less than 2 bytes length
out.writeInt16(0);
const encoding = info.collation ? info.collation.charset : 'utf8';
Handshake.writeAttribute(out, '_client_name', encoding);
Handshake.writeAttribute(out, 'MariaDB connector/Node', encoding);
Handshake.writeAttribute(out, '_client_version', encoding);
Handshake.writeAttribute(out, driverVersion, encoding);
const address = cmd.getSocket().address().address;
if (address) {
Handshake.writeAttribute(out, '_server_host', encoding);
Handshake.writeAttribute(out, address, encoding);
}
Handshake.writeAttribute(out, '_os', encoding);
Handshake.writeAttribute(out, process.platform, encoding);
Handshake.writeAttribute(out, '_client_host', encoding);
Handshake.writeAttribute(out, os.hostname(), encoding);
Handshake.writeAttribute(out, '_node_version', encoding);
Handshake.writeAttribute(out, process.versions.node, encoding);
if (opts.connectAttributes !== true) {
let attrNames = Object.keys(opts.connectAttributes);
for (let k = 0; k < attrNames.length; ++k) {
Handshake.writeAttribute(out, attrNames[k], encoding);
Handshake.writeAttribute(out, opts.connectAttributes[attrNames[k]], encoding);
}
}
//write end size
out.writeInt16AtPos(initPos);
}
out.flushPacket();
}
static writeAttribute(out, val, encoding) {
let param = Buffer.isEncoding(encoding) ? Buffer.from(val, encoding) : Iconv.encode(val, encoding);
out.writeLengthCoded(param.length);
out.writeBuffer(param, 0, param.length);
}
}
module.exports = Handshake;
@@ -0,0 +1,76 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Capabilities = require('../../../const/capabilities');
const Collations = require('../../../const/collations');
const ConnectionInformation = require('../../../misc/connection-information');
/**
* Parser server initial handshake.
* see https://mariadb.com/kb/en/library/1-connecting-connecting/#initial-handshake-packet
*/
class InitialHandshake {
constructor(packet, info) {
//protocolVersion
packet.skip(1);
info.serverVersion = {};
info.serverVersion.raw = packet.readStringNullEnded();
info.threadId = packet.readUInt32();
let seed1 = packet.readBuffer(8);
packet.skip(1); //reserved byte
let serverCapabilities = BigInt(packet.readUInt16());
info.collation = Collations.fromIndex(packet.readUInt8());
info.status = packet.readUInt16();
serverCapabilities += BigInt(packet.readUInt16()) << 16n;
let saltLength = 0;
if (serverCapabilities & Capabilities.PLUGIN_AUTH) {
saltLength = Math.max(12, packet.readUInt8() - 9);
} else {
packet.skip(1);
}
if (serverCapabilities & Capabilities.MYSQL) {
packet.skip(10);
} else {
packet.skip(6);
serverCapabilities += BigInt(packet.readUInt32()) << 32n;
}
if (serverCapabilities & Capabilities.SECURE_CONNECTION) {
let seed2 = packet.readBuffer(saltLength);
info.seed = Buffer.concat([seed1, seed2]);
} else {
info.seed = seed1;
}
packet.skip(1);
info.serverCapabilities = serverCapabilities;
/**
* check for MariaDB 10.x replication hack , remove fake prefix if needed
* MDEV-4088: in 10.0+, the real version string maybe prefixed with "5.5.5-",
* to workaround bugs in Oracle MySQL replication
**/
if (info.serverVersion.raw.startsWith('5.5.5-')) {
info.serverVersion.mariaDb = true;
info.serverVersion.raw = info.serverVersion.raw.substring('5.5.5-'.length);
} else {
//Support for MDEV-7780 faking server version
info.serverVersion.mariaDb =
info.serverVersion.raw.includes('MariaDB') || (serverCapabilities & Capabilities.MYSQL) === 0n;
}
if (serverCapabilities & Capabilities.PLUGIN_AUTH) {
this.pluginName = packet.readStringNullEnded();
} else {
this.pluginName = '';
}
ConnectionInformation.parseVersionString(info);
}
}
module.exports = InitialHandshake;
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const PluginAuth = require('./plugin-auth');
const Crypto = require('crypto');
/**
* Standard authentication plugin
*/
class NativePasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
}
start(out, opts, info) {
//seed is ended with a null byte value.
const data = this.pluginData.slice(0, 20);
let authToken = NativePasswordAuth.encryptSha1Password(opts.password, data);
out.startPacket(this);
if (authToken.length > 0) {
out.writeBuffer(authToken, 0, authToken.length);
out.flushPacket();
} else {
out.writeEmptyPacket(true);
}
this.emit('send_end');
}
static encryptSha1Password(password, seed) {
if (!password) return Buffer.alloc(0);
let hash = Crypto.createHash('sha1');
let stage1 = hash.update(password, 'utf8').digest();
hash = Crypto.createHash('sha1');
let stage2 = hash.update(stage1).digest();
hash = Crypto.createHash('sha1');
hash.update(seed);
hash.update(stage2);
let digest = hash.digest();
let returnBytes = Buffer.allocUnsafe(digest.length);
for (let i = 0; i < digest.length; i++) {
returnBytes[i] = stage1[i] ^ digest[i];
}
return returnBytes;
}
permitHash() {
return true;
}
hash(conf) {
let hash = Crypto.createHash('sha1');
let stage1 = hash.update(conf.password, 'utf8').digest();
hash = Crypto.createHash('sha1');
return hash.update(stage1).digest();
}
}
module.exports = NativePasswordAuth;
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
const PluginAuth = require('./plugin-auth');
/**
* Use PAM authentication
*/
class PamPasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
this.counter = 0;
this.multiAuthResolver = multiAuthResolver;
}
start(out, opts, info) {
this.exchange(this.pluginData, out, opts, info);
this.onPacketReceive = this.response;
}
exchange(buffer, out, opts, info) {
//conversation is :
// - first byte is information tell if question is a password (4) or clear text (2).
// - other bytes are the question to user
out.startPacket(this);
let pwd;
if (Array.isArray(opts.password)) {
pwd = opts.password[this.counter];
this.counter++;
} else {
pwd = opts.password;
}
if (pwd) out.writeString(pwd);
out.writeInt8(0);
out.flushPacket();
}
response(packet, out, opts, info) {
const marker = packet.peek();
switch (marker) {
//*********************************************************************************************************
//* OK_Packet and Err_Packet ending packet
//*********************************************************************************************************
case 0x00:
case 0xff:
this.emit('send_end');
return this.multiAuthResolver(packet, out, opts, info);
default:
let promptData = packet.readBuffer();
this.exchange(promptData, out, opts, info);
this.onPacketReceive = this.response;
}
}
}
module.exports = PamPasswordAuth;
@@ -0,0 +1,115 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2025 MariaDB Corporation Ab
'use strict';
const PluginAuth = require('./plugin-auth');
const crypto = require('crypto');
const Errors = require('../../../misc/errors');
const pkcs8Ed25519header = Buffer.from([
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20
]);
/**
* Standard authentication plugin
*/
class ParsecAuth extends PluginAuth {
#hash;
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.multiAuthResolver = multiAuthResolver;
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
}
start(out, opts, info) {
if (!info.extSalt) {
out.startPacket(this);
out.writeEmptyPacket(true); // indicate need salt
this.onPacketReceive = this.requestForSalt;
} else {
this.parseExtSalt(Buffer.from(info.extSalt, 'hex'), info);
this.sendScramble(out, opts, info);
}
}
requestForSalt(packet, out, opts, info) {
this.parseExtSalt(packet.readBufferRemaining(), info);
this.sendScramble(out, opts, info);
}
parseExtSalt(extSalt, info) {
if (extSalt.length < 2 || extSalt[0] !== 0x50 || extSalt[1] > 3) {
// expected 'P' for KDF algorithm (PBKDF2) and maximum iteration of 8192
return this.throwError(
Errors.createFatalError('Wrong parsec authentication format', Errors.ER_AUTHENTICATION_BAD_PACKET, info),
info
);
}
this.iterations = extSalt[1];
this.salt = extSalt.slice(2);
// disable for now until https://jira.mariadb.org/browse/MDEV-34846
// info.extSalt = extSalt.toString('hex');
}
sendScramble(out, opts, info) {
const derivedKey = crypto.pbkdf2Sync(opts.password || '', this.salt, 1024 << this.iterations, 32, 'sha512');
const privateKey = toPkcs8der(derivedKey);
const rawPublicKey = this.getEd25519PublicKeyFromPrivateKey(derivedKey);
this.#hash = Buffer.concat([Buffer.from([0x50, this.iterations]), this.salt, rawPublicKey]);
const client_scramble = crypto.randomBytes(32);
const message = Buffer.concat([this.pluginData, client_scramble]);
const signature = crypto.sign(null, message, privateKey);
out.startPacket(this);
out.writeBuffer(client_scramble, 0, 32);
out.writeBuffer(signature, 0, 64);
out.flushPacket();
this.emit('send_end');
this.onPacketReceive = this.multiAuthResolver;
}
getEd25519PublicKeyFromPrivateKey(privateKeyBuffer) {
// Create a KeyObject from the raw private key
const privateKey = crypto.createPrivateKey({
key: Buffer.concat([pkcs8Ed25519header, privateKeyBuffer]),
format: 'der',
type: 'pkcs8',
name: 'ed25519'
});
// Get the corresponding public key
const publicKey = crypto.createPublicKey(privateKey);
// Export the public key in raw format
return publicKey
.export({
type: 'spki',
format: 'der'
})
.subarray(-32); // The last 32 bytes contain the raw key
}
permitHash() {
return true;
}
hash(conf) {
return this.#hash;
}
}
const toPkcs8der = (rawB64) => {
// prefix for a private Ed25519
const prefixPrivateEd25519 = Buffer.from('302e020100300506032b657004220420', 'hex');
const der = Buffer.concat([prefixPrivateEd25519, rawB64]);
return crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
};
module.exports = ParsecAuth;
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Command = require('../../command');
/**
* Base authentication plugin
*/
class PluginAuth extends Command {
constructor(cmdParam, multiAuthResolver, reject) {
super(cmdParam, multiAuthResolver, reject);
this.onPacketReceive = multiAuthResolver;
}
permitHash() {
return true;
}
hash(conf) {
return null;
}
}
module.exports = PluginAuth;
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
const PluginAuth = require('./plugin-auth');
const fs = require('fs');
const crypto = require('crypto');
const Errors = require('../../../misc/errors');
const Crypto = require('crypto');
/**
* Use Sha256 authentication
*/
class Sha256PasswordAuth extends PluginAuth {
constructor(packSeq, compressPackSeq, pluginData, cmdParam, reject, multiAuthResolver) {
super(cmdParam, multiAuthResolver, reject);
this.pluginData = pluginData;
this.sequenceNo = packSeq;
this.compressSequenceNo = compressPackSeq;
this.counter = 0;
this.counter = 0;
this.initialState = true;
this.multiAuthResolver = multiAuthResolver;
}
start(out, opts, info) {
this.exchange(this.pluginData, out, opts, info);
this.onPacketReceive = this.response;
}
exchange(buffer, out, opts, info) {
if (this.initialState) {
if (!opts.password) {
out.startPacket(this);
out.writeEmptyPacket(true);
return;
} else if (opts.ssl) {
// using SSL, so sending password in clear
out.startPacket(this);
if (opts.password) {
out.writeString(opts.password);
}
out.writeInt8(0);
out.flushPacket();
return;
} else {
// retrieve public key from configuration or from server
if (opts.rsaPublicKey) {
try {
let key = opts.rsaPublicKey;
if (!key.includes('-----BEGIN')) {
// rsaPublicKey contain path
key = fs.readFileSync(key, 'utf8');
}
this.publicKey = Sha256PasswordAuth.retrievePublicKey(key);
} catch (err) {
return this.throwError(err, info);
}
} else {
if (!opts.allowPublicKeyRetrieval) {
return this.throwError(
Errors.createFatalError(
'RSA public key is not available client side. Either set option `rsaPublicKey` to indicate' +
' public key path, or allow public key retrieval with option `allowPublicKeyRetrieval`',
Errors.ER_CANNOT_RETRIEVE_RSA_KEY,
info
),
info
);
}
this.initialState = false;
// ask public Key Retrieval
out.startPacket(this);
out.writeInt8(0x01);
out.flushPacket();
return;
}
}
// send Sha256Password Packet
Sha256PasswordAuth.sendSha256PwdPacket(this, this.pluginData, this.publicKey, opts.password, out);
} else {
// has request public key
this.publicKey = Sha256PasswordAuth.retrievePublicKey(buffer.toString('utf8', 1));
Sha256PasswordAuth.sendSha256PwdPacket(this, this.pluginData, this.publicKey, opts.password, out);
}
}
static retrievePublicKey(key) {
return key.replace('(-+BEGIN PUBLIC KEY-+\\r?\\n|\\n?-+END PUBLIC KEY-+\\r?\\n?)', '');
}
static sendSha256PwdPacket(cmd, pluginData, publicKey, password, out) {
const truncatedSeed = pluginData.slice(0, pluginData.length - 1);
out.startPacket(cmd);
const enc = Sha256PasswordAuth.encrypt(truncatedSeed, password, publicKey);
out.writeBuffer(enc, 0, enc.length);
out.flushPacket();
}
static encryptSha256Password(password, seed) {
if (!password) return Buffer.alloc(0);
let hash = Crypto.createHash('sha256');
let stage1 = hash.update(password, 'utf8').digest();
hash = Crypto.createHash('sha256');
let stage2 = hash.update(stage1).digest();
hash = Crypto.createHash('sha256');
// order is different from sha 1 !!!!!
hash.update(stage2);
hash.update(seed);
let digest = hash.digest();
let returnBytes = Buffer.allocUnsafe(digest.length);
for (let i = 0; i < digest.length; i++) {
returnBytes[i] = stage1[i] ^ digest[i];
}
return returnBytes;
}
// encrypt password with public key
static encrypt(seed, password, publicKey) {
const nullFinishedPwd = Buffer.from(password + '\0');
const xorBytes = Buffer.allocUnsafe(nullFinishedPwd.length);
const seedLength = seed.length;
for (let i = 0; i < xorBytes.length; i++) {
xorBytes[i] = nullFinishedPwd[i] ^ seed[i % seedLength];
}
return crypto.publicEncrypt({ key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }, xorBytes);
}
response(packet, out, opts, info) {
const marker = packet.peek();
switch (marker) {
//*********************************************************************************************************
//* OK_Packet and Err_Packet ending packet
//*********************************************************************************************************
case 0x00:
case 0xff:
this.emit('send_end');
return this.multiAuthResolver(packet, out, opts, info);
default:
let promptData = packet.readBufferRemaining();
this.exchange(promptData, out, opts, info);
this.onPacketReceive = this.response;
}
}
}
module.exports = Sha256PasswordAuth;
@@ -0,0 +1,335 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2025 MariaDB Corporation Ab
'use strict';
const Command = require('../command');
const Errors = require('../../misc/errors');
const Capabilities = require('../../const/capabilities');
const Handshake = require('./auth/handshake');
const ServerStatus = require('../../const/server-status');
const StateChange = require('../../const/state-change');
const Collations = require('../../const/collations');
const Crypto = require('crypto');
const utils = require('../../misc/utils');
const tls = require('tls');
const authenticationPlugins = {
mysql_native_password: require('./auth/native-password-auth.js'),
mysql_clear_password: require('./auth/clear-password-auth'),
client_ed25519: require('./auth/ed25519-password-auth'),
parsec: require('./auth/parsec-auth'),
dialog: require('./auth/pam-password-auth'),
sha256_password: require('./auth/sha256-password-auth'),
caching_sha2_password: require('./auth/caching-sha2-password-auth')
};
/**
* Handle handshake.
* see https://mariadb.com/kb/en/library/1-connecting-connecting/
*/
class Authentication extends Command {
constructor(cmdParam, resolve, reject, _createSecureContext, getSocket) {
super(cmdParam, resolve, reject);
this.cmdParam = cmdParam;
this._createSecureContext = _createSecureContext;
this.getSocket = getSocket;
this.plugin = new Handshake(this, getSocket, this.handshakeResult, reject);
}
onPacketReceive(packet, out, opts, info) {
this.plugin.sequenceNo = this.sequenceNo;
this.plugin.compressSequenceNo = this.compressSequenceNo;
this.plugin.onPacketReceive(packet, out, opts, info);
}
/**
* Fast-path handshake results :
* - if plugin was the one expected by server, server will send OK_Packet / ERR_Packet.
* - if not, server send an AuthSwitchRequest packet, indicating the specific PLUGIN to use with this user.
* dispatching to plugin handler then.
*
* @param packet current packet
* @param out output buffer
* @param opts options
* @param info connection info
* @returns {*} return null if authentication succeed, depending on plugin conversation if not finished
*/
handshakeResult(packet, out, opts, info) {
const marker = packet.peek();
switch (marker) {
//*********************************************************************************************************
//* AuthSwitchRequest packet
//*********************************************************************************************************
case 0xfe:
this.dispatchAuthSwitchRequest(packet, out, opts, info);
return;
//*********************************************************************************************************
//* OK_Packet - authentication succeeded
//*********************************************************************************************************
case 0x00:
this.plugin.onPacketReceive = null;
packet.skip(1); //skip header
packet.skipLengthCodedNumber(); //skip affected rows
packet.skipLengthCodedNumber(); //skip last insert id
info.status = packet.readUInt16();
if (info.requireValidCert) {
if (info.selfSignedCertificate) {
// TLS was forced to trust, and certificate validation is required
packet.skip(2); //skip warning count
if (packet.remaining()) {
const validationHash = packet.readBufferLengthEncoded();
if (validationHash.length > 0) {
if (!this.plugin.permitHash() || !Boolean(this.cmdParam.opts.password)) {
return this.throwNewError(
'Self signed certificates. Either set `ssl: { rejectUnauthorized: false }` (trust mode) or provide server certificate to client',
true,
info,
'08000',
Errors.ER_SELF_SIGNED_NO_PWD
);
}
if (this.validateFingerPrint(validationHash, info)) {
return this.successEnd();
}
}
}
return this.throwNewError('self-signed certificate', true, info, '08000', Errors.ER_SELF_SIGNED);
} else {
// certificate is not self signed, validate server identity
const validationFunction =
opts.ssl === true || opts.ssl.checkServerIdentity === null
? tls.checkServerIdentity
: opts.ssl.checkServerIdentity;
const identityError = validationFunction(
typeof opts.ssl === 'object' && opts.ssl.servername ? opts.ssl.servername : opts.host,
info.tlsCert
);
if (identityError) {
return this.throwNewError(
'certificate identify Error: ' + identityError.message,
true,
info,
'08000',
Errors.ER_TLS_IDENTITY_ERROR
);
}
}
}
let mustRedirect = false;
if (info.status & ServerStatus.SESSION_STATE_CHANGED) {
packet.skip(2); //skip warning count
packet.skipLengthCodedNumber();
while (packet.remaining()) {
const len = packet.readUnsignedLength();
if (len > 0) {
const subPacket = packet.subPacketLengthEncoded(len);
while (subPacket.remaining()) {
const type = subPacket.readUInt8();
switch (type) {
case StateChange.SESSION_TRACK_SYSTEM_VARIABLES:
let subSubPacket;
do {
subSubPacket = subPacket.subPacketLengthEncoded(subPacket.readUnsignedLength());
const variable = subSubPacket.readStringLengthEncoded();
const value = subSubPacket.readStringLengthEncoded();
switch (variable) {
case 'character_set_client':
info.collation = Collations.fromCharset(value);
if (info.collation === undefined) {
this.throwError(new Error("unknown charset : '" + value + "'"), info);
return;
}
opts.emit('collation', info.collation);
break;
case 'redirect_url':
if (value !== '') {
mustRedirect = true;
info.redirect(value, this.successEnd.bind(this));
}
break;
case 'maxscale':
info.maxscaleVersion = value;
break;
case 'connection_id':
info.threadId = parseInt(value);
break;
default:
//variable not used by driver
}
} while (subSubPacket.remaining() > 0);
break;
case StateChange.SESSION_TRACK_SCHEMA:
const subSubPacket2 = subPacket.subPacketLengthEncoded(subPacket.readUnsignedLength());
info.database = subSubPacket2.readStringLengthEncoded();
break;
}
}
}
}
}
if (!mustRedirect) this.successEnd();
return;
//*********************************************************************************************************
//* ERR_Packet
//*********************************************************************************************************
case 0xff:
this.plugin.onPacketReceive = null;
const authErr = packet.readError(info, this.displaySql(), undefined);
authErr.fatal = true;
if (info.requireValidCert && info.selfSignedCertificate) {
// TLS was forced to trust, and certificate validation is required
return this.plugin.throwNewError(
'Self signed certificates. Either set `ssl: { rejectUnauthorized: false }` (trust mode) or provide server certificate to client',
true,
info,
'08000',
Errors.ER_SELF_SIGNED_NO_PWD
);
}
return this.plugin.throwError(authErr, info);
//*********************************************************************************************************
//* unexpected
//*********************************************************************************************************
default:
this.throwNewError(
`Unexpected type of packet during handshake phase : ${marker}`,
true,
info,
'42000',
Errors.ER_AUTHENTICATION_BAD_PACKET
);
}
}
validateFingerPrint(validationHash, info) {
if (validationHash.length === 0 || !info.tlsFingerprint) return false;
// 0x01 = SHA256 encryption
if (validationHash[0] !== 0x01) {
const err = Errors.createFatalError(
`Unexpected hash format for fingerprint hash encoding`,
Errors.ER_UNEXPECTED_PACKET,
this.info
);
if (this.opts.logger.error) this.opts.logger.error(err);
return false;
}
const pwdHash = this.plugin.hash(this.cmdParam.opts);
let hash = Crypto.createHash('sha256');
let digest = hash.update(pwdHash).update(info.seed).update(Buffer.from(info.tlsFingerprint, 'hex')).digest();
const hashHex = utils.toHexString(digest);
const serverValidationHex = validationHash.toString('ascii', 1, validationHash.length).toLowerCase();
return hashHex === serverValidationHex;
}
/**
* Handle authentication switch request : dispatch to plugin handler.
*
* @param packet packet
* @param out output writer
* @param opts options
* @param info connection information
*/
dispatchAuthSwitchRequest(packet, out, opts, info) {
let pluginName, pluginData;
if (info.clientCapabilities & Capabilities.PLUGIN_AUTH) {
packet.skip(1); //header
if (packet.remaining()) {
//AuthSwitchRequest packet.
pluginName = packet.readStringNullEnded();
pluginData = packet.readBufferRemaining();
} else {
//OldAuthSwitchRequest
pluginName = 'mysql_old_password';
pluginData = info.seed.subarray(0, 8);
}
} else {
pluginName = packet.readStringNullEnded('ascii');
pluginData = packet.readBufferRemaining();
}
if (
info.requireValidCert &&
info.selfSignedCertificate &&
Boolean(this.cmdParam.opts.password) &&
!this.plugin.permitHash()
) {
return this.throwNewError(
`Unsupported authentication plugin ${pluginName} with Self signed certificates. Either set 'ssl: { rejectUnauthorized: false }' (trust mode) or provide server certificate to client`,
true,
info,
'08000',
Errors.ER_SELF_SIGNED_BAD_PLUGIN
);
}
if (opts.restrictedAuth && !opts.restrictedAuth.includes(pluginName)) {
this.throwNewError(
`Unsupported authentication plugin ${pluginName}. Authorized plugin: ${opts.restrictedAuth.toString()}`,
true,
info,
'42000',
Errors.ER_NOT_SUPPORTED_AUTH_PLUGIN
);
return;
}
try {
this.plugin.emit('end');
this.plugin.onPacketReceive = null;
this.plugin = Authentication.pluginHandler(
pluginName,
this.plugin.sequenceNo,
this.plugin.compressSequenceNo,
pluginData,
info,
opts,
out,
this.cmdParam,
this.reject,
this.handshakeResult.bind(this)
);
this.plugin.start(out, opts, info);
} catch (err) {
this.reject(err);
}
}
static pluginHandler(
pluginName,
packSeq,
compressPackSeq,
pluginData,
info,
opts,
out,
cmdParam,
authReject,
multiAuthResolver
) {
let pluginAuth = authenticationPlugins[pluginName];
if (!pluginAuth) {
throw Errors.createFatalError(
`Client does not support authentication protocol '${pluginName}' requested by server.`,
Errors.ER_AUTHENTICATION_PLUGIN_NOT_SUPPORTED,
info,
'08004'
);
}
return new pluginAuth(packSeq, compressPackSeq, pluginData, cmdParam, authReject, multiAuthResolver);
}
}
module.exports = Authentication;
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2025 MariaDB Corporation Ab
// noinspection JSBitwiseOperatorUsage
'use strict';
const Capabilities = require('../../const/capabilities');
/**
* Initialize client capabilities according to options and server capabilities
*
* @param opts options
* @param info information
*/
module.exports.init = function (opts, info) {
let capabilities =
Capabilities.IGNORE_SPACE |
Capabilities.PROTOCOL_41 |
Capabilities.TRANSACTIONS |
Capabilities.SECURE_CONNECTION |
Capabilities.MULTI_RESULTS |
Capabilities.PS_MULTI_RESULTS |
Capabilities.SESSION_TRACK |
Capabilities.CONNECT_ATTRS |
Capabilities.PLUGIN_AUTH_LENENC_CLIENT_DATA |
Capabilities.MARIADB_CLIENT_EXTENDED_METADATA |
Capabilities.PLUGIN_AUTH;
if (opts.foundRows) {
capabilities |= Capabilities.FOUND_ROWS;
}
if (opts.permitLocalInfile) {
capabilities |= Capabilities.LOCAL_FILES;
}
if (opts.multipleStatements) {
capabilities |= Capabilities.MULTI_STATEMENTS;
}
info.eofDeprecated = !opts.keepEof && (info.serverCapabilities & Capabilities.DEPRECATE_EOF) > 0;
if (info.eofDeprecated) {
capabilities |= Capabilities.DEPRECATE_EOF;
}
if (opts.database && info.serverCapabilities & Capabilities.CONNECT_WITH_DB) {
capabilities |= Capabilities.CONNECT_WITH_DB;
}
info.serverPermitSkipMeta = (info.serverCapabilities & Capabilities.MARIADB_CLIENT_CACHE_METADATA) > 0;
if (info.serverPermitSkipMeta) {
capabilities |= Capabilities.MARIADB_CLIENT_CACHE_METADATA;
}
// use compression only if requested by client and supported by server
if (opts.compress) {
if (info.serverCapabilities & Capabilities.COMPRESS) {
capabilities |= Capabilities.COMPRESS;
} else {
opts.compress = false;
}
}
if (opts.bulk && info.serverCapabilities & Capabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) {
capabilities |= Capabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS;
capabilities |= Capabilities.BULK_UNIT_RESULTS;
}
if (opts.permitConnectionWhenExpired) {
capabilities |= Capabilities.CAN_HANDLE_EXPIRED_PASSWORDS;
}
info.clientCapabilities = capabilities & info.serverCapabilities;
};
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Capabilities = require('../../const/capabilities');
/**
* Send SSL Request packet.
* see : https://mariadb.com/kb/en/library/1-connecting-connecting/#sslrequest-packet
*
* @param cmd current command
* @param out output writer
* @param info client information
* @param opts connection options
*/
module.exports.send = function sendSSLRequest(cmd, out, info, opts) {
out.startPacket(cmd);
out.writeInt32(Number(info.clientCapabilities & BigInt(0xffffffff)));
out.writeInt32(1024 * 1024 * 1024); // max packet size
out.writeInt8(opts.collation && opts.collation.index <= 255 ? opts.collation.index : 224);
for (let i = 0; i < 19; i++) {
out.writeInt8(0);
}
if (info.serverCapabilities & Capabilities.MYSQL) {
out.writeInt32(0);
} else {
out.writeInt32(Number(info.clientCapabilities >> 32n));
}
out.flushPacket();
};
+861
View File
@@ -0,0 +1,861 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2025 MariaDB Corporation Ab
'use strict';
const Command = require('./command');
const ServerStatus = require('../const/server-status');
const ColumnDefinition = require('./column-definition');
const Errors = require('../misc/errors');
const fs = require('fs');
const Parse = require('../misc/parse');
const BinaryDecoder = require('./decoder/binary-decoder');
const TextDecoder = require('./decoder/text-decoder');
const OkPacket = require('./class/ok-packet');
const StateChange = require('../const/state-change');
const Collations = require('../const/collations');
// Set of field names that are reserved for internal use
const privateFields = new Set([
'__defineGetter__',
'__defineSetter__',
'__lookupGetter__',
'__lookupSetter__',
'__proto__'
]);
/**
* Handle COM_QUERY / COM_STMT_EXECUTE results
* @see https://mariadb.com/kb/en/library/4-server-response-packets/
*/
class Parser extends Command {
/**
* Create a new Parser instance
*
* @param {Function} resolve - Promise resolve function
* @param {Function} reject - Promise reject function
* @param {Object} connOpts - Connection options
* @param {Object} cmdParam - Command parameters
*/
constructor(resolve, reject, connOpts, cmdParam) {
super(cmdParam, resolve, reject);
this._responseIndex = 0;
this._rows = [];
this.opts = cmdParam.opts ? Object.assign({}, connOpts, cmdParam.opts) : connOpts;
this.sql = cmdParam.sql;
this.initialValues = cmdParam.values;
this.canSkipMeta = false;
}
/**
* Read Query response packet.
* Packet can be:
* - a result-set
* - an ERR_Packet
* - an OK_Packet
* - LOCAL_INFILE Packet
*
* @param {Object} packet - Query response packet
* @param {Object} out - Output writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection info
* @returns {Function|null} Next packet handler or null
*/
readResponsePacket(packet, out, opts, info) {
switch (packet.peek()) {
case 0x00: // OK response
return this.readOKPacket(packet, out, opts, info);
case 0xff: // ERROR response
return this.handleErrorPacket(packet, info);
case 0xfb: // LOCAL INFILE response
return this.readLocalInfile(packet, out, opts, info);
default: // Result set
return this.readResultSet(packet, info);
}
}
/**
* Handle error packet
*
* @param {Object} packet - Error packet
* @param {Object} info - Connection info
* @returns {null} Always returns null
* @private
*/
handleErrorPacket(packet, info) {
// In case of timeout, free accumulated rows
this._columns = null;
const err = packet.readError(info, this.opts.logParam ? this.displaySql() : this.sql, this.cmdParam.stack);
// Force in transaction status, since query will have created a transaction if autocommit is off
// Goal is to avoid unnecessary COMMIT/ROLLBACK
info.status |= ServerStatus.STATUS_IN_TRANS;
return this.throwError(err, info);
}
/**
* Read result-set packets
* @see https://mariadb.com/kb/en/library/resultset/
*
* @param {Object} packet - Column count packet
* @param {Object} info - Connection information
* @returns {Function} Next packet handler
*/
readResultSet(packet, info) {
this._columnCount = packet.readUnsignedLength();
this._rows.push([]);
if (this.canSkipMeta && info.serverPermitSkipMeta && packet.readUInt8() === 0) {
// Command supports skipping meta
// Server permits it
// And tells that no columns follow, using prepare results
return this.handleSkippedMeta(info);
}
this._columns = [];
return (this.onPacketReceive = this.readColumn);
}
/**
* Handle skipped metadata case
*
* @param {Object} info - Connection information
* @returns {Function} Next packet handler
* @private
*/
handleSkippedMeta(info) {
this._columns = this.prepare.columns;
this._columnCount = this._columns.length;
this.emit('fields', this._columns);
this.setParser();
return (this.onPacketReceive = info.eofDeprecated ? this.readResultSetRow : this.readIntermediateEOF);
}
/**
* Read OK_Packet
* @see https://mariadb.com/kb/en/library/ok_packet/
*
* @param {Object} packet - OK_Packet
* @param {Object} out - Output writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection information
* @returns {Function|null} Next packet handler or null
*/
readOKPacket(packet, out, opts, info) {
packet.skip(1); // Skip header
const affectedRows = packet.readUnsignedLength();
// Handle insertId based on options
let insertId = this.processInsertId(packet.readInsertId(), info);
info.status = packet.readUInt16();
const okPacket = new OkPacket(affectedRows, insertId, packet.readUInt16());
let mustRedirect = false;
// Process session state changes if present
if (info.status & ServerStatus.SESSION_STATE_CHANGED) {
mustRedirect = this.processSessionStateChanges(packet, info, opts);
}
// Handle streaming case
if (this.inStream) {
this.handleNewRows(okPacket);
}
// Handle redirection
if (mustRedirect) {
return null; // Redirection is handled asynchronously
}
if (
info.redirectRequest &&
(info.status & ServerStatus.STATUS_IN_TRANS) === 0 &&
(info.status & ServerStatus.MORE_RESULTS_EXISTS) === 0
) {
info.redirect(info.redirectRequest, this.okPacketSuccess.bind(this, okPacket, info));
} else {
this.okPacketSuccess(okPacket, info);
}
return null;
}
/**
* Process insertId based on connection options
*
* @param {BigInt} insertId - Raw insertId from packet
* @param {Object} info - Connection info
* @returns {BigInt|Number|String} Processed insertId
* @private
*/
processInsertId(insertId, info) {
if (this.opts.supportBigNumbers || this.opts.insertIdAsNumber) {
if (this.opts.insertIdAsNumber && this.opts.checkNumberRange && !Number.isSafeInteger(Number(insertId))) {
this.onPacketReceive = info.status & ServerStatus.MORE_RESULTS_EXISTS ? this.readResponsePacket : null;
this.throwUnexpectedError(
`last insert id value ${insertId} can't safely be converted to number`,
false,
info,
'42000',
Errors.ER_PARSING_PRECISION
);
return insertId;
}
if (this.opts.supportBigNumbers && (this.opts.bigNumberStrings || !Number.isSafeInteger(Number(insertId)))) {
return insertId.toString();
} else {
return Number(insertId);
}
}
return insertId;
}
/**
* Process session state changes
*
* @param {Object} packet - Packet containing session state changes
* @param {Object} info - Connection information
* @param {Object} opts - Connection options
* @returns {Boolean} True if redirection is needed
* @private
*/
processSessionStateChanges(packet, info, opts) {
let mustRedirect = false;
packet.skipLengthCodedNumber();
while (packet.remaining()) {
const len = packet.readUnsignedLength();
if (len > 0) {
const subPacket = packet.subPacketLengthEncoded(len);
while (subPacket.remaining()) {
const type = subPacket.readUInt8();
switch (type) {
case StateChange.SESSION_TRACK_SYSTEM_VARIABLES:
mustRedirect = this.processSystemVariables(subPacket, info, opts) || mustRedirect;
break;
case StateChange.SESSION_TRACK_SCHEMA:
info.database = this.readSchemaChange(subPacket);
break;
}
}
}
}
return mustRedirect;
}
/**
* Process system variables changes
*
* @param {Object} subPacket - Packet containing system variables
* @param {Object} info - Connection information
* @param {Object} opts - Connection options
* @returns {Boolean} True if redirection is needed
* @private
*/
processSystemVariables(subPacket, info, opts) {
let mustRedirect = false;
let subSubPacket;
do {
subSubPacket = subPacket.subPacketLengthEncoded(subPacket.readUnsignedLength());
const variable = subSubPacket.readStringLengthEncoded();
const value = subSubPacket.readStringLengthEncoded();
switch (variable) {
case 'character_set_client':
info.collation = Collations.fromCharset(value);
if (info.collation === undefined) {
this.throwError(new Error(`unknown charset: '${value}'`), info);
return false;
}
opts.emit('collation', info.collation);
break;
case 'redirect_url':
if (value !== '') {
mustRedirect = true;
info.redirect(value, this.okPacketSuccess.bind(this, this.okPacket, info));
}
break;
case 'connection_id':
info.threadId = parseInt(value);
break;
}
} while (subSubPacket.remaining() > 0);
return mustRedirect;
}
/**
* Read schema change from packet
*
* @param {Object} subPacket - Packet containing schema change
* @returns {String} New schema name
* @private
*/
readSchemaChange(subPacket) {
const subSubPacket = subPacket.subPacketLengthEncoded(subPacket.readUnsignedLength());
return subSubPacket.readStringLengthEncoded();
}
/**
* Handle OK packet success
*
* @param {Object} okPacket - OK packet
* @param {Object} info - Connection information
*/
okPacketSuccess(okPacket, info) {
if (this._responseIndex === 0) {
// Fast path for standard single result
if (info.status & ServerStatus.MORE_RESULTS_EXISTS) {
this._rows.push(okPacket);
this._responseIndex++;
return (this.onPacketReceive = this.readResponsePacket);
}
return this.success(this.opts.metaAsArray ? [okPacket, []] : okPacket);
}
this._rows.push(okPacket);
if (info.status & ServerStatus.MORE_RESULTS_EXISTS) {
this._responseIndex++;
return (this.onPacketReceive = this.readResponsePacket);
}
if (this.opts.metaAsArray) {
if (!this._meta) {
this._meta = new Array(this._responseIndex);
}
this._meta[this._responseIndex] = null;
this.success([this._rows, this._meta]);
} else {
this.success(this._rows);
}
}
/**
* Complete query with success
*
* @param {*} val - Result value
*/
success(val) {
this.successEnd(val);
this._columns = null;
this._rows = [];
}
/**
* Read column information metadata
* @see https://mariadb.com/kb/en/library/resultset/#column-definition-packet
*
* @param {Object} packet - Column definition packet
* @param {Object} out - Output writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection information
*/
readColumn(packet, out, opts, info) {
this._columns.push(new ColumnDefinition(packet, info, this.opts.rowsAsArray));
// Last column
if (this._columns.length === this._columnCount) {
this.setParser();
if (this.canSkipMeta && info.serverPermitSkipMeta && this.prepare != null) {
// Server can skip meta, but have force sending it.
// Metadata have changed, updating prepare result accordingly
if (this._responseIndex === 0) this.prepare.columns = this._columns;
}
this.emit('fields', this._columns);
this.onPacketReceive = info.eofDeprecated ? this.readResultSetRow : this.readIntermediateEOF;
}
}
/**
* Set up row parsers based on column information
*/
setParser() {
this._parseFunction = new Array(this._columnCount);
if (this.opts.typeCast) {
for (let i = 0; i < this._columnCount; i++) {
this._parseFunction[i] = this.readCastValue.bind(this, this._columns[i]);
}
} else {
const dataParser = this.binary ? BinaryDecoder.parser : TextDecoder.parser;
for (let i = 0; i < this._columnCount; i++) {
this._parseFunction[i] = dataParser(this._columns[i], this.opts);
}
}
if (this.opts.rowsAsArray) {
this.parseRow = this.parseRowAsArray;
} else {
this.tableHeader = new Array(this._columnCount);
this.parseRow = this.binary ? this.parseRowStdBinary : this.parseRowStdText;
if (this.opts.nestTables) {
this.configureNestedTables();
} else {
for (let i = 0; i < this._columnCount; i++) {
this.tableHeader[i] = this._columns[i].name();
}
this.checkDuplicates();
}
}
}
/**
* Configure nested tables format
* @private
*/
configureNestedTables() {
if (typeof this.opts.nestTables === 'string') {
for (let i = 0; i < this._columnCount; i++) {
this.tableHeader[i] = this._columns[i].table() + this.opts.nestTables + this._columns[i].name();
}
this.checkDuplicates();
} else if (this.opts.nestTables === true) {
this.parseRow = this.parseRowNested;
for (let i = 0; i < this._columnCount; i++) {
this.tableHeader[i] = [this._columns[i].table(), this._columns[i].name()];
}
this.checkNestTablesDuplicatesAndPrivateFields();
}
}
/**
* Check for duplicate column names
*/
checkDuplicates() {
if (this.opts.checkDuplicate) {
for (let i = 0; i < this._columnCount; i++) {
if (this.tableHeader.indexOf(this.tableHeader[i], i + 1) > 0) {
const dupes = this.tableHeader.reduce(
(acc, v, i, arr) => (arr.indexOf(v) !== i && acc.indexOf(v) === -1 ? acc.concat(v) : acc),
[]
);
this.throwUnexpectedError(
`Error in results, duplicate field name \`${dupes[0]}\`.\n(see option \`checkDuplicate\`)`,
false,
null,
'42000',
Errors.ER_DUPLICATE_FIELD
);
}
}
}
}
/**
* Check for duplicates and private fields in nested tables
*/
checkNestTablesDuplicatesAndPrivateFields() {
if (this.opts.checkDuplicate) {
for (let i = 0; i < this._columnCount; i++) {
for (let j = 0; j < i; j++) {
if (this.tableHeader[j][0] === this.tableHeader[i][0] && this.tableHeader[j][1] === this.tableHeader[i][1]) {
this.throwUnexpectedError(
`Error in results, duplicate field name \`${this.tableHeader[i][0]}\`.\`${this.tableHeader[i][1]}\`\n(see option \`checkDuplicate\`)`,
false,
null,
'42000',
Errors.ER_DUPLICATE_FIELD
);
}
}
}
}
for (let i = 0; i < this._columnCount; i++) {
if (privateFields.has(this.tableHeader[i][0])) {
this.throwUnexpectedError(
`Use of \`${this.tableHeader[i][0]}\` is not permitted with option \`nestTables\``,
false,
null,
'42000',
Errors.ER_PRIVATE_FIELDS_USE
);
// Continue parsing results to keep connection state
// but without assigning possible dangerous value
this.parseRow = () => {
return {};
};
}
}
}
/**
* Read intermediate EOF
* Only for server before MariaDB 10.2 / MySQL 5.7 that doesn't have CLIENT_DEPRECATE_EOF capability
* @see https://mariadb.com/kb/en/library/eof_packet/
*
* @param {Object} packet - EOF Packet
* @param {Object} out - Output writer
* @param {Object} opts - Connection options
* @param {Object} info - Connection information
* @returns {Function|null} Next packet handler or null
*/
readIntermediateEOF(packet, out, opts, info) {
if (packet.peek() !== 0xfe) {
return this.throwNewError('Error in protocol, expected EOF packet', true, info, '42000', Errors.ER_EOF_EXPECTED);
}
// Before MySQL 5.7.5, last EOF doesn't contain the good flag SERVER_MORE_RESULTS_EXISTS
// for OUT parameters. It must be checked here
// (5.7.5 does have the CLIENT_DEPRECATE_EOF capability, so this packet is not even sent)
packet.skip(3);
info.status = packet.readUInt16();
this.isOutParameter = info.status & ServerStatus.PS_OUT_PARAMS;
return (this.onPacketReceive = this.readResultSetRow);
}
/**
* Add new rows to the result set
*
* @param {Object} row - Row data
*/
handleNewRows(row) {
this._rows[this._responseIndex].push(row);
}
/**
* Check if packet is result-set end = EOF of OK_Packet with EOF header according to CLIENT_DEPRECATE_EOF capability
* or a result-set row
*
* @param packet current packet
* @param out output writer
* @param opts connection options
* @param info connection information
* @returns {*}
*/
readResultSetRow(packet, out, opts, info) {
if (packet.peek() >= 0xfe) {
if (packet.peek() === 0xff) {
//force in transaction status, since query will have created a transaction if autocommit is off
//goal is to avoid unnecessary COMMIT/ROLLBACK.
info.status |= ServerStatus.STATUS_IN_TRANS;
return this.throwError(
packet.readError(info, this.opts.logParam ? this.displaySql() : this.sql, this.cmdParam.err),
info
);
}
if ((!info.eofDeprecated && packet.length() < 13) || (info.eofDeprecated && packet.length() < 0xffffff)) {
if (!info.eofDeprecated) {
packet.skip(3);
info.status = packet.readUInt16();
} else {
packet.skip(1); //skip header
packet.skipLengthCodedNumber(); //skip update count
packet.skipLengthCodedNumber(); //skip insert id
info.status = packet.readUInt16();
}
if (
info.redirectRequest &&
(info.status & ServerStatus.STATUS_IN_TRANS) === 0 &&
(info.status & ServerStatus.MORE_RESULTS_EXISTS) === 0
) {
info.redirect(info.redirectRequest, this.resultSetEndingPacketResult.bind(this, info));
} else {
this.resultSetEndingPacketResult(info);
}
return;
}
}
this.handleNewRows(this.parseRow(packet));
}
resultSetEndingPacketResult(info) {
if (this.opts.metaAsArray) {
//return promise object as array :
// example for SELECT 1 =>
// [
// [ {"1": 1} ], //rows
// [ColumnDefinition] //meta
// ]
if (info.status & ServerStatus.MORE_RESULTS_EXISTS || this.isOutParameter) {
if (!this._meta) this._meta = [];
this._meta[this._responseIndex] = this._columns;
this._responseIndex++;
return (this.onPacketReceive = this.readResponsePacket);
}
if (this._responseIndex === 0) {
this.success([this._rows[0], this._columns]);
} else {
if (!this._meta) this._meta = [];
this._meta[this._responseIndex] = this._columns;
this.success([this._rows, this._meta]);
}
} else {
//return promise object as rows that have meta property :
// example for SELECT 1 =>
// [
// {"1": 1},
// meta: [ColumnDefinition]
// ]
Object.defineProperty(this._rows[this._responseIndex], 'meta', {
value: this._columns,
writable: true,
enumerable: this.opts.metaEnumerable
});
if (info.status & ServerStatus.MORE_RESULTS_EXISTS || this.isOutParameter) {
this._responseIndex++;
return (this.onPacketReceive = this.readResponsePacket);
}
this.success(this._responseIndex === 0 ? this._rows[0] : this._rows);
}
}
/**
* Display current SQL with parameters (truncated if too big)
*
* @returns {string}
*/
displaySql() {
if (this.opts && this.initialValues) {
if (this.sql.length > this.opts.debugLen) {
return this.sql.substring(0, this.opts.debugLen) + '...';
}
let sqlMsg = this.sql + ' - parameters:';
return Parser.logParameters(this.opts, sqlMsg, this.initialValues);
}
if (this.sql.length > this.opts.debugLen) {
return this.sql.substring(0, this.opts.debugLen) + '... - parameters:[]';
}
return this.sql + ' - parameters:[]';
}
static logParameters(opts, sqlMsg, values) {
if (opts.namedPlaceholders) {
sqlMsg += '{';
let first = true;
for (let key in values) {
if (first) {
first = false;
} else {
sqlMsg += ',';
}
sqlMsg += "'" + key + "':";
let param = values[key];
sqlMsg = Parser.logParam(sqlMsg, param);
if (sqlMsg.length > opts.debugLen) {
return sqlMsg.substring(0, opts.debugLen) + '...';
}
}
sqlMsg += '}';
} else {
sqlMsg += '[';
if (Array.isArray(values)) {
for (let i = 0; i < values.length; i++) {
if (i !== 0) sqlMsg += ',';
let param = values[i];
sqlMsg = Parser.logParam(sqlMsg, param);
if (sqlMsg.length > opts.debugLen) {
return sqlMsg.substring(0, opts.debugLen) + '...';
}
}
} else {
sqlMsg = Parser.logParam(sqlMsg, values);
if (sqlMsg.length > opts.debugLen) {
return sqlMsg.substring(0, opts.debugLen) + '...';
}
}
sqlMsg += ']';
}
return sqlMsg;
}
parseRowAsArray(packet) {
const row = new Array(this._columnCount);
const nullBitMap = this.binary ? BinaryDecoder.newRow(packet, this._columns) : null;
for (let i = 0; i < this._columnCount; i++) {
row[i] = this._parseFunction[i](packet, this.opts, this.unexpectedError, nullBitMap, i);
}
return row;
}
parseRowNested(packet) {
const row = {};
const nullBitMap = this.binary ? BinaryDecoder.newRow(packet, this._columns) : null;
for (let i = 0; i < this._columnCount; i++) {
if (!row[this.tableHeader[i][0]]) row[this.tableHeader[i][0]] = {};
row[this.tableHeader[i][0]][this.tableHeader[i][1]] = this._parseFunction[i](
packet,
this.opts,
this.unexpectedError,
nullBitMap,
i
);
}
return row;
}
parseRowStdText(packet) {
const row = {};
for (let i = 0; i < this._columnCount; i++) {
row[this.tableHeader[i]] = this._parseFunction[i](packet, this.opts, this.unexpectedError);
}
return row;
}
parseRowStdBinary(packet) {
const nullBitMap = BinaryDecoder.newRow(packet, this._columns);
const row = {};
for (let i = 0; i < this._columnCount; i++) {
row[this.tableHeader[i]] = this._parseFunction[i](packet, this.opts, this.unexpectedError, nullBitMap, i);
}
return row;
}
readCastValue(column, packet, opts, unexpectedError, nullBitmap, index) {
if (this.binary) {
BinaryDecoder.castWrapper(column, packet, opts, nullBitmap, index);
} else {
TextDecoder.castWrapper(column, packet, opts, nullBitmap, index);
}
const dataParser = this.binary ? BinaryDecoder.parser : TextDecoder.parser;
return opts.typeCast(column, dataParser(column, opts).bind(null, packet, opts, unexpectedError, nullBitmap, index));
}
readLocalInfile(packet, out, opts, info) {
packet.skip(1); //skip header
out.startPacket(this);
const fileName = packet.readStringRemaining();
if (!Parse.validateFileName(this.sql, this.initialValues, fileName)) {
out.writeEmptyPacket();
const error = Errors.createError(
"LOCAL INFILE wrong filename. '" +
fileName +
"' doesn't correspond to query " +
this.sql +
'. Query cancelled. Check for malicious server / proxy',
Errors.ER_LOCAL_INFILE_WRONG_FILENAME,
info,
'HY000',
this.sql
);
process.nextTick(this.reject, error);
this.reject = null;
this.resolve = null;
return (this.onPacketReceive = this.readResponsePacket);
}
// this.sequenceNo = 2;
// this.compressSequenceNo = 2;
let stream;
try {
stream = this.opts.infileStreamFactory ? this.opts.infileStreamFactory(fileName) : fs.createReadStream(fileName);
} catch (e) {
out.writeEmptyPacket();
const error = Errors.createError(
`LOCAL INFILE infileStreamFactory failed`,
Errors.ER_LOCAL_INFILE_NOT_READABLE,
info,
'22000',
this.opts.logParam ? this.displaySql() : this.sql
);
error.cause = e;
process.nextTick(this.reject, error);
this.reject = null;
this.resolve = null;
return (this.onPacketReceive = this.readResponsePacket);
}
stream.on(
'error',
function (err) {
out.writeEmptyPacket();
const error = Errors.createError(
`LOCAL INFILE command failed: ${err.message}`,
Errors.ER_LOCAL_INFILE_NOT_READABLE,
info,
'22000',
this.sql
);
process.nextTick(this.reject, error);
this.reject = null;
this.resolve = null;
}.bind(this)
);
stream.on('data', (chunk) => {
out.writeBuffer(chunk, 0, chunk.length);
});
stream.on('end', () => {
if (!out.isEmpty()) {
out.flushBuffer(false);
}
out.writeEmptyPacket();
});
this.onPacketReceive = this.readResponsePacket;
}
static logParam(sqlMsg, param) {
if (param == null) {
sqlMsg += param === undefined ? 'undefined' : 'null';
} else {
switch (param.constructor.name) {
case 'Buffer':
sqlMsg += '0x' + param.toString('hex', 0, Math.min(1024, param.length)) + '';
break;
case 'String':
sqlMsg += "'" + param + "'";
break;
case 'Date':
sqlMsg += getStringDate(param);
break;
case 'Object':
sqlMsg += JSON.stringify(param);
break;
default:
sqlMsg += param.toString();
}
}
return sqlMsg;
}
}
function getStringDate(param) {
return (
"'" +
('00' + (param.getMonth() + 1)).slice(-2) +
'/' +
('00' + param.getDate()).slice(-2) +
'/' +
param.getFullYear() +
' ' +
('00' + param.getHours()).slice(-2) +
':' +
('00' + param.getMinutes()).slice(-2) +
':' +
('00' + param.getSeconds()).slice(-2) +
'.' +
('000' + param.getMilliseconds()).slice(-3) +
"'"
);
}
module.exports = Parser;
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Command = require('./command');
const ServerStatus = require('../const/server-status');
const PING_COMMAND = new Uint8Array([1, 0, 0, 0, 0x0e]);
/**
* send a COM_PING: permits sending a packet containing one byte to check that the connection is active.
* see https://mariadb.com/kb/en/library/com_ping/
*/
class Ping extends Command {
constructor(cmdParam, resolve, reject) {
super(cmdParam, resolve, reject);
}
start(out, opts, info) {
if (opts.logger.query) opts.logger.query('PING');
this.onPacketReceive = this.readPingResponsePacket;
out.fastFlush(this, PING_COMMAND);
this.emit('send_end');
}
/**
* Read ping response packet.
* packet can be :
* - an ERR_Packet
* - an OK_Packet
*
* @param packet query response
* @param out output writer
* @param opts connection options
* @param info connection info
*/
readPingResponsePacket(packet, out, opts, info) {
packet.skip(1); //skip header
packet.skipLengthCodedNumber(); //affected rows
packet.skipLengthCodedNumber(); //insert ids
info.status = packet.readUInt16();
if (info.redirectRequest && (info.status & ServerStatus.STATUS_IN_TRANS) === 0) {
info.redirect(info.redirectRequest, this.successEnd.bind(this, null));
} else {
this.successEnd(null);
}
}
}
module.exports = Ping;
+170
View File
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Parser = require('./parser');
const Parse = require('../misc/parse');
const BinaryEncoder = require('./encoder/binary-encoder');
const PrepareCacheWrapper = require('./class/prepare-cache-wrapper');
const PrepareResult = require('./class/prepare-result-packet');
const ServerStatus = require('../const/server-status');
const Errors = require('../misc/errors');
const ColumnDefinition = require('./column-definition');
/**
* send a COM_STMT_PREPARE: permits sending a prepare packet
* see https://mariadb.com/kb/en/com_stmt_prepare/
*/
class Prepare extends Parser {
constructor(resolve, reject, connOpts, cmdParam, conn) {
super(resolve, reject, connOpts, cmdParam);
this.encoder = new BinaryEncoder(this.opts);
this.binary = true;
this.conn = conn;
this.executeCommand = cmdParam.executeCommand;
}
/**
* Send COM_STMT_PREPARE
*
* @param out output writer
* @param opts connection options
* @param info connection information
*/
start(out, opts, info) {
// check in cache if enabled
if (this.conn.prepareCache) {
let cachedPrepare = this.conn.prepareCache.get(this.sql);
if (cachedPrepare) {
this.emit('send_end');
return this.successEnd(cachedPrepare);
}
}
if (opts.logger.query) opts.logger.query(`PREPARE: ${this.sql}`);
this.onPacketReceive = this.readPrepareResultPacket;
if (this.opts.namedPlaceholders) {
const res = Parse.searchPlaceholder(this.sql);
this.sql = res.sql;
this.placeHolderIndex = res.placeHolderIndex;
}
out.startPacket(this);
out.writeInt8(0x16);
out.writeString(this.sql);
out.flush();
this.emit('send_end');
}
successPrepare(info, opts) {
let prepare = new PrepareResult(
this.statementId,
this.parameterCount,
this._columns,
info.database,
this.sql,
this.placeHolderIndex,
this.conn
);
if (this.conn.prepareCache) {
let cached = new PrepareCacheWrapper(prepare);
this.conn.prepareCache.set(this.sql, cached);
const cachedWrappedPrepared = cached.incrementUse();
if (this.executeCommand) this.executeCommand.prepare = cachedWrappedPrepared;
return this.successEnd(cachedWrappedPrepared);
}
if (this.executeCommand) this.executeCommand.prepare = prepare;
this.successEnd(prepare);
}
/**
* Read COM_STMT_PREPARE response Packet.
* see https://mariadb.com/kb/en/library/com_stmt_prepare/#com_stmt_prepare-response
*
* @param packet COM_STMT_PREPARE_OK packet
* @param opts connection options
* @param info connection information
* @param out output writer
* @returns {*} null or {Result.readResponsePacket} in case of multi-result-set
*/
readPrepareResultPacket(packet, out, opts, info) {
switch (packet.peek()) {
//*********************************************************************************************************
//* PREPARE response
//*********************************************************************************************************
case 0x00:
packet.skip(1); //skip header
this.statementId = packet.readInt32();
this.columnNo = packet.readUInt16();
this.parameterCount = packet.readUInt16();
this._parameterNo = this.parameterCount;
this._columns = [];
if (this._parameterNo > 0) return (this.onPacketReceive = this.skipPrepareParameterPacket);
if (this.columnNo > 0) return (this.onPacketReceive = this.readPrepareColumnsPacket);
return this.successPrepare(info, opts);
//*********************************************************************************************************
//* ERROR response
//*********************************************************************************************************
case 0xff:
const err = packet.readError(info, this.displaySql(), this.stack);
//force in transaction status, since query will have created a transaction if autocommit is off
//goal is to avoid unnecessary COMMIT/ROLLBACK.
info.status |= ServerStatus.STATUS_IN_TRANS;
this.onPacketReceive = this.readResponsePacket;
return this.throwError(err, info);
//*********************************************************************************************************
//* Unexpected response
//*********************************************************************************************************
default:
info.status |= ServerStatus.STATUS_IN_TRANS;
this.onPacketReceive = this.readResponsePacket;
return this.throwError(Errors.ER_UNEXPECTED_PACKET, info);
}
}
readPrepareColumnsPacket(packet, out, opts, info) {
this.columnNo--;
this._columns.push(new ColumnDefinition(packet, info, opts.rowsAsArray));
if (this.columnNo === 0) {
if (info.eofDeprecated) {
return this.successPrepare(info, opts);
}
this.onPacketReceive = this.skipEofPacket;
}
}
skipEofPacket(packet, out, opts, info) {
if (this.columnNo > 0) return (this.onPacketReceive = this.readPrepareColumnsPacket);
this.successPrepare(info, opts);
}
skipPrepareParameterPacket(packet, out, opts, info) {
this._parameterNo--;
if (this._parameterNo === 0) {
if (info.eofDeprecated) {
if (this.columnNo > 0) return (this.onPacketReceive = this.readPrepareColumnsPacket);
return this.successPrepare(info, opts);
}
this.onPacketReceive = this.skipEofPacket;
}
}
/**
* Display current SQL with parameters (truncated if too big)
*
* @returns {string}
*/
displaySql() {
if (this.opts) {
if (this.sql.length > this.opts.debugLen) {
return this.sql.substring(0, this.opts.debugLen) + '...';
}
}
return this.sql;
}
}
module.exports = Prepare;
+392
View File
@@ -0,0 +1,392 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Parser = require('./parser');
const Errors = require('../misc/errors');
const Parse = require('../misc/parse');
const TextEncoder = require('./encoder/text-encoder');
const { Readable } = require('stream');
const QUOTE = 0x27;
/**
* Protocol COM_QUERY
* see : https://mariadb.com/kb/en/library/com_query/
*/
class Query extends Parser {
constructor(resolve, reject, connOpts, cmdParam) {
super(resolve, reject, connOpts, cmdParam);
this.binary = false;
}
/**
* Send COM_QUERY
*
* @param out output writer
* @param opts connection options
* @param info connection information
*/
start(out, opts, info) {
if (opts.logger.query) opts.logger.query(`QUERY: ${opts.logParam ? this.displaySql() : this.sql}`);
this.onPacketReceive = this.readResponsePacket;
if (this.initialValues === undefined) {
//shortcut if no parameters
out.startPacket(this);
out.writeInt8(0x03);
if (!this.handleTimeout(out, info)) return;
out.writeString(this.sql);
out.flush();
this.emit('send_end');
return;
}
this.encodedSql = out.encodeString(this.sql);
if (this.opts.namedPlaceholders) {
try {
const parsed = Parse.splitQueryPlaceholder(
this.encodedSql,
info,
this.initialValues,
this.opts.logParam ? this.displaySql.bind(this) : () => this.sql
);
this.paramPositions = parsed.paramPositions;
this.values = parsed.values;
} catch (err) {
this.emit('send_end');
return this.throwError(err, info);
}
} else {
this.paramPositions = Parse.splitQuery(this.encodedSql);
this.values = Array.isArray(this.initialValues) ? this.initialValues : [this.initialValues];
if (!this.validateParameters(info)) return;
}
out.startPacket(this);
out.writeInt8(0x03);
if (!this.handleTimeout(out, info)) return;
this.paramPos = 0;
this.sqlPos = 0;
//********************************************
// send params
//********************************************
const len = this.paramPositions.length / 2;
for (this.valueIdx = 0; this.valueIdx < len; ) {
out.writeBuffer(this.encodedSql, this.sqlPos, this.paramPositions[this.paramPos++] - this.sqlPos);
this.sqlPos = this.paramPositions[this.paramPos++];
const value = this.values[this.valueIdx++];
if (value == null) {
out.writeStringAscii('NULL');
continue;
}
switch (typeof value) {
case 'boolean':
out.writeStringAscii(value ? 'true' : 'false');
break;
case 'bigint':
case 'number':
out.writeStringAscii(`${value}`);
break;
case 'string':
out.writeStringEscapeQuote(value);
break;
case 'object':
if (typeof value.pipe === 'function' && typeof value.read === 'function') {
this.sending = true;
//********************************************
// param is stream,
// now all params will be written by event
//********************************************
this.paramWritten = this._paramWritten.bind(this, out, info);
out.writeInt8(QUOTE); //'
value.on('data', out.writeBufferEscape.bind(out));
value.on(
'end',
function () {
out.writeInt8(QUOTE); //'
this.paramWritten();
}.bind(this)
);
return;
}
if (Object.prototype.toString.call(value) === '[object Date]') {
out.writeStringAscii(TextEncoder.getLocalDate(value));
} else if (Buffer.isBuffer(value)) {
out.writeStringAscii("_BINARY '");
out.writeBufferEscape(value);
out.writeInt8(QUOTE);
} else if (typeof value.toSqlString === 'function') {
out.writeStringEscapeQuote(String(value.toSqlString()));
} else if (Array.isArray(value)) {
if (opts.arrayParenthesis) {
out.writeStringAscii('(');
}
for (let i = 0; i < value.length; i++) {
if (i !== 0) out.writeStringAscii(',');
if (value[i] == null) {
out.writeStringAscii('NULL');
} else TextEncoder.writeParam(out, value[i], opts, info);
}
if (opts.arrayParenthesis) {
out.writeStringAscii(')');
}
} else {
if (
value.type != null &&
[
'Point',
'LineString',
'Polygon',
'MultiPoint',
'MultiLineString',
'MultiPolygon',
'GeometryCollection'
].includes(value.type)
) {
//GeoJSON format.
let prefix =
(info.isMariaDB() && info.hasMinVersion(10, 1, 4)) || (!info.isMariaDB() && info.hasMinVersion(5, 7, 6))
? 'ST_'
: '';
switch (value.type) {
case 'Point':
out.writeStringAscii(
prefix + "PointFromText('POINT(" + TextEncoder.geoPointToString(value.coordinates) + ")')"
);
break;
case 'LineString':
out.writeStringAscii(
prefix + "LineFromText('LINESTRING(" + TextEncoder.geoArrayPointToString(value.coordinates) + ")')"
);
break;
case 'Polygon':
out.writeStringAscii(
prefix +
"PolygonFromText('POLYGON(" +
TextEncoder.geoMultiArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiPoint':
out.writeStringAscii(
prefix +
"MULTIPOINTFROMTEXT('MULTIPOINT(" +
TextEncoder.geoArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiLineString':
out.writeStringAscii(
prefix +
"MLineFromText('MULTILINESTRING(" +
TextEncoder.geoMultiArrayPointToString(value.coordinates) +
")')"
);
break;
case 'MultiPolygon':
out.writeStringAscii(
prefix +
"MPolyFromText('MULTIPOLYGON(" +
TextEncoder.geoMultiPolygonToString(value.coordinates) +
")')"
);
break;
case 'GeometryCollection':
out.writeStringAscii(
prefix +
"GeomCollFromText('GEOMETRYCOLLECTION(" +
TextEncoder.geometricCollectionToString(value.geometries) +
")')"
);
break;
}
} else if (String === value.constructor) {
out.writeStringEscapeQuote(value);
break;
} else {
if (opts.permitSetMultiParamEntries) {
let first = true;
for (let key in value) {
const val = value[key];
if (typeof val === 'function') continue;
if (first) {
first = false;
} else {
out.writeStringAscii(',');
}
out.writeString('`' + key + '`');
if (val == null) {
out.writeStringAscii('=NULL');
} else {
out.writeStringAscii('=');
TextEncoder.writeParam(out, val, opts, info);
}
}
if (first) out.writeStringEscapeQuote(JSON.stringify(value));
} else {
out.writeStringEscapeQuote(JSON.stringify(value));
}
}
}
break;
}
}
out.writeBuffer(this.encodedSql, this.sqlPos, this.encodedSql.length - this.sqlPos);
out.flush();
this.emit('send_end');
}
/**
* If timeout is set, prepend query with SET STATEMENT max_statement_time=xx FOR, or throw an error
* @param out buffer
* @param info server information
* @returns {boolean} false if an error has been thrown
*/
handleTimeout(out, info) {
if (this.opts.timeout) {
if (info.isMariaDB()) {
if (info.hasMinVersion(10, 1, 2)) {
out.writeString(`SET STATEMENT max_statement_time=${this.opts.timeout / 1000} FOR `);
return true;
} else {
this.sendCancelled(
`Cannot use timeout for xpand/MariaDB server before 10.1.2. timeout value: ${this.opts.timeout}`,
Errors.ER_TIMEOUT_NOT_SUPPORTED,
info
);
return false;
}
} else {
//not available for MySQL
// max_execution time exist, but only for select, and as hint
this.sendCancelled(
`Cannot use timeout for MySQL server. timeout value: ${this.opts.timeout}`,
Errors.ER_TIMEOUT_NOT_SUPPORTED,
info
);
return false;
}
}
return true;
}
/**
* Validate that parameters exists and are defined.
*
* @param info connection info
* @returns {boolean} return false if any error occur.
*/
validateParameters(info) {
//validate parameter size.
if (this.paramPositions.length / 2 > this.values.length) {
this.sendCancelled(
`Parameter at position ${this.values.length + 1} is not set`,
Errors.ER_MISSING_PARAMETER,
info
);
return false;
}
return true;
}
_paramWritten(out, info) {
while (true) {
if (this.valueIdx === this.paramPositions.length / 2) {
//********************************************
// all parameters are written.
// flush packet
//********************************************
out.writeBuffer(this.encodedSql, this.sqlPos, this.encodedSql.length - this.sqlPos);
out.flush();
this.sending = false;
this.emit('send_end');
return;
} else {
const value = this.values[this.valueIdx++];
out.writeBuffer(this.encodedSql, this.sqlPos, this.paramPositions[this.paramPos++] - this.sqlPos);
this.sqlPos = this.paramPositions[this.paramPos++];
if (value == null) {
out.writeStringAscii('NULL');
continue;
}
if (typeof value === 'object' && typeof value.pipe === 'function' && typeof value.read === 'function') {
//********************************************
// param is stream,
//********************************************
out.writeInt8(QUOTE);
value.once(
'end',
function () {
out.writeInt8(QUOTE);
this._paramWritten(out, info);
}.bind(this)
);
value.on('data', out.writeBufferEscape.bind(out));
return;
}
//********************************************
// param isn't stream. directly write in buffer
//********************************************
TextEncoder.writeParam(out, value, this.opts, info);
}
}
}
_stream(socket, options) {
this.socket = socket;
options = options || {};
options.objectMode = true;
options.read = () => {
this.socket.resume();
};
this.inStream = new Readable(options);
this.on('fields', function (meta) {
this.inStream.emit('fields', meta);
});
this.on('error', function (err) {
this.inStream.emit('error', err);
});
this.on('close', function (err) {
this.inStream.emit('error', err);
});
this.on('end', function (err) {
if (err) this.inStream.emit('error', err);
this.socket.resume();
this.inStream.push(null);
});
this.inStream.close = function () {
this.handleNewRows = () => {};
this.socket.resume();
}.bind(this);
this.handleNewRows = function (row) {
if (!this.inStream.push(row)) {
this.socket.pause();
}
};
return this.inStream;
}
}
module.exports = Query;
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Command = require('./command');
const QUIT_COMMAND = new Uint8Array([1, 0, 0, 0, 0x01]);
/**
* Quit (close connection)
* see https://mariadb.com/kb/en/library/com_quit/
*/
class Quit extends Command {
constructor(cmdParam, resolve, reject) {
super(cmdParam, resolve, reject);
}
start(out, opts, info) {
if (opts.logger.query) opts.logger.query('QUIT');
this.onPacketReceive = this.skipResults;
out.fastFlush(this, QUIT_COMMAND);
this.emit('send_end');
this.successEnd();
}
skipResults(packet, out, opts, info) {
//deliberately empty, if server send answer
}
}
module.exports = Quit;
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Command = require('./command');
const ServerStatus = require('../const/server-status');
const RESET_COMMAND = new Uint8Array([1, 0, 0, 0, 0x1f]);
/**
* send a COM_RESET_CONNECTION: permits to reset a connection without re-authentication.
* see https://mariadb.com/kb/en/library/com_reset_connection/
*/
class Reset extends Command {
constructor(cmdParam, resolve, reject) {
super(cmdParam, resolve, reject);
}
start(out, opts, info) {
if (opts.logger.query) opts.logger.query('RESET');
this.onPacketReceive = this.readResetResponsePacket;
out.fastFlush(this, RESET_COMMAND);
this.emit('send_end');
}
/**
* Read response packet.
* packet can be :
* - an ERR_Packet
* - a OK_Packet
*
* @param packet query response
* @param out output writer
* @param opts connection options
* @param info connection info
*/
readResetResponsePacket(packet, out, opts, info) {
packet.skip(1); //skip header
packet.skipLengthCodedNumber(); //affected rows
packet.skipLengthCodedNumber(); //insert ids
info.status = packet.readUInt16();
if (info.redirectRequest && (info.status & ServerStatus.STATUS_IN_TRANS) === 0) {
info.redirect(info.redirectRequest, this.successEnd.bind(this));
} else {
this.successEnd();
}
}
}
module.exports = Reset;
+60
View File
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2015-2024 MariaDB Corporation Ab
'use strict';
const Query = require('./query');
const { Readable } = require('stream');
/**
* Protocol COM_QUERY with streaming events.
* see : https://mariadb.com/kb/en/library/com_query/
*/
class Stream extends Query {
constructor(cmdParam, connOpts, socket) {
super(
() => {},
() => {},
connOpts,
cmdParam
);
this.socket = socket;
this.inStream = new Readable({
objectMode: true,
read: () => {
this.socket.resume();
}
});
this.on('fields', function (meta) {
this.inStream.emit('fields', meta);
});
this.on('error', function (err) {
this.inStream.emit('error', err);
});
this.on('close', function (err) {
this.inStream.emit('error', err);
});
this.on('end', function (err) {
if (err) this.inStream.emit('error', err);
this.socket.resume();
this.inStream.push(null);
});
this.inStream.close = function () {
this.handleNewRows = () => {};
this.socket.resume();
}.bind(this);
}
handleNewRows(row) {
if (!this.inStream.push(row)) {
this.socket.pause();
}
}
}
module.exports = Stream;