summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor/src/components/messages/parsers/stomp
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 17:32:43 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-07 17:32:43 +0000
commit6bf0a5cb5034a7e684dcc3500e841785237ce2dd (patch)
treea68f146d7fa01f0134297619fbe7e33db084e0aa /devtools/client/netmonitor/src/components/messages/parsers/stomp
parentInitial commit. (diff)
downloadthunderbird-6bf0a5cb5034a7e684dcc3500e841785237ce2dd.tar.xz
thunderbird-6bf0a5cb5034a7e684dcc3500e841785237ce2dd.zip
Adding upstream version 1:115.7.0.upstream/1%115.7.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'devtools/client/netmonitor/src/components/messages/parsers/stomp')
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js204
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js230
5 files changed, 509 insertions, 0 deletions
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
new file mode 100644
index 0000000000..a55d5bff7a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/byte.ts
+ */
+
+"use strict";
+
+const BYTE = {
+ // LINEFEED byte (octet 10)
+ LF: "\x0A",
+ // NULL byte (octet 0)
+ NULL: "\x00",
+};
+
+module.exports = { BYTE };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
new file mode 100644
index 0000000000..679b1140b4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/frame.ts
+ */
+
+"use strict";
+
+const {
+ BYTE,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js");
+
+/**
+ * Frame class represents a STOMP frame.
+ *
+ * @internal
+ */
+class FrameImpl {
+ /**
+ * Frame constructor. `command`, `headers` and `body` are available as properties.
+ *
+ * @internal
+ */
+ constructor(params) {
+ const {
+ command,
+ headers,
+ body,
+ binaryBody,
+ escapeHeaderValues,
+ skipContentLengthHeader,
+ } = params;
+ this.command = command;
+ this.headers = Object.assign({}, headers || {});
+ if (binaryBody) {
+ this._binaryBody = binaryBody;
+ this.isBinaryBody = true;
+ } else {
+ this._body = body || "";
+ this.isBinaryBody = false;
+ }
+ this.escapeHeaderValues = escapeHeaderValues || false;
+ this.skipContentLengthHeader = skipContentLengthHeader || false;
+ }
+ /**
+ * body of the frame
+ */
+ get body() {
+ if (!this._body && this.isBinaryBody) {
+ this._body = new TextDecoder().decode(this._binaryBody);
+ }
+ return this._body;
+ }
+ /**
+ * body as Uint8Array
+ */
+ get binaryBody() {
+ if (!this._binaryBody && !this.isBinaryBody) {
+ this._binaryBody = new TextEncoder().encode(this._body);
+ }
+ return this._binaryBody;
+ }
+ /**
+ * deserialize a STOMP Frame from raw data.
+ *
+ * @internal
+ */
+ static fromRawFrame(rawFrame, escapeHeaderValues) {
+ const headers = {};
+ const trim = str => str.replace(/^\s+|\s+$/g, "");
+ // In case of repeated headers, as per standards, first value need to be used
+ for (const header of rawFrame.headers.reverse()) {
+ const key = trim(header[0]);
+ let value = trim(header[1]);
+ if (
+ escapeHeaderValues &&
+ rawFrame.command !== "CONNECT" &&
+ rawFrame.command !== "CONNECTED"
+ ) {
+ value = FrameImpl.hdrValueUnEscape(value);
+ }
+ headers[key] = value;
+ }
+ return new FrameImpl({
+ command: rawFrame.command,
+ headers,
+ binaryBody: rawFrame.binaryBody,
+ escapeHeaderValues,
+ });
+ }
+ /**
+ * @internal
+ */
+ toString() {
+ return this.serializeCmdAndHeaders();
+ }
+ /**
+ * serialize this Frame in a format suitable to be passed to WebSocket.
+ * If the body is string the output will be string.
+ * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer.
+ *
+ * @internal
+ */
+ serialize() {
+ const cmdAndHeaders = this.serializeCmdAndHeaders();
+ if (this.isBinaryBody) {
+ return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer;
+ }
+ return cmdAndHeaders + this._body + BYTE.NULL;
+ }
+ serializeCmdAndHeaders() {
+ const lines = [this.command];
+ if (this.skipContentLengthHeader) {
+ delete this.headers["content-length"];
+ }
+ for (const name of Object.keys(this.headers || {})) {
+ const value = this.headers[name];
+ if (
+ this.escapeHeaderValues &&
+ this.command !== "CONNECT" &&
+ this.command !== "CONNECTED"
+ ) {
+ lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`);
+ } else {
+ lines.push(`${name}:${value}`);
+ }
+ }
+ if (
+ this.isBinaryBody ||
+ (!this.isBodyEmpty() && !this.skipContentLengthHeader)
+ ) {
+ lines.push(`content-length:${this.bodyLength()}`);
+ }
+ return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF;
+ }
+ isBodyEmpty() {
+ return this.bodyLength() === 0;
+ }
+ bodyLength() {
+ const binaryBody = this.binaryBody;
+ return binaryBody ? binaryBody.length : 0;
+ }
+ /**
+ * Compute the size of a UTF-8 string by counting its number of bytes
+ * (and not the number of characters composing the string)
+ */
+ static sizeOfUTF8(s) {
+ return s ? new TextEncoder().encode(s).length : 0;
+ }
+ static toUnit8Array(cmdAndHeaders, binaryBody) {
+ const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders);
+ const nullTerminator = new Uint8Array([0]);
+ const uint8Frame = new Uint8Array(
+ uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length
+ );
+ uint8Frame.set(uint8CmdAndHeaders);
+ uint8Frame.set(binaryBody, uint8CmdAndHeaders.length);
+ uint8Frame.set(
+ nullTerminator,
+ uint8CmdAndHeaders.length + binaryBody.length
+ );
+ return uint8Frame;
+ }
+ /**
+ * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker.
+ *
+ * @internal
+ */
+ static marshall(params) {
+ const frame = new FrameImpl(params);
+ return frame.serialize();
+ }
+ /**
+ * Escape header values
+ */
+ static hdrValueEscape(str) {
+ return str
+ .replace(/\\/g, "\\\\")
+ .replace(/\r/g, "\\r")
+ .replace(/\n/g, "\\n")
+ .replace(/:/g, "\\c");
+ }
+ /**
+ * UnEscape header values
+ */
+ static hdrValueUnEscape(str) {
+ return str
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\c/g, ":")
+ .replace(/\\\\/g, "\\");
+ }
+}
+
+module.exports = { Frame: FrameImpl };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
new file mode 100644
index 0000000000..d5d441c543
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
@@ -0,0 +1,40 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const frameModule = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js");
+const {
+ Parser,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js");
+const {
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { Frame } = frameModule;
+
+function parseStompJs(message) {
+ let output;
+
+ function onFrame(rawFrame) {
+ const frame = Frame.fromRawFrame(rawFrame);
+ const { error, json } = parseJSON(frame.body);
+
+ output = {
+ command: frame.command,
+ headers: frame.headers,
+ body: error ? frame.body : json,
+ };
+ }
+ const onIncomingPing = () => {};
+ const parser = new Parser(onFrame, onIncomingPing);
+
+ parser.parseChunk(message);
+
+ return output;
+}
+
+module.exports = {
+ parseStompJs,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
new file mode 100644
index 0000000000..420c7479db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
@@ -0,0 +1,10 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "byte.js",
+ "frame.js",
+ "index.js",
+ "parser.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
new file mode 100644
index 0000000000..a7116627d3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/parser.ts
+ */
+
+"use strict";
+
+/**
+ * @internal
+ */
+const NULL = 0;
+/**
+ * @internal
+ */
+const LF = 10;
+/**
+ * @internal
+ */
+const CR = 13;
+/**
+ * @internal
+ */
+const COLON = 58;
+/**
+ * This is an evented, rec descent parser.
+ * A stream of Octets can be passed and whenever it recognizes
+ * a complete Frame or an incoming ping it will invoke the registered callbacks.
+ *
+ * All incoming Octets are fed into _onByte function.
+ * Depending on current state the _onByte function keeps changing.
+ * Depending on the state it keeps accumulating into _token and _results.
+ * State is indicated by current value of _onByte, all states are named as _collect.
+ *
+ * STOMP standards https://stomp.github.io/stomp-specification-1.2.html
+ * imply that all lengths are considered in bytes (instead of string lengths).
+ * So, before actual parsing, if the incoming data is String it is converted to Octets.
+ * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body.
+ *
+ * There is no peek function on the incoming data.
+ * When a state change occurs based on an Octet without consuming the Octet,
+ * the Octet, after state change, is fed again (_reinjectByte).
+ * This became possible as the state change can be determined by inspecting just one Octet.
+ *
+ * There are two modes to collect the body, if content-length header is there then it by counting Octets
+ * otherwise it is determined by NULL terminator.
+ *
+ * Following the standards, the command and headers are converted to Strings
+ * and the body is returned as Octets.
+ * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header.
+ *
+ * This parser does not use Regular Expressions as that can only operate on Strings.
+ *
+ * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or
+ * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk
+ * is pushed.
+ *
+ * Typically the higher level function will convert headers to Hash, handle unescaping of header values
+ * (which is protocol version specific), and convert body to text.
+ *
+ * Check the parser.spec.js to understand cases that this parser is supposed to handle.
+ *
+ * Part of `@stomp/stompjs`.
+ *
+ * @internal
+ */
+class Parser {
+ constructor(onFrame, onIncomingPing) {
+ this.onFrame = onFrame;
+ this.onIncomingPing = onIncomingPing;
+ this._encoder = new TextEncoder();
+ this._decoder = new TextDecoder();
+ this._token = [];
+ this._initState();
+ }
+ parseChunk(segment, appendMissingNULLonIncoming = false) {
+ let chunk;
+ if (segment instanceof ArrayBuffer) {
+ chunk = new Uint8Array(segment);
+ } else {
+ chunk = this._encoder.encode(segment);
+ }
+ // See https://github.com/stomp-js/stompjs/issues/89
+ // Remove when underlying issue is fixed.
+ //
+ // Send a NULL byte, if the last byte of a Text frame was not NULL.F
+ if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) {
+ const chunkWithNull = new Uint8Array(chunk.length + 1);
+ chunkWithNull.set(chunk, 0);
+ chunkWithNull[chunk.length] = 0;
+ chunk = chunkWithNull;
+ }
+ // tslint:disable-next-line:prefer-for-of
+ for (let i = 0; i < chunk.length; i++) {
+ const byte = chunk[i];
+ this._onByte(byte);
+ }
+ }
+ // The following implements a simple Rec Descent Parser.
+ // The grammar is simple and just one byte tells what should be the next state
+ _collectFrame(byte) {
+ if (byte === NULL) {
+ // Ignore
+ return;
+ }
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ // Incoming Ping
+ this.onIncomingPing();
+ return;
+ }
+ this._onByte = this._collectCommand;
+ this._reinjectByte(byte);
+ }
+ _collectCommand(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.command = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaders(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._setupCollectBody();
+ return;
+ }
+ this._onByte = this._collectHeaderKey;
+ this._reinjectByte(byte);
+ }
+ _reinjectByte(byte) {
+ this._onByte(byte);
+ }
+ _collectHeaderKey(byte) {
+ if (byte === COLON) {
+ this._headerKey = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaderValue;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaderValue(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.headers.push([this._headerKey, this._consumeTokenAsUTF8()]);
+ this._headerKey = undefined;
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _setupCollectBody() {
+ const contentLengthHeader = this._results.headers.filter(header => {
+ return header[0] === "content-length";
+ })[0];
+ if (contentLengthHeader) {
+ this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10);
+ this._onByte = this._collectBodyFixedSize;
+ } else {
+ this._onByte = this._collectBodyNullTerminated;
+ }
+ }
+ _collectBodyNullTerminated(byte) {
+ if (byte === NULL) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectBodyFixedSize(byte) {
+ // It is post decrement, so that we discard the trailing NULL octet
+ if (this._bodyBytesRemaining-- === 0) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _retrievedBody() {
+ this._results.binaryBody = this._consumeTokenAsRaw();
+ this.onFrame(this._results);
+ this._initState();
+ }
+ // Rec Descent Parser helpers
+ _consumeByte(byte) {
+ this._token.push(byte);
+ }
+ _consumeTokenAsUTF8() {
+ return this._decoder.decode(this._consumeTokenAsRaw());
+ }
+ _consumeTokenAsRaw() {
+ const rawResult = new Uint8Array(this._token);
+ this._token = [];
+ return rawResult;
+ }
+ _initState() {
+ this._results = {
+ command: undefined,
+ headers: [],
+ binaryBody: undefined,
+ };
+ this._token = [];
+ this._headerKey = undefined;
+ this._onByte = this._collectFrame;
+ }
+}
+
+module.exports = { Parser };