output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("hello.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
try (ZipInputStream zip = new ZipInputStream(file.open())) {
ZipEntry entry = zip.getNextEntry();
while (entry.isDirectory()) {
entry = zip.getNextEntry();
}
assertNotNull(entry);
assertEquals(basePath + "hello.txt", entry.getName());
try (Scanner scanner = new Scanner(zip)) {
assertTrue(scanner.hasNextLine());
assertEquals("Hello World!", scanner.nextLine());
assertNull("There should be no more entries", zip.getNextEntry());
}
}
}
|
#vulnerable code
private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("hello.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
ZipInputStream zip = new ZipInputStream(file.open());
ZipEntry entry = zip.getNextEntry();
while (entry.isDirectory()) {
entry = zip.getNextEntry();
}
assertNotNull(entry);
assertEquals(basePath + "hello.txt", entry.getName());
try(Scanner scanner = new Scanner(zip)){
assertTrue(scanner.hasNextLine());
assertEquals("Hello World!", scanner.nextLine());
assertNull("There should be no more entries", zip.getNextEntry());
zip.close();
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void calcRemainingQuota(Long quota, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (Objects.nonNull(quota)) {
String quotaKey = key + QUOTA_SUFFIX;
long usage = requestTime != null ? requestTime : 0L;
Long remaining = calcRemaining(quota, refreshInterval, usage, quotaKey, rate);
rate.setRemainingQuota(remaining);
}
}
|
#vulnerable code
@Override
protected void calcRemainingQuota(Long quota, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (quota != null) {
String quotaKey = key + QUOTA_SUFFIX;
handleExpiration(quotaKey, refreshInterval, rate);
long usage = requestTime != null ? requestTime : 0L;
Long current = 0L;
try {
current = this.redisTemplate.boundValueOps(quotaKey).increment(usage);
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + quotaKey + ", will return quota limit";
rateLimiterErrorHandler.handleError(msg, e);
}
rate.setRemainingQuota(Math.max(-1, quota - current));
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Long getRequestStartTime() {
final RequestContext ctx = RequestContext.getCurrentContext();
final HttpServletRequest request = ctx.getRequest();
return (Long) request.getAttribute(REQUEST_START_TIME);
}
|
#vulnerable code
private Long getRequestStartTime() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return (Long) requestAttributes.getAttribute(REQUEST_START_TIME, SCOPE_REQUEST);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Long calcRemaining(Long limit, Long refreshInterval, long usage,
String key, Rate rate) {
rate.setReset(SECONDS.toMillis(refreshInterval));
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns the value of key after the increment, check for the first increment, and the expiration time is set
if (current != null && current.equals(usage)) {
handleExpiration(key, refreshInterval);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return the current value";
rateLimiterErrorHandler.handleError(msg, e);
}
return Math.max(-1, limit - (current != null ? current : 0L));
}
|
#vulnerable code
private Long calcRemaining(Long limit, Long refreshInterval, long usage,
String key, Rate rate) {
rate.setReset(SECONDS.toMillis(refreshInterval));
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns the value of key after the increment, check for the first increment, and the expiration time is set
if (current != null && current.equals(usage)) {
handleExpiration(key, refreshInterval);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return the current value";
rateLimiterErrorHandler.handleError(msg, e);
}
return Math.max(-1, limit - current);
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void calcRemainingLimit(Long limit, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (Objects.nonNull(limit)) {
long usage = requestTime == null ? 1L : 0L;
Long remaining = calcRemaining(limit, refreshInterval, usage, key, rate);
rate.setRemaining(remaining);
}
}
|
#vulnerable code
@Override
protected void calcRemainingLimit(Long limit, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (limit != null) {
long usage = requestTime == null ? 1L : 0L;
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns 1 when the key is incremented for the first time, and the expiration time is set
if (current != null && current.equals(1L)) {
this.redisTemplate.expire(key, refreshInterval, SECONDS);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return limit";
rateLimiterErrorHandler.handleError(msg, e);
}
rate.setRemaining(Math.max(-1, limit - current));
}
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
LatticeNode getOOVNode(String text, OOV oov, int length) {
LatticeNode node = createNode();
node.setParameter(oov.leftId, oov.rightId, oov.cost);
WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, "");
node.setWordInfo(info);
return node;
}
|
#vulnerable code
void readCharacterProperty(String charDef) throws IOException {
try (InputStream input = (charDef == null) ? openFromJar("char.def") : new FileInputStream(charDef);
InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8);
LineNumberReader reader = new LineNumberReader(isReader)) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
if (line.matches("\\s*") || line.startsWith("#")) {
continue;
}
String[] cols = line.split("\\s+");
if (cols.length < 2) {
throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber());
}
if (cols[0].startsWith("0x")) {
continue;
}
CategoryType type = CategoryType.valueOf(cols[0]);
if (type == null) {
throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber());
}
if (categories.containsKey(type)) {
throw new IllegalArgumentException(
cols[0] + " is already defined at line " + reader.getLineNumber());
}
CategoryInfo info = new CategoryInfo();
info.type = type;
info.isInvoke = (!cols[1].equals("0"));
info.isGroup = (!cols[2].equals("0"));
info.length = Integer.parseInt(cols[3]);
categories.put(type, info);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
DictionaryBuilder() {
buffer = ByteBuffer.allocate(BUFFER_SIZE);
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
|
#vulnerable code
void buildLexicon(String filename, FileInputStream lexiconInput) throws IOException {
int lineno = -1;
try (InputStreamReader isr = new InputStreamReader(lexiconInput);
LineNumberReader reader = new LineNumberReader(isr)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lineno = reader.getLineNumber();
WordEntry entry = parseLine(line);
if (entry.headword != null) {
addToTrie(entry.headword, wordInfos.size());
}
params.add(entry.parameters);
wordInfos.add(entry.wordInfo);
}
} catch (Exception e) {
if (lineno > 0) {
System.err.println("Error: " + e.getMessage() + " at line " + lineno + " in " + filename);
}
throw e;
}
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
try (FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2])) {
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2]);
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
LatticeNode getOOVNode(String text, OOV oov, int length) {
LatticeNode node = createNode();
node.setParameter(oov.leftId, oov.rightId, oov.cost);
WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, "");
node.setWordInfo(info);
return node;
}
|
#vulnerable code
void readOOV(String unkDef, Grammar grammar) throws IOException {
try (InputStream input = (unkDef == null) ? openFromJar("unk.def") : new FileInputStream(unkDef);
InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8);
LineNumberReader reader = new LineNumberReader(isReader)) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
String[] cols = line.split(",");
if (cols.length < 10) {
throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber());
}
CategoryType type = CategoryType.valueOf(cols[0]);
if (type == null) {
throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber());
}
if (!categories.containsKey(type)) {
throw new IllegalArgumentException(cols[0] + " is undefined at line " + reader.getLineNumber());
}
OOV oov = new OOV();
oov.leftId = Short.parseShort(cols[1]);
oov.rightId = Short.parseShort(cols[2]);
oov.cost = Short.parseShort(cols[3]);
List<String> pos = Arrays.asList(cols[4], cols[5], cols[6], cols[7], cols[8], cols[9]);
oov.posId = grammar.getPartOfSpeechId(pos);
if (!oovList.containsKey(type)) {
oovList.put(type, new ArrayList<OOV>());
}
oovList.get(type).add(oov);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
try (FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2])) {
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2]);
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void handleRead() throws IOException {
if( !socketBuffer.hasRemaining() ) {
socketBuffer.rewind();
socketBuffer.limit( socketBuffer.capacity() );
if( sockchannel.read( socketBuffer ) == -1 ) {
if( draft == null ) {
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) {
closeConnection( CloseFrame.NORMAL, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) {
if( role == Role.SERVER )
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
else
closeConnection( CloseFrame.NORMAL, true );
} else {
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
}
}
socketBuffer.flip();
}
if( socketBuffer.hasRemaining() ) {
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( !handshakeComplete ) {
if( draft == null ) {
HandshakeState isflashedgecase = isFlashEdgeCase( socketBuffer );
if( isflashedgecase == HandshakeState.MATCHED ) {
channelWriteDirect( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( wsl.getFlashPolicy( this ) ) ) );
closeDirect( CloseFrame.FLASHPOLICY, "" );
return;
} else if( isflashedgecase == HandshakeState.MATCHING ) {
return;
}
}
HandshakeState handshakestate = null;
socketBuffer.mark();
try {
if( role == Role.SERVER ) {
if( draft == null ) {
for( Draft d : known_drafts ) {
try {
d.setParseMode( role );
socketBuffer.reset();
Handshakedata tmphandshake = d.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = d.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
ServerHandshakeBuilder response;
try {
response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return;
}
writeDirect( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) );
draft = d;
open( handshake );
handleRead();
return;
} else if( handshakestate == HandshakeState.MATCHING ) {
if( draft != null ) {
throw new InvalidHandshakeException( "multible drafts matching" );
}
draft = d;
}
} catch ( InvalidHandshakeException e ) {
// go on with an other draft
} catch ( IncompleteHandshakeException e ) {
if( socketBuffer.limit() == socketBuffer.capacity() ) {
close( CloseFrame.TOOBIG, "handshake is to big" );
}
// read more bytes for the handshake
socketBuffer.position( socketBuffer.limit() );
socketBuffer.limit( socketBuffer.capacity() );
return;
}
}
if( draft == null ) {
close( CloseFrame.PROTOCOL_ERROR, "no draft matches" );
}
return;
} else {
// special case for multiple step handshakes
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
open( handshake );
handleRead();
} else if( handshakestate != HandshakeState.MATCHING ) {
close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" );
}
return;
}
} else if( role == Role.CLIENT ) {
draft.setParseMode( role );
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ServerHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "Wwrong http function", false );
return;
}
ServerHandshake handshake = (ServerHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake );
if( handshakestate == HandshakeState.MATCHED ) {
try {
wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return;
}
open( handshake );
handleRead();
} else if( handshakestate == HandshakeState.MATCHING ) {
return;
} else {
close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" );
}
}
} catch ( InvalidHandshakeException e ) {
close( e );
}
} else {
// Receiving frames
List<Framedata> frames;
try {
frames = draft.translateFrame( socketBuffer );
for( Framedata f : frames ) {
if( DEBUG )
System.out.println( "matched frame: " + f );
Opcode curop = f.getOpcode();
if( curop == Opcode.CLOSING ) {
int code = CloseFrame.NOCODE;
String reason = "";
if( f instanceof CloseFrame ) {
CloseFrame cf = (CloseFrame) f;
code = cf.getCloseCode();
reason = cf.getMessage();
}
if( closeHandshakeSent ) {
// complete the close handshake by disconnecting
closeConnection( code, reason, true );
} else {
// echo close handshake
if( draft.getCloseHandshakeType() == CloseHandshakeType.TWOWAY )
close( code, reason );
closeConnection( code, reason, false );
}
continue;
} else if( curop == Opcode.PING ) {
wsl.onWebsocketPing( this, f );
continue;
} else if( curop == Opcode.PONG ) {
wsl.onWebsocketPong( this, f );
continue;
} else {
// process non control frames
if( currentframe == null ) {
if( f.getOpcode() == Opcode.CONTINIOUS ) {
throw new InvalidFrameException( "unexpected continious frame" );
} else if( f.isFin() ) {
// receive normal onframe message
deliverMessage( f );
} else {
// remember the frame whose payload is about to be continued
currentframe = f;
}
} else if( f.getOpcode() == Opcode.CONTINIOUS ) {
currentframe.append( f );
if( f.isFin() ) {
deliverMessage( currentframe );
currentframe = null;
}
} else {
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" );
}
}
}
} catch ( InvalidDataException e1 ) {
wsl.onWebsocketError( this, e1 );
close( e1 );
return;
}
}
}
}
|
#vulnerable code
long bufferedDataAmount() {
return bufferQueueTotalAmount;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void decode( ByteBuffer socketBuffer ) {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( readystate == READYSTATE.OPEN ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
}
|
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stop() throws IOException {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
thread.interrupt();
this.server.close();
}
|
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 52
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void close() {
if( thread != null ) {
conn.close( CloseFrame.NORMAL );
/*closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}*/
}
}
|
#vulnerable code
public void close() {
if( thread != null ) {
thread.interrupt();
closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
thread = null;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 51
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void close() {
if( thread != null ) {
conn.close( CloseFrame.NORMAL );
/*closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}*/
}
}
|
#vulnerable code
public void close() {
if( thread != null ) {
thread.interrupt();
closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void flush() throws IOException {
ByteBuffer buffer = this.bufferQueue.peek();
while ( buffer != null ) {
sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
continue;
} else {
// subtract this amount of data from the total queued (synchronized over this object)
bufferQueueTotalAmount.addAndGet(-buffer.limit());
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
}
|
#vulnerable code
public void flush() throws IOException {
ByteBuffer buffer = this.bufferQueue.peek();
while ( buffer != null ) {
sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
continue;
} else {
synchronized ( bufferQueueTotalAmount ) {
// subtract this amount of data from the total queued (synchronized over this object)
bufferQueueTotalAmount -= buffer.limit();
}
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
}
|
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 52
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int getConnectionLostTimeout() {
synchronized (syncConnectionLost) {
return connectionLostTimeout;
}
}
|
#vulnerable code
public int getConnectionLostTimeout() {
return connectionLostTimeout;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stop() throws IOException , InterruptedException {
stop( 0 );
}
|
#vulnerable code
public void stop() throws IOException , InterruptedException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
selectorthread.join();
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
this.server.close();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 34
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void start() {
if( selectorthread != null )
throw new IllegalStateException( "Already started" );
new Thread( this ).start();
}
|
#vulnerable code
public void start() {
if( thread != null )
throw new IllegalStateException( "Already started" );
new Thread( this ).start();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
}
|
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 78
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 44
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
|
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
}
|
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
this.server.close();
}
|
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 34
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
}
|
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
}
|
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return;
}
}
selectorthread.setName( "WebsocketSelector" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocket.RCVBUF );
socket.bind( address );
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocketImpl conn = null;
try {
selector.select();
registerWrite();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
// Object o = key.attachment();
continue;
}
if( key.isAcceptable() ) {
if( !onConnect( key ) ) {
key.cancel();
continue;
}
SocketChannel channel = server.accept();
channel.configureBlocking( false );
WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() );
w.key = channel.register( selector, SelectionKey.OP_READ, w );
w.channel = wsf.wrapChannel( w.key );
i.remove();
allocateBuffers( w );
continue;
}
if( key.isReadable() ) {
conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.read( buf, conn, (ByteChannel) conn.channel ) ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.channel instanceof WrappedByteChannel ) {
if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) {
iqueue.add( conn );
}
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
} catch ( RuntimeException e ) {
pushBuffer( buf );
throw e;
}
}
if( key.isWritable() ) {
conn = (WebSocketImpl) key.attachment();
if( SocketChannelIOHelper.batch( conn, (ByteChannel) conn.channel ) ) {
if( key.isValid() )
key.interestOps( SelectionKey.OP_READ );
}
}
}
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.channel );
ByteBuffer buf = takeBuffer();
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
conn.inQueue.put( buf );
queue( conn );
}
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
} catch ( InterruptedException e ) {
return;// FIXME controlled shutdown
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
}
}
|
#vulnerable code
public void run() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return;
}
}
selectorthread.setName( "WebsocketSelector" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocket.RCVBUF );
socket.bind( address );
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocketImpl conn = null;
try {
selector.select();
registerWrite();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
// Object o = key.attachment();
continue;
}
if( key.isAcceptable() ) {
if( !onConnect( key ) ) {
key.cancel();
continue;
}
SocketChannel channel = server.accept();
channel.configureBlocking( false );
WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() );
w.key = channel.register( selector, SelectionKey.OP_READ, w );
w.channel = wsf.wrapChannel( w.key );
i.remove();
allocateBuffers( w );
continue;
}
if( key.isReadable() ) {
conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.read( buf, conn, (ByteChannel) conn.channel ) ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.channel instanceof WrappedByteChannel ) {
if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) {
iqueue.add( conn );
}
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
} catch ( RuntimeException e ) {
pushBuffer( buf );
throw e;
}
}
if( key.isWritable() ) {
conn = (WebSocketImpl) key.attachment();
if( SocketChannelIOHelper.batch( conn, (ByteChannel) conn.channel ) ) {
if( key.isValid() )
key.interestOps( SelectionKey.OP_READ );
}
}
}
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.channel );
ByteBuffer buf = takeBuffer();
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
conn.inQueue.put( buf );
queue( conn );
}
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
} catch ( InterruptedException e ) {
return;// FIXME controlled shutdown
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stop() throws IOException , InterruptedException {
stop( 0 );
}
|
#vulnerable code
public void stop() throws IOException , InterruptedException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
selectorthread.join();
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
this.server.close();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
}
|
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public final void onWriteDemand( WebSocket conn ) {
try {
conn.flush();
} catch ( IOException e ) {
handleIOException( conn, e );
}
/*synchronized ( write_demands ) {
if( !write_demands.contains( conn ) ) {
write_demands.add( conn );
flusher.submit( new WebsocketWriteTask( conn ) );
}
}*/
}
|
#vulnerable code
@Override
public final void onWriteDemand( WebSocket conn ) {
selector.wakeup();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stop() throws IOException {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
thread.interrupt();
this.server.close();
}
|
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
}
|
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 74
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
}
|
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void roundTripWriteAndRead() throws TaskException, IOException {
List<String> strings = Arrays.asList("ગુજરાતી ਪੰਜਾਬੀ தமிழ்",
"ਹਰਜੋਤ ਸਿੰਘ ភាសាខ្មែរ latin ąćęłńóśźż ทดสอบ വീട मानक हिन्दी ് జ উ ☗⦄✸▃ ");
for(String str: strings) {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
new PageTextWriter(doc).write(page, new Point(10, 10), str, getStandardType1Font(StandardType1Font.HELVETICA), 10.0d, Color.BLACK);
doc.addPage(page);
PDDocumentHandler handler = new PDDocumentHandler(doc);
File tmp = IOUtils.createTemporaryPdfBuffer();
handler.savePDDocument(tmp);
PDDocument doc2 = PDFParser.parse(SeekableSources.seekableSourceFrom(tmp));
String text = new PdfTextExtractorByArea().extractTextFromArea(doc2.getPage(0), new Rectangle(0, 0, 1000, 1000));
assertEquals(noWhitespace(str), noWhitespace(text));
}
}
|
#vulnerable code
@Test
public void roundTripWriteAndRead() throws TaskException, IOException {
String str = "ਹਰਜੋਤ ਸਿੰਘ ភាសាខ្មែរ latin ąćęłńóśźż ทดสอบ വീട मानक हिन्दी ് జ উ ☗⦄✸▃ ";
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
new PageTextWriter(doc).write(page, new Point(10, 10), str, getStandardType1Font(StandardType1Font.HELVETICA), 10.0d, Color.BLACK);
doc.addPage(page);
PDDocumentHandler handler = new PDDocumentHandler(doc);
File tmp = IOUtils.createTemporaryPdfBuffer();
handler.savePDDocument(tmp);
PDDocument doc2 = PDFParser.parse(SeekableSources.seekableSourceFrom(tmp));
String text = new PdfTextExtractorByArea().extractTextFromArea(doc2.getPage(0), new Rectangle(0,0, 1000, 1000));
assertEquals(noWhitespace(str), noWhitespace(text));
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public TaskTestContext assertOutputSize(int size) {
requireMultipleOutputs();
String[] files = fileOutput.list();
assertEquals("An unexpected number of output files has been created: " + StringUtils.join(files, ","),
size, files.length);
return this;
}
|
#vulnerable code
public TaskTestContext assertOutputSize(int size) {
requireMultipleOutputs();
assertEquals("An unexpected number of output files has been created", size, fileOutput.listFiles().length);
return this;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void mergeNull() {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(null, annotationsLookup);
assertTrue(victim.getForm().getFields().isEmpty());
assertNull(destination.getDocumentCatalog().getAcroForm());
}
|
#vulnerable code
@Test
public void mergeNull() {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(null, annotationsLookup);
assertFalse(victim.hasForm());
assertNull(destination.getDocumentCatalog().getAcroForm());
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testBasics() throws TaskException, IOException {
withSource("pdf/unoptimized.pdf");
victim.execute(parameters);
assertThat(sizeOfResult(), is(lessThan(104L)));
}
|
#vulnerable code
@Test
public void testBasics() throws TaskException, IOException {
parameters.setOutput(new DirectoryTaskOutput(outputFolder));
victim.execute(parameters);
long sizeInKb = outputFolder.listFiles()[0].length() / 1000;
assertThat(sizeInKb, is(lessThan(104L)));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void canDisplayGeorgian() {
assertNotNull(findFontFor("ქართული ენა"));
}
|
#vulnerable code
@Test
public void canDisplayGeorgian() {
PDFont font = FontUtils.findFontFor(new PDDocument(), "ქართული ენა");
assertNotNull("No font available for Georgian", font);
assertThat(font.getName(), is("NotoSansGeorgian"));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void extract(PDDocument document, File output) throws TaskException {
if (document == null) {
throw new TaskException("Unable to extract text from a null document.");
}
if (output == null || !output.isFile() || !output.canWrite()) {
throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.",
output));
}
try {
outputWriter = Files.newBufferedWriter(output.toPath(), Charset.forName(encoding));
textStripper.writeText(document, outputWriter);
} catch (IOException e) {
throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e);
}
}
|
#vulnerable code
public void extract(PDDocument document, File output) throws TaskException {
if (document == null) {
throw new TaskException("Unable to extract text from a null document.");
}
if (output == null || !output.isFile() || !output.canWrite()) {
throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.",
output));
}
try {
outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), encoding));
textStripper.writeText(document, outputWriter);
} catch (IOException e) {
throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e);
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void canDisplayGeorgian() {
assertNotNull(findFontFor("ქართული ენა"));
}
|
#vulnerable code
@Test
public void canDisplayGeorgian() {
PDFont font = FontUtils.findFontFor(new PDDocument(), "ქართული ენა");
assertNotNull("No font available for Georgian", font);
assertThat(font.getName(), is("NotoSansGeorgian"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void resolveTextAndFontsWhenTextRepeats() throws TaskIOException {
write("123α456α789");
}
|
#vulnerable code
@Test
public void resolveTextAndFontsWhenTextRepeats() throws TaskIOException {
PageTextWriter writer = new PageTextWriter(new PDDocument());
List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("123α456α789", helvetica);
assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(0).getText(), is("123"));
assertThat(textAndFonts.get(1).getFont().getName(), is(not("Helvetica")));
assertThat(textAndFonts.get(1).getText(), is("α"));
assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(2).getText(), is("456"));
assertThat(textAndFonts.get(3).getFont().getName(), is(not("Helvetica")));
assertThat(textAndFonts.get(3).getText(), is("α"));
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(JpegToPdfParameters parameters) throws TaskException {
final MutableInt currentStep = new MutableInt(0);
ImagesToPdfDocumentConverter converter = new ImagesToPdfDocumentConverter() {
@Override
public void beforeImage(Source<?> source) throws TaskException {
executionContext().assertTaskNotCancelled();
currentStep.increment();
}
@Override
public void afterImage(PDImageXObject image) {
notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep.getValue()).outOf(totalSteps);
}
@Override
public void failedImage(Source<?> source, TaskIOException e) throws TaskException{
executionContext().assertTaskIsLenient(e);
notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning(
String.format("Image %s was skipped, could not be processed", source.getName()), e);
}
};
documentHandler = converter.convert(parameters.getSourceList());
File tmpFile = createTemporaryBuffer(parameters.getOutput());
LOG.debug("Created output on temporary buffer {}", tmpFile);
documentHandler.setVersionOnPDDocument(parameters.getVersion());
documentHandler.setCompress(parameters.isCompress());
documentHandler.savePDDocument(tmpFile);
String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest());
outputWriter.addOutput(file(tmpFile).name(outName));
nullSafeCloseQuietly(documentHandler);
parameters.getOutput().accept(outputWriter);
LOG.debug("Input images written to {}", parameters.getOutput());
}
|
#vulnerable code
@Override
public void execute(JpegToPdfParameters parameters) throws TaskException {
int currentStep = 0;
documentHandler = new PDDocumentHandler();
documentHandler.setCreatorOnPDDocument();
PageImageWriter imageWriter = new PageImageWriter(documentHandler.getUnderlyingPDDocument());
for (Source<?> source : parameters.getSourceList()) {
executionContext().assertTaskNotCancelled();
currentStep++;
try {
PDImageXObject image = PageImageWriter.toPDXImageObject(source);
PDRectangle mediaBox = PDRectangle.A4;
if (image.getWidth() > image.getHeight() && image.getWidth() > mediaBox.getWidth()) {
mediaBox = new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth());
}
PDPage page = documentHandler.addBlankPage(mediaBox);
// full page (scaled down only)
int width = image.getWidth();
int height = image.getHeight();
if (width > mediaBox.getWidth()) {
int targetWidth = (int) mediaBox.getWidth();
LOG.debug("Scaling image down to fit by width {} vs {}", width, targetWidth);
float ratio = (float) width / targetWidth;
width = targetWidth;
height = Math.round(height / ratio);
}
if (height > mediaBox.getHeight()) {
int targetHeight = (int) mediaBox.getHeight();
LOG.debug("Scaling image down to fit by height {} vs {}", height, targetHeight);
float ratio = (float) height / targetHeight;
height = targetHeight;
width = Math.round(width / ratio);
}
// centered on page
int x = ((int) mediaBox.getWidth() - width) / 2;
int y = ((int) mediaBox.getHeight() - height) / 2;
imageWriter.append(page, image, new Point(x, y), width, height, null, 0);
notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep).outOf(totalSteps);
} catch (TaskIOException e) {
executionContext().assertTaskIsLenient(e);
notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning(
String.format("Image %s was skipped, could not be processed", source.getName()), e);
}
}
File tmpFile = createTemporaryBuffer(parameters.getOutput());
LOG.debug("Created output on temporary buffer {}", tmpFile);
documentHandler.setVersionOnPDDocument(parameters.getVersion());
documentHandler.setCompress(parameters.isCompress());
documentHandler.savePDDocument(tmpFile);
String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest());
outputWriter.addOutput(file(tmpFile).name(outName));
nullSafeCloseQuietly(documentHandler);
parameters.getOutput().accept(outputWriter);
LOG.debug("Input images written to {}", parameters.getOutput());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void resolvedSpaceSeparately() throws TaskIOException {
write("ab cd");
}
|
#vulnerable code
@Test
public void resolvedSpaceSeparately() throws TaskIOException {
PageTextWriter writer = new PageTextWriter(new PDDocument());
List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("ab cd", helvetica);
assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(0).getText(), is("ab"));
assertThat(textAndFonts.get(1).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(1).getText(), is(" "));
assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(2).getText(), is("cd"));
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
try (ZipOutputStream zipOut = new ZipOutputStream(out)) {
for (Entry<String, File> entry : files.entrySet()) {
if (isBlank(entry.getKey())) {
throw new IOException(String.format(
"Unable to copy %s to the output stream, no output name specified.", entry.getValue()));
}
try (FileInputStream input = new FileInputStream(entry.getValue())) {
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
delete(entry.getValue());
}
}
}
}
|
#vulnerable code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
ZipOutputStream zipOut = new ZipOutputStream(out);
for (Entry<String, File> entry : files.entrySet()) {
FileInputStream input = null;
if (isBlank(entry.getKey())) {
throw new IOException(String.format("Unable to copy %s to the output stream, no output name specified.",
entry.getValue()));
}
try {
input = new FileInputStream(entry.getValue());
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
IOUtils.closeQuietly(input);
delete(entry.getValue());
}
}
IOUtils.closeQuietly(zipOut);
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCanDisplayThai() {
assertThat(findFontFor("นี่คือการทดสอบ"), is(notNullValue()));
}
|
#vulnerable code
@Test
public void testCanDisplayThai() {
PDFont noto = FontUtils.loadFont(new PDDocument(), UnicodeType0Font.NOTO_SANS_THAI_REGULAR);
assertThat(FontUtils.canDisplay("นี่คือการทดสอบ", noto), is(true));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void mergeWithSignatureRemovesSignatureValue() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(document.getDocumentCatalog().getAcroForm(), annotationsLookup);
mapping.clear();
annotationsLookup.clear();
PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_signature_signed.pdf")));
for (PDPage current : anotherDoc.getPages()) {
mapping.addLookupEntry(current, new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
}
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertFalse(victim.getForm().getFields().isEmpty());
PDAcroForm form = victim.getForm();
assertNotNull(form);
PDField signature = null;
for (PDField current : form.getFieldTree()) {
if (current.getFieldType() == COSName.SIG.getName()) {
signature = current;
}
}
assertNotNull(signature);
assertEquals("", signature.getValueAsString());
assertTrue(form.isSignaturesExist());
}
|
#vulnerable code
@Test
public void mergeWithSignatureRemovesSignatureValue() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(document.getDocumentCatalog().getAcroForm(), annotationsLookup);
mapping.clear();
annotationsLookup.clear();
PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_signature_signed.pdf")));
for (PDPage current : anotherDoc.getPages()) {
mapping.addLookupEntry(current, new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
}
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertTrue(victim.hasForm());
PDAcroForm form = victim.getForm();
assertNotNull(form);
PDField signature = null;
for (PDField current : form.getFieldTree()) {
if (current.getFieldType() == COSName.SIG.getName()) {
signature = current;
}
}
assertNotNull(signature);
assertEquals("", signature.getValueAsString());
assertTrue(form.isSignaturesExist());
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public TaskTestContext assertEmptyMultipleOutput() {
assertNotNull(fileOutput);
assertTrue("Expected an output directory", fileOutput.isDirectory());
assertEquals("Found output files while expecting none", 0,
fileOutput.listFiles((d, n) -> !n.endsWith(".tmp")).length);
return this;
}
|
#vulnerable code
public TaskTestContext assertEmptyMultipleOutput() {
assertNotNull(fileOutput);
assertTrue("Expected an output directory", fileOutput.isDirectory());
assertEquals("Found output files while expecting none", 0, fileOutput.listFiles().length);
return this;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testFindFontFor() {
assertNotNull(findFontFor("ทดสอบ")); // thai
assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek
assertNotNull(findFontFor("വീട്")); // malayalam
assertNotNull(findFontFor("मानक")); // hindi
assertNotNull(findFontFor("జ")); // telugu
assertNotNull(findFontFor("উ")); // bengali
assertNotNull(findFontFor("עברית")); // hebrew
assertNotNull(findFontFor("简化字")); // simplified chinese
assertNotNull(findFontFor("한국어/조선말")); // korean
assertNotNull(findFontFor("日本語")); // japanese
assertNotNull(findFontFor("latin ąćęłńóśźż")); // latin
}
|
#vulnerable code
@Test
public void testFindFontFor() {
assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName());
assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName());
assertNull(findFontFor(new PDDocument(), "വീട്"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String generate(NameGenerationRequest request) {
if (request == null) {
throw new IllegalArgumentException("Unable to generate a name for a null request.");
}
return toSafeFilename(prefixTypesChain.process(prefix, ofNullable(request).orElseGet(() -> nameRequest())));
}
|
#vulnerable code
public String generate(NameGenerationRequest request) {
if (request == null) {
throw new IllegalArgumentException("Unable to generate a name for a null request.");
}
String result = toSafeFilename(
prefixTypesChain.process(prefix, ofNullable(request).orElseGet(() -> nameRequest())));
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win") || osName.contains("mac")) {
// char based max length
result = shortenFilenameCharLength(result, 255);
} else {
// bytes based max length
result = shortenFilenameBytesLength(result, 254, StandardCharsets.UTF_8);
}
return result;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException {
super.before(parameters, executionContext);
mixer = new PdfAlternateMixer();
outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext);
}
|
#vulnerable code
@Override
public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException {
super.before(parameters, executionContext);
mixer = new PdfAlternateMixer(parameters.getFirstInput(), parameters.getSecondInput());
outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException {
for (File source : sources) {
if (!source.exists()) {
throw new FileNotFoundException(source.getPath());
} else if (!source.canRead()) {
throw new FileNotFoundException(source.getPath() + " (Permission denied)");
}
writeToArchive(source.getParentFile(), new File[]{ source }, archive);
}
}
|
#vulnerable code
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException {
for (File source : sources) {
if (!source.exists()) {
throw new FileNotFoundException(source.getPath());
} else if (!source.canRead()) {
throw new FileNotFoundException(source.getPath() + " (Permission denied)");
}
if (source.isFile()) {
writeToArchive(source.getParentFile(), new File[]{ source }, archive);
} else {
writeToArchive(source, source.listFiles(), archive);
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException,
ArchiveException {
return createArchiveOutputStream(archiver.getArchiveFormat(), archive);
}
|
#vulnerable code
static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException,
ArchiveException {
return createArchiveOutputStream(archiver.getFileType(), new FileOutputStream(archive));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static FileModeMapper create(ArchiveEntry entry) {
if (IS_POSIX) {
return new PosixPermissionMapper(entry);
}
// TODO: implement basic windows permission mapping (e.g. with File.setX or attrib)
return new FallbackFileModeMapper(entry);
}
|
#vulnerable code
public static FileModeMapper create(ArchiveEntry entry) {
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
// FIXME: this is really horrid, but with java 6 i need the system call to 'chmod'
// TODO: implement basic windows permission mapping (e.g. with File.setX or attrib)
return new FallbackFileModeMapper(entry);
}
// please don't use me on OS/2
return new UnixPermissionMapper(entry);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getCompressionType(), destination);
}
|
#vulnerable code
static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getFileType(), new FileOutputStream(destination));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void initialize() {
InputStream in = PinyinDic.class.getResourceAsStream(dicLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line = null;
long startPoint = System.currentTimeMillis();
while (null != (line = reader.readLine())) {
if (StringUtils.isNotBlank(line)) {
dicSet.add(line);
}
}
long endPoint = System.currentTimeMillis();
Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s",
MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this);
} catch (Exception ex) {
Logger.logger.error("read pinyin dic error.", ex);
throw new RuntimeException("read pinyin dic error.", ex);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception ex) {
//ignore ex
}
}
}
|
#vulnerable code
private void initialize() {
InputStream in = PinyinDic.class.getResourceAsStream(dicLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line = null;
long startPoint = System.currentTimeMillis();
while (null != (line = reader.readLine())) {
if (StringUtils.isNotBlank(line)) {
dicSet.add(line);
}
}
long endPoint = System.currentTimeMillis();
Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s",
MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this);
} catch (Exception ex) {
Logger.logger.error("read pinyin dic error.", ex);
throw new RuntimeException("read pinyin dic error.", ex);
}
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public List<ProjectMailTicketConfig> findAll() {
return aggregateByConfig(queries.findAllConfigs(), queries.findAllTickets());
}
|
#vulnerable code
public List<ProjectMailTicketConfig> findAll() {
List<ProjectMailTicketConfig> configs = queries.findAllConfigs();
List<ProjectMailTicket> ticketConfigs = queries.findAllTickets();
Map<Integer, List<ProjectMailTicket>> ticketConfigsByConfigId = new HashMap<>();
for(ProjectMailTicket ticketConfig: ticketConfigs) {
if(!ticketConfigsByConfigId.containsKey(ticketConfig.getConfigId())) {
ticketConfigsByConfigId.put(ticketConfig.getConfigId(), new ArrayList<ProjectMailTicket>());
}
ticketConfigsByConfigId.get(ticketConfig.getConfigId()).add(ticketConfig);
}
for(ProjectMailTicketConfig config: configs) {
if(ticketConfigsByConfigId.containsKey(config.getId())) {
config.getEntries().addAll(ticketConfigsByConfigId.get(config.getId()));
}
}
return configs;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testFindCardsId() {
Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user);
Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user);
Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user);
Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TESTBRD-" + c1.getSequence(),
"TESTBRD-" + c2.getSequence(), "TESTBRD-" + c3.getSequence()));
Assert.assertEquals(res.get("TESTBRD-" + c1.getSequence()).intValue(), c1.getId());
Assert.assertEquals(res.get("TESTBRD-" + c2.getSequence()).intValue(), c2.getId());
Assert.assertEquals(res.get("TESTBRD-" + c3.getSequence()).intValue(), c3.getId());
}
|
#vulnerable code
@Test
public void testFindCardsId() {
Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user);
Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user);
Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user);
Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TEST-BRD-" + c1.getSequence(),
"TEST-BRD-" + c2.getSequence(), "TEST-BRD-" + c3.getSequence()));
Assert.assertEquals(res.get("TEST-BRD-" + c1.getSequence()).intValue(), c1.getId());
Assert.assertEquals(res.get("TEST-BRD-" + c2.getSequence()).intValue(), c2.getId());
Assert.assertEquals(res.get("TEST-BRD-" + c3.getSequence()).intValue(), c3.getId());
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void checkNew() {
List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll();
for(ProjectMailTicketConfig entry: entries) {
MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3") ?
getPop3MailReceiver(entry.getConfig(), entry.getProperties()) :
getImapMailReceiver(entry.getConfig(), entry.getProperties());
try {
Object[] messages = receiver.receive();
LOG.info("found {} messages", messages.length);
for(int i = 0; i < messages.length; i++) {
MimeMessage message = (MimeMessage) messages[i];
String deliveredTo = getDeliveredTo(message);
for(ProjectMailTicket ticketConfig: entry.getEntries()) {
if(entry.getConfig().getFrom().equals(deliveredTo)) {
String from = getFrom(message);
try {
createCard(message.getSubject(), getTextFromMessage(message), ticketConfig.getColumnId(), from);
} catch (IOException|MessagingException e) {
LOG.error("failed to parse message content", e);
}
}
}
}
} catch (MessagingException e) {
LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId());
}
}
}
|
#vulnerable code
public void checkNew() {
List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll();
for(ProjectMailTicketConfig entry: entries) {
MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3") ?
getPop3MailReceiver(entry.getConfig(), entry.getProperties()) :
getImapMailReceiver(entry.getConfig(), entry.getProperties());
try {
Object[] messages = receiver.receive();
LOG.info("found {} messages", messages.length);
for(int i = 0; i < messages.length; i++) {
MimeMessage message = (MimeMessage) messages[i];
String deliveredTo = message.getHeader("Delivered-To", "");
for(ProjectMailTicket ticketConfig: entry.getEntries()) {
if(entry.getConfig().getFrom().equals(deliveredTo)) {
Address[] froms = message.getFrom();
String from = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
try {
createCard(message.getSubject(), getTextFromMessage(message), ticketConfig.getColumnId(), from);
} catch (IOException|MessagingException e) {
LOG.error("failed to parse message content", e);
}
}
}
}
} catch (MessagingException e) {
LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId());
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
}
|
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
if (Lizzie.leelaz.isKataGo) {
history.getData().scoreMean = stats.maxScoreMean;
}
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void clear() {
initialize();
}
|
#vulnerable code
public void clear() {
while (previousMove());
history.clear();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void drawWoodenBoard(Graphics2D g) {
if (uiConfig.getBoolean("fancy-board")) {
if (cachedBoardImage == null) {
try {
cachedBoardImage = ImageIO.read(getClass().getResourceAsStream("/assets/board.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
int shadowRadius = (int) (boardLength * MARGIN / 6);
drawTextureImage(g, cachedBoardImage, x - 2 * shadowRadius, y - 2 * shadowRadius, boardLength + 4 * shadowRadius, boardLength + 4 * shadowRadius);
g.setStroke(new BasicStroke(shadowRadius * 2));
// draw border
g.setColor(new Color(0, 0, 0, 50));
g.drawRect(x - shadowRadius, y - shadowRadius, boardLength + 2 * shadowRadius, boardLength + 2 * shadowRadius);
g.setStroke(new BasicStroke(1));
} else {
JSONArray boardColor = uiConfig.getJSONArray("board-color");
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(new Color(boardColor.getInt(0), boardColor.getInt(1), boardColor.getInt(2)));
g.fillRect(x, y, boardLength, boardLength);
}
}
|
#vulnerable code
private void drawWoodenBoard(Graphics2D g) {
if (uiConfig.getBoolean("fancy-board")) {
// fancy version
int shadowRadius = (int) (boardLength * MARGIN / 6);
BufferedImage boardImage = theme.getBoard();
// Support seamless texture
drawTextureImage(g, boardImage == null ? theme.getBoard() : boardImage, x - 2 * shadowRadius, y - 2 * shadowRadius, boardLength + 4 * shadowRadius, boardLength + 4 * shadowRadius);
g.setStroke(new BasicStroke(shadowRadius * 2));
// draw border
g.setColor(new Color(0, 0, 0, 50));
g.drawRect(x - shadowRadius, y - shadowRadius, boardLength + 2 * shadowRadius, boardLength + 2 * shadowRadius);
g.setStroke(new BasicStroke(1));
} else {
// simple version
JSONArray boardColor = uiConfig.getJSONArray("board-color");
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(new Color(boardColor.getInt(0), boardColor.getInt(1), boardColor.getInt(2)));
g.fillRect(x, y, boardLength, boardLength);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
try
{
// add SGF header
StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion));
// move to the first move
BoardHistoryList history = Lizzie.board.getHistory();
while (history.previous() != null);
// replay moves, and convert them to tags.
// * format: ";B[xy]" or ";W[xy]"
// * with 'xy' = coordinates ; or 'tt' for pass.
BoardData data;
while ((data = history.next()) != null) {
String stone;
if (Stone.BLACK.equals(data.lastMoveColor)) stone = "B";
else if (Stone.WHITE.equals(data.lastMoveColor)) stone = "W";
else continue;
char x = data.lastMove == null ? 't' : (char) (data.lastMove[0] + 'a');
char y = data.lastMove == null ? 't' : (char) (data.lastMove[1] + 'a');
builder.append(String.format(";%s[%c%c]", stone, x, y));
}
// close file
builder.append(')');
writer.append(builder.toString());
}
finally
{
writer.close();
fp.close();
}
return true;
}
|
#vulnerable code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion));
BoardHistoryList history = Lizzie.board.getHistory();
while (history.previous() != null) ;
BoardData data = null;
while ((data = history.next()) != null) {
StringBuilder tag = new StringBuilder(";");
if (data.lastMoveColor.equals(Stone.BLACK)) {
tag.append("B");
} else if (data.lastMoveColor.equals(Stone.WHITE)) {
tag.append("W");
} else {
return false;
}
char x = (char) data.lastMove[0], y = (char) data.lastMove[1];
x += 'a';
y += 'a';
tag.append(String.format("[%c%c]", x, y));
builder.append(tag);
}
builder.append(')');
writer.append(builder.toString());
writer.close();
fp.close();
return true;
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void ponder() {
isPondering = true;
startPonderTime = System.currentTimeMillis();
if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo)
analyzeAvoid(
"avoid b "
+ Lizzie.board.avoidCoords
+ " "
+ Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations")
+ " avoid w "
+ Lizzie.board.avoidCoords
+ " "
+ Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations"));
else
sendCommand(
(this.isKataGo ? "kata-analyze " : "lz-analyze ")
+ Lizzie.config
.config
.getJSONObject("leelaz")
.getInt("analyze-update-interval-centisec")
+ (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : ""));
// until it responds to this, incoming
// ponder results are obsolete
}
|
#vulnerable code
public void ponder() {
isPondering = true;
startPonderTime = System.currentTimeMillis();
if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo)
analyzeAvoid(
"avoid",
Lizzie.board.getHistory().isBlacksTurn() ? "w" : "b",
Lizzie.board.avoidCoords,
+Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations"));
else
sendCommand(
(this.isKataGo ? "kata-analyze " : "lz-analyze ")
+ Lizzie.config
.config
.getJSONObject("leelaz")
.getInt("analyze-update-interval-centisec")
+ (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : ""));
// until it responds to this, incoming
// ponder results are obsolete
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void sendCommand(String command) {
command = cmdNumber + " " + command;
cmdNumber++;
if (printCommunication) {
System.out.printf("> %s\n", command);
}
if (command.startsWith("fixed_handicap"))
isSettingHandicap = true;
try {
outputStream.write((command + "\n").getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
|
#vulnerable code
public void sendCommand(String command) {
if (printCommunication) {
System.out.printf("> %s\n", command);
}
if (command.startsWith("fixed_handicap"))
isSettingHandicap = true;
if (command.startsWith("genmove"))
isThinking = true;
try {
outputStream.write((command + "\n").getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static boolean parse(String value) {
// Drop anything outside "(;...)"
final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;{0,1}.*\\))(?s).*?");
Matcher sgfMatcher = SGF_PATTERN.matcher(value);
if (sgfMatcher.matches()) {
value = sgfMatcher.group(1);
} else {
return false;
}
// Determine the SZ property
Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*");
Matcher szMatcher = szPattern.matcher(value);
int boardWidth = 19;
int boardHeight = 19;
if (szMatcher.matches()) {
String sizeStr = szMatcher.group(1);
Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)");
Matcher sizeMatcher = sizePattern.matcher(sizeStr);
if (sizeMatcher.matches()) {
Lizzie.board.reopen(
Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2)));
} else {
int boardSize = Integer.parseInt(sizeStr);
Lizzie.board.reopen(boardSize, boardSize);
}
} else {
Lizzie.board.reopen(boardWidth, boardHeight);
}
parseValue(value, null, false);
return true;
}
|
#vulnerable code
private static boolean parse(String value) {
// Drop anything outside "(;...)"
final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;.*\\)).*?");
Matcher sgfMatcher = SGF_PATTERN.matcher(value);
if (sgfMatcher.matches()) {
value = sgfMatcher.group(1);
} else {
return false;
}
// Determine the SZ property
Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*");
Matcher szMatcher = szPattern.matcher(value);
if (szMatcher.matches()) {
String sizeStr = szMatcher.group(1);
Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)");
Matcher sizeMatcher = sizePattern.matcher(sizeStr);
if (sizeMatcher.matches()) {
Lizzie.board.reopen(
Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2)));
} else {
int boardSize = Integer.parseInt(sizeStr);
Lizzie.board.reopen(boardSize, boardSize);
}
} else {
Lizzie.board.reopen(19, 19);
}
int subTreeDepth = 0;
// Save the variation step count
Map<Integer, Integer> subTreeStepMap = new HashMap<Integer, Integer>();
// Comment of the game head
String headComment = "";
// Game properties
Map<String, String> gameProperties = new HashMap<String, String>();
Map<String, String> pendingProps = new HashMap<String, String>();
boolean inTag = false,
isMultiGo = false,
escaping = false,
moveStart = false,
addPassForMove = true;
boolean inProp = false;
String tag = "";
StringBuilder tagBuilder = new StringBuilder();
StringBuilder tagContentBuilder = new StringBuilder();
// MultiGo 's branch: (Main Branch (Main Branch) (Branch) )
// Other 's branch: (Main Branch (Branch) Main Branch)
if (value.matches("(?s).*\\)\\s*\\)")) {
isMultiGo = true;
}
String blackPlayer = "", whitePlayer = "";
// Support unicode characters (UTF-8)
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (escaping) {
// Any char following "\" is inserted verbatim
// (ref) "3.2. Text" in https://www.red-bean.com/sgf/sgf4.html
tagContentBuilder.append(c == 'n' ? "\n" : c);
escaping = false;
continue;
}
switch (c) {
case '(':
if (!inTag) {
subTreeDepth += 1;
// Initialize the step count
subTreeStepMap.put(subTreeDepth, 0);
addPassForMove = true;
pendingProps = new HashMap<String, String>();
} else {
if (i > 0) {
// Allow the comment tag includes '('
tagContentBuilder.append(c);
}
}
break;
case ')':
if (!inTag) {
if (isMultiGo) {
// Restore to the variation node
int varStep = subTreeStepMap.get(subTreeDepth);
for (int s = 0; s < varStep; s++) {
Lizzie.board.previousMove();
}
}
subTreeDepth -= 1;
} else {
// Allow the comment tag includes '('
tagContentBuilder.append(c);
}
break;
case '[':
if (!inProp) {
inProp = true;
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
inTag = true;
String tagTemp = tagBuilder.toString();
if (!tagTemp.isEmpty()) {
// Ignore small letters in tags for the long format Smart-Go file.
// (ex) "PlayerBlack" ==> "PB"
// It is the default format of mgt, an old SGF tool.
// (Mgt is still supported in Debian and Ubuntu.)
tag = tagTemp.replaceAll("[a-z]", "");
}
tagContentBuilder = new StringBuilder();
} else {
tagContentBuilder.append(c);
}
break;
case ']':
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
inTag = false;
inProp = false;
tagBuilder = new StringBuilder();
String tagContent = tagContentBuilder.toString();
// We got tag, we can parse this tag now.
if (tag.equals("B") || tag.equals("W")) {
moveStart = true;
addPassForMove = true;
int[] move = convertSgfPosToCoord(tagContent);
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
Stone color = tag.equals("B") ? Stone.BLACK : Stone.WHITE;
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
if (move == null) {
Lizzie.board.pass(color, newBranch, false);
} else {
Lizzie.board.place(move[0], move[1], color, newBranch);
}
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
} else if (tag.equals("C")) {
// Support comment
if (!moveStart) {
headComment = tagContent;
} else {
Lizzie.board.comment(tagContent);
}
} else if (tag.equals("LZ") && Lizzie.config.holdBestMovesToSgf) {
// Content contains data for Lizzie to read
String[] lines = tagContent.split("\n");
String[] line1 = lines[0].split(" ");
String line2 = "";
if (lines.length > 1) {
line2 = lines[1];
}
String versionNumber = line1[0];
Lizzie.board.getData().winrate = 100 - Double.parseDouble(line1[1]);
int numPlayouts =
Integer.parseInt(
line1[2]
.replaceAll("k", "000")
.replaceAll("m", "000000")
.replaceAll("[^0-9]", ""));
Lizzie.board.getData().setPlayouts(numPlayouts);
if (numPlayouts > 0 && !line2.isEmpty()) {
Lizzie.board.getData().bestMoves = Lizzie.leelaz.parseInfo(line2);
}
} else if (tag.equals("AB") || tag.equals("AW")) {
int[] move = convertSgfPosToCoord(tagContent);
Stone color = tag.equals("AB") ? Stone.BLACK : Stone.WHITE;
if (moveStart) {
// add to node properties
Lizzie.board.addNodeProperty(tag, tagContent);
if (addPassForMove) {
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
Lizzie.board.pass(color, newBranch, true);
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
addPassForMove = false;
}
Lizzie.board.addNodeProperty(tag, tagContent);
if (move != null) {
Lizzie.board.addStone(move[0], move[1], color);
}
} else {
if (move == null) {
Lizzie.board.pass(color);
} else {
Lizzie.board.place(move[0], move[1], color);
}
Lizzie.board.flatten();
}
} else if (tag.equals("PB")) {
blackPlayer = tagContent;
} else if (tag.equals("PW")) {
whitePlayer = tagContent;
} else if (tag.equals("KM")) {
try {
if (tagContent.trim().isEmpty()) {
tagContent = "0.0";
}
Lizzie.board.setKomi(Double.parseDouble(tagContent));
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else {
if (moveStart) {
// Other SGF node properties
if ("AE".equals(tag)) {
// remove a stone
if (addPassForMove) {
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
Stone color =
Lizzie.board.getHistory().getLastMoveColor() == Stone.WHITE
? Stone.BLACK
: Stone.WHITE;
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
Lizzie.board.pass(color, newBranch, true);
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
addPassForMove = false;
}
Lizzie.board.addNodeProperty(tag, tagContent);
int[] move = convertSgfPosToCoord(tagContent);
if (move != null) {
Lizzie.board.removeStone(
move[0], move[1], tag.equals("AB") ? Stone.BLACK : Stone.WHITE);
}
} else {
boolean firstProp = (subTreeStepMap.get(subTreeDepth) == 0);
if (firstProp) {
addProperty(pendingProps, tag, tagContent);
} else {
Lizzie.board.addNodeProperty(tag, tagContent);
}
}
} else {
addProperty(gameProperties, tag, tagContent);
}
}
break;
case ';':
break;
default:
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
if (inTag) {
if (c == '\\') {
escaping = true;
continue;
}
tagContentBuilder.append(c);
} else {
if (c != '\n' && c != '\r' && c != '\t' && c != ' ') {
tagBuilder.append(c);
}
}
}
}
Lizzie.frame.setPlayers(whitePlayer, blackPlayer);
// Rewind to game start
while (Lizzie.board.previousMove()) ;
// Set AW/AB Comment
if (!headComment.isEmpty()) {
Lizzie.board.comment(headComment);
Lizzie.frame.refresh();
}
if (gameProperties.size() > 0) {
Lizzie.board.addNodeProperties(gameProperties);
}
return true;
}
#location 128
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are computing. i think its fine.
}
}
|
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().playouts) {
history.getData().winrate = stats.maxWinrate;
history.getData().playouts = stats.totalPlayouts;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void reopen(int size) {
size = (size >= 2) ? size : 19;
if (size != boardSize) {
boardSize = size;
Zobrist.init();
clear();
Lizzie.leelaz.sendCommand("boardsize " + boardSize);
forceRefresh = true;
}
}
|
#vulnerable code
public void reopen(int size) {
size = (size == 13 || size == 9) ? size : 19;
if (size != boardSize) {
boardSize = size;
initialize();
forceRefresh = true;
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void drawMoveStatistics(Graphics2D g, int posX, int posY, int width, int height) {
if (width < 0 || height < 0)
return; // we don't have enough space
double lastWR = 50; // winrate the previous move
boolean validLastWinrate = false; // whether it was actually calculated
BoardData lastNode = Lizzie.board.getHistory().getPrevious();
if (lastNode != null && lastNode.playouts > 0) {
lastWR = lastNode.winrate;
validLastWinrate = true;
}
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
double curWR = stats.maxWinrate; // winrate on this move
boolean validWinrate = (stats.totalPlayouts > 0); // and whether it was actually calculated
if (isPlayingAgainstLeelaz && playerIsBlack == !Lizzie.board.getHistory().getData().blackToPlay)
validWinrate = false;
if (!validWinrate) {
curWR = 100 - lastWR; // display last move's winrate for now (with color difference)
}
double whiteWR, blackWR;
if (Lizzie.board.getData().blackToPlay) {
blackWR = curWR;
} else {
blackWR = 100 - curWR;
}
whiteWR = 100 - blackWR;
// Background rectangle
g.setColor(new Color(0, 0, 0, 130));
g.fillRect(posX, posY, width, height);
// border. does not include bottom edge
int strokeRadius = 3;
g.setStroke(new BasicStroke(2 * strokeRadius));
g.drawLine(posX + strokeRadius, posY + strokeRadius,
posX - strokeRadius + width, posY + strokeRadius);
g.drawLine(posX + strokeRadius, posY + 3 * strokeRadius,
posX + strokeRadius, posY - strokeRadius + height);
g.drawLine(posX - strokeRadius + width, posY + 3 * strokeRadius,
posX - strokeRadius + width, posY - strokeRadius + height);
// resize the box now so it's inside the border
posX += 2 * strokeRadius;
posY += 2 * strokeRadius;
width -= 4 * strokeRadius;
height -= 4 * strokeRadius;
// Title
Font font = OpenSansRegularBase.deriveFont(Font.PLAIN, (int) (Math.min(width, height) * 0.2));
strokeRadius = 2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.setFont(font);
// Last move
if (validLastWinrate && validWinrate)
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") +
String.format(": %.1f%%", 100 - lastWR - curWR),
posX + 2 * strokeRadius,
posY + height - 2 * strokeRadius); // - font.getSize());
else {
// I think it's more elegant to just not display anything when we don't have
// valid data --dfannius
// g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + ": ?%",
// posX + 2 * strokeRadius, posY + height - 2 * strokeRadius);
}
if (validWinrate || validLastWinrate) {
int maxBarwidth = (int) (width);
int barWidthB = (int) (blackWR * maxBarwidth / 100);
int barWidthW = (int) (whiteWR * maxBarwidth / 100);
int barPosY = posY + height / 3;
int barPosxB = (int) (posX);
int barPosxW = barPosxB + barWidthB;
int barHeight = height / 3;
// Draw winrate bars
g.fillRect(barPosxW, barPosY, barWidthW, barHeight);
g.setColor(Color.BLACK);
g.fillRect(barPosxB, barPosY, barWidthB, barHeight);
// Show percentage above bars
g.setColor(Color.WHITE);
g.drawString(String.format("%.1f%%", blackWR),
barPosxB + 2 * strokeRadius,
posY + barHeight - 2 * strokeRadius);
String winString = String.format("%.1f%%", whiteWR);
int sw = g.getFontMetrics().stringWidth(winString);
g.drawString(winString,
barPosxB + maxBarwidth - sw - 2 * strokeRadius,
posY + barHeight - 2 * strokeRadius);
g.setColor(Color.GRAY);
Stroke oldstroke = g.getStroke();
Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
new float[]{4}, 0);
g.setStroke(dashed);
int middleX = barPosxB + (int) (maxBarwidth / 2);
g.drawLine(middleX, barPosY, middleX, barPosY + barHeight);
g.setStroke(oldstroke);
}
}
|
#vulnerable code
private void drawMoveStatistics(Graphics2D g, int posX, int posY, int width, int height) {
if (width < 0 || height < 0)
return; // we don't have enough space
double lastWR;
if (Lizzie.board.getData().moveNumber == 0)
lastWR = 50;
else
lastWR = Lizzie.board.getHistory().getPrevious().winrate;
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
double curWR = stats.maxWinrate;
if (isPlayingAgainstLeelaz && playerIsBlack == !Lizzie.board.getHistory().getData().blackToPlay)
curWR = -100;
if (curWR < 0) {
curWR = 100 - lastWR;
}
double whiteWR, blackWR;
if (Lizzie.board.getData().blackToPlay) {
blackWR = curWR;
} else {
blackWR = 100 - curWR;
}
whiteWR = 100 - blackWR;
// Background rectangle
g.setColor(new Color(0, 0, 0, 130));
g.fillRect(posX, posY, width, height);
// border. does not include bottom edge
int strokeRadius = 3;
g.setStroke(new BasicStroke(2 * strokeRadius));
g.drawLine(posX + strokeRadius, posY + strokeRadius, posX - strokeRadius + width, posY + strokeRadius);
g.drawLine(posX + strokeRadius, posY + 3 * strokeRadius, posX + strokeRadius, posY - strokeRadius + height);
g.drawLine(posX - strokeRadius + width, posY + 3 * strokeRadius, posX - strokeRadius + width, posY - strokeRadius + height);
// resize the box now so it's inside the border
posX += 2 * strokeRadius;
posY += 2 * strokeRadius;
width -= 4 * strokeRadius;
height -= 4 * strokeRadius;
// Title
Font font = OpenSansRegularBase.deriveFont(Font.PLAIN, (int) (Math.min(width, height) * 0.2));
strokeRadius = 2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.setFont(font);
// Last move
if (lastWR < 0)
// In case leelaz didnt have time to calculate
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + ": ?%", posX + 2 * strokeRadius, posY + height - 2 * strokeRadius);
else
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + String.format(": %.1f%%", 100 - lastWR - curWR), posX + 2 * strokeRadius,
posY + height - 2 * strokeRadius);// - font.getSize());
int maxBarwidth = (int) (width);
int barWidthB = (int) (blackWR * maxBarwidth / 100);
int barWidthW = (int) (whiteWR * maxBarwidth / 100);
int barPosY = posY + height / 3;
int barPosxB = (int) (posX);
int barPosxW = barPosxB + barWidthB;
int barHeight = height / 3;
// Draw winrate bars
g.fillRect(barPosxW, barPosY, barWidthW, barHeight);
g.setColor(Color.BLACK);
g.fillRect(barPosxB, barPosY, barWidthB, barHeight);
// Show percentage above bars
g.setColor(Color.WHITE);
g.drawString(String.format("%.1f%%", blackWR), barPosxB + 2 * strokeRadius, posY + barHeight - 2 * strokeRadius);
String winString = String.format("%.1f%%", whiteWR);
int sw = g.getFontMetrics().stringWidth(winString);
g.drawString(winString, barPosxB + maxBarwidth - sw - 2 * strokeRadius, posY + barHeight - 2 * strokeRadius);
g.setColor(Color.GRAY);
Stroke oldstroke = g.getStroke();
Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
new float[]{4}, 0);
g.setStroke(dashed);
int middleX = barPosxB + (int) (maxBarwidth / 2);
g.drawLine(middleX, barPosY, middleX, barPosY + barHeight);
g.setStroke(oldstroke);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true));
TypeUtil.getPropertyType(A.class, "b.j", "3");
}
|
#vulnerable code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true));
TypeUtil.getPropertyType(A.class, "b.j", "3");
}
|
#vulnerable code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void executeDDL(Object test, String[] sqls) {
try {
executeSql(CONNECTION_TABLE.get(test), sqls);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
|
#vulnerable code
public static void executeDDL(Object test, String[] sqls) {
Connection connection = CONNECTION_TABLE.get(test);
try {
Statement statement = connection.createStatement();
for (int i = 0; i < sqls.length; i++) {
statement.execute(sqls[i]);
}
connection.commit();
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Properties getProperties() {
if (propertyFile!=null) {
Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ?
FileInputStream is = null;
try {
is = new FileInputStream(propertyFile);
properties.load(is);
return properties;
}
catch (FileNotFoundException e) {
throw new BuildException(propertyFile + " not found.",e);
}
catch (IOException e) {
throw new BuildException("Problem while loading " + propertyFile,e);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
} else {
return null;
}
}
|
#vulnerable code
protected Properties getProperties() {
if (propertyFile!=null) {
Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ?
try {
properties.load(new FileInputStream(propertyFile) );
return properties;
}
catch (FileNotFoundException e) {
throw new BuildException(propertyFile + " not found.",e);
}
catch (IOException e) {
throw new BuildException("Problem while loading " + propertyFile,e);
}
} else {
return null;
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void execute() {
getLog().info("Starting " + this.getClass().getSimpleName() + "...");
RevengStrategy strategy = setupReverseEngineeringStrategy();
if (propertyFile.exists()) {
executeExporter(createJdbcDescriptor(strategy, loadPropertiesFile()));
} else {
getLog().info("Property file '" + propertyFile + "' cannot be found, aborting...");
}
getLog().info("Finished " + this.getClass().getSimpleName() + "!");
}
|
#vulnerable code
public void execute() {
getLog().info("Starting " + this.getClass().getSimpleName() + "...");
RevengStrategy strategy = setupReverseEngineeringStrategy();
Properties properties = loadPropertiesFile();
MetadataDescriptor jdbcDescriptor = createJdbcDescriptor(strategy, properties);
executeExporter(jdbcDescriptor);
getLog().info("Finished " + this.getClass().getSimpleName() + "!");
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String getAllExecutors(String jobName, CuratorRepository.CuratorFrameworkOp curatorFrameworkOp) {
String executorsNodePath = SaturnExecutorsNode.getExecutorsNodePath();
if (!curatorFrameworkOp.checkExists(executorsNodePath)) {
return null;
}
StringBuilder allExecutorsBuilder = new StringBuilder();
StringBuilder offlineExecutorsBuilder = new StringBuilder();
List<String> executors = curatorFrameworkOp.getChildren(executorsNodePath);
if (executors != null && executors.size() > 0) {
for (String executor : executors) {
if (curatorFrameworkOp.checkExists(SaturnExecutorsNode.getExecutorTaskNodePath(executor))) {
continue;// 过滤容器中的Executor,容器资源只需要可以选择taskId即可
}
String ip = curatorFrameworkOp.getData(SaturnExecutorsNode.getExecutorIpNodePath(executor));
if (StringUtils.isNotBlank(ip)) {// if ip exists, means the executor is online
allExecutorsBuilder.append(executor + "(" + ip + ")").append(",");
continue;
}
offlineExecutorsBuilder.append(executor + "(该executor已离线)").append(",");// if ip is not exists,means the
// executor is offline
}
}
String containerTaskIdsStr = generateContainerTaskIdStr(curatorFrameworkOp);
allExecutorsBuilder.append(containerTaskIdsStr);
allExecutorsBuilder.append(offlineExecutorsBuilder.toString());
String preferListNodePath = JobNodePath.getConfigNodePath(jobName, "preferList");
if (curatorFrameworkOp.checkExists(preferListNodePath)) {
String preferList = curatorFrameworkOp.getData(preferListNodePath);
if (!Strings.isNullOrEmpty(preferList)) {
String[] preferExecutorList = preferList.split(",");
for (String preferExecutor : preferExecutorList) {
if (executors != null && !executors.contains(preferExecutor) && !preferExecutor.startsWith("@")) {
allExecutorsBuilder.append(preferExecutor + "(该executor已删除)").append(",");
}
}
}
}
return allExecutorsBuilder.toString();
}
|
#vulnerable code
@Override
public String getAllExecutors(String jobName, CuratorRepository.CuratorFrameworkOp curatorFrameworkOp) {
String executorsNodePath = SaturnExecutorsNode.getExecutorsNodePath();
if (!curatorFrameworkOp.checkExists(executorsNodePath)) {
return null;
}
StringBuilder allExecutorsBuilder = new StringBuilder();
StringBuilder offlineExecutorsBuilder = new StringBuilder();
List<String> executors = curatorFrameworkOp.getChildren(executorsNodePath);
if (executors != null && executors.size() > 0) {
for (String executor : executors) {
if (curatorFrameworkOp.checkExists(SaturnExecutorsNode.getExecutorTaskNodePath(executor))) {
continue;// 过滤容器中的Executor,容器资源只需要可以选择taskId即可
}
String ip = curatorFrameworkOp.getData(SaturnExecutorsNode.getExecutorIpNodePath(executor));
if (StringUtils.isNotBlank(ip)) {// if ip exists, means the executor is online
allExecutorsBuilder.append(executor + "(" + ip + ")").append(",");
continue;
}
offlineExecutorsBuilder.append(executor + "(该executor已离线)").append(",");// if ip is not exists,means the
// executor is offline
}
}
StringBuilder containerTaskIdsBuilder = new StringBuilder();
String containerNodePath = ContainerNodePath.getDcosTasksNodePath();
if (curatorFrameworkOp.checkExists(containerNodePath)) {
List<String> containerTaskIds = curatorFrameworkOp.getChildren(containerNodePath);
if (!CollectionUtils.isEmpty(containerTaskIds)) {
for (String containerTaskId : containerTaskIds) {
containerTaskIdsBuilder.append(containerTaskId + "(容器资源)").append(",");
}
}
}
allExecutorsBuilder.append(containerTaskIdsBuilder.toString());
allExecutorsBuilder.append(offlineExecutorsBuilder.toString());
String preferListNodePath = JobNodePath.getConfigNodePath(jobName, "preferList");
if (curatorFrameworkOp.checkExists(preferListNodePath)) {
String preferList = curatorFrameworkOp.getData(preferListNodePath);
if (!Strings.isNullOrEmpty(preferList)) {
String[] preferExecutorList = preferList.split(",");
for (String preferExecutor : preferExecutorList) {
if (executors != null && !executors.contains(preferExecutor) && !preferExecutor.startsWith("@")) {
allExecutorsBuilder.append(preferExecutor + "(该executor已删除)").append(",");
}
}
}
}
return allExecutorsBuilder.toString();
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void refreshTreeData() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster : zkClusters) {
InitRegistryCenterService.initTreeJson(zkCluster.getRegCenterConfList(), zkCluster.getZkAddr());
}
}
|
#vulnerable code
private void refreshTreeData() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster : zkClusters) {
InitRegistryCenterService.initTreeJson(REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr()), zkCluster.getZkAddr());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: zkCluster.getRegCenterConfList()) {
if (each != null && namespace.equals(each.getNamespace())) {
return each;
}
}
}
return null;
}
|
#vulnerable code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if (each != null && namespace.equals(each.getNamespace())) {
return each;
}
}
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
/* for(File file : saturnContainerDir.listFiles()) {
zip(file, "saturn", zos);
}*/
for(File file : runtimeLibFiles) {
zip(file, "app"+fileSeparator+"lib", zos);
}
zos.close();
}
|
#vulnerable code
public static void zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for(File file : saturnContainerDir.listFiles()) {
zip(file, "saturn", zos);
}
for(File file : runtimeLibFiles) {
zip(file, "app"+fileSeparator+"lib", zos);
}
zos.close();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
while (!halted.get()) {
try {
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted.get()) {
break;
}
}
boolean noFireTime = false; // 没有下次执行时间,初始化为false
long timeUntilTrigger = 1000;
if (triggerObj != null) {
triggerObj.updateAfterMisfire(null);
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
while (!noFireTime && timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (triggered) {
break;
}
try {
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
if (triggerObj != null) {
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
}
}
boolean goAhead;
// 触发执行只有两个条件:1.时间到了 2.点立即执行
synchronized (sigLock) {
goAhead = !halted.get() && !paused;
// 重置立即执行标志;
if (triggered) {
triggered = false;
} else if(goAhead){ // 非立即执行。即,执行时间到了,或者没有下次执行时间
goAhead = goAhead && !noFireTime; // 有下次执行时间,即执行时间到了,才执行作业
if (goAhead) { // 执行时间到了,更新执行时间
if(triggerObj != null) {
triggerObj.triggered(null);
}
} else { // 没有下次执行时间,则尝试睡一秒,防止不停的循环导致CPU使用率过高(如果cron不再改为周期性执行)
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
}
}
if (goAhead) {
job.execute();
}
} catch (RuntimeException e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, job.getJobName(), e.getMessage()), e);
}
}
}
|
#vulnerable code
@Override
public void run() {
while (!halted.get()) {
try {
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted.get()) {
break;
}
}
boolean noFireTime = false; // 没有下次执行时间,初始化为false
long timeUntilTrigger = 1000;
if (triggerObj != null) {
triggerObj.updateAfterMisfire(null);
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
while (!noFireTime && timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (triggered) {
break;
}
try {
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
if (triggerObj != null) {
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
}
}
boolean goAhead;
// 触发执行只有两个条件:1.时间到了;2。点立即执行;
synchronized (sigLock) {
goAhead = !halted.get() && !paused;
// 重置立即执行标志;
if (triggered) {
triggered = false;
} else { // 非立即执行。即,执行时间到了,或者没有下次执行时间。
goAhead = goAhead && !noFireTime;
if (goAhead && triggerObj != null) { // 执行时间到了,更新执行时间;没有下次执行时间,不更新时间,并且不执行作业
triggerObj.triggered(null);
}
}
}
if (goAhead) {
job.execute();
}
} catch (RuntimeException e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, job.getJobName(), e.getMessage()), e);
}
}
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public RegistryCenterConfiguration findConfig(String nameAndNamespace) {
if(Strings.isNullOrEmpty(nameAndNamespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: zkCluster.getRegCenterConfList()) {
if (each != null && nameAndNamespace.equals(each.getNameAndNamespace())) {
return each;
}
}
}
return null;
}
|
#vulnerable code
@Override
public RegistryCenterConfiguration findConfig(String nameAndNamespace) {
if(Strings.isNullOrEmpty(nameAndNamespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if (each != null && nameAndNamespace.equals(each.getNameAndNamespace())) {
return each;
}
}
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.