diff --git a/src/panels/TcpDumpPanel.ts b/src/panels/TcpDumpPanel.ts index 369be60c0..fa6c96b14 100644 --- a/src/panels/TcpDumpPanel.ts +++ b/src/panels/TcpDumpPanel.ts @@ -24,7 +24,16 @@ const tcpDumpCommandBase = "tcpdump --snapshot-length=0 -vvv"; const captureDir = "/tmp"; const captureFilePrefix = "vscodenodecap_"; const captureFileBasePath = `${captureDir}/${captureFilePrefix}`; -const captureFilePathRegex = `${captureFileBasePath.replace(/\//g, "\\$&")}(.*)\\.cap`; // Matches the part of the filename after the prefix +const captureFileBasePathEscaped = escapeRegExp(captureFileBasePath); +const captureFilePathRegex = `${captureFileBasePathEscaped}(.*)\\.cap`; // Matches the part of the filename after the prefix + +// Escape all regex meta characters to ensure sanitation and '/' for later use in regex pattern +export function escapeRegExp(input: string): string { + return input.replace(/(\\)?([.*+?^${}()|[\]\\/])/g, (match, backslash, char) => { + // If there's a backslash before the character, return the match unchanged. (To prevent double escaping) + return backslash ? match : `\\${char}`; + }); +} //Reference for regex syntax chars: https://262.ecma-international.org/13.0/index.html#prod-SyntaxCharacter function getPodName(node: NodeName) { return `debug-${node}`; diff --git a/src/tests/suite/TcpDumpPanel.test.ts b/src/tests/suite/TcpDumpPanel.test.ts new file mode 100644 index 000000000..d2b67c6d6 --- /dev/null +++ b/src/tests/suite/TcpDumpPanel.test.ts @@ -0,0 +1,32 @@ +import * as assert from "assert"; +import { escapeRegExp } from "../../panels/TcpDumpPanel"; + +describe("testEscapeRegExp", () => { + it("should escape special regex characters", () => { + const input = "a.b*c?d+e^f$g|h(i)j{k}l[m]n\\o"; + const expected = "a\\.b\\*c\\?d\\+e\\^f\\$g\\|h\\(i\\)j\\{k\\}l\\[m\\]n\\\\o"; + const escapedInput = escapeRegExp(input); + assert.equal(escapedInput, expected); + }); + + it("should not double escape already escaped characters", () => { + const input = "a\\.b\\*c\\?d\\+e\\^f\\$g\\|h\\(i\\)j\\{k\\}l\\[m\\]n\\\\o"; + const expected = "a\\.b\\*c\\?d\\+e\\^f\\$g\\|h\\(i\\)j\\{k\\}l\\[m\\]n\\\\o"; + const escapedInput = escapeRegExp(input); + assert.equal(escapedInput, expected); + }); + + it("should return an empty string if input is empty", () => { + const input = ""; + const expected = ""; + const escapedInput = escapeRegExp(input); + assert.equal(escapedInput, expected); + }); + + it("should return the same string if no special characters", () => { + const input = "abcdefg"; + const expected = "abcdefg"; + const escapedInput = escapeRegExp(input); + assert.equal(escapedInput, expected); + }); +});