From 7da80cb647b6a553d26977e146b4de2a13ee3801 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 11:18:05 +0800 Subject: [PATCH 1/7] fix: harden debug session loopback binding, auth handshake, and DAP framing - Replace the shared wildcard debug server socket with per-session loopback (127.0.0.1) server sockets, a 256-bit JavaDebug-Auth handshake with constant-time verification, single-client socket closure, and an unused session timeout reaper (protocolVersion >= 2 via startDebugSession). - Enforce initialize lifecycle gating in DebugAdapter before request argument deserialization, guard AttachRequestHandler against uninitialized contexts, and prevent self-PID termination in DebuggeeProcessHelper. - Slice inbound Content-Length frames by UTF-8 byte length rather than UTF-16 character count in AbstractProtocolServer, with header and body size bounds. - Bind JDI launch listening sockets strictly to 127.0.0.1 via LoopbackSocketListeningConnector with debugger-first JDWP-Handshake validation and guaranteed stopListening cleanup across launch error paths. - Add unit and OSGi end-to-end regression tests covering authentication, framing, initialization gating, loopback JDI listening, launch, oDebug, and ttach flows. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../java/debug/core/adapter/DebugAdapter.java | 22 +- .../java/debug/core/adapter/ErrorCode.java | 3 +- .../adapter/handler/AttachRequestHandler.java | 7 + .../handler/DebuggeeProcessHelper.java | 11 +- .../handler/LaunchWithDebuggingDelegate.java | 145 ++-- .../core/protocol/AbstractProtocolServer.java | 283 ++++--- .../DebugAdapterInitializationTest.java | 142 ++++ .../protocol/AbstractProtocolServerTest.java | 161 ++++ .../internal/AdvancedLaunchingConnector.java | 20 +- .../AdvancedVirtualMachineManager.java | 9 + .../debug/plugin/internal/IDebugServer.java | 7 + .../JavaDebugDelegateCommandHandler.java | 47 +- .../plugin/internal/JavaDebugServer.java | 413 ++++++++-- .../internal/JavaDebuggerServerPlugin.java | 1 + .../plugin/internal/LaunchCommandHandler.java | 2 +- .../LoopbackSocketListeningConnector.java | 402 ++++++++++ .../JavaDebugEndToEndFunctionalTest.java | 707 ++++++++++++++++++ .../plugin/internal/JavaDebugServerTest.java | 200 +++++ .../LoopbackSocketListeningConnectorTest.java | 128 ++++ 19 files changed, 2476 insertions(+), 234 deletions(-) create mode 100644 com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/adapter/handler/DebugAdapterInitializationTest.java create mode 100644 com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServerTest.java create mode 100644 com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java create mode 100644 com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java create mode 100644 com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java create mode 100644 com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/DebugAdapter.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/DebugAdapter.java index ac2a24bf9..03ce8a217 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/DebugAdapter.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/DebugAdapter.java @@ -81,11 +81,31 @@ public CompletableFuture dispatchRequest(Messages.Request req response.success = true; Command command = Command.parse(request.command); - Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType()); if (debugContext.isVmTerminated() && command != Command.DISCONNECT) { return CompletableFuture.completedFuture(response); } + if (!debugContext.isInitialized() + && command != Command.INITIALIZE + && command != Command.DISCONNECT + && command != Command.UNSUPPORTED) { + final String errorMessage = String.format( + "'%s' request is rejected since the debug session has not been initialized yet.", request.command); + logger.log(Level.SEVERE, errorMessage); + ErrorCode errorCode = ErrorCode.SESSION_NOT_INITIALIZED; + if (command == Command.LAUNCH) { + errorCode = ErrorCode.LAUNCH_FAILURE; + } else if (command == Command.ATTACH) { + errorCode = ErrorCode.ATTACH_FAILURE; + } + return AdapterUtils.createAsyncErrorResponse(response, errorCode, errorMessage); + } + if (debugContext.isInitialized() && command == Command.INITIALIZE) { + final String errorMessage = "'initialize' request is rejected since the debug session has already been initialized."; + logger.log(Level.SEVERE, errorMessage); + return AdapterUtils.createAsyncErrorResponse(response, ErrorCode.UNKNOWN_FAILURE, errorMessage); + } + Arguments cmdArgs = JsonUtils.fromJson(request.arguments, command.getArgumentType()); List handlers = this.debugContext.getLaunchMode() == LaunchMode.DEBUG ? requestHandlersForDebug.get(command) : requestHandlersForNoDebug.get(command); if (handlers != null && !handlers.isEmpty()) { diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/ErrorCode.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/ErrorCode.java index 6cfe523cf..b6c69060c 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/ErrorCode.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/ErrorCode.java @@ -36,7 +36,8 @@ public enum ErrorCode { EVALUATION_COMPILE_ERROR(2001), EVALUATE_NOT_SUSPENDED_THREAD(2002), HCR_FAILURE(3001), - INVALID_DAP_HEADER(3002); + INVALID_DAP_HEADER(3002), + SESSION_NOT_INITIALIZED(3003); private int id; diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/AttachRequestHandler.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/AttachRequestHandler.java index 5ab848c8a..001c71680 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/AttachRequestHandler.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/AttachRequestHandler.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.logging.Level; import java.util.logging.Logger; import com.microsoft.java.debug.core.Configuration; @@ -55,6 +56,12 @@ public List getTargetCommands() { @Override public CompletableFuture handle(Command command, Arguments arguments, Response response, IDebugAdapterContext context) { + if (!context.isInitialized()) { + final String errorMessage = "'attach' request is rejected since the debug session has not been initialized yet."; + logger.log(Level.SEVERE, errorMessage); + return CompletableFuture.completedFuture( + AdapterUtils.setErrorResponse(response, ErrorCode.SESSION_NOT_INITIALIZED, errorMessage)); + } AttachArguments attachArguments = (AttachArguments) arguments; context.setAttached(true); context.setSourcePaths(attachArguments.sourcePaths); diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/DebuggeeProcessHelper.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/DebuggeeProcessHelper.java index e8478fdd3..34d224c3d 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/DebuggeeProcessHelper.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/DebuggeeProcessHelper.java @@ -23,10 +23,13 @@ static void terminate(IDebugAdapterContext context) { Process debuggeeProcess = context.getDebuggeeProcess(); if (debuggeeProcess != null) { debuggeeProcess.destroy(); - } else if (context.getProcessId() > 0) { - Optional debuggeeHandle = ProcessHandle.of(context.getProcessId()); - if (debuggeeHandle.isPresent()) { - debuggeeHandle.get().destroy(); + } else { + long pid = context.getProcessId(); + if (pid > 0 && pid != ProcessHandle.current().pid()) { + Optional debuggeeHandle = ProcessHandle.of(pid); + if (debuggeeHandle.isPresent()) { + debuggeeHandle.get().destroy(); + } } } } diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/LaunchWithDebuggingDelegate.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/LaunchWithDebuggingDelegate.java index 2962294a0..aefccadee 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/LaunchWithDebuggingDelegate.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/adapter/handler/LaunchWithDebuggingDelegate.java @@ -69,13 +69,23 @@ public CompletableFuture launchInTerminal(LaunchArguments launchArgume vmHandler.setVmProvider(vmProvider); final String launchInTerminalErrorFormat = "Failed to launch debuggee in terminal. Reason: %s"; + ListeningConnector listenConnector = null; + Map args = null; + boolean listenerStarted = false; try { List connectors = vmProvider.getVirtualMachineManager().listeningConnectors(); - ListeningConnector listenConnector = connectors.get(0); - Map args = listenConnector.defaultArguments(); + listenConnector = connectors.get(0); + args = listenConnector.defaultArguments(); ((Connector.IntegerArgument) args.get("timeout")).setValue(ATTACH_TERMINAL_TIMEOUT); + Connector.Argument localAddress = args.get("localAddress"); + if (localAddress != null) { + localAddress.setValue("127.0.0.1"); + } String address = listenConnector.startListening(args); + listenerStarted = true; + final ListeningConnector activeConnector = listenConnector; + final Map activeArgs = args; final String[] names = launchArguments.mainClass.split("[/\\.]"); final String terminalName = "Debug: " + names[names.length - 1]; String[] cmds = LaunchRequestHandler.constructLaunchCommands(launchArguments, false, address); @@ -102,81 +112,89 @@ public CompletableFuture launchInTerminal(LaunchArguments launchArgume // the local .m2 repository path, it may exceed the limit. context.getProtocolServer().sendRequest(request, RUNINTERMINAL_TIMEOUT) .whenComplete((runResponse, ex) -> { - if (runResponse != null) { - if (runResponse.success) { - try { + try { + if (runResponse != null) { + if (runResponse.success) { try { - RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson( - JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class); - context.setProcessId(terminalResponse.processId); - context.setShellProcessId(terminalResponse.shellProcessId); - } catch (JsonSyntaxException e) { - logger.severe("Failed to resolve runInTerminal response: " + e.toString()); - } - VirtualMachine vm = listenConnector.accept(args); - vmHandler.connectVirtualMachine(vm); - context.setDebugSession(new DebugSession(vm)); - logger.info("Launching debuggee in terminal console succeeded."); - if (context.getShellProcessId() > 0) { - ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell(context.getShellProcessId(), cmds[0], 0); - if (debuggeeProcess != null) { - context.setProcessId(debuggeeProcess.pid()); + try { + RunInTerminalResponseBody terminalResponse = JsonUtils.fromJson( + JsonUtils.toJson(runResponse.body), RunInTerminalResponseBody.class); + context.setProcessId(terminalResponse.processId); + context.setShellProcessId(terminalResponse.shellProcessId); + } catch (JsonSyntaxException e) { + logger.severe("Failed to resolve runInTerminal response: " + e.toString()); + } + VirtualMachine vm = activeConnector.accept(activeArgs); + vmHandler.connectVirtualMachine(vm); + context.setDebugSession(new DebugSession(vm)); + logger.info("Launching debuggee in terminal console succeeded."); + if (context.getShellProcessId() > 0) { + ProcessHandle debuggeeProcess = LaunchUtils.findJavaProcessInTerminalShell( + context.getShellProcessId(), cmds[0], 0); + if (debuggeeProcess != null) { + context.setProcessId(debuggeeProcess.pid()); + } + } + resultFuture.complete(response); + } catch (TransportTimeoutException e) { + int commandLength = StringUtils.length(launchArguments.cwd) + 1; + for (String cmd : cmds) { + commandLength += StringUtils.length(cmd) + 1; } - } - resultFuture.complete(response); - } catch (TransportTimeoutException e) { - int commandLength = StringUtils.length(launchArguments.cwd) + 1; - for (String cmd : cmds) { - commandLength += StringUtils.length(cmd) + 1; - } - final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024; - String errorMessage = String.format(launchInTerminalErrorFormat, e.toString()); - if (commandLength >= threshold) { - errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. " - + "More details: " + e.toString(); - logger.severe(errorMessage - + "\r\n" - + "The estimated command line length is " + commandLength + ". " - + "Try to enable shortenCommandLine option in the debug launch configuration."); - } + final int threshold = SystemUtils.IS_OS_WINDOWS ? 8092 : 32 * 1024; + String errorMessage = String.format(launchInTerminalErrorFormat, e.toString()); + if (commandLength >= threshold) { + errorMessage = "Failed to launch debuggee in terminal. The possible reason is the command line too long. " + + "More details: " + e.toString(); + logger.severe(errorMessage + + "\r\n" + + "The estimated command line length is " + commandLength + ". " + + "Try to enable shortenCommandLine option in the debug launch configuration."); + } + resultFuture.completeExceptionally( + new DebugException( + errorMessage, + ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() + ) + ); + } catch (IOException | IllegalConnectorArgumentsException e) { + resultFuture.completeExceptionally( + new DebugException( + String.format(launchInTerminalErrorFormat, e.toString()), + ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() + ) + ); + } + } else { resultFuture.completeExceptionally( new DebugException( - errorMessage, - ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() - ) - ); - } catch (IOException | IllegalConnectorArgumentsException e) { - resultFuture.completeExceptionally( - new DebugException( - String.format(launchInTerminalErrorFormat, e.toString()), + String.format(launchInTerminalErrorFormat, runResponse.message), ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() ) ); } } else { + if (ex instanceof CompletionException && ex.getCause() != null) { + ex = ex.getCause(); + } + String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response"); resultFuture.completeExceptionally( new DebugException( - String.format(launchInTerminalErrorFormat, runResponse.message), + String.format(launchInTerminalErrorFormat, errorMessage), ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() ) ); } - } else { - if (ex instanceof CompletionException && ex.getCause() != null) { - ex = ex.getCause(); - } - String errorMessage = String.format(launchInTerminalErrorFormat, ex != null ? ex.toString() : "Null response"); - resultFuture.completeExceptionally( - new DebugException( - String.format(launchInTerminalErrorFormat, errorMessage), - ErrorCode.LAUNCH_IN_TERMINAL_FAILURE.getId() - ) - ); + } finally { + stopListeningQuietly(activeConnector, activeArgs); } }); - } catch (IOException | IllegalConnectorArgumentsException e) { + } catch (IOException | IllegalConnectorArgumentsException | RuntimeException e) { + if (listenerStarted) { + stopListeningQuietly(listenConnector, args); + } resultFuture.completeExceptionally( new DebugException( String.format(launchInTerminalErrorFormat, e.toString()), @@ -246,4 +264,15 @@ public void preLaunch(LaunchArguments launchArguments, IDebugAdapterContext cont context.setMainClass(LaunchRequestHandler.parseMainClassWithoutModuleName(launchArguments.mainClass)); context.setStepFilters(launchArguments.stepFilters); } + + private static void stopListeningQuietly(ListeningConnector connector, Map args) { + if (connector == null) { + return; + } + try { + connector.stopListening(args); + } catch (IOException | IllegalConnectorArgumentsException e) { + logger.fine("Failed to close JDI listening socket: " + e.toString()); + } + } } diff --git a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServer.java b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServer.java index 61d57bd85..5d3a3e962 100644 --- a/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServer.java +++ b/com.microsoft.java.debug.core/src/main/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServer.java @@ -11,16 +11,10 @@ package com.microsoft.java.debug.core.protocol; -import java.io.BufferedReader; -import java.io.BufferedWriter; +import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Timer; @@ -44,14 +38,20 @@ public abstract class AbstractProtocolServer implements IProtocolServer { private static final Logger logger = Logger.getLogger("java-debug"); private static final int BUFFER_SIZE = 4096; + private static final int COMPACT_THRESHOLD = 64 * 1024; + static final int MAX_HEADER_LENGTH = 8 * 1024; + static final int DEFAULT_MAX_CONTENT_LENGTH = 32 * 1024 * 1024; private static final String TWO_CRLF = "\r\n\r\n"; - private static final Pattern CONTENT_LENGTH_MATCHER = Pattern.compile("Content-Length: (\\d+)"); + private static final int TWO_CRLF_BYTES = 4; + private static final Pattern CONTENT_LENGTH_MATCHER = Pattern.compile("Content-Length: (-?\\d+)"); private static final Charset PROTOCOL_ENCODING = StandardCharsets.UTF_8; // vscode protocol uses UTF-8 as encoding format. - protected boolean terminateSession = false; + protected volatile boolean terminateSession = false; - private Reader reader; - private Writer writer; + private InputStream inputStream; + private OutputStream outputStream; + private final Object outputLock = new Object(); + private final int maxContentLength; private ByteBuffer rawData; private int contentLength = -1; @@ -71,8 +71,13 @@ public abstract class AbstractProtocolServer implements IProtocolServer { * the output stream */ public AbstractProtocolServer(InputStream input, OutputStream output) { - this.reader = new BufferedReader(new InputStreamReader(input, PROTOCOL_ENCODING)); - this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output, PROTOCOL_ENCODING))); + this(input, output, DEFAULT_MAX_CONTENT_LENGTH); + } + + AbstractProtocolServer(InputStream input, OutputStream output, int maxContentLength) { + this.inputStream = input; + this.outputStream = new BufferedOutputStream(output); + this.maxContentLength = maxContentLength; this.contentLength = -1; this.rawData = new ByteBuffer(); @@ -89,19 +94,21 @@ public AbstractProtocolServer(InputStream input, OutputStream output) { * A while-loop to parse input data and send output data constantly. */ public void run() { - char[] buffer = new char[BUFFER_SIZE]; + byte[] buffer = new byte[BUFFER_SIZE]; try { while (!this.terminateSession) { - int read = this.reader.read(buffer, 0, BUFFER_SIZE); + int read = this.inputStream.read(buffer, 0, BUFFER_SIZE); if (read == -1) { break; } - this.rawData.append(new String(buffer, 0, read).getBytes(PROTOCOL_ENCODING)); + this.rawData.append(buffer, read); this.processData(); } } catch (IOException e) { - logger.log(Level.SEVERE, String.format("Read data from io exception: %s", e.toString()), e); + if (!this.terminateSession) { + logger.log(Level.SEVERE, String.format("Read data from io exception: %s", e.toString()), e); + } } requestSubject.onComplete(); @@ -130,22 +137,22 @@ private void sendMessage(Messages.ProtocolMessage message) { String header = String.format("Content-Length: %d%s", jsonBytes.length, TWO_CRLF); byte[] headerBytes = header.getBytes(PROTOCOL_ENCODING); - ByteBuffer data = new ByteBuffer(); - data.append(headerBytes); - data.append(jsonBytes); - - String utf8Data = data.getString(PROTOCOL_ENCODING); - try { - if (message instanceof Messages.Request) { - logger.fine("\n[[REQUEST]]\n" + utf8Data); - } else if (message instanceof Messages.Event) { - logger.fine("\n[[EVENT]]\n" + utf8Data); - } else { - logger.fine("\n[[RESPONSE]]\n" + utf8Data); + if (logger.isLoggable(Level.FINE)) { + String utf8Data = header + jsonMessage; + if (message instanceof Messages.Request) { + logger.fine("\n[[REQUEST]]\n" + utf8Data); + } else if (message instanceof Messages.Event) { + logger.fine("\n[[EVENT]]\n" + utf8Data); + } else { + logger.fine("\n[[RESPONSE]]\n" + utf8Data); + } + } + synchronized (this.outputLock) { + this.outputStream.write(headerBytes); + this.outputStream.write(jsonBytes); + this.outputStream.flush(); } - this.writer.write(utf8Data); - this.writer.flush(); } catch (IOException e) { logger.log(Level.SEVERE, String.format("Write data to io exception: %s", e.toString()), e); } @@ -203,85 +210,123 @@ public void run() { } private void processData() { - while (true) { + while (!this.terminateSession) { /** * In vscode debug protocol, the content length represents the * message's byte length with utf8 format. */ if (this.contentLength >= 0) { - if (this.rawData.length() >= this.contentLength) { - byte[] buf = this.rawData.removeFirst(this.contentLength); - this.contentLength = -1; - String messageData = new String(buf, PROTOCOL_ENCODING); - try { - Messages.ProtocolMessage message = JsonUtils.fromJson(messageData, Messages.ProtocolMessage.class); - - logger.fine(String.format("\n[%s]\n%s", message.type, messageData)); - - if (message.type.equals("request")) { - Messages.Request request = JsonUtils.fromJson(messageData, Messages.Request.class); - if (this.isValidDAPRequest) { - requestSubject.onNext(request); - } else { - Messages.Response response = new Messages.Response(request.seq, request.command); - sendResponse(AdapterUtils.setErrorResponse(response, - ErrorCode.INVALID_DAP_HEADER, - String.format("'%s' request is rejected due to not being a valid DAP message.", request.command))); - } - } else if (message.type.equals("response")) { - Messages.Response response = JsonUtils.fromJson(messageData, Messages.Response.class); - responseSubject.onNext(response); - } - } catch (Exception ex) { - logger.log(Level.SEVERE, String.format("Error parsing message: %s", ex.toString()), ex); + if (this.rawData.length() < this.contentLength) { + break; + } + byte[] buf = this.rawData.removeFirst(this.contentLength); + this.contentLength = -1; + String messageData = new String(buf, PROTOCOL_ENCODING); + try { + Messages.ProtocolMessage message = JsonUtils.fromJson(messageData, Messages.ProtocolMessage.class); + if (message == null || message.type == null) { + continue; } - continue; + logger.fine(String.format("\n[%s]\n%s", message.type, messageData)); + + if (message.type.equals("request")) { + Messages.Request request = JsonUtils.fromJson(messageData, Messages.Request.class); + if (this.isValidDAPRequest) { + requestSubject.onNext(request); + } else { + Messages.Response response = new Messages.Response(request.seq, request.command); + sendResponse(AdapterUtils.setErrorResponse(response, + ErrorCode.INVALID_DAP_HEADER, + String.format("'%s' request is rejected due to not being a valid DAP message.", request.command))); + } + } else if (message.type.equals("response")) { + Messages.Response response = JsonUtils.fromJson(messageData, Messages.Response.class); + responseSubject.onNext(response); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, String.format("Error parsing message: %s", ex.toString()), ex); } + continue; } - String rawMessage = this.rawData.getString(PROTOCOL_ENCODING); - int idx = rawMessage.indexOf(TWO_CRLF); - if (idx != -1) { - Matcher matcher = CONTENT_LENGTH_MATCHER.matcher(rawMessage); - if (matcher.find()) { - final String contentLengthText = matcher.group(1); - this.contentLength = Integer.parseInt(contentLengthText); - final String headerMessage = rawMessage.substring(0, idx + TWO_CRLF.length()); - final int headerByteLength = headerMessage.getBytes(PROTOCOL_ENCODING).length; - this.rawData.removeFirst(headerByteLength); // Remove the header from the raw message. - - int expectedHeaderLength = 16 /*"Content-Length: ".length()*/ + contentLengthText.length(); - int actualHeaderLength = idx; - if (expectedHeaderLength != actualHeaderLength) { - this.isValidDAPRequest = false; - logger.log(Level.SEVERE, String.format("Illegal DAP request is detected: %s", headerMessage)); - } else { - this.isValidDAPRequest = true; - } - continue; + int idx = this.rawData.indexOfHeaderDelimiter(MAX_HEADER_LENGTH + TWO_CRLF_BYTES); + if (idx == -1) { + if (this.rawData.length() > MAX_HEADER_LENGTH) { + logger.log(Level.SEVERE, String.format( + "DAP header exceeds maximum allowed size (%d bytes).", MAX_HEADER_LENGTH)); + abortProtocolStream(); } + break; + } + + byte[] headerBytes = this.rawData.removeFirst(idx + TWO_CRLF_BYTES); + String headerMessage = new String(headerBytes, 0, idx, PROTOCOL_ENCODING); + Matcher matcher = CONTENT_LENGTH_MATCHER.matcher(headerMessage); + if (!matcher.find()) { + logger.log(Level.SEVERE, String.format("Illegal DAP header without Content-Length: %s", headerMessage)); + abortProtocolStream(); + break; + } + + final String contentLengthText = matcher.group(1); + final long parsedLength; + try { + parsedLength = Long.parseLong(contentLengthText); + } catch (NumberFormatException ex) { + logger.log(Level.SEVERE, String.format("Invalid DAP Content-Length: %s", contentLengthText)); + abortProtocolStream(); + break; + } + if (parsedLength < 0 || parsedLength > this.maxContentLength) { + logger.log(Level.SEVERE, String.format( + "DAP Content-Length %d is out of allowed bounds [0, %d].", parsedLength, this.maxContentLength)); + abortProtocolStream(); + break; } - break; + this.contentLength = (int) parsedLength; + int expectedHeaderLength = 16 /* "Content-Length: ".length() */ + contentLengthText.length(); + if (expectedHeaderLength != idx) { + this.isValidDAPRequest = false; + logger.log(Level.SEVERE, String.format("Illegal DAP request is detected: %s", headerMessage)); + } else { + this.isValidDAPRequest = true; + } } } + private void abortProtocolStream() { + this.terminateSession = true; + this.contentLength = -1; + this.rawData.clear(); + } + protected abstract void dispatchRequest(Messages.Request request); - class ByteBuffer { + static class ByteBuffer { private byte[] buffer; + private int start; + private int end; public ByteBuffer() { - this.buffer = new byte[0]; + this.buffer = new byte[BUFFER_SIZE]; + this.start = 0; + this.end = 0; } public int length() { - return this.buffer.length; + return this.end - this.start; } public String getString(Charset cs) { - return new String(this.buffer, cs); + return new String(this.buffer, this.start, length(), cs); + } + + public void clear() { + this.buffer = new byte[0]; + this.start = 0; + this.end = 0; } public void append(byte[] b) { @@ -289,19 +334,75 @@ public void append(byte[] b) { } public void append(byte[] b, int length) { - byte[] newBuffer = new byte[this.buffer.length + length]; - System.arraycopy(buffer, 0, newBuffer, 0, this.buffer.length); - System.arraycopy(b, 0, newBuffer, this.buffer.length, length); - this.buffer = newBuffer; + if (length <= 0) { + return; + } + ensureCapacity(length); + System.arraycopy(b, 0, this.buffer, this.end, length); + this.end += length; + } + + public int indexOfHeaderDelimiter(int maxScanBytes) { + int available = length(); + int scanLimit = Math.min(available, maxScanBytes); + if (scanLimit < TWO_CRLF_BYTES) { + return -1; + } + int lastStart = this.start + scanLimit - TWO_CRLF_BYTES; + for (int i = this.start; i <= lastStart; i++) { + if (this.buffer[i] == '\r' + && this.buffer[i + 1] == '\n' + && this.buffer[i + 2] == '\r' + && this.buffer[i + 3] == '\n') { + return i - this.start; + } + } + return -1; } public byte[] removeFirst(int n) { byte[] b = new byte[n]; - System.arraycopy(this.buffer, 0, b, 0, n); - byte[] newBuffer = new byte[this.buffer.length - n]; - System.arraycopy(this.buffer, n, newBuffer, 0, this.buffer.length - n); - this.buffer = newBuffer; + System.arraycopy(this.buffer, this.start, b, 0, n); + this.start += n; + if (this.start == this.end) { + this.start = 0; + this.end = 0; + if (this.buffer.length > COMPACT_THRESHOLD) { + this.buffer = new byte[BUFFER_SIZE]; + } + } else if (this.start >= COMPACT_THRESHOLD && this.start >= length()) { + int remaining = length(); + System.arraycopy(this.buffer, this.start, this.buffer, 0, remaining); + this.start = 0; + this.end = remaining; + } return b; } + + private void ensureCapacity(int additional) { + if (this.end + additional <= this.buffer.length) { + return; + } + int currentLength = length(); + if (this.start > 0 && currentLength + additional <= this.buffer.length) { + System.arraycopy(this.buffer, this.start, this.buffer, 0, currentLength); + this.start = 0; + this.end = currentLength; + return; + } + int minCapacity = currentLength + additional; + int doubled = this.buffer.length == 0 ? BUFFER_SIZE : this.buffer.length * 2; + if (doubled < 0) { + doubled = minCapacity; + } + int newCapacity = Math.max(Math.max(BUFFER_SIZE, doubled), minCapacity); + byte[] newBuffer = new byte[newCapacity]; + if (currentLength > 0) { + System.arraycopy(this.buffer, this.start, newBuffer, 0, currentLength); + } + this.buffer = newBuffer; + this.start = 0; + this.end = currentLength; + } } } diff --git a/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/adapter/handler/DebugAdapterInitializationTest.java b/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/adapter/handler/DebugAdapterInitializationTest.java new file mode 100644 index 000000000..459d06cc2 --- /dev/null +++ b/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/adapter/handler/DebugAdapterInitializationTest.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.core.adapter.handler; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import org.easymock.EasyMock; +import org.junit.Test; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.microsoft.java.debug.core.adapter.DebugAdapter; +import com.microsoft.java.debug.core.adapter.DebugAdapterContext; +import com.microsoft.java.debug.core.adapter.ICompletionsProvider; +import com.microsoft.java.debug.core.adapter.IEvaluationProvider; +import com.microsoft.java.debug.core.adapter.IHotCodeReplaceProvider; +import com.microsoft.java.debug.core.adapter.IProviderContext; +import com.microsoft.java.debug.core.adapter.ISourceLookUpProvider; +import com.microsoft.java.debug.core.adapter.IVirtualMachineManagerProvider; +import com.microsoft.java.debug.core.adapter.ProviderContext; +import com.microsoft.java.debug.core.protocol.Events.DebugEvent; +import com.microsoft.java.debug.core.protocol.IProtocolServer; +import com.microsoft.java.debug.core.protocol.Messages.Request; +import com.microsoft.java.debug.core.protocol.Messages.Response; +import com.microsoft.java.debug.core.protocol.Requests.AttachArguments; +import com.microsoft.java.debug.core.protocol.Requests.Command; + +import io.reactivex.subjects.PublishSubject; + +public class DebugAdapterInitializationTest { + + @Test + public void rejectsCommandsBeforeInitializeExceptDisconnect() { + StubProtocolServer protocolServer = new StubProtocolServer(); + DebugAdapter adapter = new DebugAdapter(protocolServer, createMinimalProviderContext()); + + String[] gatedCommands = new String[] { + "launch", "attach", "terminate", "evaluate", "threads", "setBreakpoints", "redefineClasses" + }; + for (String command : gatedCommands) { + Response response = adapter.dispatchRequest(new Request(1, command, new JsonObject())).join(); + assertFalse("Command '" + command + "' must be rejected before initialize.", response.success); + assertNotNull(response.body); + } + + JsonObject malformedLaunchArgs = new JsonObject(); + malformedLaunchArgs.add("args", new JsonArray()); + Response malformedPreInit = adapter.dispatchRequest(new Request(2, "launch", malformedLaunchArgs)).join(); + assertFalse("Malformed launch arguments before initialize must still be rejected cleanly.", malformedPreInit.success); + + Response disconnectResponse = adapter.dispatchRequest(new Request(3, "disconnect", new JsonObject())).join(); + assertTrue("Disconnect before initialize must remain permitted for clean teardown.", disconnectResponse.success); + } + + @Test + public void allowsInitializeOnceAndRejectsDuplicateInitialize() { + StubProtocolServer protocolServer = new StubProtocolServer(); + DebugAdapter adapter = new DebugAdapter(protocolServer, createMinimalProviderContext()); + + Response firstInit = adapter.dispatchRequest(new Request(1, "initialize", new JsonObject())).join(); + assertTrue(firstInit.success); + + Response duplicateInit = adapter.dispatchRequest(new Request(2, "initialize", new JsonObject())).join(); + assertFalse("Duplicate initialize on an already initialized session must be rejected.", duplicateInit.success); + } + + @Test + public void attachHandlerRejectsUninitializedContextDirectly() { + DebugAdapterContext uninitializedContext = new DebugAdapterContext( + new StubProtocolServer(), createMinimalProviderContext()); + AttachRequestHandler handler = new AttachRequestHandler(); + Response response = handler.handle( + Command.ATTACH, new AttachArguments(), new Response(1, "attach"), uninitializedContext).join(); + assertFalse("Uninitialized attach request must fail.", response.success); + assertNotNull(response.body); + } + + @Test + public void debuggeeProcessHelperDoesNotTerminateCurrentJvmProcess() { + long selfPid = ProcessHandle.current().pid(); + DebugAdapterContext context = new DebugAdapterContext(new StubProtocolServer(), createMinimalProviderContext()); + context.setProcessId(selfPid); + DebuggeeProcessHelper.terminate(context); + assertTrue("Current JVM process must remain alive.", ProcessHandle.current().isAlive()); + } + + private static IProviderContext createMinimalProviderContext() { + ProviderContext context = new ProviderContext(); + ISourceLookUpProvider sourceProvider = EasyMock.createNiceMock(ISourceLookUpProvider.class); + IVirtualMachineManagerProvider vmProvider = EasyMock.createNiceMock(IVirtualMachineManagerProvider.class); + IHotCodeReplaceProvider hcrProvider = EasyMock.createNiceMock(IHotCodeReplaceProvider.class); + EasyMock.expect(hcrProvider.getEventHub()).andReturn(PublishSubject.create()).anyTimes(); + ICompletionsProvider completionsProvider = EasyMock.createNiceMock(ICompletionsProvider.class); + IEvaluationProvider evaluationProvider = EasyMock.createNiceMock(IEvaluationProvider.class); + EasyMock.replay(sourceProvider, vmProvider, hcrProvider, completionsProvider, evaluationProvider); + + context.registerProvider(ISourceLookUpProvider.class, sourceProvider); + context.registerProvider(IVirtualMachineManagerProvider.class, vmProvider); + context.registerProvider(IHotCodeReplaceProvider.class, hcrProvider); + context.registerProvider(ICompletionsProvider.class, completionsProvider); + context.registerProvider(IEvaluationProvider.class, evaluationProvider); + return context; + } + + private static final class StubProtocolServer implements IProtocolServer { + private final List events = new ArrayList<>(); + + @Override + public void sendResponse(Response response) { + } + + @Override + public void sendEvent(DebugEvent event) { + events.add(event); + } + + @Override + public CompletableFuture sendRequest(Request request) { + return CompletableFuture.completedFuture(new Response(request.seq, request.command, true)); + } + + @Override + public CompletableFuture sendRequest(Request request, long timeout) { + return CompletableFuture.completedFuture(new Response(request.seq, request.command, true)); + } + } +} diff --git a/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServerTest.java b/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServerTest.java new file mode 100644 index 000000000..fe24fc38e --- /dev/null +++ b/com.microsoft.java.debug.core/src/test/java/com/microsoft/java/debug/core/protocol/AbstractProtocolServerTest.java @@ -0,0 +1,161 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.core.protocol; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import com.google.gson.JsonObject; +import com.microsoft.java.debug.core.adapter.ErrorCode; +import com.microsoft.java.debug.core.protocol.Messages.Request; +import com.microsoft.java.debug.core.protocol.Messages.Response; + +public class AbstractProtocolServerTest { + + @Test + public void handlesBackToBackMultiByteUtf8FramesAndEmbeddedCrLf() throws Exception { + String firstBody = "{\"seq\":1,\"type\":\"request\",\"command\":\"evaluate\"," + + "\"arguments\":{\"expression\":\"\u3053\u3093\u306b\u3061\u306f\\r\\n\\r\\n\ud83d\ude80\"}}"; + String secondBody = "{\"seq\":2,\"type\":\"request\",\"command\":\"disconnect\",\"arguments\":{}}"; + + byte[] streamBytes = concatFrames(frameDap(firstBody), frameDap(secondBody)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + List received = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch latch = new CountDownLatch(2); + + AbstractProtocolServer server = new RecordingProtocolServer( + new ByteArrayInputStream(streamBytes), out, received, latch, 1024 * 1024); + server.run(); + + assertTrue("Expected both framed requests to be dispatched.", latch.await(5, TimeUnit.SECONDS)); + assertEquals(2, received.size()); + assertEquals("evaluate", received.get(0).command); + JsonObject exprArgs = received.get(0).arguments; + assertEquals("\u3053\u3093\u306b\u3061\u306f\r\n\r\n\ud83d\ude80", exprArgs.get("expression").getAsString()); + assertEquals("disconnect", received.get(1).command); + } + + @Test + public void rejectsHttpCrossProtocolHeaderWithInvalidDapHeaderError() { + String requestJson = "{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\"}"; + byte[] jsonBytes = requestJson.getBytes(StandardCharsets.UTF_8); + String httpPayload = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " + + jsonBytes.length + "\r\n\r\n" + requestJson; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + List received = Collections.synchronizedList(new ArrayList<>()); + + AbstractProtocolServer server = new RecordingProtocolServer( + new ByteArrayInputStream(httpPayload.getBytes(StandardCharsets.UTF_8)), + out, + received, + new CountDownLatch(0), + 1024 * 1024); + server.run(); + + assertTrue("HTTP request must not be dispatched as a DAP request.", received.isEmpty()); + String outputText = out.toString(StandardCharsets.UTF_8); + assertTrue(outputText.contains("\"id\":" + ErrorCode.INVALID_DAP_HEADER.getId())); + } + + @Test + public void rejectsOversizedContentLengthBeforeAllocatingPayload() { + String oversizedFrame = "Content-Length: 999999999\r\n\r\n{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\"}"; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + List received = Collections.synchronizedList(new ArrayList<>()); + + RecordingProtocolServer server = new RecordingProtocolServer( + new ByteArrayInputStream(oversizedFrame.getBytes(StandardCharsets.US_ASCII)), + out, + received, + new CountDownLatch(0), + 4096); + server.run(); + + assertTrue(received.isEmpty()); + assertTrue(server.isTerminated()); + assertEquals(0, out.size()); + } + + @Test + public void rejectsUnboundedHeaderWithoutTerminator() { + StringBuilder headerFlood = new StringBuilder("Content-Length: 10"); + while (headerFlood.length() < 10_000) { + headerFlood.append(' '); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + List received = Collections.synchronizedList(new ArrayList<>()); + + RecordingProtocolServer server = new RecordingProtocolServer( + new ByteArrayInputStream(headerFlood.toString().getBytes(StandardCharsets.US_ASCII)), + out, + received, + new CountDownLatch(0), + 4096); + server.run(); + + assertTrue(received.isEmpty()); + assertTrue(server.isTerminated()); + assertEquals(0, out.size()); + } + + private static byte[] frameDap(String json) { + byte[] body = json.getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + return concatFrames(header, body); + } + + private static byte[] concatFrames(byte[] first, byte[] second) { + byte[] combined = new byte[first.length + second.length]; + System.arraycopy(first, 0, combined, 0, first.length); + System.arraycopy(second, 0, combined, first.length, second.length); + return combined; + } + + private static final class RecordingProtocolServer extends AbstractProtocolServer { + private final List recordedRequests; + private final CountDownLatch latch; + + RecordingProtocolServer( + ByteArrayInputStream in, + ByteArrayOutputStream out, + List recordedRequests, + CountDownLatch latch, + int maxContentLength) { + super(in, out, maxContentLength); + this.recordedRequests = recordedRequests; + this.latch = latch; + } + + boolean isTerminated() { + return this.terminateSession; + } + + @Override + protected void dispatchRequest(Request request) { + recordedRequests.add(request); + sendResponse(new Response(request.seq, request.command, true)); + latch.countDown(); + } + } +} diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java index 24c65785d..c8718e10b 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java @@ -82,7 +82,7 @@ public VirtualMachine launch(Map connectionArgs) // do nothing. } - SocketListeningConnectorImpl listenConnector = new SocketListeningConnectorImpl( + SocketListeningConnectorImpl listenConnector = new LoopbackSocketListeningConnector( virtualMachineManager()); Map args = listenConnector.defaultArguments(); ((Connector.IntegerArgument) args.get("timeout")).setValue(ACCEPT_TIMEOUT); //$NON-NLS-1$ @@ -91,7 +91,17 @@ public VirtualMachine launch(Map connectionArgs) String[] cmds = constructLaunchCommand(connectionArgs, address); /* Launch the Java process */ - final Process process = Runtime.getRuntime().exec(cmds, envVars, workingDir); + final Process process; + try { + process = Runtime.getRuntime().exec(cmds, envVars, workingDir); + } catch (IOException | RuntimeException ex) { + try { + listenConnector.stopListening(args); + } catch (IOException closeEx) { + // ignore cleanup failure + } + throw ex; + } /* A Future that will be completed if we successfully connect to the launched process, or will fail with an Exception if we do not. @@ -127,6 +137,12 @@ public VirtualMachine launch(Map connectionArgs) )); } catch (RuntimeException e) { result.completeExceptionally(e); + } finally { + try { + listenConnector.stopListening(args); + } catch (IOException e) { + /* Ignore */ + } } }); diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedVirtualMachineManager.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedVirtualMachineManager.java index a77bdda62..118858cc9 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedVirtualMachineManager.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedVirtualMachineManager.java @@ -21,6 +21,7 @@ import com.sun.jdi.VirtualMachine; import com.sun.jdi.VirtualMachineManager; import com.sun.jdi.connect.LaunchingConnector; +import com.sun.jdi.connect.ListeningConnector; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; @@ -46,6 +47,14 @@ public List launchingConnectors() { return connectors; } + @Override + public List listeningConnectors() { + List connectors = new ArrayList<>(); + connectors.add(new LoopbackSocketListeningConnector(this)); + connectors.addAll(super.listeningConnectors()); + return connectors; + } + @Override public void update(DebugSettings oldSettings, DebugSettings newSettings) { int currentTimeout = getGlobalRequestTimeout(); diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/IDebugServer.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/IDebugServer.java index 60ac3ff8a..b496035e7 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/IDebugServer.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/IDebugServer.java @@ -11,7 +11,14 @@ package com.microsoft.java.debug.plugin.internal; +import java.io.IOException; +import java.util.Map; + public interface IDebugServer { + Map startDebugSession() throws IOException; + + int startLegacyLoopbackSession() throws IOException; + int getPort(); void start(); diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugDelegateCommandHandler.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugDelegateCommandHandler.java index f4e7b0ba3..9950a07b1 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugDelegateCommandHandler.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugDelegateCommandHandler.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; @@ -54,9 +55,7 @@ public class JavaDebugDelegateCommandHandler implements IDelegateCommandHandler public Object executeCommand(String commandId, List arguments, IProgressMonitor progress) throws Exception { switch (commandId) { case DEBUG_STARTSESSION: - IDebugServer debugServer = JavaDebugServer.getInstance(); - debugServer.start(); - return debugServer.getPort(); + return startDebugSession(arguments); case RESOLVE_CLASSPATH: ResolveClasspathsHandler handler = new ResolveClasspathsHandler(); return handler.resolveClasspaths(arguments); @@ -138,4 +137,46 @@ private boolean isOnClasspath(List arguments) throws DebugException { IJavaProject javaProject = unit.getJavaProject(); return javaProject == null || javaProject.isOnClasspath(unit); } + + static Object startDebugSession(List arguments) throws Exception { + IDebugServer debugServer = JavaDebugServer.getInstance(); + int requestedProtocolVersion = parseRequestedProtocolVersion(arguments); + if (requestedProtocolVersion >= JavaDebugServer.PROTOCOL_VERSION) { + return debugServer.startDebugSession(); + } + if (Boolean.getBoolean(JavaDebugServer.ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY)) { + return debugServer.startLegacyLoopbackSession(); + } + throw new DebugException( + "Unauthenticated Java debug sessions are disabled. Upgrade the Java debugger client or pass protocolVersion >= 2."); + } + + static int parseRequestedProtocolVersion(List arguments) { + if (arguments == null || arguments.isEmpty() || arguments.get(0) == null) { + return 1; + } + Object firstArg = arguments.get(0); + if (firstArg instanceof String) { + StartDebugSessionOptions options = JsonUtils.fromJson((String) firstArg, StartDebugSessionOptions.class); + return options != null ? options.protocolVersion : 1; + } + if (firstArg instanceof Map) { + Object rawVersion = ((Map) firstArg).get("protocolVersion"); + if (rawVersion instanceof Number) { + return ((Number) rawVersion).intValue(); + } + if (rawVersion instanceof String) { + try { + return Integer.parseInt((String) rawVersion); + } catch (NumberFormatException ex) { + return 1; + } + } + } + return 1; + } + + static class StartDebugSessionOptions { + int protocolVersion = 1; + } } diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java index 32ab195b7..15c85e359 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java @@ -11,40 +11,78 @@ package com.microsoft.java.debug.plugin.internal; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Collections; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import com.microsoft.java.debug.core.Configuration; +import com.microsoft.java.debug.core.adapter.IProviderContext; import com.microsoft.java.debug.core.adapter.ProtocolServer; public class JavaDebugServer implements IDebugServer { + public static final String AUTH_HEADER_PREFIX = "JavaDebug-Auth: "; + public static final String ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY = "java.debug.allowUnauthenticatedLoopback"; + public static final int PROTOCOL_VERSION = 2; + private static final Logger logger = Logger.getLogger(Configuration.LOGGER_NAME); + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static final int AUTH_TOKEN_BYTES = 32; + private static final int DEFAULT_ACCEPT_TIMEOUT_MS = 30_000; + private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000; + private static final int MAX_AUTH_FRAME_BYTES = 256; + private static final int SESSION_BACKLOG = 8; + private static final int MAX_CONCURRENT_TASKS = 128; + private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(1); + private static JavaDebugServer singletonInstance; - private ServerSocket serverSocket = null; - private boolean isStarted = false; - private ExecutorService executor = null; + private final Supplier providerContextFactory; + private final int acceptTimeoutMs; + private final int handshakeTimeoutMs; + private final Set pendingListeners = ConcurrentHashMap.newKeySet(); + private final Set activeSessions = ConcurrentHashMap.newKeySet(); + private final AtomicBoolean stopped = new AtomicBoolean(false); + private ExecutorService executor; private JavaDebugServer() { - try { - this.serverSocket = new ServerSocket(0, 1); - } catch (IOException e) { - logger.log(Level.SEVERE, String.format("Failed to create Java Debug Server: %s", e.toString()), e); - } + this(JdtProviderContextFactory::createProviderContext, DEFAULT_ACCEPT_TIMEOUT_MS, DEFAULT_HANDSHAKE_TIMEOUT_MS); + } + + JavaDebugServer(Supplier providerContextFactory, int acceptTimeoutMs, int handshakeTimeoutMs) { + this.providerContextFactory = providerContextFactory; + this.acceptTimeoutMs = acceptTimeoutMs; + this.handshakeTimeoutMs = handshakeTimeoutMs; } /** * Gets the single instance of JavaDebugServer. * @return the JavaDebugServer instance */ - public static synchronized IDebugServer getInstance() { + public static synchronized JavaDebugServer getInstance() { if (singletonInstance == null) { singletonInstance = new JavaDebugServer(); } @@ -52,95 +90,324 @@ public static synchronized IDebugServer getInstance() { } /** - * Gets the server port. + * Shuts down the singleton debug server if it has been initialized. */ - @Override - public synchronized int getPort() { - if (this.serverSocket != null) { - return this.serverSocket.getLocalPort(); + public static synchronized void shutdownInstance() { + if (singletonInstance != null) { + singletonInstance.stop(); + singletonInstance = null; } - return -1; } /** - * Starts the server if it's not started yet. + * Starts an ephemeral loopback-only DAP session protected by a single-use 256-bit pre-DAP auth token. */ @Override - public synchronized void start() { - if (this.serverSocket != null && !this.isStarted) { - this.isStarted = true; - this.executor = new ThreadPoolExecutor(0, 100, 30L, TimeUnit.SECONDS, new SynchronousQueue()); - // Execute eventLoop in a new thread. - new Thread(new Runnable() { - - @Override - public void run() { - while (true) { - try { - // Allow server socket to service multiple clients at the same time. - // When a request comes in, create a connection thread to process it. - // Then the server goes back to listen for new connection request. - Socket connection = serverSocket.accept(); - executor.submit(createConnectionTask(connection)); - } catch (IOException e) { - logger.log(Level.SEVERE, String.format("Setup socket connection exception: %s", e.toString()), e); - closeServerSocket(); - // If exception occurs when waiting for new client connection, shut down the connection pool - // to make sure no new tasks are accepted. But the previously submitted tasks will continue to run. - shutdownConnectionPool(false); - return; - } + public Map startDebugSession() throws IOException { + ensureRunning(); + String authToken = generateAuthToken(); + byte[] expectedHandshake = (AUTH_HEADER_PREFIX + authToken + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + + InetAddress bindAddress = resolveLoopbackAddress(); + ServerSocket sessionListener = new ServerSocket(0, SESSION_BACKLOG, bindAddress); + pendingListeners.add(sessionListener); + int port = sessionListener.getLocalPort(); + String host = bindAddress.getHostAddress(); + + getOrCreateExecutor().execute(() -> acceptAuthenticatedClientLoop(sessionListener, expectedHandshake)); + + Map descriptor = new LinkedHashMap<>(); + descriptor.put("host", host); + descriptor.put("port", port); + descriptor.put("authToken", authToken); + descriptor.put("protocolVersion", PROTOCOL_VERSION); + return Collections.unmodifiableMap(descriptor); + } + + /** + * Starts a single-client ephemeral loopback-only DAP session without token authentication. + * Intended strictly for explicit compatibility opt-in when {@link #ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY} is enabled. + */ + @Override + public int startLegacyLoopbackSession() throws IOException { + ensureRunning(); + InetAddress bindAddress = resolveLoopbackAddress(); + ServerSocket sessionListener = new ServerSocket(0, 1, bindAddress); + pendingListeners.add(sessionListener); + int port = sessionListener.getLocalPort(); + + getOrCreateExecutor().execute(() -> acceptLegacySingleClient(sessionListener)); + return port; + } + + @Override + public int getPort() { + return -1; + } + + @Override + public void start() { + ensureRunning(); + } + + @Override + public synchronized void stop() { + stopped.set(true); + for (ServerSocket listener : pendingListeners) { + closeQuietly(listener); + } + pendingListeners.clear(); + + for (ActiveSession session : activeSessions) { + session.close(); + } + activeSessions.clear(); + + if (this.executor != null) { + this.executor.shutdownNow(); + this.executor = null; + } + } + + int getPendingListenerCount() { + return pendingListeners.size(); + } + + int getActiveSessionCount() { + return activeSessions.size(); + } + + private synchronized void ensureRunning() { + stopped.set(false); + getOrCreateExecutor(); + } + + private synchronized ExecutorService getOrCreateExecutor() { + if (this.executor == null || this.executor.isShutdown()) { + ThreadFactory threadFactory = runnable -> { + Thread thread = new Thread(runnable, "Java Debug Session-" + THREAD_COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + }; + this.executor = new ThreadPoolExecutor( + 0, + MAX_CONCURRENT_TASKS, + 30L, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + threadFactory); + } + return this.executor; + } + + private void acceptAuthenticatedClientLoop(ServerSocket sessionListener, byte[] expectedHandshake) { + AtomicBoolean claimed = new AtomicBoolean(false); + Set pendingCandidates = ConcurrentHashMap.newKeySet(); + long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(acceptTimeoutMs); + try { + while (!claimed.get() && !stopped.get() && !sessionListener.isClosed()) { + long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadlineNanos - System.nanoTime()); + if (remainingMs <= 0) { + break; + } + int waitMs = (int) Math.min(Integer.MAX_VALUE, Math.max(1L, remainingMs)); + Socket candidate; + try { + sessionListener.setSoTimeout(waitMs); + candidate = sessionListener.accept(); + } catch (SocketTimeoutException timeoutEx) { + break; + } catch (IOException acceptEx) { + if (!claimed.get() && !stopped.get() && !sessionListener.isClosed()) { + logger.log(Level.WARNING, String.format("Debug session accept failed: %s", acceptEx.toString()), acceptEx); } + break; } - }, "Java Debug Server").start(); + if (candidate.getInetAddress() == null || !candidate.getInetAddress().isLoopbackAddress()) { + logger.warning("Rejected non-loopback debug connection from " + candidate.getInetAddress()); + closeQuietly(candidate); + continue; + } + + pendingCandidates.add(candidate); + try { + getOrCreateExecutor().execute(() -> + handleAuthenticatedCandidate(sessionListener, candidate, expectedHandshake, claimed, pendingCandidates)); + } catch (RuntimeException rejectedEx) { + pendingCandidates.remove(candidate); + closeQuietly(candidate); + } + } + } finally { + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); + if (!claimed.get()) { + for (Socket candidate : pendingCandidates) { + closeQuietly(candidate); + } + pendingCandidates.clear(); + } } } - @Override - public synchronized void stop() { - closeServerSocket(); - shutdownConnectionPool(true); + private void handleAuthenticatedCandidate( + ServerSocket sessionListener, + Socket candidate, + byte[] expectedHandshake, + AtomicBoolean claimed, + Set pendingCandidates) { + boolean wonSession = false; + try { + candidate.setTcpNoDelay(true); + candidate.setSoTimeout(handshakeTimeoutMs); + if (!verifyAuthHandshake(candidate.getInputStream(), expectedHandshake)) { + logger.warning("Rejected unauthenticated or invalid-token connection to Java Debug Server."); + return; + } + if (!claimed.compareAndSet(false, true) || stopped.get()) { + return; + } + wonSession = true; + pendingCandidates.remove(candidate); + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); + for (Socket other : pendingCandidates) { + closeQuietly(other); + } + pendingCandidates.clear(); + + candidate.setSoTimeout(0); + runProtocolSession(candidate); + } catch (IOException e) { + if (wonSession && !stopped.get()) { + logger.log(Level.SEVERE, String.format("Authenticated debug session failed: %s", e.toString()), e); + } + } finally { + pendingCandidates.remove(candidate); + if (!wonSession) { + closeQuietly(candidate); + } + } } - private synchronized void closeServerSocket() { - if (serverSocket != null) { - try { - logger.info("Close debugserver socket port " + serverSocket.getLocalPort()); - serverSocket.close(); - } catch (IOException e) { - logger.log(Level.SEVERE, String.format("Close ServerSocket exception: %s", e.toString()), e); + private void acceptLegacySingleClient(ServerSocket sessionListener) { + Socket client = null; + try { + sessionListener.setSoTimeout(acceptTimeoutMs); + client = sessionListener.accept(); + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); + if (client.getInetAddress() == null || !client.getInetAddress().isLoopbackAddress()) { + logger.warning("Rejected non-loopback connection to legacy Java Debug Server."); + closeQuietly(client); + return; + } + client.setTcpNoDelay(true); + client.setSoTimeout(0); + runProtocolSession(client); + } catch (SocketTimeoutException timeoutEx) { + logger.warning("Timed out waiting for client connection on legacy loopback debug session."); + closeQuietly(client); + } catch (IOException e) { + if (!stopped.get()) { + logger.log(Level.WARNING, String.format("Legacy debug session socket error: %s", e.toString()), e); } + closeQuietly(client); + } finally { + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); } - serverSocket = null; } - private synchronized void shutdownConnectionPool(boolean now) { - if (this.executor != null) { - if (now) { - this.executor.shutdownNow(); - } else { - this.executor.shutdown(); + private void runProtocolSession(Socket connection) { + ActiveSession activeSession = null; + try { + ProtocolServer protocolServer = new ProtocolServer( + connection.getInputStream(), + connection.getOutputStream(), + providerContextFactory.get()); + activeSession = new ActiveSession(connection, protocolServer); + activeSessions.add(activeSession); + if (stopped.get()) { + activeSession.close(); + return; + } + protocolServer.run(); + } catch (IOException e) { + if (!stopped.get()) { + logger.log(Level.SEVERE, String.format("Socket connection exception: %s", e.toString()), e); } + } finally { + if (activeSession != null) { + activeSessions.remove(activeSession); + } + closeQuietly(connection); + logger.info("Debug connection closed"); } } - private Runnable createConnectionTask(Socket connection) { - return new Runnable() { - @Override - public void run() { - try { - ProtocolServer protocolServer = new ProtocolServer(connection.getInputStream(), connection.getOutputStream(), - JdtProviderContextFactory.createProviderContext()); - // protocol server will dispatch request and send response in a while-loop. - protocolServer.run(); - } catch (IOException e) { - logger.log(Level.SEVERE, String.format("Socket connection exception: %s", e.toString()), e); - } finally { - logger.info("Debug connection closed"); + static boolean verifyAuthHandshake(InputStream inputStream, byte[] expectedHandshake) throws IOException { + ByteArrayOutputStream frameBuffer = new ByteArrayOutputStream(expectedHandshake.length); + int state = 0; + while (frameBuffer.size() < MAX_AUTH_FRAME_BYTES) { + int nextByte = inputStream.read(); + if (nextByte < 0) { + return false; + } + frameBuffer.write(nextByte); + if (nextByte == '\r' && (state == 0 || state == 2)) { + state++; + } else if (nextByte == '\n' && (state == 1 || state == 3)) { + state++; + if (state == 4) { + return MessageDigest.isEqual(expectedHandshake, frameBuffer.toByteArray()); } + } else if (nextByte == '\r') { + state = 1; + } else { + state = 0; + } + } + return false; + } + + private static String generateAuthToken() { + byte[] randomBytes = new byte[AUTH_TOKEN_BYTES]; + SECURE_RANDOM.nextBytes(randomBytes); + return HexFormat.of().formatHex(randomBytes); + } + + private static InetAddress resolveLoopbackAddress() throws IOException { + try { + return InetAddress.getByName("127.0.0.1"); + } catch (IOException ex) { + return InetAddress.getLoopbackAddress(); + } + } + + private static void closeQuietly(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException ex) { + // ignore cleanup failure } - }; + } } + private static final class ActiveSession { + private final Socket socket; + private final ProtocolServer protocolServer; + + ActiveSession(Socket socket, ProtocolServer protocolServer) { + this.socket = socket; + this.protocolServer = protocolServer; + } + + void close() { + protocolServer.stop(); + closeQuietly(socket); + } + } } diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebuggerServerPlugin.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebuggerServerPlugin.java index d3307a5b2..fdcdfbc9a 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebuggerServerPlugin.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebuggerServerPlugin.java @@ -34,6 +34,7 @@ public void start(BundleContext context) throws Exception { @Override public void stop(BundleContext context) throws Exception { + JavaDebugServer.shutdownInstance(); LogUtils.cleanupHandlers(); } diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LaunchCommandHandler.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LaunchCommandHandler.java index 0c2b9c0ea..fc4330ede 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LaunchCommandHandler.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LaunchCommandHandler.java @@ -29,7 +29,7 @@ public class LaunchCommandHandler { public static int getLaunchCommandLength(LaunchArguments launchArguments) { String encoding = StringUtils.isBlank(launchArguments.encoding) ? StandardCharsets.UTF_8.name() : launchArguments.encoding; launchArguments.vmArgs += String.format(" -Dfile.encoding=%s", encoding); - String address = launchArguments.noDebug ? "" : "888888"; + String address = launchArguments.noDebug ? "" : "127.0.0.1:88888"; String[] commands = LaunchRequestHandler.constructLaunchCommands(launchArguments, false, address); int cwdLength = launchArguments.console == CONSOLE.internalConsole ? 0 : StringUtils.length("cd " + launchArguments.cwd + " && "); return cwdLength + String.join(" ", commands).length(); diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java new file mode 100644 index 000000000..38598cdd0 --- /dev/null +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java @@ -0,0 +1,402 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.plugin.internal; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jdi.internal.VirtualMachineManagerImpl; +import org.eclipse.jdi.internal.connect.SocketListeningConnectorImpl; + +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.connect.Connector; +import com.sun.jdi.connect.IllegalConnectorArgumentsException; +import com.sun.jdi.connect.TransportTimeoutException; +import com.sun.jdi.connect.spi.ClosedConnectionException; +import com.sun.jdi.connect.spi.Connection; + +/** + * A JDI {@link com.sun.jdi.connect.ListeningConnector} backed by Eclipse JDT's + * {@link VirtualMachineManagerImpl} that strictly binds its listening socket to + * the local loopback interface ({@code 127.0.0.1}) rather than {@code 0.0.0.0}. + */ +public class LoopbackSocketListeningConnector extends SocketListeningConnectorImpl { + public static final String ARG_PORT = "port"; + public static final String ARG_TIMEOUT = "timeout"; + public static final String ARG_LOCAL_ADDRESS = "localAddress"; + private static final String DEFAULT_LOOPBACK_ADDRESS = "127.0.0.1"; + private static final byte[] JDWP_HANDSHAKE = "JDWP-Handshake".getBytes(StandardCharsets.US_ASCII); + private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000; + private static final int MIN_JDWP_PACKET_LENGTH = 11; + + private final Object socketLock = new Object(); + private ServerSocket serverSocket; + private volatile int boundPort = -1; + + public LoopbackSocketListeningConnector(VirtualMachineManagerImpl virtualMachineManager) { + super(virtualMachineManager); + } + + @Override + public String name() { + return "com.microsoft.java.debug.LoopbackSocketListen"; + } + + @Override + public Map defaultArguments() { + Map arguments = super.defaultArguments(); + LocalAddressArgument localAddress = new LocalAddressArgument( + ARG_LOCAL_ADDRESS, + "Local loopback address to bind", + "Local address", + false); + localAddress.setValue(DEFAULT_LOOPBACK_ADDRESS); + arguments.put(localAddress.name(), localAddress); + return arguments; + } + + @Override + public String startListening(Map connectionArgs) + throws IOException, IllegalConnectorArgumentsException { + int port = parseIntegerArgument(connectionArgs, ARG_PORT, 0, 0, 65535); + InetAddress bindAddress = resolveLoopbackBindAddress(connectionArgs); + + synchronized (socketLock) { + closeServerSocketLocked(); + this.serverSocket = new ServerSocket(port, 1, bindAddress); + this.boundPort = this.serverSocket.getLocalPort(); + return bindAddress.getHostAddress() + ":" + this.boundPort; + } + } + + @Override + public void stopListening(Map connectionArgs) throws IOException { + ServerSocket toClose; + synchronized (socketLock) { + toClose = this.serverSocket; + this.serverSocket = null; + this.boundPort = -1; + } + if (toClose != null) { + toClose.close(); + } + } + + @Override + public VirtualMachine accept(Map connectionArgs) + throws IOException, IllegalConnectorArgumentsException { + int timeout = parseIntegerArgument(connectionArgs, ARG_TIMEOUT, 0, 0, Integer.MAX_VALUE); + ServerSocket currentServerSocket; + synchronized (socketLock) { + currentServerSocket = this.serverSocket; + } + if (currentServerSocket == null || currentServerSocket.isClosed()) { + throw new IOException("JDI listening connector is not currently listening."); + } + + currentServerSocket.setSoTimeout(timeout); + Socket clientSocket = null; + boolean succeeded = false; + try { + try { + clientSocket = currentServerSocket.accept(); + } catch (SocketTimeoutException e) { + throw new TransportTimeoutException(e.getMessage()); + } + + if (clientSocket.getInetAddress() == null || !clientSocket.getInetAddress().isLoopbackAddress()) { + throw new IOException("Rejected non-loopback JDWP connection from " + clientSocket.getInetAddress()); + } + + clientSocket.setTcpNoDelay(true); + int handshakeTimeout = timeout > 0 + ? Math.min(timeout, DEFAULT_HANDSHAKE_TIMEOUT_MS) : DEFAULT_HANDSHAKE_TIMEOUT_MS; + performJdwpHandshake(clientSocket, handshakeTimeout); + + Connection connection = new LoopbackSocketConnection( + clientSocket, clientSocket.getInputStream(), clientSocket.getOutputStream()); + VirtualMachine vm = establishedConnection(connection); + succeeded = true; + return vm; + } finally { + if (!succeeded && clientSocket != null) { + try { + clientSocket.close(); + } catch (IOException ex) { + // ignore cleanup error + } + } + } + } + + @Override + public boolean supportsMultipleConnections() { + return false; + } + + @Override + public int listeningPort() { + return this.boundPort; + } + + private void closeServerSocketLocked() { + if (this.serverSocket != null) { + try { + this.serverSocket.close(); + } catch (IOException ex) { + // ignore prior socket close failure + } finally { + this.serverSocket = null; + this.boundPort = -1; + } + } + } + + private static InetAddress resolveLoopbackBindAddress( + Map connectionArgs) + throws IOException, IllegalConnectorArgumentsException { + if (connectionArgs == null) { + return InetAddress.getByName(DEFAULT_LOOPBACK_ADDRESS); + } + Connector.Argument localAddrArg = connectionArgs.get(ARG_LOCAL_ADDRESS); + String value = localAddrArg != null ? localAddrArg.value() : null; + if (StringUtils.isBlank(value)) { + return InetAddress.getByName(DEFAULT_LOOPBACK_ADDRESS); + } + InetAddress resolved = InetAddress.getByName(value.trim()); + if (!resolved.isLoopbackAddress()) { + throw new IllegalConnectorArgumentsException( + "Only loopback addresses are permitted for JDI listening sockets.", ARG_LOCAL_ADDRESS); + } + return resolved; + } + + private static int parseIntegerArgument( + Map connectionArgs, + String argName, + int defaultValue, + int minValue, + int maxValue) throws IllegalConnectorArgumentsException { + if (connectionArgs == null) { + return defaultValue; + } + Connector.Argument arg = connectionArgs.get(argName); + if (arg == null || StringUtils.isBlank(arg.value())) { + return defaultValue; + } + try { + int parsed = (arg instanceof Connector.IntegerArgument) + ? ((Connector.IntegerArgument) arg).intValue() + : Integer.parseInt(arg.value().trim()); + if (parsed < minValue || parsed > maxValue) { + throw new IllegalConnectorArgumentsException( + String.format("Connector argument '%s' out of range: %d", argName, parsed), argName); + } + return parsed; + } catch (NumberFormatException ex) { + throw new IllegalConnectorArgumentsException( + String.format("Connector argument '%s' is not an integer.", argName), argName); + } + } + + private static void performJdwpHandshake(Socket socket, int timeoutMs) throws IOException { + socket.setSoTimeout(timeoutMs); + InputStream in = socket.getInputStream(); + OutputStream out = socket.getOutputStream(); + // Per the JDWP specification, the debugger side always sends "JDWP-Handshake" + // first (even when acting as the TCP listening server), and the target VM replies. + out.write(JDWP_HANDSHAKE); + out.flush(); + byte[] received = new byte[JDWP_HANDSHAKE.length]; + int offset = 0; + try { + while (offset < received.length) { + int read = in.read(received, offset, received.length - offset); + if (read < 0) { + throw new IOException("Unexpected EOF during JDWP handshake."); + } + offset += read; + } + } catch (SocketTimeoutException e) { + throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); + } + if (!Arrays.equals(JDWP_HANDSHAKE, received)) { + throw new IOException("Received invalid JDWP handshake."); + } + socket.setSoTimeout(0); + } + + static final class LoopbackSocketConnection extends Connection { + private Socket socket; + private final InputStream input; + private final OutputStream output; + + LoopbackSocketConnection(Socket socket, InputStream input, OutputStream output) { + this.socket = socket; + this.input = input; + this.output = output; + } + + @Override + public synchronized void close() throws IOException { + if (this.socket == null) { + return; + } + try { + this.socket.close(); + } finally { + this.socket = null; + } + } + + @Override + public synchronized boolean isOpen() { + return this.socket != null && !this.socket.isClosed(); + } + + @Override + public byte[] readPacket() throws IOException { + DataInputStream dataInput; + synchronized (this) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + dataInput = new DataInputStream(this.input); + } + synchronized (dataInput) { + int packetLength; + try { + packetLength = dataInput.readInt(); + } catch (IOException e) { + throw new ClosedConnectionException(); + } + if (packetLength < MIN_JDWP_PACKET_LENGTH) { + throw new IOException("JDWP Packet under 11 bytes"); + } + byte[] packet = new byte[packetLength]; + packet[0] = (byte) ((packetLength >>> 24) & 0xFF); + packet[1] = (byte) ((packetLength >>> 16) & 0xFF); + packet[2] = (byte) ((packetLength >>> 8) & 0xFF); + packet[3] = (byte) (packetLength & 0xFF); + dataInput.readFully(packet, 4, packetLength - 4); + return packet; + } + } + + @Override + public void writePacket(byte[] packet) throws IOException { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + if (packet == null) { + throw new IllegalArgumentException("Invalid JDWP Packet, packet cannot be null"); + } + if (packet.length < MIN_JDWP_PACKET_LENGTH) { + throw new IllegalArgumentException("Invalid JDWP Packet, must be at least 11 bytes: " + packet.length); + } + int packetLength = getPacketLength(packet); + if (packetLength < MIN_JDWP_PACKET_LENGTH) { + throw new IllegalArgumentException("Invalid JDWP Packet length: " + packetLength); + } + if (packetLength > packet.length) { + throw new IllegalArgumentException("Invalid JDWP packet: Specified length is greater than actual length"); + } + OutputStream targetOut; + synchronized (this) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + targetOut = this.output; + } + synchronized (targetOut) { + targetOut.write(packet, 0, packetLength); + targetOut.flush(); + } + } + + private static int getPacketLength(byte[] packet) { + return ((packet[0] & 0xFF) << 24) + | ((packet[1] & 0xFF) << 16) + | ((packet[2] & 0xFF) << 8) + | (packet[3] & 0xFF); + } + } + + private static final class LocalAddressArgument implements Connector.StringArgument { + private static final long serialVersionUID = 1L; + + private final String name; + private final String description; + private final String label; + private final boolean mustSpecify; + private String value; + + LocalAddressArgument(String name, String description, String label, boolean mustSpecify) { + this.name = name; + this.description = description; + this.label = label; + this.mustSpecify = mustSpecify; + } + + @Override + public String name() { + return this.name; + } + + @Override + public String label() { + return this.label; + } + + @Override + public String description() { + return this.description; + } + + @Override + public String value() { + return this.value; + } + + @Override + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean isValid(String candidate) { + if (StringUtils.isBlank(candidate)) { + return !this.mustSpecify; + } + try { + return InetAddress.getByName(candidate.trim()).isLoopbackAddress(); + } catch (IOException ex) { + return false; + } + } + + @Override + public boolean mustSpecify() { + return this.mustSpecify; + } + } +} diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java new file mode 100644 index 000000000..0ebc94dbe --- /dev/null +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java @@ -0,0 +1,707 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.plugin.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IncrementalProjectBuilder; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.launching.JavaRuntime; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class JavaDebugEndToEndFunctionalTest { + private static final String PROJECT_NAME = "e2e-debug-project"; + private static final String SAMPLE_SOURCE = String.join("\n", + "public class SampleDebuggee {", + " public static void main(String[] args) {", + " int counter = 42;", + " String greeting = \"Hello \\u65e5\\u672c\\u8a9e\";", + " int doubled = compute(counter);", + " int sum = 0;", + " for (int i = 0; i < 4; i++) {", + " sum += i;", + " }", + " System.out.println(\"RESULT:\" + doubled + \":\" + greeting + \":\" + sum);", + " }", + " private static int compute(int value) {", + " return value * 2;", + " }", + "}", + ""); + + private static Hashtable initialJavaCoreOptions; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private JavaDebugServer server; + private IProject workspaceProject; + private Path sourceFilePath; + private Path classesDir; + + @BeforeClass + public static void captureInitialJavaCoreOptions() { + initialJavaCoreOptions = JavaCore.getOptions(); + } + + @Before + public void setUp() throws Exception { + server = new JavaDebugServer(JdtProviderContextFactory::createProviderContext, 10_000, 1_500); + setUpSampleJavaProject(); + } + + @After + public void tearDown() throws Exception { + if (server != null) { + server.stop(); + } + if (workspaceProject != null && workspaceProject.exists()) { + workspaceProject.delete(true, true, null); + } + if (initialJavaCoreOptions != null) { + JavaCore.setOptions(new Hashtable<>(initialJavaCoreOptions)); + } + } + + @Test + public void unauthenticatedOrInvalidTokenLaunchRequestIsRejected() throws Exception { + Path sentinelFile = temporaryFolder.getRoot().toPath().resolve("unauth-marker.txt"); + Path markerDir = temporaryFolder.newFolder("marker-classes").toPath(); + Path markerJava = markerDir.resolve("LaunchMarker.java"); + String escapedSentinel = sentinelFile.toAbsolutePath().toString().replace("\\", "\\\\"); + String markerSource = String.join("\n", + "import java.nio.file.*;", + "public class LaunchMarker {", + " public static void main(String[] args) throws Exception {", + " Files.writeString(Paths.get(\"" + escapedSentinel + "\"), \"UNAUTH_MARKER\");", + " }", + "}", + ""); + Files.writeString(markerJava, markerSource, StandardCharsets.UTF_8); + compileWithJavac(markerJava, markerDir); + + Map descriptor = server.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String validToken = (String) descriptor.get("authToken"); + + JsonObject launchArgs = new JsonObject(); + launchArgs.addProperty("mainClass", "LaunchMarker"); + launchArgs.addProperty("noDebug", true); + JsonArray cp = new JsonArray(); + cp.add(markerDir.toAbsolutePath().toString()); + launchArgs.add("classPaths", cp); + + byte[] initFrame = buildDapFrame(buildRequestJson(1, "initialize", new JsonObject())); + byte[] launchFrame = buildDapFrame(buildRequestJson(2, "launch", launchArgs)); + + // 1. Raw initialize + launch with no JavaDebug-Auth header. + try (Socket unauth = new Socket()) { + unauth.connect(new InetSocketAddress(host, port), 2_000); + unauth.setSoTimeout(2_000); + unauth.getOutputStream().write(initFrame); + unauth.getOutputStream().write(launchFrame); + unauth.getOutputStream().flush(); + assertEquals(-1, unauth.getInputStream().read()); + } + Thread.sleep(200); + assertFalse("Unauthenticated launch request must never execute.", Files.exists(sentinelFile)); + + // 2. Wrong 64-hex token + initialize + launch. + String wrongToken = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + try (Socket wrongAuth = new Socket()) { + wrongAuth.connect(new InetSocketAddress(host, port), 2_000); + wrongAuth.setSoTimeout(2_000); + byte[] wrongHeader = (JavaDebugServer.AUTH_HEADER_PREFIX + wrongToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + wrongAuth.getOutputStream().write(wrongHeader); + wrongAuth.getOutputStream().write(initFrame); + wrongAuth.getOutputStream().write(launchFrame); + wrongAuth.getOutputStream().flush(); + assertEquals(-1, wrongAuth.getInputStream().read()); + } + Thread.sleep(200); + assertFalse("Wrong-token launch payload must never execute.", Files.exists(sentinelFile)); + + // 3. Legitimate client with valid token still connects cleanly afterward. + try (DapTestClient client = new DapTestClient(host, port, validToken)) { + JsonObject initResp = client.sendRequest("initialize", createInitializeArgs()); + assertTrue(initResp.get("success").getAsBoolean()); + JsonObject disconnectResp = client.sendRequest("disconnect", new JsonObject()); + assertTrue(disconnectResp.get("success").getAsBoolean()); + } + assertFalse(Files.exists(sentinelFile)); + } + + @Test + public void rejectsPreInitializeLaunchAndAttachEvenAfterValidTransportAuth() throws Exception { + Map descriptor = server.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String authToken = (String) descriptor.get("authToken"); + + try (DapTestClient client = new DapTestClient(host, port, authToken)) { + JsonObject preInitLaunch = client.sendRequest("launch", createLaunchArgs(false)); + assertFalse(preInitLaunch.get("success").getAsBoolean()); + + JsonObject attachArgs = new JsonObject(); + attachArgs.addProperty("hostName", "127.0.0.1"); + attachArgs.addProperty("port", 9); + JsonObject preInitAttach = client.sendRequest("attach", attachArgs); + assertFalse(preInitAttach.get("success").getAsBoolean()); + + JsonObject initResp = client.sendRequest("initialize", createInitializeArgs()); + assertTrue(initResp.get("success").getAsBoolean()); + + JsonObject duplicateInit = client.sendRequest("initialize", createInitializeArgs()); + assertFalse(duplicateInit.get("success").getAsBoolean()); + + JsonObject disconnectResp = client.sendRequest("disconnect", new JsonObject()); + assertTrue(disconnectResp.get("success").getAsBoolean()); + } + } + + @Test + public void fullDapDebugSessionSupportsBreakpointsVariablesEvaluateSteppingAndUtf8Output() throws Exception { + Map descriptor = server.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String authToken = (String) descriptor.get("authToken"); + + try (DapTestClient client = new DapTestClient(host, port, authToken)) { + JsonObject initResp = client.sendRequest("initialize", createInitializeArgs()); + assertTrue(initResp.get("success").getAsBoolean()); + assertTrue(initResp.getAsJsonObject("body").get("supportsConfigurationDoneRequest").getAsBoolean()); + + JsonObject launchResp = client.sendRequest("launch", createLaunchArgs(false)); + assertTrue("launch failed: " + launchResp, launchResp.get("success").getAsBoolean()); + assertNotNull(client.awaitEvent("initialized", 10_000)); + + // Set unconditional breakpoint on line 5 and conditional breakpoint (i == 2) on line 8. + JsonObject bpArgs = createBreakpointsArgs(sourceFilePath, 5, 8, "i == 2"); + JsonObject bpResp = client.sendRequest("setBreakpoints", bpArgs); + assertTrue("setBreakpoints failed: " + bpResp, bpResp.get("success").getAsBoolean()); + JsonArray bps = bpResp.getAsJsonObject("body").getAsJsonArray("breakpoints"); + assertEquals(2, bps.size()); + assertTrue(bps.get(0).getAsJsonObject().get("verified").getAsBoolean()); + assertTrue(bps.get(1).getAsJsonObject().get("verified").getAsBoolean()); + + JsonObject configDone = client.sendRequest("configurationDone", new JsonObject()); + assertTrue(configDone.get("success").getAsBoolean()); + + // 1. Hit unconditional breakpoint at line 5. + JsonObject stopped1 = client.awaitEvent("stopped", 15_000); + assertEquals("breakpoint", stopped1.getAsJsonObject("body").get("reason").getAsString()); + int threadId = stopped1.getAsJsonObject("body").get("threadId").getAsInt(); + + JsonObject threadsResp = client.sendRequest("threads", new JsonObject()); + assertTrue(threadsResp.get("success").getAsBoolean()); + assertTrue(threadsResp.getAsJsonObject("body").getAsJsonArray("threads").size() >= 1); + + int topFrameId = assertTopFrameLine(client, threadId, 5); + Map varsAtLine5 = fetchLocalVariables(client, topFrameId); + assertEquals("42", varsAtLine5.get("counter")); + assertTrue("Expected UTF-8 greeting variable, got: " + varsAtLine5.get("greeting"), + varsAtLine5.get("greeting") != null && varsAtLine5.get("greeting").contains("Hello \u65e5\u672c\u8a9e")); + + // Evaluate expressions via JdtEvaluationProvider. + JsonObject evalMathArgs = new JsonObject(); + evalMathArgs.addProperty("expression", "counter + 8"); + evalMathArgs.addProperty("frameId", topFrameId); + evalMathArgs.addProperty("context", "watch"); + JsonObject evalMathResp = client.sendRequest("evaluate", evalMathArgs); + assertTrue("evaluate failed: " + evalMathResp, evalMathResp.get("success").getAsBoolean()); + assertEquals("50", evalMathResp.getAsJsonObject("body").get("result").getAsString()); + + JsonObject evalUtf8Args = new JsonObject(); + evalUtf8Args.addProperty("expression", "greeting.length()"); + evalUtf8Args.addProperty("frameId", topFrameId); + evalUtf8Args.addProperty("context", "repl"); + JsonObject evalUtf8Resp = client.sendRequest("evaluate", evalUtf8Args); + assertTrue("UTF-8 evaluate failed: " + evalUtf8Resp, evalUtf8Resp.get("success").getAsBoolean()); + assertEquals("9", evalUtf8Resp.getAsJsonObject("body").get("result").getAsString()); + + // 2. stepIn into compute(int value) at line 13. + JsonObject stepArgs = new JsonObject(); + stepArgs.addProperty("threadId", threadId); + assertTrue(client.sendRequest("stepIn", stepArgs).get("success").getAsBoolean()); + JsonObject stoppedStepIn = client.awaitEvent("stopped", 10_000); + assertEquals("step", stoppedStepIn.getAsJsonObject("body").get("reason").getAsString()); + int computeFrameId = assertTopFrameLine(client, threadId, 13); + assertEquals("42", fetchLocalVariables(client, computeFrameId).get("value")); + + // 3. stepOut back to line 5, then stepOver (next) to line 6 where doubled == 84. + assertTrue(client.sendRequest("stepOut", stepArgs).get("success").getAsBoolean()); + assertEquals("step", client.awaitEvent("stopped", 10_000).getAsJsonObject("body").get("reason").getAsString()); + assertTrue(client.sendRequest("next", stepArgs).get("success").getAsBoolean()); + assertEquals("step", client.awaitEvent("stopped", 10_000).getAsJsonObject("body").get("reason").getAsString()); + int afterComputeFrameId = assertTopFrameLine(client, threadId, 6); + assertEquals("84", fetchLocalVariables(client, afterComputeFrameId).get("doubled")); + + // 4. continue -> hits conditional breakpoint at line 8 only when i == 2. + assertTrue(client.sendRequest("continue", stepArgs).get("success").getAsBoolean()); + JsonObject stoppedCond = client.awaitEvent("stopped", 10_000); + assertEquals("breakpoint", stoppedCond.getAsJsonObject("body").get("reason").getAsString()); + int loopFrameId = assertTopFrameLine(client, threadId, 8); + assertEquals("2", fetchLocalVariables(client, loopFrameId).get("i")); + + // 5. continue to program completion -> verify UTF-8 stdout output and terminated event. + assertTrue(client.sendRequest("continue", stepArgs).get("success").getAsBoolean()); + assertNotNull(client.awaitEvent("terminated", 10_000)); + assertTrue("Expected program stdout in DAP output events, got: " + client.getCapturedStdout(), + client.getCapturedStdout().contains("RESULT:84:Hello \u65e5\u672c\u8a9e:6")); + + JsonObject disconnectResp = client.sendRequest("disconnect", new JsonObject()); + assertTrue(disconnectResp.get("success").getAsBoolean()); + } + } + + @Test + public void noDebugLaunchAndLoopbackJdwpAttachSessionsSucceedEndToEnd() throws Exception { + // Part A: Run without debugging (noDebug: true; LaunchWithoutDebuggingDelegate skips initialized event) + Map noDebugDesc = server.startDebugSession(); + try (DapTestClient client = new DapTestClient( + (String) noDebugDesc.get("host"), + ((Number) noDebugDesc.get("port")).intValue(), + (String) noDebugDesc.get("authToken"))) { + assertTrue(client.sendRequest("initialize", createInitializeArgs()).get("success").getAsBoolean()); + assertTrue(client.sendRequest("launch", createLaunchArgs(true)).get("success").getAsBoolean()); + + assertNotNull(client.awaitEvent("terminated", 10_000)); + assertTrue("Expected noDebug stdout in DAP output events, got: " + client.getCapturedStdout(), + client.getCapturedStdout().contains("RESULT:84:Hello \u65e5\u672c\u8a9e:6")); + assertTrue(client.sendRequest("disconnect", new JsonObject()).get("success").getAsBoolean()); + } + + // Part B: Loopback JDWP attach (matching no-config debugjava address=127.0.0.1:0) + Process debuggee = startLoopbackJdwpDebuggee(); + try { + int jdwpPort = readJdwpListeningPort(debuggee.getInputStream()); + Map attachDesc = server.startDebugSession(); + try (DapTestClient client = new DapTestClient( + (String) attachDesc.get("host"), + ((Number) attachDesc.get("port")).intValue(), + (String) attachDesc.get("authToken"))) { + assertTrue(client.sendRequest("initialize", createInitializeArgs()).get("success").getAsBoolean()); + + JsonObject attachArgs = new JsonObject(); + attachArgs.addProperty("hostName", "127.0.0.1"); + attachArgs.addProperty("port", jdwpPort); + attachArgs.addProperty("projectName", PROJECT_NAME); + JsonObject attachResp = client.sendRequest("attach", attachArgs); + assertTrue("attach failed: " + attachResp, attachResp.get("success").getAsBoolean()); + assertNotNull(client.awaitEvent("initialized", 10_000)); + + JsonObject bpArgs = createBreakpointsArgs(sourceFilePath, 5, -1, null); + assertTrue(client.sendRequest("setBreakpoints", bpArgs).get("success").getAsBoolean()); + assertTrue(client.sendRequest("configurationDone", new JsonObject()).get("success").getAsBoolean()); + + JsonObject stopped = client.awaitEvent("stopped", 15_000); + assertEquals("breakpoint", stopped.getAsJsonObject("body").get("reason").getAsString()); + int threadId = stopped.getAsJsonObject("body").get("threadId").getAsInt(); + int frameId = assertTopFrameLine(client, threadId, 5); + assertEquals("42", fetchLocalVariables(client, frameId).get("counter")); + + JsonObject continueArgs = new JsonObject(); + continueArgs.addProperty("threadId", threadId); + assertTrue(client.sendRequest("continue", continueArgs).get("success").getAsBoolean()); + assertNotNull(client.awaitEvent("terminated", 10_000)); + assertTrue(debuggee.waitFor(10, TimeUnit.SECONDS)); + assertEquals(0, debuggee.exitValue()); + assertTrue(client.sendRequest("disconnect", new JsonObject()).get("success").getAsBoolean()); + } + } finally { + if (debuggee.isAlive()) { + debuggee.destroyForcibly(); + } + } + } + + private void setUpSampleJavaProject() throws Exception { + workspaceProject = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME); + if (workspaceProject.exists()) { + workspaceProject.delete(true, true, null); + } + workspaceProject.create(null); + workspaceProject.open(null); + workspaceProject.setDefaultCharset(StandardCharsets.UTF_8.name(), null); + + IProjectDescription description = workspaceProject.getDescription(); + description.setNatureIds(new String[] {JavaCore.NATURE_ID}); + workspaceProject.setDescription(description, null); + + IFolder srcFolder = workspaceProject.getFolder("src"); + srcFolder.create(true, true, null); + IFolder binFolder = workspaceProject.getFolder("bin"); + binFolder.create(true, true, null); + + IJavaProject javaProject = JavaCore.create(workspaceProject); + IClasspathEntry[] classpath = new IClasspathEntry[] { + JavaCore.newSourceEntry(srcFolder.getFullPath()), + JavaRuntime.getDefaultJREContainerEntry() + }; + javaProject.setRawClasspath(classpath, binFolder.getFullPath(), null); + + IFile sourceFile = srcFolder.getFile("SampleDebuggee.java"); + sourceFile.create(new ByteArrayInputStream(SAMPLE_SOURCE.getBytes(StandardCharsets.UTF_8)), true, null); + sourceFile.setCharset(StandardCharsets.UTF_8.name(), null); + workspaceProject.build(IncrementalProjectBuilder.FULL_BUILD, null); + + sourceFilePath = Paths.get(sourceFile.getLocationURI()); + classesDir = Paths.get(binFolder.getLocationURI()); + if (!Files.exists(classesDir.resolve("SampleDebuggee.class"))) { + compileWithJavac(sourceFilePath, classesDir); + } + } + + private static void compileWithJavac(Path javaSource, Path outputDir) throws Exception { + String javacBin = Paths.get(System.getProperty("java.home"), "bin", + File.separatorChar == '\\' ? "javac.exe" : "javac").toString(); + Process proc = new ProcessBuilder( + javacBin, "-g", "-encoding", "UTF-8", "-d", outputDir.toAbsolutePath().toString(), + javaSource.toAbsolutePath().toString()) + .redirectErrorStream(true) + .start(); + String output; + try (InputStream in = proc.getInputStream()) { + output = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + assertTrue("javac timed out", proc.waitFor(15, TimeUnit.SECONDS)); + assertEquals("javac failed: " + output, 0, proc.exitValue()); + } + + private Process startLoopbackJdwpDebuggee() throws IOException { + String javaBin = Paths.get(System.getProperty("java.home"), "bin", + File.separatorChar == '\\' ? "java.exe" : "java").toString(); + return new ProcessBuilder( + javaBin, + "-Dfile.encoding=UTF-8", + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0", + "-cp", + classesDir.toAbsolutePath().toString(), + "SampleDebuggee") + .redirectErrorStream(true) + .start(); + } + + private static int readJdwpListeningPort(InputStream processOut) throws Exception { + Pattern pattern = Pattern.compile( + "Listening for transport dt_socket at address:\\s*(?:127\\.0\\.0\\.1:|localhost:)?(\\d+)"); + CompletableFuture portFuture = CompletableFuture.supplyAsync(() -> { + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(processOut, StandardCharsets.UTF_8)); + String line; + while ((line = reader.readLine()) != null) { + Matcher matcher = pattern.matcher(line); + if (matcher.find()) { + return Integer.parseInt(matcher.group(1)); + } + } + throw new IllegalStateException("Process exited without printing JDWP listening port."); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }); + return portFuture.get(10, TimeUnit.SECONDS); + } + + private static int assertTopFrameLine(DapTestClient client, int threadId, int expectedLine) throws Exception { + JsonObject stackArgs = new JsonObject(); + stackArgs.addProperty("threadId", threadId); + JsonObject stackResp = client.sendRequest("stackTrace", stackArgs); + assertTrue(stackResp.get("success").getAsBoolean()); + JsonArray frames = stackResp.getAsJsonObject("body").getAsJsonArray("stackFrames"); + assertTrue(frames.size() >= 1); + JsonObject topFrame = frames.get(0).getAsJsonObject(); + assertEquals(expectedLine, topFrame.get("line").getAsInt()); + return topFrame.get("id").getAsInt(); + } + + private static Map fetchLocalVariables(DapTestClient client, int frameId) throws Exception { + JsonObject scopesArgs = new JsonObject(); + scopesArgs.addProperty("frameId", frameId); + JsonObject scopesResp = client.sendRequest("scopes", scopesArgs); + assertTrue(scopesResp.get("success").getAsBoolean()); + JsonArray scopes = scopesResp.getAsJsonObject("body").getAsJsonArray("scopes"); + int localRef = scopes.get(0).getAsJsonObject().get("variablesReference").getAsInt(); + + JsonObject varsArgs = new JsonObject(); + varsArgs.addProperty("variablesReference", localRef); + JsonObject varsResp = client.sendRequest("variables", varsArgs); + assertTrue(varsResp.get("success").getAsBoolean()); + Map result = new HashMap<>(); + for (JsonElement elem : varsResp.getAsJsonObject("body").getAsJsonArray("variables")) { + JsonObject obj = elem.getAsJsonObject(); + result.put(obj.get("name").getAsString(), obj.get("value").getAsString()); + } + return result; + } + + private static JsonObject createInitializeArgs() { + JsonObject args = new JsonObject(); + args.addProperty("adapterID", "java"); + args.addProperty("linesStartAt1", true); + args.addProperty("columnsStartAt1", true); + args.addProperty("pathFormat", "path"); + return args; + } + + private JsonObject createLaunchArgs(boolean noDebug) { + JsonObject args = new JsonObject(); + args.addProperty("mainClass", "SampleDebuggee"); + args.addProperty("projectName", PROJECT_NAME); + args.addProperty("encoding", "UTF-8"); + args.addProperty("vmArgs", "-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8"); + args.addProperty("noDebug", noDebug); + JsonArray cp = new JsonArray(); + cp.add(classesDir.toAbsolutePath().toString()); + args.add("classPaths", cp); + return args; + } + + private static JsonObject createBreakpointsArgs(Path file, int line1, int line2, String line2Condition) { + JsonObject source = new JsonObject(); + source.addProperty("path", file.toAbsolutePath().toString()); + source.addProperty("name", file.getFileName().toString()); + + JsonArray breakpoints = new JsonArray(); + JsonObject bp1 = new JsonObject(); + bp1.addProperty("line", line1); + breakpoints.add(bp1); + if (line2 > 0) { + JsonObject bp2 = new JsonObject(); + bp2.addProperty("line", line2); + if (line2Condition != null) { + bp2.addProperty("condition", line2Condition); + } + breakpoints.add(bp2); + } + + JsonObject args = new JsonObject(); + args.add("source", source); + args.add("breakpoints", breakpoints); + return args; + } + + private static String buildRequestJson(int seq, String command, JsonObject args) { + JsonObject req = new JsonObject(); + req.addProperty("seq", seq); + req.addProperty("type", "request"); + req.addProperty("command", command); + req.add("arguments", args); + return req.toString(); + } + + private static byte[] buildDapFrame(String json) { + byte[] body = json.getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + byte[] frame = new byte[header.length + body.length]; + System.arraycopy(header, 0, frame, 0, header.length); + System.arraycopy(body, 0, frame, header.length, body.length); + return frame; + } + + private static final class DapTestClient implements Closeable { + private final Socket socket; + private final OutputStream out; + private final AtomicInteger nextSeq = new AtomicInteger(1); + private final Map> pendingResponses = new HashMap<>(); + private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + private final StringBuilder stdoutBuffer = new StringBuilder(); + private final Thread readerThread; + + DapTestClient(String host, int port, String authToken) throws IOException { + this.socket = new Socket(); + this.socket.connect(new InetSocketAddress(host, port), 5_000); + this.out = this.socket.getOutputStream(); + byte[] handshake = (JavaDebugServer.AUTH_HEADER_PREFIX + authToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + this.out.write(handshake); + this.out.flush(); + + this.readerThread = new Thread(this::readLoop, "DapTestClient-Reader"); + this.readerThread.setDaemon(true); + this.readerThread.start(); + } + + JsonObject sendRequest(String command, JsonObject arguments) throws Exception { + int seq = nextSeq.getAndIncrement(); + CompletableFuture responseFuture = new CompletableFuture<>(); + synchronized (pendingResponses) { + pendingResponses.put(seq, responseFuture); + } + byte[] frame = buildDapFrame(buildRequestJson(seq, command, arguments)); + synchronized (out) { + out.write(frame); + out.flush(); + } + return responseFuture.get(15, TimeUnit.SECONDS); + } + + JsonObject awaitEvent(String eventName, long timeoutMs) throws Exception { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs); + List unmatched = new ArrayList<>(); + try { + while (true) { + long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remainingMs <= 0) { + throw new AssertionError("Timed out waiting for DAP event '" + eventName + "'"); + } + JsonObject evt = eventQueue.poll(remainingMs, TimeUnit.MILLISECONDS); + if (evt == null) { + throw new AssertionError("Timed out waiting for DAP event '" + eventName + "'"); + } + if (eventName.equals(evt.get("event").getAsString())) { + return evt; + } + unmatched.add(evt); + } + } finally { + for (JsonObject evt : unmatched) { + eventQueue.offer(evt); + } + } + } + + String getCapturedStdout() { + synchronized (stdoutBuffer) { + return stdoutBuffer.toString(); + } + } + + private void readLoop() { + try { + InputStream in = socket.getInputStream(); + while (!socket.isClosed()) { + JsonObject msg = readNextMessage(in); + if (msg == null) { + break; + } + String type = msg.get("type").getAsString(); + if ("response".equals(type)) { + int reqSeq = msg.get("request_seq").getAsInt(); + CompletableFuture pending; + synchronized (pendingResponses) { + pending = pendingResponses.remove(reqSeq); + } + if (pending != null) { + pending.complete(msg); + } + } else if ("event".equals(type)) { + if ("output".equals(msg.get("event").getAsString())) { + JsonObject body = msg.getAsJsonObject("body"); + if (body != null && body.has("output")) { + synchronized (stdoutBuffer) { + stdoutBuffer.append(body.get("output").getAsString()); + } + } + } + eventQueue.offer(msg); + } + } + } catch (IOException ex) { + // Socket closed at end of test + } finally { + synchronized (pendingResponses) { + for (CompletableFuture future : pendingResponses.values()) { + future.completeExceptionally(new IOException("DAP socket closed")); + } + pendingResponses.clear(); + } + } + } + + private static JsonObject readNextMessage(InputStream in) throws IOException { + ByteArrayOutputStream headerBuf = new ByteArrayOutputStream(); + int state = 0; + while (state < 4) { + int b = in.read(); + if (b < 0) { + return null; + } + headerBuf.write(b); + if (b == '\r' && (state == 0 || state == 2)) { + state++; + } else if (b == '\n' && (state == 1 || state == 3)) { + state++; + } else if (b == '\r') { + state = 1; + } else { + state = 0; + } + } + String header = headerBuf.toString(StandardCharsets.US_ASCII); + String prefix = "Content-Length: "; + int start = header.indexOf(prefix); + int end = header.indexOf("\r\n", start); + int contentLength = Integer.parseInt(header.substring(start + prefix.length(), end).trim()); + byte[] bodyBytes = in.readNBytes(contentLength); + if (bodyBytes.length < contentLength) { + return null; + } + return JsonParser.parseString(new String(bodyBytes, StandardCharsets.UTF_8)).getAsJsonObject(); + } + + @Override + public void close() throws IOException { + socket.close(); + } + } +} diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java new file mode 100644 index 000000000..2db3c9c46 --- /dev/null +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.plugin.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.microsoft.java.debug.core.DebugException; + +public class JavaDebugServerTest { + private JavaDebugServer server; + + @Before + public void setUp() { + server = new JavaDebugServer(JdtProviderContextFactory::createProviderContext, 2_000, 500); + } + + @After + public void tearDown() { + if (server != null) { + server.stop(); + } + System.clearProperty(JavaDebugServer.ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY); + } + + @Test + public void rejectsUnauthenticatedRawDapConnectionAndStillAcceptsValidClient() throws Exception { + Map descriptor = server.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String authToken = (String) descriptor.get("authToken"); + + assertEquals("127.0.0.1", host); + assertTrue(port > 0); + assertNotNull(authToken); + assertEquals(64, authToken.length()); + + // 1. Rogue unauthenticated client sends raw DAP initialize without token. + try (Socket unauthSocket = new Socket()) { + unauthSocket.connect(new InetSocketAddress(host, port), 1_000); + unauthSocket.setSoTimeout(1_000); + byte[] rawInit = buildDapFrame("{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\",\"arguments\":{}}"); + unauthSocket.getOutputStream().write(rawInit); + unauthSocket.getOutputStream().flush(); + int read = unauthSocket.getInputStream().read(); + assertEquals("Unauthenticated socket must be closed without emitting any DAP response.", -1, read); + } + + // 2. Rogue stalled scanner holds an open socket without sending anything. + try (Socket stalledScanner = new Socket()) { + stalledScanner.connect(new InetSocketAddress(host, port), 1_000); + + // 3. Legitimate client connects concurrently with auth header + initialize in one write. + try (Socket validClient = new Socket()) { + validClient.connect(new InetSocketAddress(host, port), 1_000); + validClient.setSoTimeout(2_000); + + byte[] authBytes = (JavaDebugServer.AUTH_HEADER_PREFIX + authToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + byte[] initFrame = buildDapFrame( + "{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\",\"arguments\":{\"adapterID\":\"java\"}}"); + byte[] disconnectFrame = buildDapFrame( + "{\"seq\":2,\"type\":\"request\",\"command\":\"disconnect\",\"arguments\":{}}"); + + OutputStream out = validClient.getOutputStream(); + ByteArrayOutputStream combined = new ByteArrayOutputStream(); + combined.write(authBytes); + combined.write(initFrame); + out.write(combined.toByteArray()); + out.flush(); + + String firstMessage = readSingleDapBody(validClient.getInputStream()); + assertTrue("Expected initialize response/event, got: " + firstMessage, + firstMessage.contains("\"initialize\"") || firstMessage.contains("\"initialized\"")); + + // Verify serverSocket closed immediately: even replaying the valid token on a 2nd connection fails. + assertPortClosed(host, port); + + out.write(disconnectFrame); + out.flush(); + } + } + } + + @Test + public void closesUnusedSessionListenerAfterAcceptTimeout() throws Exception { + JavaDebugServer shortServer = new JavaDebugServer(JdtProviderContextFactory::createProviderContext, 250, 150); + try { + Map descriptor = shortServer.startDebugSession(); + int port = ((Number) descriptor.get("port")).intValue(); + Thread.sleep(500); + assertEquals(0, shortServer.getPendingListenerCount()); + assertPortClosed("127.0.0.1", port); + } finally { + shortServer.stop(); + } + } + + @Test + public void legacyZeroArgStartSessionIsDisabledByDefault() throws Exception { + try { + JavaDebugDelegateCommandHandler.startDebugSession(Collections.emptyList()); + fail("Expected DebugException when calling startDebugSession without protocolVersion >= 2."); + } catch (DebugException ex) { + assertTrue(ex.getMessage().contains("disabled")); + } + } + + @Test + public void protocolVersionTwoCommandReturnsAuthenticatedSessionMap() throws Exception { + Object result = JavaDebugDelegateCommandHandler.startDebugSession( + Collections.singletonList("{\"protocolVersion\":2}")); + try { + assertTrue(result instanceof Map); + Map map = (Map) result; + assertEquals(2, ((Number) map.get("protocolVersion")).intValue()); + assertEquals(64, ((String) map.get("authToken")).length()); + assertTrue(((Number) map.get("port")).intValue() > 0); + } finally { + JavaDebugServer.shutdownInstance(); + } + } + + private static void assertPortClosed(String host, int port) throws InterruptedException { + for (int attempt = 0; attempt < 10; attempt++) { + try (Socket replay = new Socket()) { + replay.connect(new InetSocketAddress(host, port), 200); + Thread.sleep(50); + } catch (ConnectException expected) { + return; + } catch (IOException other) { + return; + } + } + fail("Expected session ServerSocket on port " + port + " to be closed."); + } + + private static byte[] buildDapFrame(String json) { + byte[] body = json.getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + byte[] full = new byte[header.length + body.length]; + System.arraycopy(header, 0, full, 0, header.length); + System.arraycopy(body, 0, full, header.length, body.length); + return full; + } + + private static String readSingleDapBody(InputStream in) throws IOException { + ByteArrayOutputStream headerBuf = new ByteArrayOutputStream(); + int state = 0; + while (state < 4) { + int b = in.read(); + if (b < 0) { + throw new IOException("Unexpected EOF while reading DAP response header."); + } + headerBuf.write(b); + if (b == '\r' && (state == 0 || state == 2)) { + state++; + } else if (b == '\n' && (state == 1 || state == 3)) { + state++; + } else if (b == '\r') { + state = 1; + } else { + state = 0; + } + } + String header = headerBuf.toString(StandardCharsets.US_ASCII); + String prefix = "Content-Length: "; + int idx = header.indexOf(prefix); + int end = header.indexOf("\r\n", idx); + int length = Integer.parseInt(header.substring(idx + prefix.length(), end).trim()); + byte[] body = in.readNBytes(length); + return new String(body, StandardCharsets.UTF_8); + } +} diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java new file mode 100644 index 000000000..53ed2b049 --- /dev/null +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (c) 2026 Microsoft Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Microsoft Corporation - initial API and implementation + *******************************************************************************/ + +package com.microsoft.java.debug.plugin.internal; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.file.Paths; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.connect.Connector; +import com.sun.jdi.connect.IllegalConnectorArgumentsException; +import com.sun.jdi.connect.ListeningConnector; +import com.sun.jdi.connect.TransportTimeoutException; + +public class LoopbackSocketListeningConnectorTest { + + @Test + public void defaultListeningConnectorIsLoopbackOnlyAndRejectsWildcardAddresses() throws Exception { + AdvancedVirtualMachineManager vmManager = new AdvancedVirtualMachineManager(); + ListeningConnector connector = vmManager.listeningConnectors().get(0); + assertTrue(connector instanceof LoopbackSocketListeningConnector); + + Map badArgs = connector.defaultArguments(); + badArgs.get(LoopbackSocketListeningConnector.ARG_LOCAL_ADDRESS).setValue("0.0.0.0"); + try { + connector.startListening(badArgs); + fail("Expected IllegalConnectorArgumentsException for wildcard 0.0.0.0 bind address."); + } catch (IllegalConnectorArgumentsException expected) { + assertTrue(expected.argumentNames().contains(LoopbackSocketListeningConnector.ARG_LOCAL_ADDRESS)); + } + + Map args = connector.defaultArguments(); + ((Connector.IntegerArgument) args.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(150); + String address = connector.startListening(args); + try { + assertTrue("Expected 127.0.0.1:, got: " + address, address.startsWith("127.0.0.1:")); + int port = Integer.parseInt(address.substring("127.0.0.1:".length())); + + InetAddress localHost = InetAddress.getLocalHost(); + if (!localHost.isLoopbackAddress()) { + try (Socket externalSocket = new Socket()) { + externalSocket.connect(new InetSocketAddress(localHost, port), 200); + fail("Loopback JDI listener must not accept connections on non-loopback NIC " + localHost); + } catch (Exception expected) { + // Expected connection refusal / timeout on non-loopback interface + } + } + + try { + connector.accept(args); + fail("Expected TransportTimeoutException when no debuggee connects."); + } catch (TransportTimeoutException expected) { + // Expected timeout contract required by LaunchWithDebuggingDelegate + } + } finally { + connector.stopListening(args); + } + } + + @Test + public void acceptsRealDebuggeeJvmOverLoopbackAndClosesCleanly() throws Exception { + AdvancedVirtualMachineManager vmManager = new AdvancedVirtualMachineManager(); + LoopbackSocketListeningConnector connector = new LoopbackSocketListeningConnector(vmManager); + Map args = connector.defaultArguments(); + ((Connector.IntegerArgument) args.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(10_000); + + String listenAddress = connector.startListening(args); + Process debuggee = null; + VirtualMachine vm = null; + try { + CompletableFuture vmFuture = CompletableFuture.supplyAsync(() -> { + try { + return connector.accept(args); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + + String javaBin = Paths.get(System.getProperty("java.home"), "bin", + File.separatorChar == '\\' ? "java.exe" : "java").toString(); + ProcessBuilder pb = new ProcessBuilder( + javaBin, + "-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=" + listenAddress, + "-version"); + pb.redirectErrorStream(true); + debuggee = pb.start(); + + vm = vmFuture.get(10, TimeUnit.SECONDS); + assertNotNull(vm); + assertNotNull(vm.version()); + connector.stopListening(args); + vm.resume(); + assertTrue(debuggee.waitFor(10, TimeUnit.SECONDS)); + } finally { + connector.stopListening(args); + if (vm != null) { + try { + vm.dispose(); + } catch (Exception ignore) { + // Debuggee may have already exited after resume() + } + } + if (debuggee != null && debuggee.isAlive()) { + debuggee.destroyForcibly(); + } + } + } +} From 472beffb00e4b98e4e34c3c6587e0c30bdad9dac Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 11:26:59 +0800 Subject: [PATCH 2/7] test: handle TCP reset when server closes rejected sockets on macOS On BSD/macOS kernels, closing a socket while unread client bytes remain in SO_RCVBUF sends a TCP RST (SocketException: Connection reset) rather than a FIN (-1 EOF). Accept either EOF or SocketException after connect when verifying that unauthenticated or invalid-token sockets are closed without emitting any DAP response. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../JavaDebugEndToEndFunctionalTest.java | 48 +++++++++++-------- .../plugin/internal/JavaDebugServerTest.java | 31 ++++++++---- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java index 0ebc94dbe..a44c3226c 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java @@ -27,6 +27,7 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; +import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -153,30 +154,15 @@ public void unauthenticatedOrInvalidTokenLaunchRequestIsRejected() throws Except byte[] launchFrame = buildDapFrame(buildRequestJson(2, "launch", launchArgs)); // 1. Raw initialize + launch with no JavaDebug-Auth header. - try (Socket unauth = new Socket()) { - unauth.connect(new InetSocketAddress(host, port), 2_000); - unauth.setSoTimeout(2_000); - unauth.getOutputStream().write(initFrame); - unauth.getOutputStream().write(launchFrame); - unauth.getOutputStream().flush(); - assertEquals(-1, unauth.getInputStream().read()); - } + sendAndAssertRejectedWithoutResponse(host, port, initFrame, launchFrame); Thread.sleep(200); assertFalse("Unauthenticated launch request must never execute.", Files.exists(sentinelFile)); // 2. Wrong 64-hex token + initialize + launch. String wrongToken = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - try (Socket wrongAuth = new Socket()) { - wrongAuth.connect(new InetSocketAddress(host, port), 2_000); - wrongAuth.setSoTimeout(2_000); - byte[] wrongHeader = (JavaDebugServer.AUTH_HEADER_PREFIX + wrongToken + "\r\n\r\n") - .getBytes(StandardCharsets.US_ASCII); - wrongAuth.getOutputStream().write(wrongHeader); - wrongAuth.getOutputStream().write(initFrame); - wrongAuth.getOutputStream().write(launchFrame); - wrongAuth.getOutputStream().flush(); - assertEquals(-1, wrongAuth.getInputStream().read()); - } + byte[] wrongHeader = (JavaDebugServer.AUTH_HEADER_PREFIX + wrongToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + sendAndAssertRejectedWithoutResponse(host, port, wrongHeader, initFrame, launchFrame); Thread.sleep(200); assertFalse("Wrong-token launch payload must never execute.", Files.exists(sentinelFile)); @@ -411,6 +397,30 @@ private void setUpSampleJavaProject() throws Exception { } } + private static void sendAndAssertRejectedWithoutResponse(String host, int port, byte[]... chunks) + throws IOException { + ByteArrayOutputStream combined = new ByteArrayOutputStream(); + for (byte[] chunk : chunks) { + combined.write(chunk); + } + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host, port), 2_000); + socket.setSoTimeout(2_000); + try { + socket.getOutputStream().write(combined.toByteArray()); + socket.getOutputStream().flush(); + } catch (SocketException ignored) { + // Server may reset the socket immediately once the invalid header is detected. + } + try { + int read = socket.getInputStream().read(); + assertEquals(-1, read); + } catch (SocketException expectedReset) { + // Closing a socket with unread bytes in SO_RCVBUF sends TCP RST on BSD/macOS. + } + } + } + private static void compileWithJavac(Path javaSource, Path outputDir) throws Exception { String javacBin = Paths.get(System.getProperty("java.home"), "bin", File.separatorChar == '\\' ? "javac.exe" : "javac").toString(); diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java index 2db3c9c46..2b0d9ccef 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java @@ -23,6 +23,7 @@ import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; +import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; @@ -62,15 +63,8 @@ public void rejectsUnauthenticatedRawDapConnectionAndStillAcceptsValidClient() t assertEquals(64, authToken.length()); // 1. Rogue unauthenticated client sends raw DAP initialize without token. - try (Socket unauthSocket = new Socket()) { - unauthSocket.connect(new InetSocketAddress(host, port), 1_000); - unauthSocket.setSoTimeout(1_000); - byte[] rawInit = buildDapFrame("{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\",\"arguments\":{}}"); - unauthSocket.getOutputStream().write(rawInit); - unauthSocket.getOutputStream().flush(); - int read = unauthSocket.getInputStream().read(); - assertEquals("Unauthenticated socket must be closed without emitting any DAP response.", -1, read); - } + byte[] rawInit = buildDapFrame("{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\",\"arguments\":{}}"); + sendAndAssertRejectedWithoutResponse(host, port, rawInit); // 2. Rogue stalled scanner holds an open socket without sending anything. try (Socket stalledScanner = new Socket()) { @@ -147,6 +141,25 @@ public void protocolVersionTwoCommandReturnsAuthenticatedSessionMap() throws Exc } } + private static void sendAndAssertRejectedWithoutResponse(String host, int port, byte[] payload) throws IOException { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(host, port), 1_000); + socket.setSoTimeout(1_000); + try { + socket.getOutputStream().write(payload); + socket.getOutputStream().flush(); + } catch (SocketException ignored) { + // Server may reset the socket immediately once the invalid prefix is detected. + } + try { + int read = socket.getInputStream().read(); + assertEquals("Unauthenticated socket must be closed without emitting any DAP response.", -1, read); + } catch (SocketException expectedReset) { + // Closing a socket with unread bytes in SO_RCVBUF sends TCP RST on BSD/macOS. + } + } + } + private static void assertPortClosed(String host, int port) throws InterruptedException { for (int attempt = 0; attempt < 10; attempt++) { try (Socket replay = new Socket()) { From c2489401841f2eca1eae9704ed9aa439c79472a4 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 11:48:46 +0800 Subject: [PATCH 3/7] fix: bound JDWP packet length, handshake deadline, and rejected listener cleanup - Enforce an upper JDWP packet-size bound (64 MiB default) in LoopbackSocketConnection.readPacket() and close the connection before allocating oversized buffers. - Enforce an absolute wall-clock deadline across performJdwpHandshake() reads so slow-drip peers cannot stretch per-read SO_TIMEOUT. - Remove and close session listeners when executor submission throws in startDebugSession() and startLegacyLoopbackSession(). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../plugin/internal/JavaDebugServer.java | 28 +++++++- .../LoopbackSocketListeningConnector.java | 26 +++++++- .../plugin/internal/JavaDebugServerTest.java | 27 ++++++++ .../LoopbackSocketListeningConnectorTest.java | 65 +++++++++++++++++++ 4 files changed, 142 insertions(+), 4 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java index 15c85e359..1bf97e5e4 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java @@ -63,6 +63,7 @@ public class JavaDebugServer implements IDebugServer { private final Supplier providerContextFactory; private final int acceptTimeoutMs; private final int handshakeTimeoutMs; + private final int maxConcurrentTasks; private final Set pendingListeners = ConcurrentHashMap.newKeySet(); private final Set activeSessions = ConcurrentHashMap.newKeySet(); private final AtomicBoolean stopped = new AtomicBoolean(false); @@ -73,9 +74,18 @@ private JavaDebugServer() { } JavaDebugServer(Supplier providerContextFactory, int acceptTimeoutMs, int handshakeTimeoutMs) { + this(providerContextFactory, acceptTimeoutMs, handshakeTimeoutMs, MAX_CONCURRENT_TASKS); + } + + JavaDebugServer( + Supplier providerContextFactory, + int acceptTimeoutMs, + int handshakeTimeoutMs, + int maxConcurrentTasks) { this.providerContextFactory = providerContextFactory; this.acceptTimeoutMs = acceptTimeoutMs; this.handshakeTimeoutMs = handshakeTimeoutMs; + this.maxConcurrentTasks = maxConcurrentTasks; } /** @@ -114,7 +124,13 @@ public Map startDebugSession() throws IOException { int port = sessionListener.getLocalPort(); String host = bindAddress.getHostAddress(); - getOrCreateExecutor().execute(() -> acceptAuthenticatedClientLoop(sessionListener, expectedHandshake)); + try { + getOrCreateExecutor().execute(() -> acceptAuthenticatedClientLoop(sessionListener, expectedHandshake)); + } catch (RuntimeException ex) { + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); + throw ex; + } Map descriptor = new LinkedHashMap<>(); descriptor.put("host", host); @@ -136,7 +152,13 @@ public int startLegacyLoopbackSession() throws IOException { pendingListeners.add(sessionListener); int port = sessionListener.getLocalPort(); - getOrCreateExecutor().execute(() -> acceptLegacySingleClient(sessionListener)); + try { + getOrCreateExecutor().execute(() -> acceptLegacySingleClient(sessionListener)); + } catch (RuntimeException ex) { + pendingListeners.remove(sessionListener); + closeQuietly(sessionListener); + throw ex; + } return port; } @@ -191,7 +213,7 @@ private synchronized ExecutorService getOrCreateExecutor() { }; this.executor = new ThreadPoolExecutor( 0, - MAX_CONCURRENT_TASKS, + this.maxConcurrentTasks, 30L, TimeUnit.SECONDS, new SynchronousQueue<>(), diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java index 38598cdd0..b8d53297a 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java @@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; +import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdi.internal.VirtualMachineManagerImpl; @@ -43,6 +44,8 @@ public class LoopbackSocketListeningConnector extends SocketListeningConnectorIm public static final String ARG_PORT = "port"; public static final String ARG_TIMEOUT = "timeout"; public static final String ARG_LOCAL_ADDRESS = "localAddress"; + public static final String MAX_JDWP_PACKET_PROPERTY = "java.debug.jdwp.maxPacketBytes"; + static final int DEFAULT_MAX_JDWP_PACKET_LENGTH = 64 * 1024 * 1024; private static final String DEFAULT_LOOPBACK_ADDRESS = "127.0.0.1"; private static final byte[] JDWP_HANDSHAKE = "JDWP-Handshake".getBytes(StandardCharsets.US_ASCII); private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000; @@ -219,7 +222,9 @@ private static int parseIntegerArgument( } private static void performJdwpHandshake(Socket socket, int timeoutMs) throws IOException { - socket.setSoTimeout(timeoutMs); + int boundedTimeoutMs = Math.max(1, timeoutMs); + long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(boundedTimeoutMs); + socket.setSoTimeout(boundedTimeoutMs); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); // Per the JDWP specification, the debugger side always sends "JDWP-Handshake" @@ -230,6 +235,12 @@ private static void performJdwpHandshake(Socket socket, int timeoutMs) throws IO int offset = 0; try { while (offset < received.length) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); + } + int remainingMs = (int) Math.max(1L, Math.min(Integer.MAX_VALUE, TimeUnit.NANOSECONDS.toMillis(remainingNanos))); + socket.setSoTimeout(remainingMs); int read = in.read(received, offset, received.length - offset); if (read < 0) { throw new IOException("Unexpected EOF during JDWP handshake."); @@ -245,6 +256,14 @@ private static void performJdwpHandshake(Socket socket, int timeoutMs) throws IO socket.setSoTimeout(0); } + static int resolveMaxJdwpPacketLength() { + Integer configured = Integer.getInteger(MAX_JDWP_PACKET_PROPERTY); + if (configured != null && configured >= MIN_JDWP_PACKET_LENGTH) { + return configured; + } + return DEFAULT_MAX_JDWP_PACKET_LENGTH; + } + static final class LoopbackSocketConnection extends Connection { private Socket socket; private final InputStream input; @@ -290,8 +309,13 @@ public byte[] readPacket() throws IOException { throw new ClosedConnectionException(); } if (packetLength < MIN_JDWP_PACKET_LENGTH) { + close(); throw new IOException("JDWP Packet under 11 bytes"); } + if (packetLength > resolveMaxJdwpPacketLength()) { + close(); + throw new IOException("JDWP Packet exceeds maximum allowed length: " + packetLength); + } byte[] packet = new byte[packetLength]; packet[0] = (byte) ((packetLength >>> 24) & 0xFF); packet[1] = (byte) ((packetLength >>> 16) & 0xFF); diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java index 2b0d9ccef..2fd054a11 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java @@ -27,6 +27,7 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; +import java.util.concurrent.RejectedExecutionException; import org.junit.After; import org.junit.Before; @@ -116,6 +117,32 @@ public void closesUnusedSessionListenerAfterAcceptTimeout() throws Exception { } } + @Test + public void closesListenerWhenExecutorSubmissionIsRejected() throws Exception { + JavaDebugServer singleSlotServer = new JavaDebugServer( + JdtProviderContextFactory::createProviderContext, 5_000, 1_000, 1); + try { + singleSlotServer.startDebugSession(); + assertEquals(1, singleSlotServer.getPendingListenerCount()); + + try { + singleSlotServer.startDebugSession(); + fail("Expected RejectedExecutionException when executor capacity is saturated."); + } catch (RejectedExecutionException expected) { + assertEquals(1, singleSlotServer.getPendingListenerCount()); + } + + try { + singleSlotServer.startLegacyLoopbackSession(); + fail("Expected RejectedExecutionException when legacy submission is saturated."); + } catch (RejectedExecutionException expected) { + assertEquals(1, singleSlotServer.getPendingListenerCount()); + } + } finally { + singleSlotServer.stop(); + } + } + @Test public void legacyZeroArgStartSessionIsDisabledByDefault() throws Exception { try { diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java index 53ed2b049..92e16758f 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java @@ -11,13 +11,17 @@ package com.microsoft.java.debug.plugin.internal; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.DataOutputStream; import java.io.File; +import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Paths; import java.util.Map; @@ -125,4 +129,65 @@ public void acceptsRealDebuggeeJvmOverLoopbackAndClosesCleanly() throws Exceptio } } } + + @Test + public void rejectsOversizedJdwpPacketAndClosesConnection() throws Exception { + InetAddress loopback = InetAddress.getByName("127.0.0.1"); + try (ServerSocket server = new ServerSocket(0, 1, loopback); + Socket peer = new Socket()) { + peer.connect(new InetSocketAddress(loopback, server.getLocalPort()), 1_000); + try (Socket accepted = server.accept()) { + LoopbackSocketListeningConnector.LoopbackSocketConnection connection = + new LoopbackSocketListeningConnector.LoopbackSocketConnection( + accepted, accepted.getInputStream(), accepted.getOutputStream()); + DataOutputStream out = new DataOutputStream(peer.getOutputStream()); + out.writeInt(Integer.MAX_VALUE); + out.flush(); + + try { + connection.readPacket(); + fail("Expected IOException for oversized JDWP packet length."); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains("exceeds maximum allowed length")); + } + assertFalse("Connection must be closed after oversized packet rejection.", connection.isOpen()); + } + } + } + + @Test + public void enforcesAbsoluteHandshakeDeadlineAgainstSlowDripPeer() throws Exception { + AdvancedVirtualMachineManager vmManager = new AdvancedVirtualMachineManager(); + LoopbackSocketListeningConnector connector = new LoopbackSocketListeningConnector(vmManager); + Map args = connector.defaultArguments(); + ((Connector.IntegerArgument) args.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(200); + + String listenAddress = connector.startListening(args); + int port = Integer.parseInt(listenAddress.substring("127.0.0.1:".length())); + CompletableFuture dripClient = CompletableFuture.runAsync(() -> { + try (Socket slowPeer = new Socket()) { + slowPeer.connect(new InetSocketAddress("127.0.0.1", port), 1_000); + byte[] partial = "JDWP-Handshake".getBytes(); + for (byte b : partial) { + slowPeer.getOutputStream().write(b); + slowPeer.getOutputStream().flush(); + Thread.sleep(70); + } + } catch (Exception ignored) { + // Expected once server closes socket at absolute deadline. + } + }); + + long startNanos = System.nanoTime(); + try { + connector.accept(args); + fail("Expected TransportTimeoutException for slow-drip JDWP handshake."); + } catch (TransportTimeoutException expected) { + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue("Expected handshake deadline near 200ms, took " + elapsedMs + "ms", elapsedMs < 900); + } finally { + connector.stopListening(args); + dripClient.get(2, TimeUnit.SECONDS); + } + } } From 0488a4bd91a5585c7fbe21bb03608a92d685bf44 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 12:25:44 +0800 Subject: [PATCH 4/7] fix(plugin): isolate session pools, bound auth deadline, and serialize JDWP I/O Separate listener, handshake, and session worker pools with per-listener candidate permits, enforce an absolute authentication handshake deadline across reads, and serialize JDWP socket packet reads and writes while preserving mid-packet EOF errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../plugin/internal/JavaDebugServer.java | 249 ++++++++++++++---- .../LoopbackSocketListeningConnector.java | 82 ++++-- .../plugin/internal/JavaDebugServerTest.java | 140 ++++++++++ .../LoopbackSocketListeningConnectorTest.java | 139 ++++++++++ 4 files changed, 539 insertions(+), 71 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java index 1bf97e5e4..c4ec3c377 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java @@ -29,6 +29,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; +import java.util.concurrent.Semaphore; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -55,7 +56,10 @@ public class JavaDebugServer implements IDebugServer { private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000; private static final int MAX_AUTH_FRAME_BYTES = 256; private static final int SESSION_BACKLOG = 8; - private static final int MAX_CONCURRENT_TASKS = 128; + private static final int DEFAULT_MAX_CONCURRENT_LISTENERS = 64; + private static final int DEFAULT_MAX_CONCURRENT_HANDSHAKES = 64; + private static final int DEFAULT_MAX_CANDIDATES_PER_LISTENER = 8; + private static final int DEFAULT_MAX_CONCURRENT_SESSIONS = 128; private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(1); private static JavaDebugServer singletonInstance; @@ -63,29 +67,62 @@ public class JavaDebugServer implements IDebugServer { private final Supplier providerContextFactory; private final int acceptTimeoutMs; private final int handshakeTimeoutMs; - private final int maxConcurrentTasks; + private final int maxConcurrentListeners; + private final int maxConcurrentHandshakes; + private final int maxCandidatesPerListener; + private final int maxConcurrentSessions; private final Set pendingListeners = ConcurrentHashMap.newKeySet(); private final Set activeSessions = ConcurrentHashMap.newKeySet(); private final AtomicBoolean stopped = new AtomicBoolean(false); - private ExecutorService executor; + private ExecutorService listenerExecutor; + private ExecutorService handshakeExecutor; + private ExecutorService sessionExecutor; private JavaDebugServer() { this(JdtProviderContextFactory::createProviderContext, DEFAULT_ACCEPT_TIMEOUT_MS, DEFAULT_HANDSHAKE_TIMEOUT_MS); } JavaDebugServer(Supplier providerContextFactory, int acceptTimeoutMs, int handshakeTimeoutMs) { - this(providerContextFactory, acceptTimeoutMs, handshakeTimeoutMs, MAX_CONCURRENT_TASKS); + this( + providerContextFactory, + acceptTimeoutMs, + handshakeTimeoutMs, + DEFAULT_MAX_CONCURRENT_LISTENERS, + DEFAULT_MAX_CONCURRENT_HANDSHAKES, + DEFAULT_MAX_CANDIDATES_PER_LISTENER, + DEFAULT_MAX_CONCURRENT_SESSIONS); } JavaDebugServer( Supplier providerContextFactory, int acceptTimeoutMs, int handshakeTimeoutMs, - int maxConcurrentTasks) { + int maxConcurrentListeners) { + this( + providerContextFactory, + acceptTimeoutMs, + handshakeTimeoutMs, + maxConcurrentListeners, + DEFAULT_MAX_CONCURRENT_HANDSHAKES, + DEFAULT_MAX_CANDIDATES_PER_LISTENER, + DEFAULT_MAX_CONCURRENT_SESSIONS); + } + + JavaDebugServer( + Supplier providerContextFactory, + int acceptTimeoutMs, + int handshakeTimeoutMs, + int maxConcurrentListeners, + int maxConcurrentHandshakes, + int maxCandidatesPerListener, + int maxConcurrentSessions) { this.providerContextFactory = providerContextFactory; this.acceptTimeoutMs = acceptTimeoutMs; this.handshakeTimeoutMs = handshakeTimeoutMs; - this.maxConcurrentTasks = maxConcurrentTasks; + this.maxConcurrentListeners = maxConcurrentListeners; + this.maxConcurrentHandshakes = maxConcurrentHandshakes; + this.maxCandidatesPerListener = maxCandidatesPerListener; + this.maxConcurrentSessions = maxConcurrentSessions; } /** @@ -125,7 +162,7 @@ public Map startDebugSession() throws IOException { String host = bindAddress.getHostAddress(); try { - getOrCreateExecutor().execute(() -> acceptAuthenticatedClientLoop(sessionListener, expectedHandshake)); + getOrCreateListenerExecutor().execute(() -> acceptAuthenticatedClientLoop(sessionListener, expectedHandshake)); } catch (RuntimeException ex) { pendingListeners.remove(sessionListener); closeQuietly(sessionListener); @@ -153,7 +190,7 @@ public int startLegacyLoopbackSession() throws IOException { int port = sessionListener.getLocalPort(); try { - getOrCreateExecutor().execute(() -> acceptLegacySingleClient(sessionListener)); + getOrCreateListenerExecutor().execute(() -> acceptLegacySingleClient(sessionListener)); } catch (RuntimeException ex) { pendingListeners.remove(sessionListener); closeQuietly(sessionListener); @@ -185,10 +222,12 @@ public synchronized void stop() { } activeSessions.clear(); - if (this.executor != null) { - this.executor.shutdownNow(); - this.executor = null; - } + shutdownExecutor(this.listenerExecutor); + this.listenerExecutor = null; + shutdownExecutor(this.handshakeExecutor); + this.handshakeExecutor = null; + shutdownExecutor(this.sessionExecutor); + this.sessionExecutor = null; } int getPendingListenerCount() { @@ -201,45 +240,95 @@ int getActiveSessionCount() { private synchronized void ensureRunning() { stopped.set(false); - getOrCreateExecutor(); + getOrCreateListenerExecutor(); + getOrCreateHandshakeExecutor(); + getOrCreateSessionExecutor(); } - private synchronized ExecutorService getOrCreateExecutor() { - if (this.executor == null || this.executor.isShutdown()) { - ThreadFactory threadFactory = runnable -> { - Thread thread = new Thread(runnable, "Java Debug Session-" + THREAD_COUNTER.getAndIncrement()); - thread.setDaemon(true); - return thread; - }; - this.executor = new ThreadPoolExecutor( - 0, - this.maxConcurrentTasks, - 30L, - TimeUnit.SECONDS, - new SynchronousQueue<>(), - threadFactory); + private synchronized ExecutorService getOrCreateListenerExecutor() { + if (this.listenerExecutor == null || this.listenerExecutor.isShutdown()) { + this.listenerExecutor = createBoundedExecutor("Java Debug Listener-", this.maxConcurrentListeners); + } + return this.listenerExecutor; + } + + private synchronized ExecutorService getOrCreateHandshakeExecutor() { + if (this.handshakeExecutor == null || this.handshakeExecutor.isShutdown()) { + this.handshakeExecutor = createBoundedExecutor("Java Debug Handshake-", this.maxConcurrentHandshakes); + } + return this.handshakeExecutor; + } + + private synchronized ExecutorService getOrCreateSessionExecutor() { + if (this.sessionExecutor == null || this.sessionExecutor.isShutdown()) { + this.sessionExecutor = createBoundedExecutor("Java Debug Session-", this.maxConcurrentSessions); + } + return this.sessionExecutor; + } + + private static ExecutorService createBoundedExecutor(String threadPrefix, int maxThreads) { + ThreadFactory threadFactory = runnable -> { + Thread thread = new Thread(runnable, threadPrefix + THREAD_COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + }; + return new ThreadPoolExecutor( + 0, + maxThreads, + 30L, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + threadFactory); + } + + private static void shutdownExecutor(ExecutorService pool) { + if (pool != null) { + pool.shutdownNow(); } - return this.executor; } private void acceptAuthenticatedClientLoop(ServerSocket sessionListener, byte[] expectedHandshake) { + Semaphore candidateSlots = new Semaphore(maxCandidatesPerListener); AtomicBoolean claimed = new AtomicBoolean(false); Set pendingCandidates = ConcurrentHashMap.newKeySet(); long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(acceptTimeoutMs); try { while (!claimed.get() && !stopped.get() && !sessionListener.isClosed()) { - long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadlineNanos - System.nanoTime()); - if (remainingMs <= 0) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + break; + } + long acquireWaitMs = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(remainingNanos)); + boolean acquired; + try { + acquired = candidateSlots.tryAcquire(acquireWaitMs, TimeUnit.MILLISECONDS); + } catch (InterruptedException interruptedEx) { + Thread.currentThread().interrupt(); break; } - int waitMs = (int) Math.min(Integer.MAX_VALUE, Math.max(1L, remainingMs)); + if (!acquired) { + break; + } + if (claimed.get() || stopped.get() || sessionListener.isClosed()) { + candidateSlots.release(); + break; + } + + remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + candidateSlots.release(); + break; + } + int waitMs = (int) Math.min(Integer.MAX_VALUE, Math.max(1L, TimeUnit.NANOSECONDS.toMillis(remainingNanos))); Socket candidate; try { sessionListener.setSoTimeout(waitMs); candidate = sessionListener.accept(); } catch (SocketTimeoutException timeoutEx) { + candidateSlots.release(); break; } catch (IOException acceptEx) { + candidateSlots.release(); if (!claimed.get() && !stopped.get() && !sessionListener.isClosed()) { logger.log(Level.WARNING, String.format("Debug session accept failed: %s", acceptEx.toString()), acceptEx); } @@ -249,16 +338,30 @@ private void acceptAuthenticatedClientLoop(ServerSocket sessionListener, byte[] if (candidate.getInetAddress() == null || !candidate.getInetAddress().isLoopbackAddress()) { logger.warning("Rejected non-loopback debug connection from " + candidate.getInetAddress()); closeQuietly(candidate); + candidateSlots.release(); continue; } pendingCandidates.add(candidate); + if (claimed.get() || stopped.get()) { + pendingCandidates.remove(candidate); + closeQuietly(candidate); + candidateSlots.release(); + break; + } try { - getOrCreateExecutor().execute(() -> - handleAuthenticatedCandidate(sessionListener, candidate, expectedHandshake, claimed, pendingCandidates)); + getOrCreateHandshakeExecutor().execute(() -> + handleAuthenticatedCandidate( + sessionListener, + candidate, + expectedHandshake, + claimed, + pendingCandidates, + candidateSlots)); } catch (RuntimeException rejectedEx) { pendingCandidates.remove(candidate); closeQuietly(candidate); + candidateSlots.release(); } } } finally { @@ -278,19 +381,22 @@ private void handleAuthenticatedCandidate( Socket candidate, byte[] expectedHandshake, AtomicBoolean claimed, - Set pendingCandidates) { - boolean wonSession = false; + Set pendingCandidates, + Semaphore candidateSlots) { + boolean handedOffToSession = false; + boolean permitReleased = false; try { + if (claimed.get() || stopped.get()) { + return; + } candidate.setTcpNoDelay(true); - candidate.setSoTimeout(handshakeTimeoutMs); - if (!verifyAuthHandshake(candidate.getInputStream(), expectedHandshake)) { + if (!verifyAuthHandshake(candidate, expectedHandshake, handshakeTimeoutMs)) { logger.warning("Rejected unauthenticated or invalid-token connection to Java Debug Server."); return; } if (!claimed.compareAndSet(false, true) || stopped.get()) { return; } - wonSession = true; pendingCandidates.remove(candidate); pendingListeners.remove(sessionListener); closeQuietly(sessionListener); @@ -300,14 +406,21 @@ private void handleAuthenticatedCandidate( pendingCandidates.clear(); candidate.setSoTimeout(0); - runProtocolSession(candidate); - } catch (IOException e) { - if (wonSession && !stopped.get()) { + candidateSlots.release(); + permitReleased = true; + + getOrCreateSessionExecutor().execute(() -> runProtocolSession(candidate)); + handedOffToSession = true; + } catch (IOException | RuntimeException e) { + if (claimed.get() && !stopped.get()) { logger.log(Level.SEVERE, String.format("Authenticated debug session failed: %s", e.toString()), e); } } finally { pendingCandidates.remove(candidate); - if (!wonSession) { + if (!permitReleased) { + candidateSlots.release(); + } + if (!handedOffToSession) { closeQuietly(candidate); } } @@ -315,6 +428,7 @@ private void handleAuthenticatedCandidate( private void acceptLegacySingleClient(ServerSocket sessionListener) { Socket client = null; + boolean handedOffToSession = false; try { sessionListener.setSoTimeout(acceptTimeoutMs); client = sessionListener.accept(); @@ -322,23 +436,25 @@ private void acceptLegacySingleClient(ServerSocket sessionListener) { closeQuietly(sessionListener); if (client.getInetAddress() == null || !client.getInetAddress().isLoopbackAddress()) { logger.warning("Rejected non-loopback connection to legacy Java Debug Server."); - closeQuietly(client); return; } client.setTcpNoDelay(true); client.setSoTimeout(0); - runProtocolSession(client); + Socket acceptedClient = client; + getOrCreateSessionExecutor().execute(() -> runProtocolSession(acceptedClient)); + handedOffToSession = true; } catch (SocketTimeoutException timeoutEx) { logger.warning("Timed out waiting for client connection on legacy loopback debug session."); - closeQuietly(client); - } catch (IOException e) { + } catch (IOException | RuntimeException e) { if (!stopped.get()) { logger.log(Level.WARNING, String.format("Legacy debug session socket error: %s", e.toString()), e); } - closeQuietly(client); } finally { pendingListeners.remove(sessionListener); closeQuietly(sessionListener); + if (!handedOffToSession) { + closeQuietly(client); + } } } @@ -369,11 +485,43 @@ private void runProtocolSession(Socket connection) { } } + static boolean verifyAuthHandshake(Socket candidate, byte[] expectedHandshake, int handshakeTimeoutMs) throws IOException { + long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(handshakeTimeoutMs); + return verifyAuthHandshake( + candidate.getInputStream(), + expectedHandshake, + deadlineNanos, + candidate::setSoTimeout); + } + static boolean verifyAuthHandshake(InputStream inputStream, byte[] expectedHandshake) throws IOException { + return verifyAuthHandshake(inputStream, expectedHandshake, Long.MAX_VALUE, timeout -> { + // Stream-only unit helper has no socket timeout hook. + }); + } + + private static boolean verifyAuthHandshake( + InputStream inputStream, + byte[] expectedHandshake, + long deadlineNanos, + SocketTimeoutUpdater timeoutUpdater) throws IOException { ByteArrayOutputStream frameBuffer = new ByteArrayOutputStream(expectedHandshake.length); int state = 0; while (frameBuffer.size() < MAX_AUTH_FRAME_BYTES) { - int nextByte = inputStream.read(); + if (deadlineNanos != Long.MAX_VALUE) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + return false; + } + int remainingMs = (int) Math.max(1L, Math.min(Integer.MAX_VALUE, TimeUnit.NANOSECONDS.toMillis(remainingNanos))); + timeoutUpdater.setSoTimeout(remainingMs); + } + int nextByte; + try { + nextByte = inputStream.read(); + } catch (SocketTimeoutException timeoutEx) { + return false; + } if (nextByte < 0) { return false; } @@ -394,6 +542,11 @@ static boolean verifyAuthHandshake(InputStream inputStream, byte[] expectedHands return false; } + @FunctionalInterface + private interface SocketTimeoutUpdater { + void setSoTimeout(int timeoutMs) throws IOException; + } + private static String generateAuthToken() { byte[] randomBytes = new byte[AUTH_TOKEN_BYTES]; SECURE_RANDOM.nextBytes(randomBytes); diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java index b8d53297a..c50b7760b 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java @@ -12,6 +12,7 @@ package com.microsoft.java.debug.plugin.internal; import java.io.DataInputStream; +import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -265,13 +266,15 @@ static int resolveMaxJdwpPacketLength() { } static final class LoopbackSocketConnection extends Connection { + private final Object readLock = new Object(); + private final Object writeLock = new Object(); private Socket socket; - private final InputStream input; + private final DataInputStream dataInput; private final OutputStream output; LoopbackSocketConnection(Socket socket, InputStream input, OutputStream output) { this.socket = socket; - this.input = input; + this.dataInput = new DataInputStream(input); this.output = output; } @@ -294,20 +297,43 @@ public synchronized boolean isOpen() { @Override public byte[] readPacket() throws IOException { - DataInputStream dataInput; - synchronized (this) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + synchronized (this.readLock) { if (!isOpen()) { throw new ClosedConnectionException(); } - dataInput = new DataInputStream(this.input); - } - synchronized (dataInput) { - int packetLength; + int b0; + int b1; + int b2; + int b3; try { - packetLength = dataInput.readInt(); - } catch (IOException e) { - throw new ClosedConnectionException(); + b0 = this.dataInput.read(); + if (b0 < 0) { + // Eclipse JDT's PacketReceiveManager passes readPacket() directly to JdwpPacket.build(), + // which throws ArrayIndexOutOfBoundsException on empty arrays; it expects ClosedConnectionException + // on a clean packet-boundary EOF to trigger normal VMDisconnectEvent dispatch. + throw new ClosedConnectionException(); + } + b1 = this.dataInput.read(); + b2 = this.dataInput.read(); + b3 = this.dataInput.read(); + } catch (ClosedConnectionException closedEx) { + throw closedEx; + } catch (IOException ioEx) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + throw ioEx; + } + if ((b1 | b2 | b3) < 0) { + throw new EOFException("Unexpected EOF in JDWP packet header"); } + int packetLength = ((b0 & 0xFF) << 24) + | ((b1 & 0xFF) << 16) + | ((b2 & 0xFF) << 8) + | (b3 & 0xFF); if (packetLength < MIN_JDWP_PACKET_LENGTH) { close(); throw new IOException("JDWP Packet under 11 bytes"); @@ -317,11 +343,18 @@ public byte[] readPacket() throws IOException { throw new IOException("JDWP Packet exceeds maximum allowed length: " + packetLength); } byte[] packet = new byte[packetLength]; - packet[0] = (byte) ((packetLength >>> 24) & 0xFF); - packet[1] = (byte) ((packetLength >>> 16) & 0xFF); - packet[2] = (byte) ((packetLength >>> 8) & 0xFF); - packet[3] = (byte) (packetLength & 0xFF); - dataInput.readFully(packet, 4, packetLength - 4); + packet[0] = (byte) b0; + packet[1] = (byte) b1; + packet[2] = (byte) b2; + packet[3] = (byte) b3; + try { + this.dataInput.readFully(packet, 4, packetLength - 4); + } catch (IOException ioEx) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + throw ioEx; + } return packet; } } @@ -344,16 +377,19 @@ public void writePacket(byte[] packet) throws IOException { if (packetLength > packet.length) { throw new IllegalArgumentException("Invalid JDWP packet: Specified length is greater than actual length"); } - OutputStream targetOut; - synchronized (this) { + synchronized (this.writeLock) { if (!isOpen()) { throw new ClosedConnectionException(); } - targetOut = this.output; - } - synchronized (targetOut) { - targetOut.write(packet, 0, packetLength); - targetOut.flush(); + try { + this.output.write(packet, 0, packetLength); + this.output.flush(); + } catch (IOException ioEx) { + if (!isOpen()) { + throw new ClosedConnectionException(); + } + throw ioEx; + } } } diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java index 2fd054a11..8e5419455 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java @@ -25,9 +25,12 @@ import java.net.Socket; import java.net.SocketException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; @@ -143,6 +146,115 @@ public void closesListenerWhenExecutorSubmissionIsRejected() throws Exception { } } + @Test + public void enforcesAbsoluteAuthHandshakeDeadlineAgainstSlowDripClient() throws Exception { + JavaDebugServer deadlineServer = new JavaDebugServer( + JdtProviderContextFactory::createProviderContext, 5_000, 200); + try { + Map descriptor = deadlineServer.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String authToken = (String) descriptor.get("authToken"); + + long startNanos = System.nanoTime(); + try (Socket slowClient = new Socket()) { + slowClient.connect(new InetSocketAddress(host, port), 1_000); + slowClient.setSoTimeout(1_000); + byte[] authBytes = (JavaDebugServer.AUTH_HEADER_PREFIX + authToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + try { + for (byte b : authBytes) { + slowClient.getOutputStream().write(b); + slowClient.getOutputStream().flush(); + Thread.sleep(60); + } + } catch (SocketException ignored) { + // Expected once server closes socket at absolute handshake deadline. + } + try { + int next = slowClient.getInputStream().read(); + assertEquals(-1, next); + } catch (SocketException ignored) { + // Expected TCP RST on platforms with unread bytes buffered. + } + } + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue("Expected slow-drip auth handshake to fail near 200ms, took " + elapsedMs + "ms", + elapsedMs < 1_200); + + // Listener is still open within its 5s accept window and accepts a fast valid client. + authenticateAndDisconnect(host, port, authToken); + } finally { + deadlineServer.stop(); + } + } + + @Test + public void stalledClientsOnOneSessionCannotStarveOtherSessionsOrPool() throws Exception { + JavaDebugServer isolatedServer = new JavaDebugServer( + JdtProviderContextFactory::createProviderContext, 5_000, 1_500, 4, 4, 2, 4); + List stalledSockets = new ArrayList<>(); + try { + Map floodedSession = isolatedServer.startDebugSession(); + String host1 = (String) floodedSession.get("host"); + int port1 = ((Number) floodedSession.get("port")).intValue(); + + // Open more stalled sockets on session 1 than both per-listener (2) and total handshake (4) caps. + for (int i = 0; i < 5; i++) { + Socket s = new Socket(); + s.connect(new InetSocketAddress(host1, port1), 1_000); + stalledSockets.add(s); + } + Thread.sleep(100); + + // Creating and authenticating an unrelated session 2 must still succeed without starvation. + Map healthySession = isolatedServer.startDebugSession(); + authenticateAndDisconnect( + (String) healthySession.get("host"), + ((Number) healthySession.get("port")).intValue(), + (String) healthySession.get("authToken")); + } finally { + for (Socket s : stalledSockets) { + try { + s.close(); + } catch (IOException ignored) { + // Ignore + } + } + isolatedServer.stop(); + } + } + + @Test + public void saturatingPendingListenersDoesNotStarveAuthenticationOfExistingSessions() throws Exception { + JavaDebugServer cappedServer = new JavaDebugServer( + JdtProviderContextFactory::createProviderContext, 5_000, 1_500, 2, 4, 2, 4); + try { + Map s1 = cappedServer.startDebugSession(); + Map s2 = cappedServer.startDebugSession(); + assertEquals(2, cappedServer.getPendingListenerCount()); + + try { + cappedServer.startDebugSession(); + fail("Expected RejectedExecutionException when listener pool is full."); + } catch (RejectedExecutionException expected) { + assertEquals(2, cappedServer.getPendingListenerCount()); + } + + // Even with listener pool 100% full before connecting, both pending sessions authenticate cleanly. + authenticateAndDisconnect( + (String) s1.get("host"), + ((Number) s1.get("port")).intValue(), + (String) s1.get("authToken")); + authenticateAndDisconnect( + (String) s2.get("host"), + ((Number) s2.get("port")).intValue(), + (String) s2.get("authToken")); + } finally { + cappedServer.stop(); + } + } + @Test public void legacyZeroArgStartSessionIsDisabledByDefault() throws Exception { try { @@ -168,6 +280,34 @@ public void protocolVersionTwoCommandReturnsAuthenticatedSessionMap() throws Exc } } + private static void authenticateAndDisconnect(String host, int port, String authToken) throws IOException { + try (Socket validClient = new Socket()) { + validClient.connect(new InetSocketAddress(host, port), 1_000); + validClient.setSoTimeout(2_000); + + byte[] authBytes = (JavaDebugServer.AUTH_HEADER_PREFIX + authToken + "\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII); + byte[] initFrame = buildDapFrame( + "{\"seq\":1,\"type\":\"request\",\"command\":\"initialize\",\"arguments\":{\"adapterID\":\"java\"}}"); + byte[] disconnectFrame = buildDapFrame( + "{\"seq\":2,\"type\":\"request\",\"command\":\"disconnect\",\"arguments\":{}}"); + + OutputStream out = validClient.getOutputStream(); + ByteArrayOutputStream combined = new ByteArrayOutputStream(); + combined.write(authBytes); + combined.write(initFrame); + out.write(combined.toByteArray()); + out.flush(); + + String firstMessage = readSingleDapBody(validClient.getInputStream()); + assertTrue("Expected initialize response/event, got: " + firstMessage, + firstMessage.contains("\"initialize\"") || firstMessage.contains("\"initialized\"")); + + out.write(disconnectFrame); + out.flush(); + } + } + private static void sendAndAssertRejectedWithoutResponse(String host, int port, byte[] payload) throws IOException { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), 1_000); diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java index 92e16758f..7c4c7e6c5 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java @@ -11,12 +11,15 @@ package com.microsoft.java.debug.plugin.internal; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.DataOutputStream; +import java.io.EOFException; import java.io.File; import java.io.IOException; import java.net.InetAddress; @@ -24,8 +27,11 @@ import java.net.ServerSocket; import java.net.Socket; import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Test; @@ -35,6 +41,7 @@ import com.sun.jdi.connect.IllegalConnectorArgumentsException; import com.sun.jdi.connect.ListeningConnector; import com.sun.jdi.connect.TransportTimeoutException; +import com.sun.jdi.connect.spi.ClosedConnectionException; public class LoopbackSocketListeningConnectorTest { @@ -190,4 +197,136 @@ public void enforcesAbsoluteHandshakeDeadlineAgainstSlowDripPeer() throws Except dripClient.get(2, TimeUnit.SECONDS); } } + + @Test + public void distinguishesCleanEofFromTruncatedPacketAndClosedConnection() throws Exception { + InetAddress loopback = InetAddress.getByName("127.0.0.1"); + + // 1. Clean EOF between packets throws ClosedConnectionException required by Eclipse JDT PacketReceiveManager. + try (ServerSocket server = new ServerSocket(0, 1, loopback); + Socket peer = new Socket()) { + peer.connect(new InetSocketAddress(loopback, server.getLocalPort()), 1_000); + try (Socket accepted = server.accept()) { + LoopbackSocketListeningConnector.LoopbackSocketConnection connection = + new LoopbackSocketListeningConnector.LoopbackSocketConnection( + accepted, accepted.getInputStream(), accepted.getOutputStream()); + peer.shutdownOutput(); + try { + connection.readPacket(); + fail("Expected ClosedConnectionException on clean packet-boundary EOF for Eclipse JDT."); + } catch (ClosedConnectionException expected) { + assertTrue(connection.isOpen()); + } + + connection.close(); + try { + connection.readPacket(); + fail("Expected ClosedConnectionException after local close()."); + } catch (ClosedConnectionException expected) { + assertFalse(connection.isOpen()); + } + } + } + + // 2. Truncated 2-byte header throws EOFException (not ClosedConnectionException). + try (ServerSocket server = new ServerSocket(0, 1, loopback); + Socket peer = new Socket()) { + peer.connect(new InetSocketAddress(loopback, server.getLocalPort()), 1_000); + try (Socket accepted = server.accept()) { + LoopbackSocketListeningConnector.LoopbackSocketConnection connection = + new LoopbackSocketListeningConnector.LoopbackSocketConnection( + accepted, accepted.getInputStream(), accepted.getOutputStream()); + peer.getOutputStream().write(new byte[] {0, 0}); + peer.shutdownOutput(); + try { + connection.readPacket(); + fail("Expected EOFException for truncated JDWP header."); + } catch (EOFException expected) { + assertTrue(connection.isOpen()); + } + } + } + + // 3. Truncated body throws EOFException (not ClosedConnectionException). + try (ServerSocket server = new ServerSocket(0, 1, loopback); + Socket peer = new Socket()) { + peer.connect(new InetSocketAddress(loopback, server.getLocalPort()), 1_000); + try (Socket accepted = server.accept()) { + LoopbackSocketListeningConnector.LoopbackSocketConnection connection = + new LoopbackSocketListeningConnector.LoopbackSocketConnection( + accepted, accepted.getInputStream(), accepted.getOutputStream()); + DataOutputStream out = new DataOutputStream(peer.getOutputStream()); + out.writeInt(15); + out.write(new byte[] {1, 2, 3}); + out.flush(); + peer.shutdownOutput(); + try { + connection.readPacket(); + fail("Expected EOFException for truncated JDWP body."); + } catch (EOFException expected) { + assertTrue(connection.isOpen()); + } + } + } + } + + @Test + public void serializesConcurrentPacketReadsWithoutCorruptingStream() throws Exception { + InetAddress loopback = InetAddress.getByName("127.0.0.1"); + try (ServerSocket server = new ServerSocket(0, 1, loopback); + Socket peer = new Socket()) { + peer.connect(new InetSocketAddress(loopback, server.getLocalPort()), 1_000); + try (Socket accepted = server.accept()) { + LoopbackSocketListeningConnector.LoopbackSocketConnection connection = + new LoopbackSocketListeningConnector.LoopbackSocketConnection( + accepted, accepted.getInputStream(), accepted.getOutputStream()); + + byte[] packetA = new byte[15]; + packetA[3] = 15; + Arrays.fill(packetA, 4, 15, (byte) 0x2A); + + byte[] packetB = new byte[15]; + packetB[3] = 15; + Arrays.fill(packetB, 4, 15, (byte) 0x5B); + + CountDownLatch readersReady = new CountDownLatch(2); + CompletableFuture firstRead = CompletableFuture.supplyAsync(() -> { + readersReady.countDown(); + try { + return connection.readPacket(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }); + CompletableFuture secondRead = CompletableFuture.supplyAsync(() -> { + readersReady.countDown(); + try { + return connection.readPacket(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + }); + + assertTrue(readersReady.await(2, TimeUnit.SECONDS)); + for (byte b : packetA) { + peer.getOutputStream().write(b); + peer.getOutputStream().flush(); + } + for (byte b : packetB) { + peer.getOutputStream().write(b); + peer.getOutputStream().flush(); + } + + List received = Arrays.asList( + firstRead.get(2, TimeUnit.SECONDS), + secondRead.get(2, TimeUnit.SECONDS)); + if (Arrays.equals(packetA, received.get(0))) { + assertArrayEquals(packetB, received.get(1)); + } else { + assertArrayEquals(packetB, received.get(0)); + assertArrayEquals(packetA, received.get(1)); + } + } + } + } } From 61dc0af0dcca366a54c6c7dc62476ea9d3fdeb1b Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 12:48:16 +0800 Subject: [PATCH 5/7] fix(plugin): bound launch failure cleanup and async test javac drain Close the JDWP listener immediately on launch failure, drain debuggee stdout/stderr asynchronously with bounded timeouts while terminating the child process, and drain javac output asynchronously in end-to-end test compilation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../internal/AdvancedLaunchingConnector.java | 222 +++++++++++++----- .../JavaDebugEndToEndFunctionalTest.java | 21 +- .../LoopbackSocketListeningConnectorTest.java | 73 ++++++ 3 files changed, 255 insertions(+), 61 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java index c8718e10b..d8c80767f 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java @@ -11,6 +11,7 @@ package com.microsoft.java.debug.plugin.internal; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -20,8 +21,10 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.commons.io.IOUtils; import org.eclipse.jdi.internal.VirtualMachineImpl; import org.eclipse.jdi.internal.VirtualMachineManagerImpl; import org.eclipse.jdi.internal.connect.SocketLaunchingConnectorImpl; @@ -41,6 +44,10 @@ */ public class AdvancedLaunchingConnector extends SocketLaunchingConnectorImpl implements LaunchingConnector { private static final int ACCEPT_TIMEOUT = 10 * 1000; + private static final long PROCESS_TERMINATE_TIMEOUT_MS = 2_000L; + private static final long PROCESS_FORCE_TERMINATE_TIMEOUT_MS = 2_000L; + private static final long STREAM_DRAIN_TIMEOUT_MS = 2_000L; + private static final int MAX_DIAGNOSTIC_BYTES = 64 * 1024; public AdvancedLaunchingConnector(VirtualMachineManagerImpl virtualMachineManager) { super(virtualMachineManager); @@ -82,8 +89,7 @@ public VirtualMachine launch(Map connectionArgs) // do nothing. } - SocketListeningConnectorImpl listenConnector = new LoopbackSocketListeningConnector( - virtualMachineManager()); + SocketListeningConnectorImpl listenConnector = createListeningConnector(); Map args = listenConnector.defaultArguments(); ((Connector.IntegerArgument) args.get("timeout")).setValue(ACCEPT_TIMEOUT); //$NON-NLS-1$ String address = listenConnector.startListening(args); @@ -95,11 +101,7 @@ public VirtualMachine launch(Map connectionArgs) try { process = Runtime.getRuntime().exec(cmds, envVars, workingDir); } catch (IOException | RuntimeException ex) { - try { - listenConnector.stopListening(args); - } catch (IOException closeEx) { - // ignore cleanup failure - } + stopListeningQuietly(listenConnector, args); throw ex; } @@ -107,70 +109,94 @@ public VirtualMachine launch(Map connectionArgs) will fail with an Exception if we do not. */ final CompletableFuture result = new CompletableFuture<>(); + final AtomicBoolean outcomeClaimed = new AtomicBoolean(false); /* Listen for the debug connection from the Java process */ - CompletableFuture.runAsync(() -> { + Thread acceptThread = new Thread(() -> { try { VirtualMachineImpl vm = (VirtualMachineImpl) listenConnector.accept(args); vm.setLaunchedProcess(process); - result.complete(vm); - } catch (IllegalConnectorArgumentsException e) { - result.completeExceptionally(e); + if (outcomeClaimed.compareAndSet(false, true)) { + result.complete(vm); + } else { + try { + vm.dispose(); + } catch (RuntimeException ignored) { + // Process exit handler already claimed launch failure. + } + } } catch (IOException e) { - if (result.isDone()) { - /* The result Future has already been completed by the Process onExit hook */ + stopListeningQuietly(listenConnector, args); + if (!outcomeClaimed.compareAndSet(false, true)) { + /* The result Future is already being completed by the Process onExit hook */ return; } - - final String stdout = streamToString(process.getInputStream()); - final String stderr = streamToString(process.getErrorStream()); - - process.destroy(); - - result.completeExceptionally(new LaunchException( - String.format("VM did not connect within given time: %d ms", ACCEPT_TIMEOUT), - process, - false, - -1, - stdout, - stderr - )); - } catch (RuntimeException e) { - result.completeExceptionally(e); - } finally { try { - listenConnector.stopListening(args); - } catch (IOException e) { - /* Ignore */ + CompletableFuture stdoutFuture = + drainStreamAsync(process.getInputStream(), "JavaDebug-LaunchStdoutDrain"); + CompletableFuture stderrFuture = + drainStreamAsync(process.getErrorStream(), "JavaDebug-LaunchStderrDrain"); + + terminateProcessBounded(process); + + final String stdout = awaitBoundedOutput(stdoutFuture, process.getInputStream()); + final String stderr = awaitBoundedOutput(stderrFuture, process.getErrorStream()); + + LaunchException launchEx = new LaunchException( + String.format("VM did not connect within given time: %d ms", ACCEPT_TIMEOUT), + process, + false, + -1, + stdout, + stderr + ); + launchEx.initCause(e); + result.completeExceptionally(launchEx); + } catch (Throwable t) { + result.completeExceptionally(t); } + } catch (IllegalConnectorArgumentsException | RuntimeException e) { + stopListeningQuietly(listenConnector, args); + if (outcomeClaimed.compareAndSet(false, true)) { + terminateProcessBounded(process); + closeStreamQuietly(process.getInputStream()); + closeStreamQuietly(process.getErrorStream()); + } + result.completeExceptionally(e); + } finally { + stopListeningQuietly(listenConnector, args); } - }); + }, "JavaDebug-LaunchAccept"); + acceptThread.setDaemon(true); + acceptThread.start(); /* Wait for the Java process to exit; if it exits before the debug connection is made, report it as an error. */ process.onExit().thenAcceptAsync(theProcess -> { - if (result.isDone()) { - /* The result Future has already been completed by successfully connecting to the debug connection */ + if (!outcomeClaimed.compareAndSet(false, true)) { + /* The result Future has already been claimed by the accept handler */ return; } + try { + stopListeningQuietly(listenConnector, args); - final int exitStatus = theProcess.exitValue(); - final String stdout = streamToString(process.getInputStream()); - final String stderr = streamToString(process.getErrorStream()); - - result.completeExceptionally(new LaunchException( - String.format("VM exited with status %d", exitStatus), - theProcess, - true, - exitStatus, - stdout, - stderr - )); + final int exitStatus = theProcess.exitValue(); + CompletableFuture stdoutFuture = + drainStreamAsync(theProcess.getInputStream(), "JavaDebug-ExitStdoutDrain"); + CompletableFuture stderrFuture = + drainStreamAsync(theProcess.getErrorStream(), "JavaDebug-ExitStderrDrain"); + final String stdout = awaitBoundedOutput(stdoutFuture, theProcess.getInputStream()); + final String stderr = awaitBoundedOutput(stderrFuture, theProcess.getErrorStream()); - /* Stop the debug connection attempt */ - try { - listenConnector.stopListening(args); - } catch (IOException e) { - /* Ignore */ + result.completeExceptionally(new LaunchException( + String.format("VM exited with status %d", exitStatus), + theProcess, + true, + exitStatus, + stdout, + stderr + )); + } catch (Throwable t) { + result.completeExceptionally(t); } }); @@ -189,15 +215,97 @@ public VirtualMachine launch(Map connectionArgs) throw new IllegalStateException("Unexpected exception thrown when launching VM", e.getCause()); } } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + stopListeningQuietly(listenConnector, args); + terminateProcessBounded(process); + closeStreamQuietly(process.getInputStream()); + closeStreamQuietly(process.getErrorStream()); throw new VMStartException("VM start interrupted", process); } } - private String streamToString(final InputStream inputStream) { + SocketListeningConnectorImpl createListeningConnector() { + return new LoopbackSocketListeningConnector(virtualMachineManager()); + } + + private static void stopListeningQuietly( + SocketListeningConnectorImpl listenConnector, Map args) { + try { + listenConnector.stopListening(args); + } catch (IOException ignored) { + // Ignore cleanup failure + } + } + + private static void terminateProcessBounded(Process process) { + if (process == null || !process.isAlive()) { + return; + } + process.destroy(); try { - return IOUtils.toString(inputStream, StandardCharsets.UTF_8); - } catch (IOException ioe) { + if (!process.waitFor(PROCESS_TERMINATE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + process.destroyForcibly(); + process.waitFor(PROCESS_FORCE_TERMINATE_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } + } catch (InterruptedException ie) { + process.destroyForcibly(); + Thread.currentThread().interrupt(); + } + } + + private static CompletableFuture drainStreamAsync(final InputStream inputStream, final String threadName) { + CompletableFuture future = new CompletableFuture<>(); + Thread reader = new Thread(() -> { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + try { + byte[] chunk = new byte[4096]; + int read; + while ((read = inputStream.read(chunk)) != -1) { + int remaining = MAX_DIAGNOSTIC_BYTES - buffer.size(); + if (remaining > 0) { + buffer.write(chunk, 0, Math.min(read, remaining)); + } + } + future.complete(buffer.toString(StandardCharsets.UTF_8)); + } catch (IOException ioe) { + future.complete(buffer.size() > 0 ? buffer.toString(StandardCharsets.UTF_8) : null); + } + }, threadName); + reader.setDaemon(true); + reader.start(); + return future; + } + + private static String awaitBoundedOutput(CompletableFuture future, InputStream stream) { + try { + return future.get(STREAM_DRAIN_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (TimeoutException te) { + closeStreamQuietly(stream); + try { + return future.get(200L, TimeUnit.MILLISECONDS); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException | TimeoutException ignored) { + return null; + } + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + closeStreamQuietly(stream); return null; + } catch (ExecutionException ee) { + return null; + } + } + + private static void closeStreamQuietly(InputStream stream) { + if (stream == null) { + return; + } + try { + stream.close(); + } catch (IOException ignored) { + // Ignore stream close failure } } diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java index a44c3226c..5787c4dac 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugEndToEndFunctionalTest.java @@ -429,11 +429,24 @@ private static void compileWithJavac(Path javaSource, Path outputDir) throws Exc javaSource.toAbsolutePath().toString()) .redirectErrorStream(true) .start(); - String output; - try (InputStream in = proc.getInputStream()) { - output = new String(in.readAllBytes(), StandardCharsets.UTF_8); + CompletableFuture outputFuture = new CompletableFuture<>(); + Thread drainThread = new Thread(() -> { + try (InputStream in = proc.getInputStream()) { + outputFuture.complete(new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } catch (IOException ex) { + outputFuture.complete(ex.toString()); + } + }, "JavaDebugTest-JavacDrain"); + drainThread.setDaemon(true); + drainThread.start(); + boolean finished = proc.waitFor(15, TimeUnit.SECONDS); + if (!finished) { + proc.destroyForcibly(); + proc.waitFor(5, TimeUnit.SECONDS); + proc.getInputStream().close(); } - assertTrue("javac timed out", proc.waitFor(15, TimeUnit.SECONDS)); + String output = outputFuture.get(5, TimeUnit.SECONDS); + assertTrue("javac timed out: " + output, finished); assertEquals("javac failed: " + output, 0, proc.exitValue()); } diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java index 7c4c7e6c5..07d9e0451 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java @@ -33,9 +33,14 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.eclipse.jdi.internal.VirtualMachineManagerImpl; +import org.eclipse.jdi.internal.connect.SocketListeningConnectorImpl; import org.junit.Test; +import com.microsoft.java.debug.core.DebugUtility; +import com.microsoft.java.debug.core.LaunchException; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; @@ -329,4 +334,72 @@ public void serializesConcurrentPacketReadsWithoutCorruptingStream() throws Exce } } } + + @Test + public void launchTerminatesRunningDebuggeePromptlyAfterAcceptHandshakeFailure() throws Exception { + VirtualMachineManagerImpl vmManager = new AdvancedVirtualMachineManager(); + AtomicBoolean listenerStopped = new AtomicBoolean(false); + Socket[] heldSocketRef = new Socket[1]; + + AdvancedLaunchingConnector connector = new AdvancedLaunchingConnector(vmManager) { + @Override + SocketListeningConnectorImpl createListeningConnector() { + return new SocketListeningConnectorImpl(vmManager) { + private ServerSocket serverSocket; + + @Override + public String startListening(Map args) throws IOException { + this.serverSocket = new ServerSocket(0, 5, InetAddress.getByName("127.0.0.1")); + return "127.0.0.1:" + this.serverSocket.getLocalPort(); + } + + @Override + public VirtualMachine accept(Map args) throws IOException { + this.serverSocket.setSoTimeout(10_000); + // Hold the debuggee's socket open past stopListening() so the launched JVM stays alive + // with open stdout/stderr pipes unless terminateProcessBounded() kills it. + heldSocketRef[0] = this.serverSocket.accept(); + throw new IOException("Simulated malformed JDWP handshake"); + } + + @Override + public void stopListening(Map args) throws IOException { + listenerStopped.set(true); + if (this.serverSocket != null) { + this.serverSocket.close(); + } + } + }; + } + }; + + Map launchArgs = connector.defaultArguments(); + launchArgs.get(DebugUtility.HOME).setValue(System.getProperty("java.home")); + launchArgs.get(DebugUtility.EXEC).setValue(File.separatorChar == '\\' ? "java.exe" : "java"); + launchArgs.get(DebugUtility.SUSPEND).setValue("true"); + launchArgs.get(DebugUtility.MAIN).setValue("-version"); + + try { + CompletableFuture failureFuture = CompletableFuture.supplyAsync(() -> { + try { + connector.launch(launchArgs); + throw new AssertionError("Expected LaunchException when accept() fails"); + } catch (LaunchException expected) { + return expected; + } catch (Exception unexpected) { + throw new RuntimeException(unexpected); + } + }); + + LaunchException launchEx = failureFuture.get(10, TimeUnit.SECONDS); + assertNotNull(launchEx.getCause()); + assertTrue(listenerStopped.get()); + assertNotNull(launchEx.process()); + assertFalse("Launched process should be terminated on handshake failure", launchEx.process().isAlive()); + } finally { + if (heldSocketRef[0] != null) { + heldSocketRef[0].close(); + } + } + } } From 6e6e436817bb515bff309ad0a0375d64e0b75702 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Mon, 30 Nov 2026 13:09:09 +0800 Subject: [PATCH 6/7] fix: complete launch future only from winning outcome handler Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../plugin/internal/AdvancedLaunchingConnector.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java index d8c80767f..fe157f74a 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/AdvancedLaunchingConnector.java @@ -158,11 +158,14 @@ public VirtualMachine launch(Map connectionArgs) } catch (IllegalConnectorArgumentsException | RuntimeException e) { stopListeningQuietly(listenConnector, args); if (outcomeClaimed.compareAndSet(false, true)) { - terminateProcessBounded(process); - closeStreamQuietly(process.getInputStream()); - closeStreamQuietly(process.getErrorStream()); + try { + terminateProcessBounded(process); + closeStreamQuietly(process.getInputStream()); + closeStreamQuietly(process.getErrorStream()); + } finally { + result.completeExceptionally(e); + } } - result.completeExceptionally(e); } finally { stopListeningQuietly(listenConnector, args); } From d604976b6ad6b62f30e29f44e777b32c36b6ecc6 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Tue, 1 Dec 2026 16:31:01 +0800 Subject: [PATCH 7/7] feat: add JDWP handshake usage telemetry and handshake timeout overrides Record structured `jdwp handshake` usage telemetry (`outcome`, `duration`, `timeoutMs`) inside `LoopbackSocketListeningConnector.performJdwpHandshake` and allow overriding the 5-second DAP and JDWP handshake timeouts via `java.debug.dap.handshakeTimeoutMs` and `java.debug.jdwp.handshakeTimeoutMs` system properties. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../plugin/internal/JavaDebugServer.java | 19 +- .../LoopbackSocketListeningConnector.java | 96 +++++--- .../plugin/internal/JavaDebugServerTest.java | 49 ++++ .../LoopbackSocketListeningConnectorTest.java | 233 ++++++++++++++++++ 4 files changed, 365 insertions(+), 32 deletions(-) diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java index c4ec3c377..1daf299b2 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/JavaDebugServer.java @@ -47,13 +47,14 @@ public class JavaDebugServer implements IDebugServer { public static final String AUTH_HEADER_PREFIX = "JavaDebug-Auth: "; public static final String ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY = "java.debug.allowUnauthenticatedLoopback"; + public static final String HANDSHAKE_TIMEOUT_PROPERTY = "java.debug.dap.handshakeTimeoutMs"; public static final int PROTOCOL_VERSION = 2; + static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000; private static final Logger logger = Logger.getLogger(Configuration.LOGGER_NAME); private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final int AUTH_TOKEN_BYTES = 32; private static final int DEFAULT_ACCEPT_TIMEOUT_MS = 30_000; - private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000; private static final int MAX_AUTH_FRAME_BYTES = 256; private static final int SESSION_BACKLOG = 8; private static final int DEFAULT_MAX_CONCURRENT_LISTENERS = 64; @@ -79,7 +80,7 @@ public class JavaDebugServer implements IDebugServer { private ExecutorService sessionExecutor; private JavaDebugServer() { - this(JdtProviderContextFactory::createProviderContext, DEFAULT_ACCEPT_TIMEOUT_MS, DEFAULT_HANDSHAKE_TIMEOUT_MS); + this(JdtProviderContextFactory::createProviderContext, DEFAULT_ACCEPT_TIMEOUT_MS, 0); } JavaDebugServer(Supplier providerContextFactory, int acceptTimeoutMs, int handshakeTimeoutMs) { @@ -390,7 +391,7 @@ private void handleAuthenticatedCandidate( return; } candidate.setTcpNoDelay(true); - if (!verifyAuthHandshake(candidate, expectedHandshake, handshakeTimeoutMs)) { + if (!verifyAuthHandshake(candidate, expectedHandshake, effectiveHandshakeTimeoutMs())) { logger.warning("Rejected unauthenticated or invalid-token connection to Java Debug Server."); return; } @@ -485,6 +486,18 @@ private void runProtocolSession(Socket connection) { } } + static int resolveHandshakeTimeoutMs() { + Integer configured = Integer.getInteger(HANDSHAKE_TIMEOUT_PROPERTY); + if (configured != null && configured > 0) { + return configured; + } + return DEFAULT_HANDSHAKE_TIMEOUT_MS; + } + + private int effectiveHandshakeTimeoutMs() { + return handshakeTimeoutMs > 0 ? handshakeTimeoutMs : resolveHandshakeTimeoutMs(); + } + static boolean verifyAuthHandshake(Socket candidate, byte[] expectedHandshake, int handshakeTimeoutMs) throws IOException { long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(handshakeTimeoutMs); return verifyAuthHandshake( diff --git a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java index c50b7760b..3efb608fb 100644 --- a/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java +++ b/com.microsoft.java.debug.plugin/src/main/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnector.java @@ -22,6 +22,7 @@ import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -29,6 +30,7 @@ import org.eclipse.jdi.internal.VirtualMachineManagerImpl; import org.eclipse.jdi.internal.connect.SocketListeningConnectorImpl; +import com.microsoft.java.debug.core.UsageDataSession; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; @@ -46,10 +48,11 @@ public class LoopbackSocketListeningConnector extends SocketListeningConnectorIm public static final String ARG_TIMEOUT = "timeout"; public static final String ARG_LOCAL_ADDRESS = "localAddress"; public static final String MAX_JDWP_PACKET_PROPERTY = "java.debug.jdwp.maxPacketBytes"; + public static final String HANDSHAKE_TIMEOUT_PROPERTY = "java.debug.jdwp.handshakeTimeoutMs"; static final int DEFAULT_MAX_JDWP_PACKET_LENGTH = 64 * 1024 * 1024; + static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000; private static final String DEFAULT_LOOPBACK_ADDRESS = "127.0.0.1"; private static final byte[] JDWP_HANDSHAKE = "JDWP-Handshake".getBytes(StandardCharsets.US_ASCII); - private static final int DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000; private static final int MIN_JDWP_PACKET_LENGTH = 11; private final Object socketLock = new Object(); @@ -132,8 +135,7 @@ public VirtualMachine accept(Map connectio } clientSocket.setTcpNoDelay(true); - int handshakeTimeout = timeout > 0 - ? Math.min(timeout, DEFAULT_HANDSHAKE_TIMEOUT_MS) : DEFAULT_HANDSHAKE_TIMEOUT_MS; + int handshakeTimeout = resolveHandshakeTimeoutMs(timeout); performJdwpHandshake(clientSocket, handshakeTimeout); Connection connection = new LoopbackSocketConnection( @@ -224,37 +226,73 @@ private static int parseIntegerArgument( private static void performJdwpHandshake(Socket socket, int timeoutMs) throws IOException { int boundedTimeoutMs = Math.max(1, timeoutMs); - long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(boundedTimeoutMs); - socket.setSoTimeout(boundedTimeoutMs); - InputStream in = socket.getInputStream(); - OutputStream out = socket.getOutputStream(); - // Per the JDWP specification, the debugger side always sends "JDWP-Handshake" - // first (even when acting as the TCP listening server), and the target VM replies. - out.write(JDWP_HANDSHAKE); - out.flush(); - byte[] received = new byte[JDWP_HANDSHAKE.length]; - int offset = 0; + long startNanos = System.nanoTime(); + long deadlineNanos = startNanos + TimeUnit.MILLISECONDS.toNanos(boundedTimeoutMs); + String outcome = "io_error"; try { - while (offset < received.length) { - long remainingNanos = deadlineNanos - System.nanoTime(); - if (remainingNanos <= 0) { - throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); - } - int remainingMs = (int) Math.max(1L, Math.min(Integer.MAX_VALUE, TimeUnit.NANOSECONDS.toMillis(remainingNanos))); - socket.setSoTimeout(remainingMs); - int read = in.read(received, offset, received.length - offset); - if (read < 0) { - throw new IOException("Unexpected EOF during JDWP handshake."); + socket.setSoTimeout(boundedTimeoutMs); + InputStream in = socket.getInputStream(); + OutputStream out = socket.getOutputStream(); + // Per the JDWP specification, the debugger side always sends "JDWP-Handshake" + // first (even when acting as the TCP listening server), and the target VM replies. + out.write(JDWP_HANDSHAKE); + out.flush(); + byte[] received = new byte[JDWP_HANDSHAKE.length]; + int offset = 0; + try { + while (offset < received.length) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0) { + outcome = "timeout"; + throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); + } + int remainingMs = (int) Math.max( + 1L, + Math.min(Integer.MAX_VALUE, TimeUnit.NANOSECONDS.toMillis(remainingNanos))); + socket.setSoTimeout(remainingMs); + int read = in.read(received, offset, received.length - offset); + if (read < 0) { + outcome = "eof"; + throw new IOException("Unexpected EOF during JDWP handshake."); + } + offset += read; } - offset += read; + } catch (SocketTimeoutException e) { + outcome = "timeout"; + throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); + } + if (!Arrays.equals(JDWP_HANDSHAKE, received)) { + outcome = "invalid"; + throw new IOException("Received invalid JDWP handshake."); } - } catch (SocketTimeoutException e) { - throw new TransportTimeoutException("Timed out waiting for JDWP handshake."); + socket.setSoTimeout(0); + outcome = "success"; + } finally { + long durationMs = Math.max(0L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos)); + recordJdwpHandshakeUsage(outcome, durationMs, boundedTimeoutMs); } - if (!Arrays.equals(JDWP_HANDSHAKE, received)) { - throw new IOException("Received invalid JDWP handshake."); + } + + private static void recordJdwpHandshakeUsage(String outcome, long durationMs, int timeoutMs) { + try { + Map data = new HashMap<>(); + data.put("outcome", outcome); + data.put("duration", durationMs); + data.put("timeoutMs", String.valueOf(timeoutMs)); + UsageDataSession.recordInfo("jdwp handshake", data); + } catch (RuntimeException ex) { + // Telemetry must never interfere with JDWP handshake execution. + } + } + + static int resolveHandshakeTimeoutMs(int acceptTimeoutMs) { + Integer configured = Integer.getInteger(HANDSHAKE_TIMEOUT_PROPERTY); + if (configured != null && configured > 0) { + return configured; } - socket.setSoTimeout(0); + return acceptTimeoutMs > 0 + ? Math.min(acceptTimeoutMs, DEFAULT_HANDSHAKE_TIMEOUT_MS) + : DEFAULT_HANDSHAKE_TIMEOUT_MS; } static int resolveMaxJdwpPacketLength() { diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java index 8e5419455..8364d0aef 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/JavaDebugServerTest.java @@ -52,6 +52,7 @@ public void tearDown() { server.stop(); } System.clearProperty(JavaDebugServer.ALLOW_UNAUTHENTICATED_LOOPBACK_PROPERTY); + System.clearProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY); } @Test @@ -280,6 +281,54 @@ public void protocolVersionTwoCommandReturnsAuthenticatedSessionMap() throws Exc } } + @Test + public void resolvesAuthHandshakeTimeoutFromSystemPropertyWithFallback() { + System.clearProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY); + assertEquals(JavaDebugServer.DEFAULT_HANDSHAKE_TIMEOUT_MS, JavaDebugServer.resolveHandshakeTimeoutMs()); + + System.setProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY, "12345"); + assertEquals(12_345, JavaDebugServer.resolveHandshakeTimeoutMs()); + + System.setProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY, "0"); + assertEquals(JavaDebugServer.DEFAULT_HANDSHAKE_TIMEOUT_MS, JavaDebugServer.resolveHandshakeTimeoutMs()); + + System.setProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY, "-100"); + assertEquals(JavaDebugServer.DEFAULT_HANDSHAKE_TIMEOUT_MS, JavaDebugServer.resolveHandshakeTimeoutMs()); + + System.setProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY, "not-a-number"); + assertEquals(JavaDebugServer.DEFAULT_HANDSHAKE_TIMEOUT_MS, JavaDebugServer.resolveHandshakeTimeoutMs()); + } + + @Test + public void appliesAuthHandshakeTimeoutSystemPropertyOverrideWhenUsingDefaultTimeout() throws Exception { + System.setProperty(JavaDebugServer.HANDSHAKE_TIMEOUT_PROPERTY, "200"); + JavaDebugServer dynamicTimeoutServer = new JavaDebugServer( + JdtProviderContextFactory::createProviderContext, 5_000, 0); + try { + Map descriptor = dynamicTimeoutServer.startDebugSession(); + String host = (String) descriptor.get("host"); + int port = ((Number) descriptor.get("port")).intValue(); + String authToken = (String) descriptor.get("authToken"); + + long startNanos = System.nanoTime(); + try (Socket stalledClient = new Socket()) { + stalledClient.connect(new InetSocketAddress(host, port), 1_000); + stalledClient.setSoTimeout(1_500); + int read = stalledClient.getInputStream().read(); + assertEquals(-1, read); + } catch (SocketException ignored) { + // Expected TCP RST on platforms with unread bytes. + } + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue("Expected auth handshake property override near 200ms, took " + elapsedMs + "ms", + elapsedMs < 1_200); + + authenticateAndDisconnect(host, port, authToken); + } finally { + dynamicTimeoutServer.stop(); + } + } + private static void authenticateAndDisconnect(String host, int port, String authToken) throws IOException { try (Socket validClient = new Socket()) { validClient.connect(new InetSocketAddress(host, port), 1_000); diff --git a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java index 07d9e0451..c1b09e1b9 100644 --- a/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java +++ b/com.microsoft.java.debug.plugin/src/test/java/com/microsoft/java/debug/plugin/internal/LoopbackSocketListeningConnectorTest.java @@ -26,7 +26,9 @@ import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; +import java.nio.charset.StandardCharsets; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -34,13 +36,17 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; import org.eclipse.jdi.internal.VirtualMachineManagerImpl; import org.eclipse.jdi.internal.connect.SocketListeningConnectorImpl; import org.junit.Test; +import com.microsoft.java.debug.core.Configuration; import com.microsoft.java.debug.core.DebugUtility; import com.microsoft.java.debug.core.LaunchException; +import com.microsoft.java.debug.core.UsageDataStore; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.IllegalConnectorArgumentsException; @@ -402,4 +408,231 @@ public void stopListening(Map args) throws } } } + + @Test + public void resolvesHandshakeTimeoutFromSystemPropertyWithFallback() { + try { + System.clearProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY); + assertEquals( + LoopbackSocketListeningConnector.DEFAULT_HANDSHAKE_TIMEOUT_MS, + LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(0)); + assertEquals( + LoopbackSocketListeningConnector.DEFAULT_HANDSHAKE_TIMEOUT_MS, + LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(10_000)); + assertEquals(200, LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(200)); + + System.setProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY, "15000"); + assertEquals(15_000, LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(10_000)); + assertEquals(15_000, LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(200)); + + System.setProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY, "0"); + assertEquals( + LoopbackSocketListeningConnector.DEFAULT_HANDSHAKE_TIMEOUT_MS, + LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(10_000)); + + System.setProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY, "-500"); + assertEquals(250, LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(250)); + + System.setProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY, "invalid"); + assertEquals( + LoopbackSocketListeningConnector.DEFAULT_HANDSHAKE_TIMEOUT_MS, + LoopbackSocketListeningConnector.resolveHandshakeTimeoutMs(0)); + } finally { + System.clearProperty(LoopbackSocketListeningConnector.HANDSHAKE_TIMEOUT_PROPERTY); + } + } + + @Test + public void recordsUsageTelemetryForJdwpHandshakeOutcomesAndDistinguishesAcceptTimeout() throws Exception { + Logger usageLogger = Logger.getLogger(Configuration.USAGE_DATA_LOGGER_NAME); + Level previousLevel = usageLogger.getLevel(); + boolean hasUsageHandler = Arrays.stream(usageLogger.getHandlers()) + .anyMatch(UsageDataLogHandler.class::isInstance); + UsageDataLogHandler temporaryHandler = hasUsageHandler ? null : new UsageDataLogHandler(Level.ALL); + if (temporaryHandler != null) { + usageLogger.setLevel(Level.ALL); + usageLogger.addHandler(temporaryHandler); + } + UsageDataStore.getInstance().fetchAll(); + + AdvancedVirtualMachineManager vmManager = new AdvancedVirtualMachineManager(); + LoopbackSocketListeningConnector connector = new LoopbackSocketListeningConnector(vmManager); + try { + // 1. accept() timeout without any client must NOT emit a "jdwp handshake" usage entry. + Map acceptTimeoutArgs = connector.defaultArguments(); + ((Connector.IntegerArgument) acceptTimeoutArgs.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(100); + connector.startListening(acceptTimeoutArgs); + try { + connector.accept(acceptTimeoutArgs); + fail("Expected TransportTimeoutException on idle accept()."); + } catch (TransportTimeoutException expected) { + // expected + } finally { + connector.stopListening(acceptTimeoutArgs); + } + assertTrue("Idle accept() timeout must not record jdwp handshake usage data.", + fetchJdwpHandshakeEntries().isEmpty()); + + // 2. Stalled peer triggers handshake timeout and records outcome="timeout". + Map timeoutArgs = connector.defaultArguments(); + ((Connector.IntegerArgument) timeoutArgs.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(150); + String timeoutAddr = connector.startListening(timeoutArgs); + int timeoutPort = Integer.parseInt(timeoutAddr.substring("127.0.0.1:".length())); + CompletableFuture stalledClient = CompletableFuture.runAsync(() -> { + try (Socket s = new Socket()) { + s.connect(new InetSocketAddress("127.0.0.1", timeoutPort), 1_000); + Thread.sleep(600); + } catch (Exception ignored) { + // Closed when server handshake times out. + } + }); + try { + connector.accept(timeoutArgs); + fail("Expected TransportTimeoutException on stalled JDWP peer."); + } catch (TransportTimeoutException expected) { + // expected + } finally { + connector.stopListening(timeoutArgs); + stalledClient.get(2, TimeUnit.SECONDS); + } + List> timeoutEntries = fetchJdwpHandshakeEntries(); + assertEquals(1, timeoutEntries.size()); + assertEquals("timeout", timeoutEntries.get(0).get("outcome")); + assertEquals("150", timeoutEntries.get(0).get("timeoutMs")); + assertTrue(timeoutEntries.get(0).get("duration") instanceof Number); + assertTrue(((Number) timeoutEntries.get(0).get("duration")).longValue() >= 0L); + + // 3. Invalid handshake payload records outcome="invalid". + Map invalidArgs = connector.defaultArguments(); + ((Connector.IntegerArgument) invalidArgs.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(1_000); + String invalidAddr = connector.startListening(invalidArgs); + int invalidPort = Integer.parseInt(invalidAddr.substring("127.0.0.1:".length())); + CompletableFuture badPeer = CompletableFuture.runAsync(() -> { + try (Socket s = new Socket()) { + s.setSoTimeout(2_000); + s.connect(new InetSocketAddress("127.0.0.1", invalidPort), 1_000); + s.getOutputStream().write("NOT-A-HANDSHAKE".getBytes(StandardCharsets.US_ASCII)); + s.getOutputStream().flush(); + // Keep socket open and drain server bytes until server rejects and closes, + // avoiding a Windows TCP RST on close-with-unread-data. + byte[] sink = new byte[64]; + while (s.getInputStream().read(sink) != -1) { + // drain + } + } catch (Exception ignored) { + // ignore + } + }); + try { + connector.accept(invalidArgs); + fail("Expected IOException for invalid JDWP handshake."); + } catch (IOException expected) { + assertTrue("Unexpected message: " + expected.getMessage(), + expected.getMessage().contains("invalid JDWP handshake")); + } finally { + connector.stopListening(invalidArgs); + badPeer.get(2, TimeUnit.SECONDS); + } + List> invalidEntries = fetchJdwpHandshakeEntries(); + assertEquals(1, invalidEntries.size()); + assertEquals("invalid", invalidEntries.get(0).get("outcome")); + + // 4. Peer closing immediately records outcome="eof". + Map eofArgs = connector.defaultArguments(); + ((Connector.IntegerArgument) eofArgs.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(1_000); + String eofAddr = connector.startListening(eofArgs); + int eofPort = Integer.parseInt(eofAddr.substring("127.0.0.1:".length())); + CompletableFuture eofPeer = CompletableFuture.runAsync(() -> { + try (Socket s = new Socket()) { + s.setSoTimeout(2_000); + s.connect(new InetSocketAddress("127.0.0.1", eofPort), 1_000); + s.shutdownOutput(); + // Drain server handshake bytes until server closes so EOF is not preempted by TCP RST. + byte[] sink = new byte[64]; + while (s.getInputStream().read(sink) != -1) { + // drain + } + } catch (Exception ignored) { + // ignore + } + }); + try { + connector.accept(eofArgs); + fail("Expected IOException for EOF during JDWP handshake."); + } catch (IOException expected) { + assertTrue("Unexpected message: " + expected.getMessage(), + expected.getMessage().contains("EOF")); + } finally { + connector.stopListening(eofArgs); + eofPeer.get(2, TimeUnit.SECONDS); + } + List> eofEntries = fetchJdwpHandshakeEntries(); + assertEquals(1, eofEntries.size()); + assertEquals("eof", eofEntries.get(0).get("outcome")); + + // 5. Real debuggee JVM records outcome="success" with non-negative duration. + Map okArgs = connector.defaultArguments(); + ((Connector.IntegerArgument) okArgs.get(LoopbackSocketListeningConnector.ARG_TIMEOUT)).setValue(10_000); + String okAddr = connector.startListening(okArgs); + Process debuggee = null; + VirtualMachine vm = null; + try { + CompletableFuture vmFuture = CompletableFuture.supplyAsync(() -> { + try { + return connector.accept(okArgs); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + }); + String javaBin = Paths.get(System.getProperty("java.home"), "bin", + File.separatorChar == '\\' ? "java.exe" : "java").toString(); + ProcessBuilder pb = new ProcessBuilder( + javaBin, + "-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=" + okAddr, + "-version"); + pb.redirectErrorStream(true); + debuggee = pb.start(); + vm = vmFuture.get(10, TimeUnit.SECONDS); + connector.stopListening(okArgs); + vm.resume(); + assertTrue(debuggee.waitFor(10, TimeUnit.SECONDS)); + } finally { + connector.stopListening(okArgs); + if (vm != null) { + try { + vm.dispose(); + } catch (Exception ignore) { + // already exited + } + } + if (debuggee != null && debuggee.isAlive()) { + debuggee.destroyForcibly(); + } + } + List> okEntries = fetchJdwpHandshakeEntries(); + assertEquals(1, okEntries.size()); + assertEquals("success", okEntries.get(0).get("outcome")); + assertTrue(okEntries.get(0).get("duration") instanceof Number); + assertTrue(((Number) okEntries.get(0).get("duration")).longValue() >= 0L); + } finally { + if (temporaryHandler != null) { + usageLogger.removeHandler(temporaryHandler); + usageLogger.setLevel(previousLevel); + } + UsageDataStore.getInstance().fetchAll(); + } + } + + private static List> fetchJdwpHandshakeEntries() { + List> matches = new ArrayList<>(); + for (Object item : UsageDataStore.getInstance().fetchAll()) { + if (item instanceof Map) { + Map entry = (Map) item; + if ("jdwp handshake".equals(entry.get("description"))) { + matches.add(entry); + } + } + } + return matches; + } }