UNPKG

pg-server

Version:

Postgres DB server emulator, proxy or honeypot

272 lines 10.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CommandParser = void 0; const buffer_reader_1 = require("./buffer-reader"); const commands_1 = require("./commands"); const utils_1 = require("../utils"); // every message is prefixed with a single bye const CODE_LENGTH = 1; // every message has an int32 length which includes itself but does // NOT include the code in the length const LEN_LENGTH = 4; const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH; const emptyBuffer = Buffer.allocUnsafe(0); class CommandParser { constructor(_callback, opts) { this._callback = _callback; this.buffer = emptyBuffer; this.bufferLength = 0; this.bufferOffset = 0; this.reader = new buffer_reader_1.BufferReader(); this.started = false; if ((opts === null || opts === void 0 ? void 0 : opts.mode) === 'binary') { throw new Error('Binary mode not supported yet'); } this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || 'text'; } process(command, offset, len) { let callingback = true; let thisData; this._callback({ command, getRawData: () => { if (thisData) { return thisData; } if (!callingback) { throw new Error(`If you're interested in raw data, please ask for it sooner`); } return thisData = this.buffer.slice(offset, offset + len); }, }); callingback = false; } parse(buffer) { this.mergeBuffer(buffer); const bufferFullLength = this.bufferOffset + this.bufferLength; let offset = this.bufferOffset; if (!this.started) { this.reader.setBuffer(0, this.buffer); const len = this.reader.int32(); const ret = this.parseInit(); this.started = true; this.process(ret, offset, len); offset += len; } else { while (offset + HEADER_LENGTH <= bufferFullLength) { // code is 1 byte long - it identifies the message type const code = this.buffer[offset]; // length is 1 Uint32BE - it is the length of the message EXCLUDING the code const length = this.buffer.readUInt32BE(offset + CODE_LENGTH); const fullMessageLength = CODE_LENGTH + length; if (fullMessageLength + offset <= bufferFullLength) { const message = this.handlePacket(offset + HEADER_LENGTH, code, length); this.process(message, offset, fullMessageLength); offset += fullMessageLength; } else { break; } } } if (offset === bufferFullLength) { // No more use for the buffer this.buffer = emptyBuffer; this.bufferLength = 0; this.bufferOffset = 0; } else { // Adjust the cursors of remainingBuffer this.bufferLength = bufferFullLength - offset; this.bufferOffset = offset; } } mergeBuffer(buffer) { if (this.bufferLength > 0) { const newLength = this.bufferLength + buffer.byteLength; const newFullLength = newLength + this.bufferOffset; if (newFullLength > this.buffer.byteLength) { // We can't concat the new buffer with the remaining one let newBuffer; if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer newBuffer = this.buffer; } else { // Allocate a new larger buffer let newBufferLength = this.buffer.byteLength * 2; while (newLength >= newBufferLength) { newBufferLength *= 2; } newBuffer = Buffer.allocUnsafe(newBufferLength); } // Move the remaining buffer to the new one this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength); this.buffer = newBuffer; this.bufferOffset = 0; } // Concat the new buffer with the remaining one buffer.copy(this.buffer, this.bufferOffset + this.bufferLength); this.bufferLength = newLength; } else { this.buffer = buffer; this.bufferOffset = 0; this.bufferLength = buffer.byteLength; } } handlePacket(offset, type, length) { this.reader.setBuffer(offset, this.buffer); switch (type) { case commands_1.CommandCode.init: throw new Error('Connection already started up'); case commands_1.CommandCode.startup: return this.parseStartup(); case commands_1.CommandCode.parse: return this.parseParse(); case commands_1.CommandCode.bind: return this.parseBind(); case commands_1.CommandCode.describe: case commands_1.CommandCode.close: return this.portalOp(type); case commands_1.CommandCode.execute: return { type, portal: this.reader.cstring(), rows: this.reader.uint32(), }; case commands_1.CommandCode.flush: case commands_1.CommandCode.sync: case commands_1.CommandCode.end: case commands_1.CommandCode.copyDone: return { type }; case commands_1.CommandCode.query: return { type, query: this.reader.cstring(), }; case commands_1.CommandCode.copyFail: return { type, message: this.reader.cstring(), }; case commands_1.CommandCode.copyFromChunk: return { type, buffer: this.reader.bytes(length), }; default: (0, utils_1.expectNever)(type); throw new Error(`unknown command code: ${type.toString(16)}`); } } valuesRead() { const lenFormats = this.reader.int16(); let types = Array(lenFormats); for (let i = 0; i < lenFormats; i++) { types[i] = this.reader.int16(); } const lenValues = this.reader.int16(); // as per spec, if no format is specified, then it means that we have to use text format // https://www.postgresql.org/docs/16/protocol-message-formats.html if (!lenFormats) { types = Array(lenValues).fill(0 /* ParamType.STRING */); } const ret = Array(lenValues); for (let i = 0; i < lenValues; i++) { const type = types[i]; switch (type) { case 0 /* ParamType.STRING */: const strLen = this.reader.int32(); if (strLen >= 0) { ret[i] = this.reader.string(strLen); } else { ret[i] = null; } break; case 1 /* ParamType.BINARY */: const bufLen = this.reader.int32(); ret[i] = this.reader.bytes(bufLen); ; break; } } return ret; } parseInit() { // === PROTOCOL VERSION const major = this.reader.int16(); const minor = this.reader.int16(); if (major !== 3) { throw new Error(`Unsupported protocol version: ${major}.${minor}`); } // === OPTIONS const options = {}; while (true) { const option = this.reader.cstring(); if (!option) { break; } options[option] = this.reader.cstring(); } return { type: commands_1.CommandCode.init, version: { major, minor }, options, }; } parseStartup() { const hash = this.reader.cstring(); return { type: commands_1.CommandCode.startup, md5: hash, }; } parseParse() { const queryName = this.reader.cstring(); const query = this.reader.cstring(); const len = this.reader.int16(); const parameters = []; for (var i = 0; i < len; i++) { parameters.push(this.reader.int32()); } return { type: commands_1.CommandCode.parse, parameters, query, queryName, }; } parseBind() { const portal = this.reader.cstring(); const statement = this.reader.cstring(); const values = this.valuesRead(); const binary = this.reader.int16() === 1 /* ParamType.BINARY */; return { type: commands_1.CommandCode.bind, portal, statement, binary, values, }; } portalOp(type) { const description = this.reader.cstring(); switch (description[0]) { case 'P': case 'S': break; default: throw new Error('Unknown description ' + description); } return { type, portalType: description[0], name: description.length > 1 ? description.substring(1) : undefined, }; } } exports.CommandParser = CommandParser; //# sourceMappingURL=command-parser.js.map