{"record":{"id":"38b075d41db3d973","repo":"TooTallNate/Java-WebSocket","slug":"buffer-underflow-occurred-after-a-wrap-i-don-t-th","errorCode":null,"errorMessage":"Buffer underflow occurred after a wrap. I don't think we should ever get here.","messagePattern":"Buffer underflow occurred after a wrap\\. I don't think we should ever get here\\.","errorType":"exception","errorClass":"SSLException","httpStatus":null,"severity":"error","filePath":"src/main/java/org/java_websocket/SSLSocketChannel.java","lineNumber":226,"sourceCode":"  public synchronized int write(ByteBuffer output) throws IOException {\n    int num = 0;\n    while (output.hasRemaining()) {\n      // The loop has a meaning for (outgoing) messages larger than 16KB.\n      // Every wrap call will remove 16KB from the original message and send it to the remote peer.\n      myNetData.clear();\n      SSLEngineResult result = engine.wrap(output, myNetData);\n      switch (result.getStatus()) {\n        case OK:\n          myNetData.flip();\n          while (myNetData.hasRemaining()) {\n            num += socketChannel.write(myNetData);\n          }\n          break;\n        case BUFFER_OVERFLOW:\n          myNetData = enlargePacketBuffer(myNetData);\n          break;\n        case BUFFER_UNDERFLOW:\n          throw new SSLException(\n              \"Buffer underflow occurred after a wrap. I don't think we should ever get here.\");\n        case CLOSED:\n          closeConnection();\n          return 0;\n        default:\n          throw new IllegalStateException(\"Invalid SSL status: \" + result.getStatus());\n      }\n    }\n    return num;\n  }\n\n  /**\n   * Implements the handshake protocol between two peers, required for the establishment of the\n   * SSL/TLS connection. During the handshake, encryption configuration information - such as the\n   * list of available cipher suites - will be exchanged and if the handshake is successful will\n   * lead to an established SSL/TLS session.\n   * <p>\n   * <p/>","sourceCodeStart":208,"sourceCodeEnd":244,"githubUrl":"https://github.com/TooTallNate/Java-WebSocket/blob/afeacbf8c0f6f6a761c9d9daed8c813dd3b8ed7d/src/main/java/org/java_websocket/SSLSocketChannel.java#L208-L244","documentation":"During SSLSocketChannel.write(), engine.wrap() returned BUFFER_UNDERFLOW. BUFFER_UNDERFLOW from wrap() is contradictory — wrap consumes application data and produces network data, so it should never report 'not enough inbound data'. The library treats it as an unrecoverable TLS-layer anomaly and throws SSLException.","triggerScenarios":"engine.wrap(myAppData, myNetData) inside write() returns SSLEngineResult.Status.BUFFER_UNDERFLOW — essentially only possible with a corrupted/misconfigured SSLEngine or wrong buffers handed to wrap().","commonSituations":"Rare; seen with custom SSLEngine implementations, JDK TLS bugs, or code that accidentally swapped the app/net buffers passed to wrap().","solutions":["Verify you are not swapping arguments: wrap consumes myAppData and writes to myNetData","Catch SSLException, close the connection and reconnect/rehandshake","Upgrade the JDK/library — this usually indicates an engine-level bug"],"exampleFix":"// before\nchannel.writeAndHandshake(data); // throws SSLException on underflow\n// after\ntry {\n  channel.writeAndHandshake(data);\n} catch (SSLException e) {\n  channel.closeConnection();\n  reconnect();\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { channel.write(data); } catch (SSLException e) { log.error(\"TLS write failed: {}\", e.getMessage()); channel.closeConnection(); scheduleReconnect(); }","preventionTips":["Always pass (appData, netData) in that order to wrap()","Treat SSLException during write as fatal for the connection; reconnect with a fresh handshake"],"tags":["websocket","ssl","ssl-exception","buffer"],"backgroundTag":"internal-invariant-violation","analyzedSha":"afeacbf8c0f6f6a761c9d9daed8c813dd3b8ed7d","analyzedAt":"2026-09-09T14:39:47.546Z","contentChangedAt":"2026-09-09T14:39:47.546Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}