From 69ae50a01d110dc9cf1e8418a6234cc99076784d Mon Sep 17 00:00:00 2001 From: Reinier Cruz Date: Thu, 8 Aug 2024 16:27:12 +0000 Subject: [PATCH] Escaping special regex chars --- src/panels/TcpDumpPanel.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/panels/TcpDumpPanel.ts b/src/panels/TcpDumpPanel.ts index 369be60c0..bf14b0ccc 100644 --- a/src/panels/TcpDumpPanel.ts +++ b/src/panels/TcpDumpPanel.ts @@ -24,7 +24,14 @@ 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 +function escapeRegExp(input: string): string { + return input.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); //Escapes by adding '\' to every matched string $& +} +//Reference for regex syntax chars: https://262.ecma-international.org/13.0/index.html#prod-SyntaxCharacter function getPodName(node: NodeName) { return `debug-${node}`; @@ -53,6 +60,20 @@ function getCaptureFromFilePath(filePath: string): string | null { return fileMatch && fileMatch[1]; } +// Test function to verify escaping +function testEscapeRegExp() { + const testString = "/tmp/vscodenodecap_*+?^${}()|[]\\"; + const expectedEscapedString = "\\/tmp\\/vscodenodecap_\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\"; + + const actualEscapedString = escapeRegExp(testString); + console.assert( + actualEscapedString === expectedEscapedString, + `Expected ${expectedEscapedString}, but got ${actualEscapedString}`, + ); +} + +testEscapeRegExp(); + export class TcpDumpPanel extends BasePanel<"tcpDump"> { constructor(extensionUri: Uri) { super(extensionUri, "tcpDump", {