anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: tootallnate/java-websocket
Issue: Bad rsv 4 on android

Hello, our team using this library for connecting websocket server on Android platform,
sometimes,  there are 'bad rsv 4' errors occurred. Seems same problem with #430.

```
04-27 14:26:09.960 I/System.out( 1564): D/WebsocketChannel: 000000	48 54 54 50 2f 31 2e 31 20 31 30 31 20 53 77 69 74 63  HTTP/1.1 101 Switc
04-27 14:26:09.960 D/WebSocketChannel( 1564): onError:org.java_websocket.exceptions.InvalidFrameException: bad rsv 4
```

The debug log above shows the **WebSocketImpl** treat the handshake response as normal websocket frame and decode it, then throw an InvalidFrameException.

Our client tries to reconnect to server endlessly when it is in condition of unstable network environment. 
So is it possible that method **org.java_websocket.WebSocketImpl#decode**  was invoked after **WebSocketClient** closed in some extreme cases?

Changed files:
src/main/java/org/java_websocket/WebSocketImpl.java

diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java
index f3c3142..560651d 100644
--- a/src/main/java/org/java_websocket/WebSocketImpl.java
+++ b/src/main/java/org/java_websocket/WebSocketImpl.java
@@ -151,7 +151,9 @@ public class WebSocketImpl implements WebSocket {
 			System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
 
 		if( readystate != READYSTATE.NOT_YET_CONNECTED ) {
-			decodeFrames( socketBuffer );
+			if ( readystate == READYSTATE.OPEN ) {
+				decodeFrames( socketBuffer );
+			}
 		} else {
 			if( decodeHandshake( socketBuffer ) ) {
 				assert ( tmpHandshakeBytes.hasRemaining() != socketBuffer.hasRemaining() || !socketBuffer.hasRemaining() ); // the buffers will never have remaining bytes at the same time
Repository: tootallnate/java-websocket
Issue: Endless loop in client upon close() when using wss

First, thanks so much for creating the library, it's really useful. I am using this via gottox/socket-io (client) and have run into this nasty problem of an endless loop in SSLSocketChannel2.java when closing a connection (maybe after the other side closed first). A couple of these failures is all it takes to pin the CPU at 100% as the threads that execute these loops pile up.

I doubt this is the correct fix, but what I did was change the following in SSLSocketChannel2.readRemaining(), which seems to work.

``` java
        if( inCrypt.hasRemaining() ) {
            unwrap();
            int amount = transfereTo( inData, dst );
>>>         if (engineStatus == SSLEngineResult.Status.CLOSED) {
>>>             return -1;
>>>         }
            if( amount > 0 )
                return amount;
        }
```

EDIT by @Davidisudadi: formatted code


Changed files:
src/main/java/org/java_websocket/SSLSocketChannel2.java

diff --git a/src/main/java/org/java_websocket/SSLSocketChannel2.java b/src/main/java/org/java_websocket/SSLSocketChannel2.java
index ba8d8f8..e540612 100644
--- a/src/main/java/org/java_websocket/SSLSocketChannel2.java
+++ b/src/main/java/org/java_websocket/SSLSocketChannel2.java
@@ -5,6 +5,13 @@
  */
 package org.java_websocket;
 
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLEngineResult.Status;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSession;
+import java.io.EOFException;
 import java.io.IOException;
 import java.net.Socket;
 import java.net.SocketAddress;
@@ -20,13 +27,6 @@ import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
 
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-import javax.net.ssl.SSLEngineResult.Status;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
 /**
  * Implements the relevant portions of the SocketChannel interface with the SSLEngine wrapper.
  */
@@ -213,6 +213,9 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel {
 		//	createBuffers( sslEngine.getSession() );
 		//}
 		int num = socketChannel.write( wrap( src ) );
+        if (writeEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) {
+            throw new EOFException("Connection is closed");
+        }
 		return num;
 
 	}
@@ -286,6 +289,9 @@ public class SSLSocketChannel2 implements ByteChannel, WrappedByteChannel {
 		if( inCrypt.hasRemaining() ) {
 			unwrap();
 			int amount = transfereTo( inData, dst );
+            if (readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED) {
+                return -1;
+            }
 			if( amount > 0 )
 				return amount;
 		}
Repository: tootallnate/java-websocket
Issue: Websocket server returning 401; can't handle on client side

I have a websocket server that returns 401 on the http handshake
I can't figure out how to get that information on the websocket client

Two things I can't figure out:
1. Where can I get the http status code returned form the server (401 in this case)
   onClose is called but with irrelevant code (-1) which I saw in your code that it means "never connected"
2. onError is called but for totally different reason. I get onError ssl == null
   why would the client library continue to try to decode the handshake, or something like that, when the socket wasn't upgraded (101)? why not just stop there? The ssl error is irrelevant here and is fired do to the fact that the server did not upgrade the socket

What I did to get the status code from the server was to subclass my own Draft, implement acceptHandshakeAsClient and copyInsance; this gave me access to the handshake response
When I see that the status code is 401 I return NOT_MATCHED
This is the only place I saw I can get the status code, but it makes me do ugly things like saving the status code in a variable to be used by onClose and onError which are then called (but with irrelevant data - code == -1 and error exception is ssl == null)

Thanks


Changed files:
src/main/java/org/java_websocket/WebSocketImpl.java

diff --git a/src/main/java/org/java_websocket/WebSocketImpl.java b/src/main/java/org/java_websocket/WebSocketImpl.java
index 74aca19..7cc3330 100644
--- a/src/main/java/org/java_websocket/WebSocketImpl.java
+++ b/src/main/java/org/java_websocket/WebSocketImpl.java
@@ -447,11 +447,11 @@ public class WebSocketImpl implements WebSocket {
 			} else if( code == CloseFrame.FLASHPOLICY ) {
 				assert ( remote );
 				flushAndClose( CloseFrame.FLASHPOLICY, message, true );
+			} else if( code == CloseFrame.PROTOCOL_ERROR ) { // this endpoint found a PROTOCOL_ERROR
+				flushAndClose( code, message, remote );
 			} else {
 				flushAndClose( CloseFrame.NEVER_CONNECTED, message, false );
 			}
-			if( code == CloseFrame.PROTOCOL_ERROR )// this endpoint found a PROTOCOL_ERROR
-				flushAndClose( code, message, remote );
 			readystate = READYSTATE.CLOSING;
 			tmpHandshakeBytes = null;
 			return;
Repository: tootallnate/java-websocket
Issue: Draft_6455 flagged by Veracode CWE-331 replace Random with SecureRandom

Our veracode scan flagged usage of `Random` in Draft_6455.java as a vulnerability.

https://cwe.mitre.org/data/definitions/331.html

According to Websocket Protocol:

For example, each masking could be drawn from a cryptographically strong random number generator. If the same key is used or a decipherable pattern exists for how the next key is chosen, the attacker can send a message that, when masked, could appear to be an HTTP request (by taking the message the attacker wishes to see on the wire and masking it with the next masking key to be used, the masking key will effectively unmask the data when the client applies it).

According to this specification the library should be using SecureRandom to prevent brute force attacks.

**Environment(please complete the following information):**
 - Version used: 1.5.1
 - Java version: 1.8
 - Operating System and version: Android
 - Endpoint Name and version:
 - Link to your project:

**Additional context**
Add any other context about the problem here.


Changed files:
src/main/java/org/java_websocket/drafts/Draft_6455.java

diff --git a/src/main/java/org/java_websocket/drafts/Draft_6455.java b/src/main/java/org/java_websocket/drafts/Draft_6455.java
index 06c964d..68feb61 100644
--- a/src/main/java/org/java_websocket/drafts/Draft_6455.java
+++ b/src/main/java/org/java_websocket/drafts/Draft_6455.java
@@ -29,6 +29,7 @@ import java.math.BigInteger;
 import java.nio.ByteBuffer;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Calendar;
@@ -36,7 +37,6 @@ import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
-import java.util.Random;
 import java.util.TimeZone;
 import org.java_websocket.WebSocketImpl;
 import org.java_websocket.enums.CloseHandshakeType;
@@ -150,7 +150,7 @@ public class Draft_6455 extends Draft {
   /**
    * Attribute for the reusable random instance
    */
-  private final Random reuseableRandom = new Random();
+  private final SecureRandom reuseableRandom = new SecureRandom();
 
   /**
    * Attribute for the maximum allowed size of a frame
Repository: tootallnate/java-websocket
Issue: Crash on Android due to missing method `setEndpointIdentificationAlgorithm` on 1.5.0.

Websocket library 1.5.0
The same code was not crashing on 1.4.1

This is the entire stack trace. I got it through Crashlytics so I cannot describe steps that led to it.

```
Fatal Exception: java.lang.NoSuchMethodError: No virtual method setEndpointIdentificationAlgorithm(Ljava/lang/String;)V in class Ljavax/net/ssl/SSLParameters; or its super classes (declaration of 'javax.net.ssl.SSLParameters' appears in /system/framework/core-libart.jar)
       at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:476)
       at java.lang.Thread.run(Thread.java:831)
```

Android 5.0.1 (API 21).
Brand: HUAWEI
Model: P8 Lite


Changed files:
src/test/java/org/java_websocket/issues/Issue997Test.java, src/main/java/org/java_websocket/client/WebSocketClient.java

diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java
index 0bbcfe5..4d735de 100644
--- a/src/main/java/org/java_websocket/client/WebSocketClient.java
+++ b/src/main/java/org/java_websocket/client/WebSocketClient.java
@@ -472,8 +472,6 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
 			if (socket instanceof SSLSocket) {
 				SSLSocket sslSocket = (SSLSocket)socket;
 				SSLParameters sslParameters = sslSocket.getSSLParameters();
-				// Make sure we perform hostname validation
-				sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
 				onSetSSLParameters(sslParameters);
 				sslSocket.setSSLParameters(sslParameters);
 			}
@@ -520,10 +518,14 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
 
 	/**
 	 * Apply specific SSLParameters
+	 * If you override this method make sure to always call super.onSetSSLParameters() to ensure the hostname validation is active
 	 *
 	 * @param sslParameters the SSLParameters which will be used for the SSLSocket
 	 */
 	protected void onSetSSLParameters(SSLParameters sslParameters) {
+		// If you run into problem on Android (NoSuchMethodException), check out the wiki https://github.com/TooTallNate/Java-WebSocket/wiki/No-such-method-error-setEndpointIdentificationAlgorithm
+		// Perform hostname validation
+		sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
 	}
 
 	/**
diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java
index 0fc81bc..493dd69 100644
--- a/src/test/java/org/java_websocket/issues/Issue997Test.java
+++ b/src/test/java/org/java_websocket/issues/Issue997Test.java
@@ -143,6 +143,8 @@ public class Issue997Test {
 
         @Override
         protected void onSetSSLParameters(SSLParameters sslParameters) {
+            // Always call super to ensure hostname validation is active by default
+            super.onSetSSLParameters(sslParameters);
             if (endpointIdentificationAlgorithm != null) {
                 sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
             }
Repository: tootallnate/java-websocket
Issue: Exclude default port from wss host

<!--- Provide a general summary of the issue in the Title above -->
I'm working with a server balanced by a proxy that redirect my request to the targeted server depends on the URL I requested.

One of these servers has a secure Websocket (I mean wss) and it works on the default port (443).

In your client (class WebSocketClient.java) you avoid to include the port in the host by: `port != WebSocket.DEFAULT_PORT ? ":" + port : ""`, but this works only for ws default port and not for wss that now is including ":443" at the end of the host. In my app, for example I want to connect to "wss://app.example.com" and without this check it's trying to connect to "wss://app.example.com:443" and the proxy cannot resolve this host.

## Possible Solution
Adding a check for DEFAULT_WSS_PORT as well as the check for DEFAULT_PORT it solves the problem.
```java
String host = uri.getHost() + ( 
			(port != WebSocket.DEFAULT_PORT && port != WbSocket.DEFAULT_WSS_PORT)
			? ":" + port : "" );
```

Changed files:
src/main/java/org/java_websocket/client/WebSocketClient.java

diff --git a/src/main/java/org/java_websocket/client/WebSocketClient.java b/src/main/java/org/java_websocket/client/WebSocketClient.java
index da30d5b..00e40fd 100644
--- a/src/main/java/org/java_websocket/client/WebSocketClient.java
+++ b/src/main/java/org/java_websocket/client/WebSocketClient.java
@@ -434,7 +434,10 @@ public abstract class WebSocketClient extends AbstractWebSocket implements Runna
 		if( part2 != null )
 			path += '?' + part2;
 		int port = getPort();
-		String host = uri.getHost() + ( port != WebSocket.DEFAULT_PORT ? ":" + port : "" );
+		String host = uri.getHost() + ( 
+			(port != WebSocket.DEFAULT_PORT && port != WebSocket.DEFAULT_WSS_PORT)
+			? ":" + port 
+			: "" );
 
 		HandshakeImpl1Client handshake = new HandshakeImpl1Client();
 		handshake.setResourceDescriptor( path );
Repository: tootallnate/java-websocket
Issue: WebSocketServer freezes in stop() method

Hello,

first I would like to thank you for creating a great and useful library.

I'am using it in Android application to communicate with website. 
When I try to stop the server, the application sometimes stops responding.
The main thread is indefinitely waiting in "WebSocketServer.stop()" method in "selectorThread.join()" line, because the "selectorThread" never ends. This happens because "selectorThread" is waiting in "run()" method in "selector.select()" line.

Do you know what could be the cause of this behavior?

Thank you all in advance for any help you can provide.

Regards,
Vito


Changed files:
src/main/java/org/java_websocket/server/WebSocketServer.java

diff --git a/src/main/java/org/java_websocket/server/WebSocketServer.java b/src/main/java/org/java_websocket/server/WebSocketServer.java
index 5fc6a39..12cea2f 100644
--- a/src/main/java/org/java_websocket/server/WebSocketServer.java
+++ b/src/main/java/org/java_websocket/server/WebSocketServer.java
@@ -216,16 +216,10 @@ public abstract class WebSocketServer extends WebSocketAdapter implements Runnab
 		}
 
 		synchronized ( this ) {
-			if( selectorthread != null ) {
-				if( Thread.currentThread() != selectorthread ) {
-
-				}
-				if( selectorthread != Thread.currentThread() ) {
-					if( socketsToClose.size() > 0 )
-						selectorthread.join( timeout );// isclosed will tell the selectorthread to go down after the last connection was closed
-					selectorthread.interrupt();// in case the selectorthread did not terminate in time we send the interrupt
-					selectorthread.join();
-				}
+			if( selectorthread != null && selectorthread != Thread.currentThread() ) {
+				selector.wakeup();
+				selectorthread.interrupt();
+				selectorthread.join( timeout );
 			}
 		}
 	}