instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPostUTF8() {
HttpResponse response = Unirest.post(MockServer.POSTJSON)
.header("accept", "application/json")
.field("param3", "こんにちは")
.asJson();
FormCapture json = TestUtils.read(response, FormCapture.class);
json.assertQuery("param3", "こんにちは");
} | #vulnerable code
@Test
public void testPostUTF8() {
HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").asJson();
assertEquals(response.getBody().getObject().getJSONObject("form").getString("param3"), "こんにちは");
}
#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 testPostArray() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.post(MockServer.POST)
.field("name", "Mark")
.field("name", "Tom")
.asJson();
parse(response)
.assertParam("name", "Mark")
.assertParam("name", "Tom");
} | #vulnerable code
@Test
public void testPostArray() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson();
JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name");
assertEquals(2, names.length());
assertEquals("Mark", names.getString(0));
assertEquals("Tom", names.getString(1));
}
#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 testRequests() throws JSONException {
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("param1", "value1")
.field("param2","bye")
.asJson();
assertTrue(jsonResponse.getHeaders().size() > 0);
assertTrue(jsonResponse.getBody().toString().length() > 0);
assertFalse(jsonResponse.getRawBody() == null);
assertEquals(200, jsonResponse.getCode());
JsonNode json = jsonResponse.getBody();
assertFalse(json.isArray());
assertNotNull(json.getObject());
assertNotNull(json.getArray());
assertEquals(1, json.getArray().length());
assertNotNull(json.getArray().get(0));
} | #vulnerable code
@Test
public void testRequests() throws Exception {
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
.header("accept", "application/json")
.field("param1", "value1")
.field("param2","bye")
.asJson();
assertTrue(jsonResponse.getHeaders().size() > 0);
assertTrue(jsonResponse.getBody().toString().length() > 0);
assertFalse(jsonResponse.getRawBody() == null);
assertEquals(200, jsonResponse.getCode());
JsonNode json = jsonResponse.getBody();
assertFalse(json.isArray());
assertNotNull(json.getObject());
assertNotNull(json.getArray());
assertEquals(1, json.getArray().length());
assertNotNull(json.getArray().get(0));
}
#location 10
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public boolean isStarted() {
try {
lock.lock();
return client.getState() == CuratorFrameworkState.STARTED;
} finally {
lock.unlock();
}
} | #vulnerable code
public boolean isStarted() {
return client.getState() == CuratorFrameworkState.STARTED;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSourceSinkStartResumeRollingEverySecond() throws Exception {
//This is the config that is required to make the VanillaChronicle roll every second
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
assertNotNull(sourceBasePath);
assertNotNull(sinkBasePath);
final Chronicle source = ChronicleQueueBuilder.source(
ChronicleQueueBuilder.vanilla(sourceBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build())
.bindAddress("localhost", BASE_PORT + 104)
.build();
ExcerptAppender appender = source.createAppender();
System.out.print("writing 100 items will take take 10 seconds.");
for (int i = 0; i < 100; i++) {
appender.startExcerpt();
int value = 1000000000 + i;
appender.append(value).append(' '); //this space is really important.
appender.finish();
Thread.sleep(100);
if(i % 10==0) {
System.out.print(".");
}
}
appender.close();
System.out.print("\n");
//create a tailer to get the first 50 items then exit the tailer
final Chronicle sink1 = ChronicleQueueBuilder.sink(
ChronicleQueueBuilder.vanilla(sinkBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build())
.connectAddress("localhost", BASE_PORT + 104)
.build();
final ExcerptTailer tailer1 = sink1.createTailer().toStart();
System.out.println("Sink1 reading first 50 items then stopping");
for( int count=0; count < 50 ;) {
if(tailer1.nextIndex()) {
assertEquals(1000000000 + count, tailer1.parseLong());
tailer1.finish();
count++;
}
}
tailer1.close();
sink1.close();
//TODO: fix sink1.checkCounts(1, 1);
//now resume the tailer to get the first 50 items
final Chronicle sink2 = ChronicleQueueBuilder.sink(
ChronicleQueueBuilder.vanilla(sinkBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build())
.connectAddress("localhost", BASE_PORT + 104)
.build();
//Take the tailer to the last index (item 50) and start reading from there.
final ExcerptTailer tailer2 = sink2.createTailer().toEnd();
assertEquals(1000000000 + 49, tailer2.parseLong());
tailer2.finish();
System.out.println("Sink2 restarting to continue to read the next 50 items");
for(int count=50 ; count < 100 ; ) {
if(tailer2.nextIndex()) {
assertEquals(1000000000 + count, tailer2.parseLong());
tailer2.finish();
count++;
}
}
tailer2.close();
sink2.close();
//TODO: fix sink2.checkCounts(1, 1);
sink2.clear();
source.close();
//TODO: fix source.checkCounts(1, 1);
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
} | #vulnerable code
@Test
public void testSourceSinkStartResumeRollingEverySecond() throws Exception {
//This is the config that is required to make the VanillaChronicle roll every second
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
assertNotNull(sourceBasePath);
assertNotNull(sinkBasePath);
final ChronicleSource source = new ChronicleSource(
ChronicleQueueBuilder.vanilla(sourceBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build(),
8888);
ExcerptAppender appender = source.createAppender();
System.out.print("writing 100 items will take take 10 seconds.");
for (int i = 0; i < 100; i++) {
appender.startExcerpt();
int value = 1000000000 + i;
appender.append(value).append(' '); //this space is really important.
appender.finish();
Thread.sleep(100);
if(i % 10==0) {
System.out.print(".");
}
}
appender.close();
System.out.print("\n");
//create a tailer to get the first 50 items then exit the tailer
final ChronicleSink sink1 = new ChronicleSink(
ChronicleQueueBuilder.vanilla(sinkBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build(),
"localhost",
8888);
final ExcerptTailer tailer1 = sink1.createTailer().toStart();
System.out.println("Sink1 reading first 50 items then stopping");
for( int count=0; count < 50 ;) {
if(tailer1.nextIndex()) {
assertEquals(1000000000 + count, tailer1.parseLong());
tailer1.finish();
count++;
}
}
tailer1.close();
sink1.close();
sink1.checkCounts(1, 1);
//now resume the tailer to get the first 50 items
final ChronicleSink sink2 = new ChronicleSink(
ChronicleQueueBuilder.vanilla(sinkBasePath)
.entriesPerCycle(1L << 20)
.cycleLength(1000, false)
.cycleFormat("yyyyMMddHHmmss")
.indexBlockSize(16L << 10)
.build(),
"localhost",
8888);
//Take the tailer to the last index (item 50) and start reading from there.
final ExcerptTailer tailer2 = sink2.createTailer().toEnd();
assertEquals(1000000000 + 49, tailer2.parseLong());
tailer2.finish();
System.out.println("Sink2 restarting to continue to read the next 50 items");
for(int count=50 ; count < 100 ; ) {
if(tailer2.nextIndex()) {
assertEquals(1000000000 + count, tailer2.parseLong());
tailer2.finish();
count++;
}
}
tailer2.close();
sink2.close();
sink2.checkCounts(1, 1);
sink2.clear();
source.close();
source.checkCounts(1, 1);
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
#location 30
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(
new VanillaChronicle(sourceBasePath), 0);
final ChronicleSink sink = new ChronicleSink(
new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort());
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
} | #vulnerable code
@Test
public void testReplication1() throws IOException {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(new VanillaChronicle(sourceBasePath), 0);
final ChronicleSink sink = new ChronicleSink(new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort());
try {
final ExcerptAppender appender = source.createAppender();
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
while(!tailer.nextIndex());
long val = tailer.parseLong();
//System.out.println("" + val);
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
appender.close();
tailer.close();
} finally {
sink.close();
sink.checkCounts(1, 1);
sink.clear();
source.close();
source.checkCounts(1, 1);
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
}
#location 32
#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... ignored) throws IOException {
String basePath = TMP + "/ExampleCacheMain";
ChronicleTools.deleteOnExit(basePath);
CachePerfMain map = new CachePerfMain(basePath, 64);
buildkeylist(keys);
long duration;
for (int i = 0; i < 2; i++) {
duration = putTest(keys, "base", map);
System.out.printf(i
+ "th iter: Took %.3f secs to put seq %,d entries%n",
duration / 1e9, keys);
}
for (int i = 0; i < 2; i++) {
duration = getTest(keys, map);
System.out.printf(i
+ "th iter: Took %.3f secs to get seq %,d entries%n",
duration / 1e9, keys);
}
shufflelist();
for (int i = 0; i < 2; i++) {
System.gc();
duration = getTest(keys, map);
System.out.printf(i
+ "th iter: Took %.3f secs to get random %,d entries%n",
duration / 1e9, keys);
}
for (int i = 0; i < 2; i++) {
duration = putTest(keys, "modif", map);
System.out
.printf(i
+ "th iter: Took %.3f secs to update random %,d entries%n",
duration / 1e9, keys);
}
} | #vulnerable code
public static void main(String... ignored) throws IOException {
String basePath = TMP + "/ExampleCacheMain";
ChronicleTools.deleteOnExit(basePath);
CachePerfMain map = new CachePerfMain(basePath, 32);
long start = System.nanoTime();
buildkeylist(keys);
StringBuilder name = new StringBuilder();
StringBuilder surname = new StringBuilder();
Person person = new Person(name, surname, 0);
for (int i = 0; i < keys; i++) {
name.setLength(0);
name.append("name");
name.append(i);
surname.setLength(0);
surname.append("surname");
surname.append(i);
person.set_age(i % 100);
map.put(i, person);
}
long end = System.nanoTime();
System.out.printf("Took %.3f secs to add %,d entries%n",
(end - start) / 1e9, keys);
long duration;
for (int i = 0; i < 2; i++) {
duration = randomGet(keys, map);
System.out.printf(i
+ "th iter: Took %.3f secs to get seq %,d entries%n",
duration / 1e9, keys);
}
System.out.println("before shuffle");
shufflelist();
System.out.println("after shuffle");
for (int i = 0; i < 2; i++) {
System.gc();
duration = randomGet(keys, map);
System.out.printf(i
+ "th iter: Took %.3f secs to get random %,d entries%n",
duration / 1e9, keys);
}
}
#location 27
#vulnerability type CHECKERS_PRINTF_ARGS |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPricePublishing1() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 2)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 2)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
reader.read();
long start = System.nanoTime();
int prices = 12000000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | #vulnerable code
@Test
public void testPricePublishing1() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
reader.read();
long start = System.nanoTime();
int prices = 12000000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void shouldBeAbleToDumpReadOnlyQueueFile() throws Exception {
if (OS.isWindows())
return;
final File dataDir = DirectoryUtils.tempDir(DumpQueueMainTest.class.getSimpleName());
try (final SingleChronicleQueue queue = SingleChronicleQueueBuilder.
binary(dataDir).
build()) {
final ExcerptAppender excerptAppender = queue.acquireAppender();
excerptAppender.writeText("first");
excerptAppender.writeText("last");
final Path queueFile = Files.list(dataDir.toPath()).
filter(p -> p.toString().endsWith(SingleChronicleQueue.SUFFIX)).
findFirst().orElseThrow(() ->
new AssertionError("Could not find queue file in directory " + dataDir));
assertThat(queueFile.toFile().setWritable(false), is(true));
final CountingOutputStream countingOutputStream = new CountingOutputStream();
DumpQueueMain.dump(queueFile.toFile(), new PrintStream(countingOutputStream), Long.MAX_VALUE);
assertThat(countingOutputStream.bytes, is(not(0L)));
}
} | #vulnerable code
@Test
public void shouldBeAbleToDumpReadOnlyQueueFile() throws Exception {
if (OS.isWindows())
return;
final File dataDir = DirectoryUtils.tempDir(DumpQueueMainTest.class.getSimpleName());
final SingleChronicleQueue queue = SingleChronicleQueueBuilder.
binary(dataDir).
build();
final ExcerptAppender excerptAppender = queue.acquireAppender();
excerptAppender.writeText("first");
excerptAppender.writeText("last");
final Path queueFile = Files.list(dataDir.toPath()).
filter(p -> p.toString().endsWith(SingleChronicleQueue.SUFFIX)).
findFirst().orElseThrow(() ->
new AssertionError("Could not find queue file in directory " + dataDir));
assertThat(queueFile.toFile().setWritable(false), is(true));
final CountingOutputStream countingOutputStream = new CountingOutputStream();
DumpQueueMain.dump(queueFile.toFile(), new PrintStream(countingOutputStream), Long.MAX_VALUE);
assertThat(countingOutputStream.bytes, is(not(0L)));
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static long getCurrentQueueFileLength(final Path dataDir) throws IOException {
try (RandomAccessFile file = new RandomAccessFile(
Files.list(dataDir).filter(p -> p.toString().endsWith("cq4")).findFirst().
orElseThrow(AssertionError::new).toFile(), "r")) {
return file.length();
}
} | #vulnerable code
private static long getCurrentQueueFileLength(final Path dataDir) throws IOException {
return new RandomAccessFile(
Files.list(dataDir).filter(p -> p.toString().endsWith("cq4")).findFirst().
orElseThrow(AssertionError::new).toFile(), "r").length();
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPersistedLocalVanillaSink_001() throws Exception {
final int port = BASE_PORT + 301;
final String basePath = getVanillaTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build();
final Chronicle source = ChronicleQueueBuilder.source(chronicle)
.bindAddress("localhost", port)
.build();
final Chronicle sink = ChronicleQueueBuilder.sink(chronicle)
.sharedChronicle(true)
.connectAddress("localhost",port)
.build();
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
appender.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
} | #vulnerable code
@Test
public void testPersistedLocalVanillaSink_001() throws Exception {
final int port = BASE_PORT + 301;
final String basePath = getVanillaTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.vanilla(basePath).build();
final ChronicleSource source = new ChronicleSource(chronicle, port);
final Chronicle sink = localChronicleSink(chronicle, "localhost", port);
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
appender.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
}
#location 55
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void init() {
tableStore.doWithExclusiveLock(ts -> {
maxCycleValue = ts.acquireValueFor(HIGHEST_CREATED_CYCLE);
minCycleValue = ts.acquireValueFor(LOWEST_CREATED_CYCLE);
lock = ts.acquireValueFor(LOCK);
modCount = ts.acquireValueFor(MOD_COUNT);
if (lock.getVolatileValue() == Long.MIN_VALUE) {
lock.compareAndSwapValue(Long.MIN_VALUE, 0);
}
if (modCount.getVolatileValue() == Long.MIN_VALUE) {
modCount.compareAndSwapValue(Long.MIN_VALUE, 0);
}
return this;
});
} | #vulnerable code
@Override
public void init() {
final long timeoutAt = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(20L);
boolean warnedOnFailure = false;
while (System.currentTimeMillis() < timeoutAt) {
try (final FileChannel channel = FileChannel.open(tableStore.file().toPath(),
StandardOpenOption.WRITE);
final FileLock fileLock = channel.tryLock()) {
maxCycleValue = tableStore.acquireValueFor(HIGHEST_CREATED_CYCLE);
minCycleValue = tableStore.acquireValueFor(LOWEST_CREATED_CYCLE);
lock = tableStore.acquireValueFor(LOCK);
modCount = tableStore.acquireValueFor(MOD_COUNT);
if (lock.getVolatileValue() == Long.MIN_VALUE) {
lock.compareAndSwapValue(Long.MIN_VALUE, 0);
}
if (modCount.getVolatileValue() == Long.MIN_VALUE) {
modCount.compareAndSwapValue(Long.MIN_VALUE, 0);
}
return;
} catch (IOException | RuntimeException e) {
// failed to acquire the lock, wait until other operation completes
if (!warnedOnFailure) {
LOGGER.warn("Failed to acquire a lock on the directory-listing file: {}:{}. Retrying.",
e.getClass().getSimpleName(), e.getMessage());
warnedOnFailure = true;
}
Jvm.pause(50L);
}
}
throw new IllegalStateException("Unable to claim exclusive lock on file " + tableStore.file());
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPricePublishing2() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 3)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 3)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | #vulnerable code
@Test
public void testPricePublishing2() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 3);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 3);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 4)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 4)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | #vulnerable code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testFlowAroundSingleThreadedWriteDiffrentSizeBuffers() throws Exception {
for (int j = 23 + 34; j < 100; j++) {
try (DirectStore allocate = DirectStore.allocate(j)) {
final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes());
for (int i = 0; i < 50; i++) {
bytesRingBuffer.offer(output.clear());
assertEquals(EXPECTED, bytesRingBuffer.take(maxSize -> input.clear()).readUTF());
}
}
}
} | #vulnerable code
@Test
public void testFlowAroundSingleThreadedWriteDiffrentSizeBuffers() throws Exception {
for (int j = 23 + 34; j < 100; j++) {
try (DirectStore allocate = DirectStore.allocate(j)) {
final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes());
for (int i = 0; i < 50; i++) {
bytesRingBuffer.offer(output.clear());
assertEquals(EXPECTED, bytesRingBuffer.poll(input.clear()).readUTF());
}
}
}
}
#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 testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.vanilla(sourceBasePath)
.source()
.bindAddress("localhost", BASE_PORT + 101)
.build();
final Chronicle sink = ChronicleQueueBuilder.vanilla(sinkBasePath)
.sink()
.connectAddress("localhost", BASE_PORT + 101)
.build();
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
} | #vulnerable code
@Test
public void testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(
ChronicleQueueBuilder.vanilla(sourceBasePath).build(), 0);
final ChronicleSink sink = new ChronicleSink(
ChronicleQueueBuilder.vanilla(sinkBasePath).build(), "localhost", source.getLocalPort());
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
}
#location 62
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static void unlock(@NotNull String dir) {
File path = new File(dir);
if (!path.isDirectory()) {
System.err.println("Path argument must be a queue directory");
System.exit(1);
}
File storeFilePath = new File(path, QUEUE_METADATA_FILE);
if (!storeFilePath.exists()) {
System.err.println("Metadata file not found, nothing to unlock");
System.exit(0);
}
final TableStore<?> store = SingleTableBuilder.binary(storeFilePath, Metadata.NoMeta.INSTANCE).readOnly(false).build();
// appender lock
(new TableStoreWriteLock(store, BusyTimedPauser::new, 0L, "chronicle.append.lock")).forceUnlockLockAndDontWarn();
// write lock
(new TableStoreWriteLock(store, BusyTimedPauser::new, 0L)).forceUnlockLockAndDontWarn();
System.out.println("Done");
} | #vulnerable code
private static void unlock(@NotNull String dir) {
File path = new File(dir);
if (!path.isDirectory()) {
System.err.println("Path argument must be a queue directory");
System.exit(1);
}
File storeFilePath = new File(path, QUEUE_METADATA_FILE);
if (!storeFilePath.exists()) {
System.err.println("Metadata file not found, nothing to unlock");
System.exit(0);
}
TableStore store = SingleTableBuilder.binary(storeFilePath, Metadata.NoMeta.INSTANCE).readOnly(false).build();
TSQueueLock queueLock = new TSQueueLock(store, BusyTimedPauser::new, 0L);
// writeLock AKA appendLock
TableStoreWriteLock writeLock = new TableStoreWriteLock(store, BusyTimedPauser::new, 0L);
forceUnlock(queueLock);
forceUnlock(writeLock);
System.out.println("Done");
}
#location 20
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPersistedLocalIndexedSink_001() throws Exception {
final int port = BASE_PORT + 201;
final String basePath = getIndexedTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build();
final Chronicle source = ChronicleQueueBuilder.source(chronicle)
.bindAddress("localhost", port)
.build();
final Chronicle sink = ChronicleQueueBuilder.sink(chronicle)
.sharedChronicle(true)
.connectAddress("localhost", port)
.build();
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
}
appender.close();
} catch (Exception e) {
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i - 1, tailer1.index());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
} | #vulnerable code
@Test
public void testPersistedLocalIndexedSink_001() throws Exception {
final int port = BASE_PORT + 201;
final String basePath = getIndexedTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build();
final ChronicleSource source = new ChronicleSource(chronicle, port);
final Chronicle sink = localChronicleSink(chronicle, "localhost", port);
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
}
appender.close();
} catch (Exception e) {
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i - 1, tailer1.index());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
}
#location 55
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@NotNull
private WireStore acquireStore(final long cycle, final long epoch) {
@NotNull final RollCycle rollCycle = builder.rollCycle();
@NotNull final String cycleFormat = this.dateCache.formatFor(cycle);
@NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX);
try {
final File parentFile = cycleFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
final WireType wireType = builder.wireType();
final MappedBytes mappedBytes = mappedBytes(builder, cycleFile);
//noinspection PointlessBitwiseExpression
if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA
| Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) {
final SingleChronicleQueueStore wireStore = new
SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch);
final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4);
wireType.apply(bytes).getValueOut().typedMarshallable(wireStore);
final long length = bytes.writePosition();
wireStore.install(
length,
true,
cycle,
builder
);
mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large"));
return wireStore;
} else {
long end = System.currentTimeMillis() + TIMEOUT;
while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) {
if (System.currentTimeMillis() > end) {
throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile);
}
Jvm.pause(1);
}
mappedBytes.readPosition(0);
mappedBytes.writePosition(mappedBytes.capacity());
final int len = Wires.lengthOf(mappedBytes.readVolatileInt());
final long length = mappedBytes.readPosition() + len;
mappedBytes.readLimit(length);
//noinspection unchecked
final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable();
wireStore.install(length, false, cycle, builder);
return wireStore;
}
} catch (FileNotFoundException e) {
throw Jvm.rethrow(e);
}
} | #vulnerable code
@NotNull
private WireStore acquireStore(final long cycle, final long epoch) {
@NotNull final RollCycle rollCycle = builder.rollCycle();
@NotNull final String cycleFormat = this.dateCache.formatFor(cycle);
@NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX);
try {
final File parentFile = cycleFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
final WireType wireType = builder.wireType();
final MappedBytes mappedBytes = mappedBytes(builder, cycleFile);
//noinspection PointlessBitwiseExpression
if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA
| Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) {
final SingleChronicleQueueStore wireStore = new
SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch);
final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4);
wireType.apply(bytes).getValueOut().typedMarshallable(wireStore);
final long length = bytes.writePosition();
final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, true);
wiredBytes.delegate().install(
wiredBytes.headerLength(),
wiredBytes.headerCreated(),
cycle,
builder
);
mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large"));
return wiredBytes.delegate();
} else {
long end = System.currentTimeMillis() + TIMEOUT;
while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) {
if (System.currentTimeMillis() > end) {
throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile);
}
Jvm.pause(1);
}
mappedBytes.readPosition(0);
mappedBytes.writePosition(mappedBytes.capacity());
final int len = Wires.lengthOf(mappedBytes.readVolatileInt());
final long length = mappedBytes.readPosition() + len;
mappedBytes.readLimit(length);
//noinspection unchecked
final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable();
final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, false);
wiredBytes.delegate().install(
wiredBytes.headerLength(),
wiredBytes.headerCreated(),
cycle,
builder);
return wiredBytes.delegate();
}
} catch (FileNotFoundException e) {
throw Jvm.rethrow(e);
}
}
#location 37
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testWriteAndRead() throws Exception {
try (DirectStore allocate = DirectStore.allocate(150)) {
final BytesRingBuffer bytesRingBuffer = new BytesRingBuffer(allocate.bytes());
bytesRingBuffer.offer(output.clear());
Bytes actual = bytesRingBuffer.take(maxSize -> input.clear());
assertEquals(EXPECTED, actual.readUTF());
}
} | #vulnerable code
@Test
public void testWriteAndRead() throws Exception {
try (DirectStore allocate = DirectStore.allocate(150)) {
final BytesQueue bytesRingBuffer = new BytesQueue(allocate.bytes());
bytesRingBuffer.offer(output.clear());
Bytes poll = bytesRingBuffer.poll(input.clear());
assertEquals(EXPECTED, poll.readUTF());
}
}
#location 8
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public long exceptsPerCycle(int cycle) {
StoreTailer tailer = acquireTailer();
try {
long index = rollCycle.toIndex(cycle, 0);
if (tailer.moveToIndex(index)) {
assert tailer.store != null && tailer.store.refCount() > 0;
return tailer.store.lastSequenceNumber(tailer) + 1;
} else {
return -1;
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} finally {
tailer.release();
}
} | #vulnerable code
public long exceptsPerCycle(int cycle) {
StoreTailer tailer = acquireTailer();
try {
long index = rollCycle.toIndex(cycle, 0);
if (tailer.moveToIndex(index)) {
assert tailer.store.refCount() > 0;
return tailer.store.lastSequenceNumber(tailer) + 1;
} else {
return -1;
}
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} finally {
tailer.release();
}
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.vanilla(sourceBasePath)
.source()
.bindAddress("localhost", BASE_PORT + 101)
.build();
final Chronicle sink = ChronicleQueueBuilder.vanilla(sinkBasePath)
.sink()
.connectAddress("localhost", BASE_PORT + 101)
.build();
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
} | #vulnerable code
@Test
public void testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(
ChronicleQueueBuilder.vanilla(sourceBasePath).build(), 0);
final ChronicleSink sink = new ChronicleSink(
ChronicleQueueBuilder.vanilla(sinkBasePath).build(), "localhost", source.getLocalPort());
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
}
#location 59
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 4)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 4)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | #vulnerable code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
int lastIndexFile(int cycle) {
return lastIndexFile(cycle, 0);
} | #vulnerable code
int lastIndexFile(int cycle, int defaultCycle) {
int maxIndex = -1;
final File cyclePath = new File(baseFile, dateCache.formatFor(cycle));
final File[] files = cyclePath.listFiles();
if (files != null) {
for (final File file : files) {
String name = file.getName();
if (name.startsWith(FILE_NAME_PREFIX)) {
int index = Integer.parseInt(name.substring(FILE_NAME_PREFIX.length()));
if (maxIndex < index) {
maxIndex = index;
}
}
}
}
return maxIndex != -1 ? maxIndex : defaultCycle;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public synchronized LongValue acquireValueFor(CharSequence key) {
StringBuilder sb = Wires.acquireStringBuilder();
mappedBytes.reserve();
try {
mappedBytes.readPosition(0);
mappedBytes.readLimit(mappedBytes.realCapacity());
while (mappedWire.readDataHeader()) {
int header = mappedBytes.readInt();
if (Wires.isNotComplete(header))
break;
long readPosition = mappedBytes.readPosition();
int length = Wires.lengthOf(header);
ValueIn valueIn = mappedWire.readEventName(sb);
if (StringUtils.equalsCaseIgnore(key, sb)) {
return valueIn.int64ForBinding(null);
}
mappedBytes.readPosition(readPosition + length);
}
// not found
int safeLength = Maths.toUInt31(mappedBytes.realCapacity() - mappedBytes.readPosition());
mappedBytes.writeLimit(mappedBytes.realCapacity());
mappedBytes.writePosition(mappedBytes.readPosition());
long pos = recovery.writeHeader(mappedWire, Wires.UNKNOWN_LENGTH, safeLength, timeoutMS, null);
LongValue longValue = wireType.newLongReference().get();
mappedWire.writeEventName(key).int64forBinding(Long.MIN_VALUE, longValue);
mappedWire.updateHeader(pos, false);
return longValue;
} catch (StreamCorruptedException | EOFException e) {
throw new IORuntimeException(e);
} finally {
mappedBytes.release();
}
} | #vulnerable code
@Override
public synchronized LongValue acquireValueFor(CharSequence key) {
StringBuilder sb = Wires.acquireStringBuilder();
mappedBytes.reserve();
try {
mappedBytes.readPosition(0);
mappedBytes.readLimit(mappedBytes.realCapacity());
while (mappedWire.readDataHeader()) {
int header = mappedBytes.readInt();
if (Wires.isNotComplete(header))
break;
long readPosition = mappedBytes.readPosition();
int length = Wires.lengthOf(header);
ValueIn valueIn = mappedWire.readEventName(sb);
if (StringUtils.equalsCaseIgnore(key, sb)) {
return valueIn.int64ForBinding(null);
}
mappedBytes.readPosition(readPosition + length);
}
// not found
int safeLength = Maths.toUInt31(mappedBytes.realCapacity() - mappedBytes.readPosition());
mappedBytes.writeLimit(mappedBytes.realCapacity());
mappedBytes.writePosition(mappedBytes.readPosition());
long pos = recovery.writeHeader(mappedWire, Wires.UNKNOWN_LENGTH, safeLength, 10_000, null);
LongValue longValue = wireType.newLongReference().get();
mappedWire.writeEventName(key).int64forBinding(Long.MIN_VALUE, longValue);
mappedWire.updateHeader(pos, false);
return longValue;
} catch (StreamCorruptedException | EOFException e) {
throw new IORuntimeException(e);
} finally {
mappedBytes.release();
}
}
#location 24
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Raft.VoteResponse requestVote(Raft.VoteRequest request) {
raftNode.getLock().lock();
try {
Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder();
responseBuilder.setGranted(false);
responseBuilder.setTerm(raftNode.getCurrentTerm());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
raftNode.stepDown(request.getTerm());
}
boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm()
|| (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm()
&& request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getVotedFor() == 0 && logIsOk) {
raftNode.stepDown(request.getTerm());
raftNode.setVotedFor(request.getServerId());
raftNode.getRaftLog().updateMetaData(raftNode.getCurrentTerm(), raftNode.getVotedFor(), null);
responseBuilder.setGranted(true);
responseBuilder.setTerm(raftNode.getCurrentTerm());
}
LOG.info("Receive RequestVote request from server {} " +
"in term {} (my term is {}), granted={}",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm(), responseBuilder.getGranted());
return responseBuilder.build();
} finally {
raftNode.getLock().unlock();
}
} | #vulnerable code
@Override
public Raft.VoteResponse requestVote(Raft.VoteRequest request) {
LOG.info("Receive RequestVote request from server {} " +
"in term {} (my term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
raftNode.getLock().lock();
try {
Raft.VoteResponse.Builder responseBuilder = Raft.VoteResponse.newBuilder();
responseBuilder.setGranted(false);
responseBuilder.setTerm(raftNode.getCurrentTerm());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
raftNode.stepDown(request.getTerm());
}
boolean logIsOk = request.getLastLogTerm() > raftNode.getRaftLog().getLastLogTerm()
|| (request.getLastLogTerm() == raftNode.getRaftLog().getLastLogTerm()
&& request.getLastLogIndex() >= raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getVotedFor() == 0 && logIsOk) {
raftNode.stepDown(request.getTerm());
raftNode.setVotedFor(request.getServerId());
raftNode.getRaftLog().updateMetaData(raftNode.getCurrentTerm(), raftNode.getVotedFor(), null);
responseBuilder.setGranted(true);
responseBuilder.setTerm(raftNode.getCurrentTerm());
}
return responseBuilder.build();
} finally {
raftNode.getLock().unlock();
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
raftNode.getLock().lock();
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
raftNode.stepDown(request.getTerm());
}
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
raftNode.getLock().unlock();
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// truncate segment log from index
long lastIndexKept = index - 1;
raftNode.getRaftLog().truncateSuffix(lastIndexKept);
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// apply state machine
for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) {
raftNode.getStateMachine().apply(
raftNode.getRaftLog().getEntry(index).getData().toByteArray());
}
}
raftNode.getLock().unlock();
return responseBuilder.build();
} | #vulnerable code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
responseBuilder.setTerm(request.getTerm());
}
raftNode.stepDown(request.getTerm());
raftNode.resetElectionTimer();
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// TODO: truncate segment log from index
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// TODO: apply state machine
}
return responseBuilder.build();
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
raftNode.getLock().lock();
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
raftNode.stepDown(request.getTerm());
}
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
raftNode.getLock().unlock();
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// truncate segment log from index
long lastIndexKept = index - 1;
raftNode.getRaftLog().truncateSuffix(lastIndexKept);
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// apply state machine
for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) {
raftNode.getStateMachine().apply(
raftNode.getRaftLog().getEntry(index).getData().toByteArray());
}
}
raftNode.getLock().unlock();
return responseBuilder.build();
} | #vulnerable code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
responseBuilder.setTerm(request.getTerm());
}
raftNode.stepDown(request.getTerm());
raftNode.resetElectionTimer();
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// TODO: truncate segment log from index
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// TODO: apply state machine
}
return responseBuilder.build();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void replicate(byte[] data) {
lock.lock();
Raft.LogEntry logEntry = Raft.LogEntry.newBuilder()
.setTerm(currentTerm)
.setType(Raft.EntryType.ENTRY_TYPE_DATA)
.setData(ByteString.copyFrom(data)).build();
List<Raft.LogEntry> entries = new ArrayList<>();
entries.add(logEntry);
long newLastLogIndex = raftLog.append(entries);
for (final Peer peer : peers) {
executorService.submit(new Runnable() {
@Override
public void run() {
appendEntries(peer);
}
});
}
// sync wait condition commitIndex >= newLastLogIndex
// TODO: add timeout
try {
while (commitIndex < newLastLogIndex) {
try {
commitIndexCondition.await();
} catch (InterruptedException ex) {
LOG.warn(ex.getMessage());
}
}
} finally {
lock.unlock();
}
} | #vulnerable code
public void replicate(byte[] data) {
Raft.LogEntry logEntry = Raft.LogEntry.newBuilder()
.setTerm(currentTerm)
.setType(Raft.EntryType.ENTRY_TYPE_DATA)
.setData(ByteString.copyFrom(data)).build();
List<Raft.LogEntry> entries = new ArrayList<>();
entries.add(logEntry);
long newLastLogIndex = raftLog.append(entries);
for (final Peer peer : peers) {
executorService.submit(new Runnable() {
@Override
public void run() {
appendEntries(peer);
}
});
}
// sync wait condition commitIndex >= newLastLogIndex
// TODO: add timeout
lock.lock();
try {
while (commitIndex < newLastLogIndex) {
try {
commitIndexCondition.await();
} catch (InterruptedException ex) {
LOG.warn(ex.getMessage());
}
}
} finally {
lock.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 installSnapshot(Peer peer) {
Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder();
requestBuilder.setServerId(localServer.getServerId());
requestBuilder.setTerm(currentTerm);
// send snapshot
Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest(
null, 0, 0);
peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot",
request, new InstallSnapshotResponseCallback(peer, request));
isSnapshoting = true;
} | #vulnerable code
public void installSnapshot(Peer peer) {
Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder();
requestBuilder.setServerId(localServer.getServerId());
requestBuilder.setTerm(currentTerm);
// send snapshot
try {
snapshotLock.readLock().lock();
Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest(
null, 0, 0);
peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot",
request, new InstallSnapshotResponseCallback(peer, request));
isSnapshoting = true;
} finally {
snapshotLock.readLock().unlock();
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
raftNode.getLock().lock();
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
raftNode.stepDown(request.getTerm());
}
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
raftNode.getLock().unlock();
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// truncate segment log from index
long lastIndexKept = index - 1;
raftNode.getRaftLog().truncateSuffix(lastIndexKept);
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// apply state machine
for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) {
raftNode.getStateMachine().apply(
raftNode.getRaftLog().getEntry(index).getData().toByteArray());
}
}
raftNode.getLock().unlock();
return responseBuilder.build();
} | #vulnerable code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
responseBuilder.setTerm(request.getTerm());
}
raftNode.stepDown(request.getTerm());
raftNode.resetElectionTimer();
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// TODO: truncate segment log from index
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// TODO: apply state machine
}
return responseBuilder.build();
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void takeSnapshot() {
if (raftLog.getTotalSize() < RaftOption.snapshotMinLogSize) {
return;
}
if (lastAppliedIndex <= snapshot.getMetaData().getLastIncludedIndex()) {
return;
}
long lastAppliedTerm = 0;
if (lastAppliedIndex >= raftLog.getFirstLogIndex()
&& lastAppliedIndex <= raftLog.getLastLogIndex()) {
lastAppliedTerm = raftLog.getEntry(lastAppliedIndex).getTerm();
}
if (!isSnapshoting) {
isSnapshoting = true;
// take snapshot
String tmpSnapshotDir = snapshot.getSnapshotDir() + ".tmp";
snapshot.updateMetaData(tmpSnapshotDir, lastAppliedIndex, lastAppliedTerm);
String tmpSnapshotDataDir = tmpSnapshotDir + File.pathSeparator + "data";
stateMachine.writeSnapshot(tmpSnapshotDataDir);
try {
FileUtils.moveDirectory(new File(tmpSnapshotDir), new File(snapshot.getSnapshotDir()));
} catch (IOException ex) {
LOG.warn("move direct failed, msg={}", ex.getMessage());
}
}
} | #vulnerable code
public void takeSnapshot() {
if (raftLog.getTotalSize() < RaftOption.snapshotMinLogSize) {
return;
}
if (lastAppliedIndex <= lastSnapshotIndex) {
return;
}
long lastAppliedTerm = 0;
if (lastAppliedIndex >= raftLog.getStartLogIndex()
&& lastAppliedIndex <= raftLog.getLastLogIndex()) {
lastAppliedTerm = raftLog.getEntry(lastAppliedIndex).getTerm();
}
snapshotLock.writeLock().lock();
// take snapshot
String tmpSnapshotDir = snapshot.getSnapshotDir() + ".tmp";
snapshot.updateMetaData(tmpSnapshotDir, lastAppliedIndex, lastAppliedTerm);
String tmpSnapshotDataDir = tmpSnapshotDir + File.pathSeparator + "data";
stateMachine.writeSnapshot(tmpSnapshotDataDir);
try {
FileUtils.moveDirectory(new File(tmpSnapshotDir), new File(snapshot.getSnapshotDir()));
lastSnapshotIndex = lastAppliedIndex;
lastSnapshotTerm = lastAppliedTerm;
} catch (IOException ex) {
LOG.warn("move direct failed, msg={}", ex.getMessage());
}
snapshotLock.writeLock().unlock();
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) {
raftNode.getLock().lock();
Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
if (request.getTerm() < raftNode.getCurrentTerm()) {
LOG.info("Caller({}) is stale. Our term is {}, theirs is {}",
request.getServerId(), raftNode.getCurrentTerm(), request.getTerm());
raftNode.getLock().unlock();
return responseBuilder.build();
}
raftNode.stepDown(request.getTerm());
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
// write snapshot data to local
String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp";
File file = new File(tmpSnapshotDir);
if (file.exists() && request.getIsFirst()) {
file.delete();
file.mkdir();
}
if (request.getIsFirst()) {
raftNode.getSnapshot().updateMetaData(tmpSnapshotDir,
request.getSnapshotMetaData().getLastIncludedIndex(),
request.getSnapshotMetaData().getLastIncludedTerm());
}
// write to file
RandomAccessFile randomAccessFile = null;
try {
String currentDataFileName = tmpSnapshotDir + File.pathSeparator
+ "data" + File.pathSeparator + request.getFileName();
File currentDataFile = new File(currentDataFileName);
if (!currentDataFile.exists()) {
currentDataFile.createNewFile();
}
randomAccessFile = RaftFileUtils.openFile(
tmpSnapshotDir + File.pathSeparator + "data",
request.getFileName(), "rw");
randomAccessFile.skipBytes((int) request.getOffset());
randomAccessFile.write(request.getData().toByteArray());
if (randomAccessFile != null) {
try {
randomAccessFile.close();
randomAccessFile = null;
} catch (Exception ex2) {
LOG.warn("close failed");
}
}
// move tmp dir to snapshot dir if this is the last package
File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir());
if (snapshotDirFile.exists()) {
snapshotDirFile.delete();
}
FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile);
responseBuilder.setSuccess(true);
} catch (IOException ex) {
LOG.warn("io exception, msg={}", ex.getMessage());
} finally {
RaftFileUtils.closeFile(randomAccessFile);
}
raftNode.getLock().unlock();
return responseBuilder.build();
} | #vulnerable code
@Override
public Raft.InstallSnapshotResponse installSnapshot(Raft.InstallSnapshotRequest request) {
Raft.InstallSnapshotResponse.Builder responseBuilder = Raft.InstallSnapshotResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
raftNode.getLock().lock();
if (request.getTerm() < raftNode.getCurrentTerm()) {
LOG.info("Caller({}) is stale. Our term is {}, theirs is {}",
request.getServerId(), raftNode.getCurrentTerm(), request.getTerm());
raftNode.getLock().unlock();
return responseBuilder.build();
}
raftNode.stepDown(request.getTerm());
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
raftNode.getLock().unlock();
// write snapshot data to local
String tmpSnapshotDir = raftNode.getSnapshot().getSnapshotDir() + ".tmp";
File file = new File(tmpSnapshotDir);
if (file.exists() && request.getIsFirst()) {
file.delete();
file.mkdir();
}
if (request.getIsFirst()) {
raftNode.getSnapshot().updateMetaData(tmpSnapshotDir,
request.getSnapshotMetaData().getLastIncludedIndex(),
request.getSnapshotMetaData().getLastIncludedTerm());
}
// write to file
RandomAccessFile randomAccessFile = null;
try {
String currentDataFileName = tmpSnapshotDir + File.pathSeparator
+ "data" + File.pathSeparator + request.getFileName();
File currentDataFile = new File(currentDataFileName);
if (!currentDataFile.exists()) {
currentDataFile.createNewFile();
}
randomAccessFile = RaftFileUtils.openFile(
tmpSnapshotDir + File.pathSeparator + "data",
request.getFileName(), "rw");
randomAccessFile.skipBytes((int) request.getOffset());
randomAccessFile.write(request.getData().toByteArray());
if (randomAccessFile != null) {
try {
randomAccessFile.close();
randomAccessFile = null;
} catch (Exception ex2) {
LOG.warn("close failed");
}
}
// move tmp dir to snapshot dir if this is the last package
File snapshotDirFile = new File(raftNode.getSnapshot().getSnapshotDir());
if (snapshotDirFile.exists()) {
snapshotDirFile.delete();
}
FileUtils.moveDirectory(new File(tmpSnapshotDir), snapshotDirFile);
responseBuilder.setSuccess(true);
} catch (IOException ex) {
LOG.warn("io exception, msg={}", ex.getMessage());
} finally {
RaftFileUtils.closeFile(randomAccessFile);
}
return responseBuilder.build();
}
#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 installSnapshot(Peer peer) {
Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder();
requestBuilder.setServerId(localServer.getServerId());
requestBuilder.setTerm(currentTerm);
// send snapshot
Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest(
null, 0, 0);
peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot",
request, new InstallSnapshotResponseCallback(peer, request));
isSnapshoting = true;
} | #vulnerable code
public void installSnapshot(Peer peer) {
Raft.InstallSnapshotRequest.Builder requestBuilder = Raft.InstallSnapshotRequest.newBuilder();
requestBuilder.setServerId(localServer.getServerId());
requestBuilder.setTerm(currentTerm);
// send snapshot
try {
snapshotLock.readLock().lock();
Raft.InstallSnapshotRequest request = this.buildInstallSnapshotRequest(
null, 0, 0);
peer.getRpcClient().asyncCall("RaftConsensusService.installSnapshot",
request, new InstallSnapshotResponseCallback(peer, request));
isSnapshoting = true;
} finally {
snapshotLock.readLock().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 replicate(byte[] data) {
lock.lock();
Raft.LogEntry logEntry = Raft.LogEntry.newBuilder()
.setTerm(currentTerm)
.setType(Raft.EntryType.ENTRY_TYPE_DATA)
.setData(ByteString.copyFrom(data)).build();
List<Raft.LogEntry> entries = new ArrayList<>();
entries.add(logEntry);
long newLastLogIndex = raftLog.append(entries);
for (final Peer peer : peers) {
executorService.submit(new Runnable() {
@Override
public void run() {
appendEntries(peer);
}
});
}
// sync wait condition commitIndex >= newLastLogIndex
// TODO: add timeout
try {
while (commitIndex < newLastLogIndex) {
try {
commitIndexCondition.await();
} catch (InterruptedException ex) {
LOG.warn(ex.getMessage());
}
}
} finally {
lock.unlock();
}
} | #vulnerable code
public void replicate(byte[] data) {
Raft.LogEntry logEntry = Raft.LogEntry.newBuilder()
.setTerm(currentTerm)
.setType(Raft.EntryType.ENTRY_TYPE_DATA)
.setData(ByteString.copyFrom(data)).build();
List<Raft.LogEntry> entries = new ArrayList<>();
entries.add(logEntry);
long newLastLogIndex = raftLog.append(entries);
for (final Peer peer : peers) {
executorService.submit(new Runnable() {
@Override
public void run() {
appendEntries(peer);
}
});
}
// sync wait condition commitIndex >= newLastLogIndex
// TODO: add timeout
lock.lock();
try {
while (commitIndex < newLastLogIndex) {
try {
commitIndexCondition.await();
} catch (InterruptedException ex) {
LOG.warn(ex.getMessage());
}
}
} finally {
lock.unlock();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Set<String> getURLTokens(String path) {
List<String> tokens = FileHelper.processFile(path, br -> {
List<String> ts = new ArrayList<>();
String s;
while ((s = br.readLine()) != null) {
ts.add(s);
}
return ts;
}).orElse(new ArrayList<>());
return new HashSet<>(tokens);
} | #vulnerable code
public Set<String> getURLTokens(String path) {
Set<String> urlTokens = new HashSet<>();
BufferedReader in;
try {
in = new BufferedReader(
new FileReader(new File(path))
);
String s;
while ((s = in.readLine()) != null) {
urlTokens.add(s);
}
in.close();
return urlTokens;
} catch (IOException e) {
logger.error("IOException when readFollowees user data from file : {}", e);
return null;
}
}
#location 16
#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) {
ElasticsearchUploader esUploader = new ElasticsearchUploader();
ElasticsearchUploader.logger.info("aaa");
} | #vulnerable code
public static void main(String[] args) {
TransportClient client = null;
try {
// on startup
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));
// on shutdown
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
#location 6
#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) {
ZhihuConfiguration configuration = new ZhihuConfiguration();
String pipelinePath = configuration.getMemberPath();
Spider spider = Spider.create(new ZhihuMemberPageProcessor())
.setScheduler(new FixedFileCacheQueueScheduler(pipelinePath))
.addPipeline(new ZhihuMemberPipeline(pipelinePath))
.thread(20);
ZhihuMemberUrlTokenGetter getter = new ZhihuMemberUrlTokenGetter();
for (String token : getter.getUrlTokens()) {
spider.addUrl(generateMemberUrl(token));
}
spider.run();
} | #vulnerable code
public static void main(String[] args) {
String pipelinePath = "/Users/brian/todo/data/webmagic";
String tokenPath = "/Users/brian/todo/data/backup/url_tokens/users.txt";
ZhihuMemberUrlTokenGetter getter = new ZhihuMemberUrlTokenGetter();
Spider spider = Spider.create(new ZhihuMemberPageProcessor())
.setScheduler(new FixedFileCacheQueueScheduler(pipelinePath))
.addPipeline(new ZhihuMemberPipeline(pipelinePath))
.thread(20);
for (String token : getter.getUrlTokens(tokenPath)) {
spider.addUrl(generateMemberUrl(token));
}
spider.run();
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) {
final JsonObject hostJson = readHostJson();
final JsonObject extensionBundle = hostJson == null ? null : hostJson.getAsJsonObject(EXTENSION_BUNDLE);
if (extensionBundle != null && extensionBundle.has("id") &&
StringUtils.equalsIgnoreCase(extensionBundle.get("id").getAsString(), EXTENSION_BUNDLE_ID)) {
getLog().info(SKIP_INSTALL_EXTENSIONS_BUNDLE);
return false;
}
final boolean isNonHttpTriggersExist = bindingTypes.stream().anyMatch(binding ->
!Arrays.asList(FUNCTION_WITHOUT_FUNCTION_EXTENSION).contains(binding));
if (!isNonHttpTriggersExist) {
getLog().info(SKIP_INSTALL_EXTENSIONS_HTTP);
return false;
}
return true;
} | #vulnerable code
protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) {
final JsonObject hostJson = readHostJson();
final JsonObject extensionBundle = hostJson.getAsJsonObject(EXTENSION_BUNDLE);
if (extensionBundle != null && extensionBundle.has("id") &&
StringUtils.equalsIgnoreCase(extensionBundle.get("id").getAsString(), EXTENSION_BUNDLE_ID)) {
getLog().info(SKIP_INSTALL_EXTENSIONS_BUNDLE);
return false;
}
final boolean isNonHttpTriggersExist = bindingTypes.stream().anyMatch(binding ->
!Arrays.asList(FUNCTION_WITHOUT_FUNCTION_EXTENSION).contains(binding));
if (!isNonHttpTriggersExist) {
getLog().info(SKIP_INSTALL_EXTENSIONS_HTTP);
return false;
}
return 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 testGetAzureTokenCredentials() throws Exception {
// 1. use azure-secret.json
File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(null);
assertNotNull(cred);
assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId());
// 2. use azure cli(non SP)
testConfigDir = new File(this.getClass().getResource("/azure-cli/default/azureProfile.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials();
assertNotNull(cred);
assertTrue(cred instanceof AzureCliCredentials);
final AzureCliCredentials cliCred = (AzureCliCredentials) cred;
assertEquals("00000000-0000-0000-0000-000000000001", cliCred.defaultSubscriptionId());
assertEquals("00000000-0000-0000-0000-000000000002", cliCred.clientId());
assertEquals("00000000-0000-0000-0000-000000000003", cliCred.domain());
assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment());
// 3. use azure cli(SP)
testConfigDir = new File(this.getClass().getResource("/azure-cli/sp/azureProfile.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials();
assertNotNull(cred);
assertTrue(cred instanceof AzureCliCredentials);
final AzureCliCredentials azureCliCredential = (AzureCliCredentials) cred;
assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId());
assertEquals("00000000-0000-0000-0000-000000000002", azureCliCredential.clientId());
assertEquals("00000000-0000-0000-0000-000000000003", cred.domain());
assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment());
// 4. use cloud shell
TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure");
assertTrue(AzureAuthHelper.isInCloudShell());
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "non-exist-folder");
cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials();
assertNotNull(cred);
assertTrue(cred instanceof MSICredentials);
// 5. all of the ways have been tried
TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null);
assertNull(AzureAuthHelper.getAzureTokenCredentials(null));
} | #vulnerable code
@Test
public void testGetAzureTokenCredentials() throws Exception {
// 1. use azure-secret.json
File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(null);
assertNotNull(cred);
assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId());
// 2. use azure cli(non SP)
testConfigDir = new File(this.getClass().getResource("/azure-cli/default/azureProfile.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
cred = AzureAuthHelper.getAzureTokenCredentials(null);
assertNotNull(cred);
assertTrue(cred instanceof AzureCliCredentials);
final AzureCliCredentials cliCred = (AzureCliCredentials) cred;
assertEquals("00000000-0000-0000-0000-000000000001", cliCred.defaultSubscriptionId());
assertEquals("00000000-0000-0000-0000-000000000002", cliCred.clientId());
assertEquals("00000000-0000-0000-0000-000000000003", cliCred.domain());
assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment());
// 3. use azure cli(SP)
testConfigDir = new File(this.getClass().getResource("/azure-cli/sp/azureProfile.json").getFile()).getParentFile();
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath());
cred = AzureAuthHelper.getAzureTokenCredentials(null);
assertNotNull(cred);
assertTrue(cred instanceof AzureCliCredentials);
final AzureCliCredentials azureCliCredential = (AzureCliCredentials) cred;
assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId());
assertEquals("00000000-0000-0000-0000-000000000002", azureCliCredential.clientId());
assertEquals("00000000-0000-0000-0000-000000000003", cred.domain());
assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment());
// 4. use cloud shell
TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure");
assertTrue(AzureAuthHelper.isInCloudShell());
TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "non-exist-folder");
cred = AzureAuthHelper.getAzureTokenCredentials(null);
assertNotNull(cred);
assertTrue(cred instanceof MSICredentials);
// 5. all of the ways have been tried
TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null);
assertNull(AzureAuthHelper.getAzureTokenCredentials(null));
}
#location 17
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#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 prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#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() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
if (printProcDoc) {
PropDocReader docReader = new PropDocReader(ctx);
docReader.load();
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
} | #vulnerable code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
if (printProcDoc) {
PropDocReader docReader = new PropDocReader(ctx);
docReader.load();
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 依次启动
try {
ctx.init();
ctx.startServers();
if (mainClass.getAnnotation(IocBean.class) != null)
ctx.getIoc().get(mainClass);
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareStarterClassList() throws Exception {
HashSet<String> classNames = new HashSet<>();
Enumeration<URL> _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter");
while (_en.hasMoreElements()) {
URL url = _en.nextElement();
log.debug("Found " + url);
try (InputStream ins = url.openStream()) {
InputStreamReader reader = new InputStreamReader(ins);
String tmp = Streams.readAndClose(reader);
if (!Strings.isBlank(tmp)) {
for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) {
String className = _tmp.trim();
if (!classNames.add(className))
continue;
Class<?> klass = ctx.getClassLoader().loadClass(className);
if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) {
starterIocLoader.addClass(klass);
}
starterClasses.add(klass);
}
}
}
}
} | #vulnerable code
public void prepareStarterClassList() throws Exception {
starterClasses = new ArrayList<>();
HashSet<String> classNames = new HashSet<>();
Enumeration<URL> _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter");
while (_en.hasMoreElements()) {
URL url = _en.nextElement();
log.debug("Found " + url);
try (InputStream ins = url.openStream()) {
InputStreamReader reader = new InputStreamReader(ins);
String tmp = Streams.readAndClose(reader);
if (!Strings.isBlank(tmp)) {
for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) {
String className = _tmp.trim();
if (!classNames.add(className))
continue;
Class<?> klass = ctx.getClassLoader().loadClass(className);
if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) {
starterIocLoader.addClass(klass);
}
starterClasses.add(klass);
}
}
}
}
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#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 prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#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 prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
if (getAppContext().getConf().get("nutz.propdoc.packages") != null) {
for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) {
for (Class<?> klass : Scans.me().scanPackage(pkg)) {
if (klass.isInterface())
continue;
docReader.addClass(klass);
}
}
}
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
} | #vulnerable code
public void prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
}
#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() {
try {
if (execute()) {
synchronized (lock) {
lock.wait();
}
}
// 收尾
_shutdown();
}
catch (Throwable e) {
Logs.get().error("something happen", e);
}
} | #vulnerable code
public void run() {
try {
_run();
}
catch (Throwable e) {
Logs.get().error("something happen", e);
}
}
#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 prepareIoc() {
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf()));
ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this));
}
} | #vulnerable code
public void prepareIoc() throws Exception {
if (ctx.getComboIocLoader() == null) {
int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64);
List<String> args = new ArrayList<>();
args.add("*js");
args.add("ioc/");
args.add("*tx");
args.add("*async");
args.add(""+asyncPoolSize);
args.add("*anno");
args.add(ctx.getPackage());
IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class);
if (iocBy != null) {
String[] tmp = iocBy.args();
ArrayList<String> _args = new ArrayList<>();
for (int i=0;i<tmp.length;i++) {
if (tmp[i].startsWith("*")) {
if (!_args.isEmpty()) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
_args.clear();
}
}
_args.add(tmp[i]);
}
if (_args.size() > 0) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
}
}
ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()])));
}
// 用于加载Starter的IocLoader
starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter");
ctx.getComboIocLoader().addLoader(starterIocLoader);
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf()));
ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this));
}
}
#location 45
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void init() throws Exception {
// 创建基础服务器
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setIdleTimeout(getThreadPoolIdleTimeout());
threadPool.setMinThreads(getMinThreads());
threadPool.setMaxThreads(getMaxThreads());
server = new Server(threadPool);
HttpConfiguration httpConfig = conf.make(HttpConfiguration.class, "jetty.httpConfig.");
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
connector = new ServerConnector(server, httpFactory);
connector.setHost(getHost());
connector.setPort(getPort());
connector.setIdleTimeout(getIdleTimeout());
server.setConnectors(new Connector[]{connector});
// 设置应用上下文
wac = new WebAppContext();
wac.setContextPath(getContextPath());
// wac.setExtractWAR(false);
// wac.setCopyWebInf(true);
// wac.setProtectedTargets(new String[]{"/java", "/javax", "/org",
// "/net", "/WEB-INF", "/META-INF"});
wac.setTempDirectory(new File("temp"));
wac.setClassLoader(classLoader);
wac.setConfigurationDiscovered(true);
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
wac.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
}
List<Resource> resources = new ArrayList<>();
for (String resourcePath : getResourcePaths()) {
File f = new File(resourcePath);
if (f.exists()) {
resources.add(Resource.newResource(f));
}
Enumeration<URL> urls = appContext.getClassLoader().getResources(resourcePath);
while (urls.hasMoreElements()) {
resources.add(Resource.newResource(urls.nextElement()));
}
}
if (conf.has(PROP_STATIC_PATH_LOCAL)) {
File f = new File(conf.get(PROP_STATIC_PATH_LOCAL));
if (f.exists()) {
log.debug("found static local path, add it : " + f.getAbsolutePath());
resources.add(0, Resource.newResource(f));
} else {
log.debug("static local path not exist, skip it : " + f.getPath());
}
}
wac.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()])) {
@Override
public Resource addPath(String path) throws IOException, MalformedURLException {
// TODO 为啥ResourceCollection读取WEB-INF的时候返回null
// 从而导致org.eclipse.jetty.webapp.WebAppContext.getWebInf()抛NPE
// 先临时hack吧
Resource resource = super.addPath(path);
if (resource == null && "WEB-INF/".equals(path)) {
return Resource.newResource(new File("XXXX"));
}
return resource;
}
});
if (conf.getBoolean(PROP_GZIP_ENABLE, false)) {
GzipHandler gzip = new GzipHandler();
gzip.setHandler(wac);
gzip.setMinGzipSize(conf.getInt(PROP_GZIP_MIN_CONTENT_SIZE, 512));
gzip.setCompressionLevel(conf.getInt(PROP_GZIP_LEVEL, Deflater.DEFAULT_COMPRESSION));
server.setHandler(gzip);
}
else {
server.setHandler(wac);
}
List<String> list = Configuration.ClassList.serverDefault(server);
list.add("org.eclipse.jetty.annotations.AnnotationConfiguration");
wac.setConfigurationClasses(list);
wac.getServletContext().setExtendedListenerTypes(true);
wac.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());
ErrorHandler ep = Lang.first(appContext.getBeans(ErrorHandler.class));
if(ep == null){
ErrorPageErrorHandler handler = new ErrorPageErrorHandler();
handler.setErrorPages(getErrorPages());
ep = handler;
}
wac.setErrorHandler(ep);
wac.setWelcomeFiles(getWelcomeFiles());
// 设置一下额外的东西
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", getMaxFormContentSize());
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
addNutzSupport();
ServerContainer sc = WebSocketServerContainerInitializer.configureContext(wac);
for (Class<?> klass : Scans.me().scanPackage(appContext.getPackage())) {
if (klass.getAnnotation(ServerEndpoint.class) != null) {
sc.addEndpoint(klass);
}
}
} | #vulnerable code
public void init() throws Exception {
// 创建基础服务器
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setIdleTimeout(getThreadPoolIdleTimeout());
threadPool.setMinThreads(getMinThreads());
threadPool.setMaxThreads(getMaxThreads());
server = new Server(threadPool);
HttpConfiguration httpConfig = conf.make(HttpConfiguration.class, "jetty.httpConfig.");
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
ServerConnector connector = new ServerConnector(server, httpFactory);
connector.setHost(getHost());
connector.setPort(getPort());
connector.setIdleTimeout(getIdleTimeout());
server.setConnectors(new Connector[]{connector});
// 设置应用上下文
wac = new WebAppContext();
wac.setContextPath(getContextPath());
// wac.setExtractWAR(false);
// wac.setCopyWebInf(true);
// wac.setProtectedTargets(new String[]{"/java", "/javax", "/org",
// "/net", "/WEB-INF", "/META-INF"});
wac.setTempDirectory(new File("temp"));
wac.setClassLoader(classLoader);
wac.setConfigurationDiscovered(true);
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
wac.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
}
List<Resource> resources = new ArrayList<>();
for (String resourcePath : getResourcePaths()) {
File f = new File(resourcePath);
if (f.exists()) {
resources.add(Resource.newResource(f));
}
Enumeration<URL> urls = appContext.getClassLoader().getResources(resourcePath);
while (urls.hasMoreElements()) {
resources.add(Resource.newResource(urls.nextElement()));
}
}
if (conf.has(PROP_STATIC_PATH_LOCAL)) {
File f = new File(conf.get(PROP_STATIC_PATH_LOCAL));
if (f.exists()) {
log.debug("found static local path, add it : " + f.getAbsolutePath());
resources.add(0, Resource.newResource(f));
} else {
log.debug("static local path not exist, skip it : " + f.getPath());
}
}
wac.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()])) {
@Override
public Resource addPath(String path) throws IOException, MalformedURLException {
// TODO 为啥ResourceCollection读取WEB-INF的时候返回null
// 从而导致org.eclipse.jetty.webapp.WebAppContext.getWebInf()抛NPE
// 先临时hack吧
Resource resource = super.addPath(path);
if (resource == null && "WEB-INF/".equals(path)) {
return Resource.newResource(new File("XXXX"));
}
return resource;
}
});
if (conf.getBoolean(PROP_GZIP_ENABLE, false)) {
GzipHandler gzip = new GzipHandler();
gzip.setHandler(wac);
gzip.setMinGzipSize(conf.getInt(PROP_GZIP_MIN_CONTENT_SIZE, 512));
gzip.setCompressionLevel(conf.getInt(PROP_GZIP_LEVEL, Deflater.DEFAULT_COMPRESSION));
server.setHandler(gzip);
}
else {
server.setHandler(wac);
}
List<String> list = Configuration.ClassList.serverDefault(server);
list.add("org.eclipse.jetty.annotations.AnnotationConfiguration");
wac.setConfigurationClasses(list);
wac.getServletContext().setExtendedListenerTypes(true);
wac.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());
ErrorHandler ep = Lang.first(appContext.getBeans(ErrorHandler.class));
if(ep == null){
ErrorPageErrorHandler handler = new ErrorPageErrorHandler();
handler.setErrorPages(getErrorPages());
ep = handler;
}
wac.setErrorHandler(ep);
wac.setWelcomeFiles(getWelcomeFiles());
// 设置一下额外的东西
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", getMaxFormContentSize());
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
addNutzSupport();
ServerContainer sc = WebSocketServerContainerInitializer.configureContext(wac);
for (Class<?> klass : Scans.me().scanPackage(appContext.getPackage())) {
if (klass.getAnnotation(ServerEndpoint.class) != null) {
sc.addEndpoint(klass);
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
} | #vulnerable code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
if (printProcDoc) {
PropDocReader docReader = new PropDocReader(ctx);
docReader.load();
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareIoc() throws Exception {
if (ctx.getComboIocLoader() == null) {
int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64);
List<String> args = new ArrayList<>();
args.add("*js");
args.add("ioc/");
args.add("*tx");
args.add("*async");
args.add(""+asyncPoolSize);
args.add("*anno");
args.add(ctx.getPackage());
IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class);
if (iocBy != null) {
String[] tmp = iocBy.args();
ArrayList<String> _args = new ArrayList<>();
for (int i=0;i<tmp.length;i++) {
if (tmp[i].startsWith("*")) {
if (!_args.isEmpty()) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
_args.clear();
}
}
_args.add(tmp[i]);
}
if (_args.size() > 0) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
}
}
ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()])));
}
// 用于加载Starter的IocLoader
starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter");
ctx.getComboIocLoader().addLoader(starterIocLoader);
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf()));
ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this));
}
} | #vulnerable code
public void prepareIoc() throws Exception {
if (ctx.getComboIocLoader() == null) {
int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64);
List<String> args = new ArrayList<>();
args.add("*js");
args.add("ioc/");
args.add("*tx");
args.add("*async");
args.add(""+asyncPoolSize);
args.add("*anno");
args.add(ctx.getPackage());
IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class);
if (iocBy != null) {
String[] tmp = iocBy.args();
ArrayList<String> _args = new ArrayList<>();
for (int i=0;i<tmp.length;i++) {
if (tmp[i].startsWith("*")) {
if (!_args.isEmpty()) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
_args.clear();
}
}
_args.add(tmp[i]);
}
if (_args.size() > 0) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
}
}
ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()])));
}
// 用于加载Starter的IocLoader
starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter");
ctx.getComboIocLoader().addLoader(starterIocLoader);
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get()));
}
}
#location 57
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#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() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
} | #vulnerable code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
if (printProcDoc) {
PropDocReader docReader = new PropDocReader(ctx);
docReader.load();
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
}
#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 shutdown() {
log.info("ok, shutting down ...");
if (lock == null) {
_shutdown();
}
else {
synchronized (lock) {
lock.notify();
}
}
} | #vulnerable code
public void shutdown() {
log.info("ok, shutting down ...");
synchronized (lock) {
lock.notify();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@RequestMapping("/logout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession();
if (session != null) {
session.invalidate();
}
return "redirect:/";
} | #vulnerable code
@RequestMapping("/logout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession();
// 注销本地会话
if (session != null) {
session.invalidate();
}
// 如果是客户端发起的注销请求
String token = (String) session.getAttribute(AuthConst.TOKEN);
List<String> clientUrls = authService.remove(token);
if (clientUrls != null && clientUrls.size() > 0) {
Map<String, String> params = new HashMap<String, String>();
params.put(AuthConst.LOGOUT_REQUEST, AuthConst.LOGOUT_REQUEST);
params.put(AuthConst.TOKEN, token);
for (String url : clientUrls) {
AuthUtil.post(url, params);
}
}
// 重定向到登录页面
return "redirect:/";
}
#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 testSegModeOther() throws IOException {
JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"),
true);
for (String sentence : sentences) {
TokenStream tokenStream = analyzer.tokenStream(null,
new StringReader(sentence));
tokenStream.reset();
while (tokenStream.incrementToken()) {
CharTermAttribute termAtt = tokenStream
.getAttribute(CharTermAttribute.class);
OffsetAttribute offsetAtt = tokenStream
.getAttribute(OffsetAttribute.class);
System.out
.println(termAtt.toString() + ","
+ offsetAtt.startOffset() + ","
+ offsetAtt.endOffset());
}
tokenStream.reset();
}
analyzer.close();
} | #vulnerable code
@Test
public void testSegModeOther() throws IOException {
JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"),
true);
for (String sentence : sentences) {
TokenStream tokenStream = analyzer.tokenStream(null,
new StringReader(sentence));
tokenStream.reset();
while (tokenStream.incrementToken()) {
CharTermAttribute termAtt = tokenStream
.getAttribute(CharTermAttribute.class);
OffsetAttribute offsetAtt = tokenStream
.getAttribute(OffsetAttribute.class);
System.out
.println(termAtt.toString() + ","
+ offsetAtt.startOffset() + ","
+ offsetAtt.endOffset());
}
tokenStream.reset();
}
}
#location 19
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET)
public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
String aoData = request.getParameter("aoData");
JSONArray jsonArray = JSON.parseArray(aoData);
int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0;
for (Object obj : jsonArray) {
JSONObject jsonObj = (JSONObject) obj;
if ("sEcho".equals(jsonObj.getString("name"))) {
sEcho = jsonObj.getIntValue("value");
} else if ("iDisplayStart".equals(jsonObj.getString("name"))) {
iDisplayStart = jsonObj.getIntValue("value");
} else if ("iDisplayLength".equals(jsonObj.getString("name"))) {
iDisplayLength = jsonObj.getIntValue("value");
}
}
JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip));
int offset = 0;
JSONArray retArr = new JSONArray();
for (Object tmp : ret) {
JSONObject tmp2 = (JSONObject) tmp;
if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) {
JSONObject obj = new JSONObject();
obj.put("partition", tmp2.getInteger("partition"));
if (tmp2.getLong("logSize") == 0) {
obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("logsize", tmp2.getLong("logSize"));
}
if (tmp2.getLong("offset") == -1) {
obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>");
}
obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>");
obj.put("owner", tmp2.getString("owner"));
obj.put("created", tmp2.getString("create"));
obj.put("modify", tmp2.getString("modify"));
retArr.add(obj);
}
offset++;
}
JSONObject obj = new JSONObject();
obj.put("sEcho", sEcho);
obj.put("iTotalRecords", ret.size());
obj.put("iTotalDisplayRecords", ret.size());
obj.put("aaData", retArr);
try {
byte[] output = GzipUtils.compressToByte(obj.toJSONString());
response.setContentLength(output == null ? "NULL".toCharArray().length : output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} | #vulnerable code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET)
public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
String aoData = request.getParameter("aoData");
JSONArray jsonArray = JSON.parseArray(aoData);
int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0;
for (Object obj : jsonArray) {
JSONObject jsonObj = (JSONObject) obj;
if ("sEcho".equals(jsonObj.getString("name"))) {
sEcho = jsonObj.getIntValue("value");
} else if ("iDisplayStart".equals(jsonObj.getString("name"))) {
iDisplayStart = jsonObj.getIntValue("value");
} else if ("iDisplayLength".equals(jsonObj.getString("name"))) {
iDisplayLength = jsonObj.getIntValue("value");
}
}
JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip));
int offset = 0;
JSONArray retArr = new JSONArray();
for (Object tmp : ret) {
JSONObject tmp2 = (JSONObject) tmp;
if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) {
JSONObject obj = new JSONObject();
obj.put("partition", tmp2.getInteger("partition"));
if (tmp2.getLong("logSize") == 0) {
obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("logsize", tmp2.getLong("logSize"));
}
if (tmp2.getLong("offset") == -1) {
obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>");
}
obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>");
obj.put("owner", tmp2.getString("owner"));
obj.put("created", tmp2.getString("create"));
obj.put("modify", tmp2.getString("modify"));
retArr.add(obj);
}
offset++;
}
JSONObject obj = new JSONObject();
obj.put("sEcho", sEcho);
obj.put("iTotalRecords", ret.size());
obj.put("iTotalDisplayRecords", ret.size());
obj.put("aaData", retArr);
try {
byte[] output = GzipUtils.compressToByte(obj.toJSONString());
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#location 60
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET)
public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
try {
byte[] output = GzipUtils.compressToByte(OffsetService.getOffsetsGraph(group, topic));
response.setContentLength(output == null ? "NULL".toCharArray().length : output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} | #vulnerable code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET)
public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
try {
byte[] output = GzipUtils.compressToByte(OffsetService.getOffsetsGraph(group, topic));
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET)
public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
try {
byte[] output = GzipUtils.compressToByte(AlarmService.getTopics(ip));
response.setContentLength(output == null ? "NULL".toCharArray().length : output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} | #vulnerable code
@RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET)
public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
try {
byte[] output = GzipUtils.compressToByte(AlarmService.getTopics(ip));
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private static Map<RaftPeer, NettyRpcService> initRpcServices(
Collection<RaftServer> servers, RaftConfiguration conf) {
final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>();
for (RaftServer s : servers) {
final NettyRpcService rpc = newNettyRpcService(s, conf);
peerRpcs.put(new RaftPeer(s.getId(), rpc.getInetSocketAddress()), rpc);
}
return peerRpcs;
} | #vulnerable code
private static Map<RaftPeer, NettyRpcService> initRpcServices(
Collection<RaftServer> servers, RaftConfiguration conf) {
final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>();
for (RaftServer s : servers) {
final String address = getAddress(s.getId(), conf);
final int port = RaftUtils.newInetSocketAddress(address).getPort();
final NettyRpcService rpc = new NettyRpcService(port, s);
peerRpcs.put(new RaftPeer(s.getId(), rpc.getInetSocketAddress()), rpc);
}
return peerRpcs;
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@BeforeClass
public static void beforeClass() {
cluster = new LogServiceCluster(3);
cluster.createWorkers(3);
workers = cluster.getWorkers();
assert(workers.size() == 3);
} | #vulnerable code
@BeforeClass
public static void beforeClass() {
cluster = new LogServiceCluster(3);
cluster.createWorkers(3);
List<LogServer> workers = cluster.getWorkers();
assert(workers.size() == 3);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void setupServer(){
servers = new ArrayList<>(peers.size());
singleDataStreamStateMachines = new ArrayList<>(peers.size());
// start stream servers on raft peers.
for (int i = 0; i < peers.size(); i++) {
SingleDataStreamStateMachine singleDataStreamStateMachine = new SingleDataStreamStateMachine();
singleDataStreamStateMachines.add(singleDataStreamStateMachine);
final DataStreamServerImpl streamServer = new DataStreamServerImpl(
peers.get(i), singleDataStreamStateMachine, properties, null);
final DataStreamServerRpc rpc = streamServer.getServerRpc();
if (i == 0) {
// only the first server routes requests to peers.
List<RaftPeer> otherPeers = new ArrayList<>(peers);
otherPeers.remove(peers.get(i));
rpc.addPeers(otherPeers);
}
rpc.start();
servers.add(streamServer);
}
} | #vulnerable code
private void setupServer(){
servers = new ArrayList<>(peers.size());
singleDataStreamStateMachines = new ArrayList<>(peers.size());
// start stream servers on raft peers.
for (int i = 0; i < peers.size(); i++) {
SingleDataStreamStateMachine singleDataStreamStateMachine = new SingleDataStreamStateMachine();
singleDataStreamStateMachines.add(singleDataStreamStateMachine);
DataStreamServerImpl streamServer;
if (i == 0) {
// only the first server routes requests to peers.
List<RaftPeer> otherPeers = new ArrayList<>(peers);
otherPeers.remove(peers.get(i));
streamServer = new DataStreamServerImpl(
peers.get(i), properties, null, singleDataStreamStateMachine, otherPeers);
} else {
streamServer = new DataStreamServerImpl(
peers.get(i), singleDataStreamStateMachine, properties, null);
}
servers.add(streamServer);
streamServer.getServerRpc().startServer();
}
// start peer clients on stream servers
for (DataStreamServerImpl streamServer : servers) {
((NettyServerStreamRpc) streamServer.getServerRpc()).startClientToPeers();
}
}
#location 20
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testZeroSizeInProgressFile() throws Exception {
final RaftStorage storage = RaftStorageTestUtils.newRaftStorage(storageDir);
final File file = storage.getStorageDir().getOpenLogFile(0);
storage.close();
// create zero size in-progress file
LOG.info("file: " + file);
Assert.assertTrue(file.createNewFile());
final Path path = file.toPath();
Assert.assertTrue(Files.exists(path));
Assert.assertEquals(0, Files.size(path));
// getLogSegmentFiles should remove it.
final List<RaftStorageDirectory.LogPathAndIndex> logs = storage.getStorageDir().getLogSegmentFiles();
Assert.assertEquals(0, logs.size());
Assert.assertFalse(Files.exists(path));
} | #vulnerable code
@Test
public void testZeroSizeInProgressFile() throws Exception {
final RaftStorage storage = new RaftStorage(storageDir, StartupOption.REGULAR);
final File file = storage.getStorageDir().getOpenLogFile(0);
storage.close();
// create zero size in-progress file
LOG.info("file: " + file);
Assert.assertTrue(file.createNewFile());
final Path path = file.toPath();
Assert.assertTrue(Files.exists(path));
Assert.assertEquals(0, Files.size(path));
// getLogSegmentFiles should remove it.
final List<RaftStorageDirectory.LogPathAndIndex> logs = storage.getStorageDir().getLogSegmentFiles();
Assert.assertEquals(0, logs.size());
Assert.assertFalse(Files.exists(path));
}
#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 testDataStreamDisabled() throws Exception {
try {
setup(1);
final RaftClient client = newRaftClientForDataStream();
exception.expect(UnsupportedOperationException.class);
exception.expectMessage(DisabledDataStreamClientFactory.class.getName()
+ "$1 does not support streamAsync");
// stream() will create a header request, thus it will hit UnsupportedOperationException due to
// DisabledDataStreamFactory.
client.getDataStreamApi().stream();
} finally {
shutdown();
}
} | #vulnerable code
@Test
public void testDataStreamDisabled() throws Exception {
try {
setup(1);
final DataStreamClientImpl client = newDataStreamClientImpl();
exception.expect(UnsupportedOperationException.class);
exception.expectMessage(DisabledDataStreamClientFactory.class.getName()
+ "$1 does not support streamAsync");
// stream() will create a header request, thus it will hit UnsupportedOperationException due to
// DisabledDataStreamFactory.
client.stream();
} finally {
shutdown();
}
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite(
List<String> paths, FileStoreClient fileStoreClient) throws IOException {
Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>();
for(String path : paths) {
File file = new File(path);
final long fileLength = file.length();
Preconditions.assertTrue(fileLength == getFileSizeInBytes(), "Unexpected file size: expected size is "
+ getFileSizeInBytes() + " but actual size is " + fileLength);
FileInputStream fis = new FileInputStream(file);
final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length());
if (dataStreamType.equals("DirectByteBuffer")) {
fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("MappedByteBuffer")) {
fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("NettyFileRegion")) {
fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file));
} else {
System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo");
}
}
return fileMap;
} | #vulnerable code
private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite(
List<String> paths, FileStoreClient fileStoreClient) throws IOException {
Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>();
for(String path : paths) {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length());
if (dataStreamType.equals("DirectByteBuffer")) {
fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("MappedByteBuffer")) {
fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("NettyFileRegion")) {
fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file));
} else {
System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo");
}
}
return fileMap;
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception {
final long leaderApplied = RaftServerTestUtil.getLastAppliedIndex(cluster.getLeader());
// make sure retry cache has the entry
for (RaftServer.Division server : cluster.iterateDivisions()) {
LOG.info("check server " + server.getId());
if (RaftServerTestUtil.getLastAppliedIndex(server) < leaderApplied) {
Thread.sleep(1000);
}
Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server));
Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId));
// make sure there is only one log entry committed
Assert.assertEquals(1, count(RaftServerTestUtil.getRaftLog(server), oldLastApplied + 1));
}
} | #vulnerable code
public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception {
long leaderApplied = cluster.getLeader().getState().getLastAppliedIndex();
// make sure retry cache has the entry
for (RaftServerImpl server : cluster.iterateServerImpls()) {
LOG.info("check server " + server.getId());
if (server.getState().getLastAppliedIndex() < leaderApplied) {
Thread.sleep(1000);
}
Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server));
Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId));
// make sure there is only one log entry committed
Assert.assertEquals(1, count(server.getState().getLog(), oldLastApplied + 1));
}
}
#location 2
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(timeout = 1000)
public void testRestartingScheduler() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance();
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
for(int i = 0; i < 2; i++) {
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertFalse(scheduler.hasScheduler());
}
errorHandler.assertNoError();
} | #vulnerable code
@Test(timeout = 1000)
public void testRestartingScheduler() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1);
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
for(int i = 0; i < 2; i++) {
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertFalse(scheduler.hasScheduler());
}
errorHandler.assertNoError();
}
#location 31
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(timeout = 1000)
public void testSingleTask() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance();
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(250, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertFalse(scheduler.hasScheduler());
errorHandler.assertNoError();
scheduler.setGracePeriod(grace);
} | #vulnerable code
@Test(timeout = 1000)
public void testSingleTask() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1);
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(250, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertFalse(scheduler.hasScheduler());
errorHandler.assertNoError();
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite(
List<String> paths, FileStoreClient fileStoreClient) throws IOException {
Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>();
for(String path : paths) {
File file = new File(path);
final long fileLength = file.length();
Preconditions.assertTrue(fileLength == getFileSizeInBytes(), "Unexpected file size: expected size is "
+ getFileSizeInBytes() + " but actual size is " + fileLength);
FileInputStream fis = new FileInputStream(file);
final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length());
if (dataStreamType.equals("DirectByteBuffer")) {
fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("MappedByteBuffer")) {
fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("NettyFileRegion")) {
fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file));
} else {
System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo");
}
}
return fileMap;
} | #vulnerable code
private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite(
List<String> paths, FileStoreClient fileStoreClient) throws IOException {
Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>();
for(String path : paths) {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length());
if (dataStreamType.equals("DirectByteBuffer")) {
fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("MappedByteBuffer")) {
fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel()));
} else if (dataStreamType.equals("NettyFileRegion")) {
fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file));
} else {
System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo");
}
}
return fileMap;
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(timeout = 1000)
public void testExtendingGracePeriod() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance();
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
{
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
}
{
// submit another task during grace period
final AtomicBoolean fired2 = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired2.get());
fired2.set(true);
}, errorHandler);
Thread.sleep(100);
Assert.assertFalse(fired2.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired2.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired2.get());
Assert.assertFalse(scheduler.hasScheduler());
}
errorHandler.assertNoError();
} | #vulnerable code
@Test(timeout = 1000)
public void testExtendingGracePeriod() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1);
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
{
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
}
{
// submit another task during grace period
final AtomicBoolean fired2 = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired2.get());
fired2.set(true);
}, errorHandler);
Thread.sleep(100);
Assert.assertFalse(fired2.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired2.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired2.get());
Assert.assertFalse(scheduler.hasScheduler());
}
errorHandler.assertNoError();
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Inventory deserializeInventory(JsonElement data, String title) {
Preconditions.checkArgument(data.isJsonPrimitive());
return InventorySerialization.decodeInventory(data.getAsString(), title);
} | #vulnerable code
public static Inventory deserializeInventory(JsonElement data, String title) {
Preconditions.checkArgument(data.isJsonPrimitive());
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) {
try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) {
Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt(), title);
for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, (ItemStack) dataInput.readObject());
}
return inventory;
}
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException(e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static ItemStack deserializeItemstack(JsonElement data) {
Preconditions.checkArgument(data.isJsonPrimitive());
return InventorySerialization.decodeItemStack(data.getAsString());
} | #vulnerable code
public static ItemStack deserializeItemstack(JsonElement data) {
Preconditions.checkArgument(data.isJsonPrimitive());
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) {
try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) {
return (ItemStack) dataInput.readObject();
}
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException(e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public synchronized boolean saveApi(ApiResult apiResult) {
boolean successful = false;
Connection connection;
PreparedStatement preparedStatement = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)");
preparedStatement.setString(1, apiResult.getPublicKey());
preparedStatement.setString(2, apiResult.getPrivateKey());
preparedStatement.setString(3, apiResult.getLastUsed());
preparedStatement.setString(4, apiResult.getData());
preparedStatement.execute();
successful = true;
}
catch(SQLException ex) {
Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(preparedStatement);
}
return successful;
} | #vulnerable code
public synchronized boolean saveApi(ApiResult apiResult) {
boolean successful = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)");
preparedStatement.setString(1, apiResult.getPublicKey());
preparedStatement.setString(2, apiResult.getPrivateKey());
preparedStatement.setString(3, apiResult.getLastUsed());
preparedStatement.setString(4, apiResult.getData());
preparedStatement.execute();
successful = true;
}
catch(SQLException ex) {
Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(resultSet);
Helpers.closeQuietly(preparedStatement);
}
return successful;
}
#location 25
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public synchronized boolean saveApi(ApiResult apiResult) {
boolean successful = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)");
preparedStatement.setString(1, apiResult.getPublicKey());
preparedStatement.setString(2, apiResult.getPrivateKey());
preparedStatement.setString(3, apiResult.getLastUsed());
preparedStatement.setString(4, apiResult.getData());
preparedStatement.execute();
successful = true;
}
catch(SQLException ex) {
Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(resultSet);
Helpers.closeQuietly(preparedStatement);
Helpers.closeQuietly(connection);
}
return successful;
} | #vulnerable code
public synchronized boolean saveApi(ApiResult apiResult) {
boolean successful = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)");
stmt.setString(1, apiResult.getPublicKey());
stmt.setString(2, apiResult.getPrivateKey());
stmt.setString(3, apiResult.getLastUsed());
stmt.setString(4, apiResult.getData());
stmt.execute();
successful = true;
this.cache.remove(apiResult.getPublicKey());
this.genericCache.remove(apiAllApiCacheKey);
}
catch(SQLException ex) {
successful = false;
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
return successful;
}
#location 29
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/server/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
List<String> revisions = new ArrayList<>();
for(RevCommit rev: logs) {
System.out.println(rev.getCommitTime() + " " + rev.getName());
revisions.add(rev.getName());
}
revisions = Lists.reverse(revisions);
// TODO currently this is ignoring the very first commit changes need to include those
for (int i = 1; i < revisions.size(); i++) {
System.out.println("///////////////////////////////////////////////");
this.getRevisionChanges(localRepository, git, revisions.get(i - 1), revisions.get(i));
}
} | #vulnerable code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/server/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
List<String> revisions = new ArrayList<>();
for(RevCommit rev: logs) {
System.out.println(rev.getCommitTime() + " " + rev.getName());
revisions.add(rev.getName());
}
revisions = Lists.reverse(revisions);
// TODO currently this is ignoring the very first commit changes need to include those
for (int i = 1; i < revisions.size(); i++) {
System.out.println("///////////////////////////////////////////////");
this.getRevisionChanges(revisions.get(i - 1), revisions.get(i));
}
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
List<String> fileLines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessCharset(new File(filePath))));
try {
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
fileLines.add(line);
if (lineCount == maxFileLineDepth) {
return fileLines;
}
}
}
finally {
reader.close();
}
return fileLines;
} | #vulnerable code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath))));
List<String> fileLines = new ArrayList<>();
String line = "";
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
fileLines.add(line);
if (lineCount == maxFileLineDepth) {
return fileLines;
}
}
return fileLines;
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public SlocCount countStats(String contents, String languageName) {
if (contents == null || contents.isEmpty()) {
return new SlocCount();
}
FileClassifierResult fileClassifierResult = this.database.get(languageName);
State currentState = State.S_BLANK;
int endPoint = contents.length() - 1;
String endString = null;
ArrayList<String> endComments = new ArrayList<>();
int linesCount = 0;
int blankCount = 0;
int codeCount = 0;
int commentCount = 0;
int complexity = 0;
for (int index=0; index < contents.length(); index++) {
if (!isWhitespace(contents.charAt(index))) {
switch (currentState) {
case S_CODE:
if (fileClassifierResult.nestedmultiline || endComments.size() == 0) {
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
endComments.add(endString);
currentState = State.S_MULTICOMMENT_CODE;
break;
}
}
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT_CODE;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
} else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
break;
case S_MULTICOMMENT_BLANK:
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
}
if (!this.isWhitespace(contents.charAt(index))) {
currentState = State.S_CODE;
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
}
break;
case S_STRING:
if (contents.charAt(index - 1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) {
currentState = State.S_CODE;
}
break;
case S_MULTICOMMENT:
case S_MULTICOMMENT_CODE:
if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) {
if (currentState == State.S_MULTICOMMENT_CODE) {
currentState = State.S_CODE;
} else {
// TODO check if out of bounds
if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index + 1))) {
currentState = State.S_MULTICOMMENT_BLANK;
} else {
currentState = State.S_MULTICOMMENT_CODE;
}
}
}
break;
}
}
// This means the end of processing the line so calculate the stats according to what state
// we are currently in
if (contents.charAt(index) == '\n' || index == endPoint) {
linesCount++;
switch (currentState) {
case S_BLANK:
blankCount++;
break;
case S_COMMENT:
case S_MULTICOMMENT:
case S_MULTICOMMENT_BLANK:
commentCount++;
break;
case S_CODE:
case S_STRING:
case S_COMMENT_CODE:
case S_MULTICOMMENT_CODE:
codeCount++;
break;
}
// If we are in a multiline comment that started after some code then we need
// to move to a multiline comment if a multiline comment then stay there
// otherwise we reset back into a blank state
if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) {
currentState = State.S_BLANK;
} else {
currentState = State.S_MULTICOMMENT;
}
}
}
return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity);
} | #vulnerable code
public SlocCount countStats(String contents, String languageName) {
if (contents == null || contents.isEmpty()) {
return new SlocCount();
}
FileClassifierResult fileClassifierResult = this.database.get(languageName);
State currentState = State.S_BLANK;
int endPoint = contents.length() - 1;
String endString = null;
int linesCount = 0;
int blankCount = 0;
int codeCount = 0;
int commentCount = 0;
int complexity = 0;
for (int index=0; index < contents.length(); index++) {
switch (currentState) {
case S_BLANK:
case S_MULTICOMMENT_BLANK:
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
}
if (!this.isWhitespace(contents.charAt(index))) {
currentState = State.S_CODE;
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
}
break;
case S_CODE:
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT_CODE;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
} else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
break;
case S_STRING:
if (contents.charAt(index-1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) {
currentState = State.S_CODE;
}
break;
case S_MULTICOMMENT:
case S_MULTICOMMENT_CODE:
if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) {
if (currentState == State.S_MULTICOMMENT_CODE) {
currentState = State.S_CODE;
} else {
// TODO check if out of bounds
if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index+1))) {
currentState = State.S_MULTICOMMENT_BLANK;
} else {
currentState = State.S_MULTICOMMENT_CODE;
}
}
}
break;
}
// This means the end of processing the line so calculate the stats according to what state
// we are currently in
if (contents.charAt(index) == '\n' || index == endPoint) {
linesCount++;
switch (currentState) {
case S_BLANK:
blankCount++;
break;
case S_COMMENT:
case S_MULTICOMMENT:
case S_MULTICOMMENT_BLANK:
commentCount++;
break;
case S_CODE:
case S_STRING:
case S_COMMENT_CODE:
case S_MULTICOMMENT_CODE:
codeCount++;
break;
}
// If we are in a multiline comment that started after some code then we need
// to move to a multiline comment if a multiline comment then stay there
// otherwise we reset back into a blank state
if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) {
currentState = State.S_BLANK;
} else {
currentState = State.S_MULTICOMMENT;
}
}
}
return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity);
}
#location 22
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException {
List<String> lines = new ArrayList<>();
Scanner input = new Scanner(new File(filePath));
try {
int counter = 0;
while (input.hasNextLine() && counter < maxFileLineDepth) {
lines.add(input.nextLine());
counter++;
}
}
finally {
input.close();
}
return lines;
} | #vulnerable code
public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException {
List<String> lines = new ArrayList<>();
Scanner input = new Scanner(new File(filePath));
int counter = 0;
while(input.hasNextLine() && counter < maxFileLineDepth)
{
lines.add(input.nextLine());
counter++;
}
return lines;
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) {
boolean changed = false;
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
Singleton.getLogger().info("SVN: attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
ProcessBuilder processBuilder;
if (useCredentials) {
processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update");
}
else {
processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update", "--username", repoUserName, "--password", repoPassword);
}
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
BufferedReader bufferedReader = null;
try {
String previousRevision = this.getCurrentRevision(repoLocations, repoName);
Singleton.getLogger().info("SVN: update previous revision " + previousRevision);
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
bufferedReader = new BufferedReader(isr);
String line;
while ((line = bufferedReader.readLine()) != null) {
Singleton.getLogger().info("svn update: " + line);
}
String currentRevision = this.getCurrentRevision(repoLocations, repoName);
Singleton.getLogger().info("SVN: update current revision " + currentRevision);
if (!previousRevision.equals(currentRevision)) {
return this.getDiffBetweenRevisions(repoLocations, repoName, previousRevision);
}
} catch (IOException | InvalidPathException ex) {
changed = false;
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateSvnRepository for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
Helpers.closeQuietly(bufferedReader);
}
return new RepositoryChanged(changed, changedFiles, deletedFiles);
} | #vulnerable code
public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) {
boolean changed = false;
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
Singleton.getLogger().info("SVN: attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
ProcessBuilder processBuilder;
if (useCredentials) {
processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update");
}
else {
processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update", "--username", repoUserName, "--password", repoPassword);
}
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
try {
String previousRevision = this.getCurrentRevision(repoLocations, repoName);
Singleton.getLogger().info("SVN: update previous revision " + previousRevision);
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
Singleton.getLogger().info("svn update: " + line);
}
String currentRevision = this.getCurrentRevision(repoLocations, repoName);
Singleton.getLogger().info("SVN: update current revision " + currentRevision);
if (!previousRevision.equals(currentRevision)) {
return this.getDiffBetweenRevisions(repoLocations, repoName, previousRevision);
}
} catch (IOException | InvalidPathException ex) {
changed = false;
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateSvnRepository for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
}
return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
#location 40
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public synchronized void createTableIfMissing() {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='repo';");
resultSet = preparedStatement.executeQuery();
String value = Values.EMPTYSTRING;
while (resultSet.next()) {
value = resultSet.getString("name");
}
if (Singleton.getHelpers().isNullEmptyOrWhitespace(value)) {
preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS \"repo\" (\"name\" VARCHAR PRIMARY KEY NOT NULL ,\"scm\" VARCHAR,\"url\" VARCHAR,\"username\" VARCHAR,\"password\" VARCHAR, \"source\", \"branch\" VARCHAR, data text);");
preparedStatement.execute();
}
}
catch (SQLException ex) {
this.logger.severe(String.format("5ec972ce::error in class %s exception %s searchcode was to create the api key table, so api calls will fail", ex.getClass(), ex.getMessage()));
}
finally {
this.helpers.closeQuietly(resultSet);
this.helpers.closeQuietly(preparedStatement);
}
} | #vulnerable code
public synchronized void createTableIfMissing() {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS \"repo\" (\"name\" VARCHAR PRIMARY KEY NOT NULL ,\"scm\" VARCHAR,\"url\" VARCHAR,\"username\" VARCHAR,\"password\" VARCHAR, \"source\", \"branch\" VARCHAR, data text);");
preparedStatement.execute();
}
catch (SQLException ex) {
this.logger.severe(String.format("5ec972ce::error in class %s exception %s", ex.getClass(), ex.getMessage()));
}
finally {
this.helpers.closeQuietly(resultSet);
this.helpers.closeQuietly(preparedStatement);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public synchronized void deleteApiByPublicKey(String publicKey) {
Connection connection;
PreparedStatement preparedStatement = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("delete from api where publickey=?;");
preparedStatement.setString(1, publicKey);
preparedStatement.execute();
}
catch(SQLException ex) {
Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(preparedStatement);
}
} | #vulnerable code
public synchronized void deleteApiByPublicKey(String publicKey) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("delete from api where publickey=?;");
preparedStatement.setString(1, publicKey);
preparedStatement.execute();
}
catch(SQLException ex) {
Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(resultSet);
Helpers.closeQuietly(preparedStatement);
}
}
#location 18
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) {
List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
// -w is to ignore whitespace bug
ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName);
// The / part is required due to centos bug for version 1.1.1
processBuilder.directory(new File(repoLocations + "/" + repoName));
Process process = null;
BufferedReader bufferedReader = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
bufferedReader = new BufferedReader(isr);
String line;
DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");
HashMap<String, CodeOwner> owners = new HashMap<>();
boolean foundSomething = false;
while ((line = bufferedReader.readLine()) != null) {
Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
String[] split = line.split("\t");
if (split.length > 2 && split[1].length() != 0) {
foundSomething = true;
String author = split[1].substring(1);
int commitTime = (int) (System.currentTimeMillis() / 1000);
try {
commitTime = (int) (df.parse(split[2]).getTime() / 1000);
}
catch(ParseException ex) {
Singleton.getLogger().info("time parse expection for " + repoName + fileName);
}
if (owners.containsKey(author)) {
CodeOwner codeOwner = owners.get(author);
codeOwner.incrementLines();
int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();
if (commitTime > timestamp) {
codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
}
owners.put(author, codeOwner);
} else {
owners.put(author, new CodeOwner(author, 1, commitTime));
}
}
}
if (foundSomething == false) {
// External call for CentOS issue
String[] split = fileName.split("/");
if ( split.length != 1) {
codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations, String.join("/", Arrays.asList(split).subList(1, split.length)));
}
} else {
codeOwners = new ArrayList<>(owners.values());
}
} catch (IOException | StringIndexOutOfBoundsException ex) {
Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
Helpers.closeQuietly(bufferedReader);
}
return codeOwners;
} | #vulnerable code
public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) {
List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
// -w is to ignore whitespace bug
ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName);
// The / part is required due to centos bug for version 1.1.1
processBuilder.directory(new File(repoLocations + "/" + repoName));
Process process = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");
HashMap<String, CodeOwner> owners = new HashMap<>();
boolean foundSomething = false;
while ((line = br.readLine()) != null) {
Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
String[] split = line.split("\t");
if (split.length > 2 && split[1].length() != 0) {
foundSomething = true;
String author = split[1].substring(1);
int commitTime = (int) (System.currentTimeMillis() / 1000);
try {
commitTime = (int) (df.parse(split[2]).getTime() / 1000);
}
catch(ParseException ex) {
Singleton.getLogger().info("time parse expection for " + repoName + fileName);
}
if (owners.containsKey(author)) {
CodeOwner codeOwner = owners.get(author);
codeOwner.incrementLines();
int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();
if (commitTime > timestamp) {
codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
}
owners.put(author, codeOwner);
} else {
owners.put(author, new CodeOwner(author, 1, commitTime));
}
}
}
if (foundSomething == false) {
// External call for CentOS issue
String[] split = fileName.split("/");
if ( split.length != 1) {
codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations, String.join("/", Arrays.asList(split).subList(1, split.length)));
}
} else {
codeOwners = new ArrayList<>(owners.values());
}
} catch (IOException | StringIndexOutOfBoundsException ex) {
Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
}
return codeOwners;
}
#location 67
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testIsBinaryWhiteListedExtension() {
SearchcodeLib sl = new SearchcodeLib();
ArrayList<String> codeLines = new ArrayList<>();
codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你");
FileClassifier fileClassifier = new FileClassifier();
for(FileClassifierResult fileClassifierResult: fileClassifier.getDatabase()) {
for(String extension: fileClassifierResult.extensions) {
BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension);
assertThat(isBinary.isBinary()).isFalse();
}
}
} | #vulnerable code
public void testIsBinaryWhiteListedExtension() {
SearchcodeLib sl = new SearchcodeLib();
ArrayList<String> codeLines = new ArrayList<>();
codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你");
FileClassifier fileClassifier = new FileClassifier();
for(Classifier classifier: fileClassifier.getClassifier()) {
for(String extension: classifier.extensions) {
BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension);
assertThat(isBinary.isBinary()).isFalse();
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) {
CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000));
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml", fileName);
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
BufferedReader bufferedReader = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
bufferedReader = new BufferedReader(isr);
String line;
StringBuilder bf = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
bf.append(Helpers.removeUTF8BOM(line));
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(bf.toString().getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("entry");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Node node = eElement.getElementsByTagName("commit").item(0);
Element e = (Element) node;
owner.setName(e.getElementsByTagName("author").item(0).getTextContent());
}
}
} catch (IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
Helpers.closeQuietly(bufferedReader);
}
return owner;
} | #vulnerable code
private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) {
CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000));
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml", fileName);
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder bf = new StringBuilder();
while ((line = br.readLine()) != null) {
bf.append(Helpers.removeUTF8BOM(line));
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(bf.toString().getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("entry");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Node node = eElement.getElementsByTagName("commit").item(0);
Element e = (Element) node;
owner.setName(e.getElementsByTagName("author").item(0).getTextContent());
}
}
} catch (IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
}
return owner;
}
#location 43
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public synchronized boolean saveRepo(RepoResult repoResult) {
RepoResult existing = this.getRepoByName(repoResult.getName());
this.cache.remove(repoResult.getName());
boolean isNew = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
// Update with new details
try {
connection = this.dbConfig.getConnection();
if (existing != null) {
preparedStatement = connection.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?");
preparedStatement.setString(8, repoResult.getName());
}
else {
isNew = true;
preparedStatement = connection.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)");
}
preparedStatement.setString(1, repoResult.getName());
preparedStatement.setString(2, repoResult.getScm());
preparedStatement.setString(3, repoResult.getUrl());
preparedStatement.setString(4, repoResult.getUsername());
preparedStatement.setString(5, repoResult.getPassword());
preparedStatement.setString(6, repoResult.getSource());
preparedStatement.setString(7, repoResult.getBranch());
preparedStatement.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(preparedStatement);
Helpers.closeQuietly(connection);
}
this.genericCache.remove(this.repoCountCacheKey);
this.genericCache.remove(this.repoAllRepoCacheKey);
return isNew;
} | #vulnerable code
@Override
public synchronized boolean saveRepo(RepoResult repoResult) {
RepoResult existing = this.getRepoByName(repoResult.getName());
this.cache.remove(repoResult.getName());
boolean isNew = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
if (existing != null) {
// Update with new details
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?");
stmt.setString(1, repoResult.getName());
stmt.setString(2, repoResult.getScm());
stmt.setString(3, repoResult.getUrl());
stmt.setString(4, repoResult.getUsername());
stmt.setString(5, repoResult.getPassword());
stmt.setString(6, repoResult.getSource());
stmt.setString(7, repoResult.getBranch());
// Target the row
stmt.setString(8, repoResult.getName());
stmt.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
}
else {
isNew = true;
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)");
stmt.setString(1, repoResult.getName());
stmt.setString(2, repoResult.getScm());
stmt.setString(3, repoResult.getUrl());
stmt.setString(4, repoResult.getUsername());
stmt.setString(5, repoResult.getPassword());
stmt.setString(6, repoResult.getSource());
stmt.setString(7, repoResult.getBranch());
stmt.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
}
this.genericCache.remove(this.repoCountCacheKey);
this.genericCache.remove(this.repoAllRepoCacheKey);
return isNew;
}
#location 35
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testMultipleRetrieveCache() {
String randomApiString = this.getRandomString();
this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", ""));
for(int i=0; i < 500; i++) {
Optional<ApiResult> apiByPublicKey = this.api.getApiByPublicKey(randomApiString);
assertThat(apiByPublicKey.get().getPublicKey()).isEqualTo(randomApiString);
assertThat(apiByPublicKey.get().getPrivateKey()).isEqualTo("privateKey");
}
this.api.deleteApiByPublicKey(randomApiString);
} | #vulnerable code
public void testMultipleRetrieveCache() {
String randomApiString = this.getRandomString();
this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", ""));
for(int i=0; i < 500; i++) {
ApiResult apiResult = this.api.getApiByPublicKey(randomApiString);
assertThat(apiResult.getPublicKey()).isEqualTo(randomApiString);
assertThat(apiResult.getPrivateKey()).isEqualTo("privateKey");
}
this.api.deleteApiByPublicKey(randomApiString);
}
#location 9
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
List<String> fileLines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessCharset(new File(filePath))));
try {
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
fileLines.add(line);
if (lineCount == maxFileLineDepth) {
return fileLines;
}
}
}
finally {
reader.close();
}
return fileLines;
} | #vulnerable code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath))));
List<String> fileLines = new ArrayList<>();
String line = "";
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
fileLines.add(line);
if (lineCount == maxFileLineDepth) {
return fileLines;
}
}
return fileLines;
}
#location 14
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void testExecuteNothingInQueue() throws JobExecutionException {
IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob();
IndexGitRepoJob spy = spy(indexGitRepoJob);
when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue());
JobExecutionContext mockContext = Mockito.mock(JobExecutionContext.class);
JobDetail mockDetail = Mockito.mock(JobDetail.class);
JobDataMap mockJobDataMap = Mockito.mock(JobDataMap.class);
CodeIndexer mockCodeIndexer = Mockito.mock(CodeIndexer.class);
when(mockJobDataMap.get("REPOLOCATIONS")).thenReturn("");
when(mockJobDataMap.get("LOWMEMORY")).thenReturn("true");
when(mockDetail.getJobDataMap()).thenReturn(mockJobDataMap);
when(mockContext.getJobDetail()).thenReturn(mockDetail);
when(mockCodeIndexer.shouldPauseAdding()).thenReturn(false);
spy.codeIndexer = mockCodeIndexer;
spy.execute(mockContext);
assertThat(spy.haveRepoResult).isFalse();
} | #vulnerable code
public void testExecuteNothingInQueue() throws JobExecutionException {
IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob();
IndexGitRepoJob spy = spy(indexGitRepoJob);
when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue());
spy.execute(null);
assertThat(spy.haveRepoResult).isFalse();
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/server/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
List<String> revisions = new ArrayList<>();
for(RevCommit rev: logs) {
System.out.println(rev.getCommitTime() + " " + rev.getName());
revisions.add(rev.getName());
}
revisions = Lists.reverse(revisions);
for (int i = 1; i < revisions.size(); i++) {
System.out.println("///////////////////////////////////////////////");
this.getRevisionChanges(revisions.get(i - 1), revisions.get(i));
}
} | #vulnerable code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/.timelord/test/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
for(RevCommit rev: logs) {
System.out.println(rev.getName());
git.checkout().setName(rev.getName()).call();
}
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
lifxMap = null;
aGsonHandler = null;
validLifx = bridgeSettings.isValidLifx();
log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured."));
if(validLifx) {
try {
log.info("Open Lifx client....");
InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress());
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress);
InetAddress bcastInetAddr = null;
if (networkInterface != null) {
for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) {
InetAddress addr = ifaceAddr.getAddress();
if (addr instanceof Inet4Address) {
bcastInetAddr = ifaceAddr.getBroadcast();
break;
}
}
}
if(bcastInetAddr != null) {
lifxMap = new HashMap<String, LifxDevice>();
log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress());
client = new LFXClient(bcastInetAddr.getHostAddress());
client.getLights().addLightCollectionListener(new MyLightListener(lifxMap));
client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap));
client.open(false);
aGsonHandler =
new GsonBuilder()
.create();
} else {
log.warn("Could not open LIFX, no bcast addr available, check your upnp config address.");
client = null;
validLifx = false;
return this;
}
} catch (IOException e) {
log.warn("Could not open LIFX, with IO Exception", e);
client = null;
validLifx = false;
return this;
} catch (InterruptedException e) {
log.warn("Could not open LIFX, with Interruprted Exception", e);
client = null;
validLifx = false;
return this;
}
}
return this;
} | #vulnerable code
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
lifxMap = null;
aGsonHandler = null;
validLifx = bridgeSettings.isValidLifx();
log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured."));
if(validLifx) {
try {
log.info("Open Lifx client....");
InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress());
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress);
InetAddress bcastInetAddr = null;
if (networkInterface != null) {
for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) {
InetAddress addr = ifaceAddr.getAddress();
if (addr instanceof Inet4Address) {
bcastInetAddr = ifaceAddr.getBroadcast();
break;
}
}
}
lifxMap = new HashMap<String, LifxDevice>();
log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress());
client = new LFXClient(bcastInetAddr.getHostAddress());
client.getLights().addLightCollectionListener(new MyLightListener(lifxMap));
client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap));
client.open(false);
} catch (IOException e) {
log.warn("Could not open LIFX, with IO Exception", e);
client = null;
return this;
} catch (InterruptedException e) {
log.warn("Could not open LIFX, with Interruprted Exception", e);
client = null;
return this;
}
aGsonHandler =
new GsonBuilder()
.create();
}
return this;
}
#location 23
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity,
Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) {
Socket dataSendSocket = null;
log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString());
String theUrl = anItem.getItem().getAsString();
if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) {
String intermediate = theUrl.substring(theUrl.indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
String port = null;
InetAddress IPAddress = null;
dataSendSocket = theSockets.get(hostPortion);
if(dataSendSocket == null) {
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1);
} else
hostAddr = hostPortion;
try {
IPAddress = InetAddress.getByName(hostAddr);
} catch (UnknownHostException e) {
// noop
}
try {
dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
theSockets.put(hostPortion, dataSendSocket);
} catch (Exception e) {
// noop
}
}
theUrlBody = TimeDecode.replaceTimeValue(theUrlBody);
if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false);
sendData = theUrlBody.getBytes();
}
try {
DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream());
outToClient.write(sendData);
outToClient.flush();
} catch (Exception e) {
// noop
}
} else
log.warn("Tcp Call to be presented as tcp://<ip_address>:<port>/payload, format of request unknown: " + theUrl);
return null;
} | #vulnerable code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity,
Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) {
log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString());
String theUrl = anItem.getItem().getAsString();
if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) {
String intermediate = theUrl.substring(theUrl.indexOf("://") + 3);
String hostPortion = intermediate.substring(0, intermediate.indexOf('/'));
String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1);
String hostAddr = null;
String port = null;
InetAddress IPAddress = null;
if (hostPortion.contains(":")) {
hostAddr = hostPortion.substring(0, intermediate.indexOf(':'));
port = hostPortion.substring(intermediate.indexOf(':') + 1);
} else
hostAddr = hostPortion;
try {
IPAddress = InetAddress.getByName(hostAddr);
} catch (UnknownHostException e) {
// noop
}
theUrlBody = TimeDecode.replaceTimeValue(theUrlBody);
if (theUrlBody.startsWith("0x")) {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true);
sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2));
} else {
theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false);
sendData = theUrlBody.getBytes();
}
try {
Socket dataSendSocket = new Socket(IPAddress, Integer.parseInt(port));
DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream());
outToClient.write(sendData);
outToClient.flush();
dataSendSocket.close();
} catch (Exception e) {
// noop
}
} else
log.warn("Tcp Call to be presented as tcp://<ip_address>:<port>/payload, format of request unknown: " + theUrl);
return null;
}
#location 39
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) {
String validUser = null;
boolean found = false;
if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null")
&& !aUser.equalsIgnoreCase("")) {
if (securityDescriptor.getWhitelist() != null) {
Set<String> theUserIds = securityDescriptor.getWhitelist().keySet();
Iterator<String> userIterator = theUserIds.iterator();
while (userIterator.hasNext()) {
validUser = userIterator.next();
if (validUser.equals(aUser)) {
found = true;
log.debug("validateWhitelistUser: found a user <" + aUser + ">");
}
}
}
}
if(!found && !strict) {
log.debug("validateWhitelistUser: a user was not found and it is not strict rules <" + aUser + "> being created");
newWhitelistUser(aUser, userDescription);
found = true;
}
if (!found) {
log.debug("validateWhitelistUser: a user was not found and it is strict rules <" + aUser + ">");
return HueErrorResponse.createResponse("1", "/api/" + aUser == null ? "" : aUser, "unauthorized user", null, null, null).getTheErrors();
}
return null;
} | #vulnerable code
public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) {
String validUser = null;
boolean found = false;
if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null")
&& !aUser.equalsIgnoreCase("")) {
if (securityDescriptor.getWhitelist() != null) {
Set<String> theUserIds = securityDescriptor.getWhitelist().keySet();
Iterator<String> userIterator = theUserIds.iterator();
while (userIterator.hasNext()) {
validUser = userIterator.next();
if (validUser.equals(aUser))
found = true;
}
}
}
if(!found && !strict) {
newWhitelistUser(aUser, userDescription);
found = true;
}
if (!found) {
return HueErrorResponse.createResponse("1", "/api/" + aUser, "unauthorized user", null, null, null).getTheErrors();
}
Object anUser = securityDescriptor.getWhitelist().remove(DEPRACATED_INTERNAL_USER);
if(anUser != null)
setSettingsChanged(true);
return null;
}
#location 27
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden()));
String responseString = null;
String intermediate;
if (anItem.getItem().getAsString().contains("exec://"))
intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3);
else
intermediate = anItem.getItem().getAsString();
intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, intensity, targetBri, targetBriInc, false);
if (colorData != null) {
intermediate = ColorDecode.replaceColorData(intermediate, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false);
}
intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device);
intermediate = TimeDecode.replaceTimeValue(intermediate);
String execGarden = theSettings.getBridgeSecurity().getExecGarden();
if(execGarden != null && !execGarden.trim().isEmpty()) {
intermediate = new File(execGarden.trim(), intermediate).getAbsolutePath();
}
String anError = doExecRequest(intermediate, lightId);
if (anError != null) {
responseString = anError;
}
return responseString;
} | #vulnerable code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden()));
String responseString = null;
String intermediate;
if (anItem.getItem().getAsString().contains("exec://"))
intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3);
else
intermediate = anItem.getItem().getAsString();
intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, intensity, targetBri, targetBriInc, false);
if (colorData != null) {
intermediate = ColorDecode.replaceColorData(intermediate, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false);
}
intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device);
intermediate = TimeDecode.replaceTimeValue(intermediate);
String execGarden = theSettings.getBridgeSecurity().getExecGarden();
if(execGarden != null && !execGarden.trim().isEmpty()) {
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
intermediate = execGarden + "\\" + intermediate;
else
intermediate = execGarden + "/" + intermediate;
}
String anError = doExecRequest(intermediate, lightId);
if (anError != null) {
responseString = anError;
}
return responseString;
}
#location 18
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden()));
String responseString = null;
String intermediate;
if (anItem.getItem().getAsString().contains("exec://"))
intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3);
else
intermediate = anItem.getItem().getAsString();
intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, itensity, targetBri, targetBriInc, false);
intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device);
intermediate = TimeDecode.replaceTimeValue(intermediate);
String execGarden = theSettings.getBridgeSecurity().getExecGarden();
execGarden = execGarden.trim();
if(execGarden != null && !execGarden.isEmpty()) {
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
intermediate = execGarden + "\\" + intermediate;
else
intermediate = execGarden + "/" + intermediate;
}
String anError = doExecRequest(intermediate, lightId);
if (anError != null) {
responseString = anError;
}
return responseString;
} | #vulnerable code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.getItem().getAsString());
String responseString = null;
String intermediate;
if (anItem.getItem().getAsString().contains("exec://"))
intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3);
else
intermediate = anItem.getItem().getAsString();
intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, itensity, targetBri, targetBriInc, false);
intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device);
intermediate = TimeDecode.replaceTimeValue(intermediate);
if(execGarden != null) {
if(System.getProperty("os.name").toLowerCase().indexOf("win") > 0)
intermediate = execGarden + "\\" + intermediate;
else
intermediate = execGarden + "/" + intermediate;
}
String anError = doExecRequest(intermediate, lightId);
if (anError != null) {
responseString = anError;
}
return responseString;
}
#location 14
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(HABridge.class);
DeviceResource theResources;
HomeManager homeManager;
HueMulator theHueMulator;
UDPDatagramSender udpSender;
UpnpSettingsResource theSettingResponder;
UpnpListener theUpnpListener;
SystemControl theSystem;
BridgeSettings bridgeSettings;
Version theVersion;
theVersion = new Version();
log.info("HA Bridge (v" + theVersion.getVersion() + ") starting....");
bridgeSettings = new BridgeSettings();
// sparkjava config directive to set html static file location for Jetty
staticFileLocation("/public");
while(!bridgeSettings.getBridgeControl().isStop()) {
bridgeSettings.buildSettings();
bridgeSettings.getBridgeSecurity().removeTestUsers();
log.info("HA Bridge initializing....");
// sparkjava config directive to set ip address for the web server to listen on
ipAddress(bridgeSettings.getBridgeSettingsDescriptor().getWebaddress());
// sparkjava config directive to set port for the web server to listen on
port(bridgeSettings.getBridgeSettingsDescriptor().getServerPort());
if(!bridgeSettings.getBridgeControl().isReinit())
init();
bridgeSettings.getBridgeControl().setReinit(false);
// setup system control api first
theSystem = new SystemControl(bridgeSettings, theVersion);
theSystem.setupServer();
// setup the UDP Datagram socket to be used by the HueMulator and the upnpListener
udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort());
if(udpSender == null) {
bridgeSettings.getBridgeControl().setStop(true);
}
else {
//Setup the device connection homes through the manager
homeManager = new HomeManager();
homeManager.buildHomes(bridgeSettings, udpSender);
// setup the class to handle the resource setup rest api
theResources = new DeviceResource(bridgeSettings, homeManager);
// setup the class to handle the upnp response rest api
theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor());
theSettingResponder.setupServer();
// setup the class to handle the hue emulator rest api
theHueMulator = new HueMulator(bridgeSettings, theResources.getDeviceRepository(), homeManager);
theHueMulator.setupServer();
// wait for the sparkjava initialization of the rest api classes to be complete
awaitInitialization();
// start the upnp ssdp discovery listener
theUpnpListener = new UpnpListener(bridgeSettings.getBridgeSettingsDescriptor(), bridgeSettings.getBridgeControl(), udpSender);
if(theUpnpListener.startListening())
log.info("HA Bridge (v" + theVersion.getVersion() + ") reinitialization requessted....");
else
bridgeSettings.getBridgeControl().setStop(true);
if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged())
bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor());
homeManager.closeHomes();
udpSender.closeResponseSocket();
udpSender = null;
}
stop();
if(!bridgeSettings.getBridgeControl().isStop()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
bridgeSettings.getBridgeSecurity().removeTestUsers();
if(bridgeSettings.getBridgeSecurity().isSettingsChanged())
bridgeSettings.updateConfigFile();
log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting....");
System.exit(0);
} | #vulnerable code
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(HABridge.class);
DeviceResource theResources;
HomeManager homeManager;
HueMulator theHueMulator;
UDPDatagramSender udpSender;
UpnpSettingsResource theSettingResponder;
UpnpListener theUpnpListener;
SystemControl theSystem;
BridgeSettings bridgeSettings;
Version theVersion;
theVersion = new Version();
log.info("HA Bridge (v" + theVersion.getVersion() + ") starting....");
bridgeSettings = new BridgeSettings();
// sparkjava config directive to set html static file location for Jetty
staticFileLocation("/public");
while(!bridgeSettings.getBridgeControl().isStop()) {
bridgeSettings.buildSettings();
log.info("HA Bridge initializing....");
// sparkjava config directive to set ip address for the web server to listen on
ipAddress(bridgeSettings.getBridgeSettingsDescriptor().getWebaddress());
// sparkjava config directive to set port for the web server to listen on
port(bridgeSettings.getBridgeSettingsDescriptor().getServerPort());
if(!bridgeSettings.getBridgeControl().isReinit())
init();
bridgeSettings.getBridgeControl().setReinit(false);
// setup system control api first
theSystem = new SystemControl(bridgeSettings, theVersion);
theSystem.setupServer();
// setup the UDP Datagram socket to be used by the HueMulator and the upnpListener
udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort());
if(udpSender == null) {
bridgeSettings.getBridgeControl().setStop(true);
}
else {
//Setup the device connection homes through the manager
homeManager = new HomeManager();
homeManager.buildHomes(bridgeSettings, udpSender);
// setup the class to handle the resource setup rest api
theResources = new DeviceResource(bridgeSettings, homeManager);
// setup the class to handle the upnp response rest api
theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor());
theSettingResponder.setupServer();
// setup the class to handle the hue emulator rest api
theHueMulator = new HueMulator(bridgeSettings, theResources.getDeviceRepository(), homeManager);
theHueMulator.setupServer();
// wait for the sparkjava initialization of the rest api classes to be complete
awaitInitialization();
// start the upnp ssdp discovery listener
theUpnpListener = new UpnpListener(bridgeSettings.getBridgeSettingsDescriptor(), bridgeSettings.getBridgeControl(), udpSender);
if(theUpnpListener.startListening())
log.info("HA Bridge (v" + theVersion.getVersion() + ") reinitialization requessted....");
else
bridgeSettings.getBridgeControl().setStop(true);
if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged())
bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor());
homeManager.closeHomes();
udpSender.closeResponseSocket();
udpSender = null;
}
stop();
if(!bridgeSettings.getBridgeControl().isStop()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
bridgeSettings.getBridgeSecurity().removeTestUsers();
if(bridgeSettings.getBridgeSecurity().isSettingsChanged())
bridgeSettings.updateConfigFile();
log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting....");
System.exit(0);
}
#location 26
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i);
Categorie controllerCat = new Categorie();
controllerCat.setName("Controller");
controllerCat.setId("0");
categoryMap.put(controllerCat.getId(),controllerCat);
ListIterator<Device> theIterator = theSdata.getDevices().listIterator();
Device theDevice = null;
while (theIterator.hasNext()) {
theDevice = theIterator.next();
if(theDevice.getRoom() != null && roomMap.get(theDevice.getRoom()) != null)
theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName());
else
theDevice.setRoom("no room");
if(theDevice.getCategory() != null && categoryMap.get(theDevice.getCategory()) != null)
theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName());
else
theDevice.setCategory("<unknown>");
}
ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator();
Scene theScene = null;
while (theSecneIter.hasNext()) {
theScene = theSecneIter.next();
theScene.setRoom(roomMap.get(theScene.getRoom()).getName());
}
} | #vulnerable code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i);
Categorie controllerCat = new Categorie();
controllerCat.setName("Controller");
controllerCat.setId("0");
categoryMap.put(controllerCat.getId(),controllerCat);
ListIterator<Device> theIterator = theSdata.getDevices().listIterator();
Device theDevice = null;
while (theIterator.hasNext()) {
theDevice = theIterator.next();
if(theDevice.getRoom() != null)
theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName());
else
theDevice.setRoom("<unknown>");
if(theDevice.getCategory() != null)
theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName());
else
theDevice.setCategory("<unknown>");
}
ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator();
Scene theScene = null;
while (theSecneIter.hasNext()) {
theScene = theSecneIter.next();
theScene.setRoom(roomMap.get(theScene.getRoom()).getName());
}
}
#location 19
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
getLogger().log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
} | #vulnerable code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
}
#location 33
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return loadPlugin(file, false);
} | #vulnerable code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
JavaPlugin result = null;
PluginDescriptionFile description = null;
if (!file.exists()) {
throw new InvalidPluginException(new FileNotFoundException(String.format("%s does not exist", file.getPath())));
}
try {
JarFile jar = new JarFile(file);
JarEntry entry = jar.getJarEntry("plugin.yml");
if (entry == null) {
throw new InvalidPluginException(new FileNotFoundException("Jar does not contain plugin.yml"));
}
InputStream stream = jar.getInputStream(entry);
description = new PluginDescriptionFile(stream);
stream.close();
jar.close();
} catch (IOException ex) {
throw new InvalidPluginException(ex);
} catch (YAMLException ex) {
throw new InvalidPluginException(ex);
}
File dataFolder = new File(file.getParentFile(), description.getName());
File oldDataFolder = getDataFolder(file);
// Found old data folder
if (dataFolder.equals(oldDataFolder)) {
// They are equal -- nothing needs to be done!
} else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) {
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) found old-data folder: %s next to the new one: %s",
description.getName(),
file,
oldDataFolder,
dataFolder
));
} else if (oldDataFolder.isDirectory() && !dataFolder.exists()) {
if (!oldDataFolder.renameTo(dataFolder)) {
throw new InvalidPluginException(new Exception("Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'"));
}
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) renamed data folder: '%s' to '%s'",
description.getName(),
file,
oldDataFolder,
dataFolder
));
}
if (dataFolder.exists() && !dataFolder.isDirectory()) {
throw new InvalidPluginException(new Exception(String.format(
"Projected datafolder: '%s' for %s (%s) exists and is not a directory",
dataFolder,
description.getName(),
file
)));
}
ArrayList<String> depend;
try {
depend = (ArrayList)description.getDepend();
if(depend == null) {
depend = new ArrayList<String>();
}
} catch (ClassCastException ex) {
throw new InvalidPluginException(ex);
}
for(String pluginName : depend) {
if(loaders == null) {
throw new UnknownDependencyException(pluginName);
}
PluginClassLoader current = loaders.get(pluginName);
if(current == null) {
throw new UnknownDependencyException(pluginName);
}
}
PluginClassLoader loader = null;
try {
URL[] urls = new URL[1];
urls[0] = file.toURI().toURL();
loader = new PluginClassLoader(this, urls, getClass().getClassLoader());
Class<?> jarClass = Class.forName(description.getMain(), true, loader);
Class<? extends JavaPlugin> plugin = jarClass.asSubclass(JavaPlugin.class);
Constructor<? extends JavaPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, server, description, dataFolder, file, loader);
} catch (Throwable ex) {
throw new InvalidPluginException(ex);
}
loaders.put(description.getName(), (PluginClassLoader)loader);
return (Plugin)result;
}
#location 13
#vulnerability type RESOURCE_LEAK |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.