output
stringlengths 79
30.1k
| instruction
stringclasses 1
value | input
stringlengths 216
28.9k
|
---|---|---|
#fixed code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testInitArgsForUserNameAndPasswordWithSpaces() {
try {
final SqlLine sqlLine = new SqlLine();
final DatabaseConnection[] databaseConnection = new DatabaseConnection[1];
new MockUp<sqlline.DatabaseConnections>() {
@Mock
public void setConnection(DatabaseConnection connection) {
databaseConnection[0] = connection;
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
String[] connectionArgs = new String[]{
"-u", ConnectionSpec.H2.url, "-n", "\"user'\\\" name\"",
"-p", "\"user \\\"'\\\"password\"",
"-e", "!set maxwidth 80"};
begin(sqlLine, os, false, connectionArgs);
assertEquals(ConnectionSpec.H2.url, databaseConnection[0].getUrl());
Properties infoProperties =
FieldReflection.getFieldValue(
databaseConnection[0].getClass().getDeclaredField("info"),
databaseConnection[0]);
assertNotNull(infoProperties);
assertEquals("user'\" name", infoProperties.getProperty("user"));
assertEquals("user \"'\"password",
infoProperties.getProperty("password"));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
#location 18
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testConnectWithDbPropertyAsParameter() {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(sqlLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
sqlLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
sqlLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
sqlLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testConnectWithDbPropertyAsParameter() {
SqlLine beeLine = new SqlLine();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
SqlLine.Status status =
begin(beeLine, os, false, "-e", "!set maxwidth 80");
assertThat(status, equalTo(SqlLine.Status.OK));
DispatchCallback dc = new DispatchCallback();
beeLine.runCommands(dc,
"!set maxwidth 80",
"!set incremental true");
String fakeNonEmptyPassword = "nonEmptyPasswd";
final byte[] bytes =
fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8);
beeLine.runCommands(dc, "!connect "
+ " -p PASSWORD_HASH TRUE "
+ ConnectionSpec.H2.url + " "
+ ConnectionSpec.H2.username + " "
+ StringUtils.convertBytesToHex(bytes));
beeLine.runCommands(dc, "!tables");
String output = os.toString("UTF8");
final String expected = "| TABLE_CAT | TABLE_SCHEM | "
+ "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |";
assertThat(output, containsString(expected));
beeLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(beeLine.isExit());
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 26
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testGetDeclaredFields() throws Exception {
String javaVersion = System.getProperty("java.specification.version");
if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testGetDeclaredFields() throws Exception {
if (System.getProperty("java.specification.version").startsWith("9")) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testJPopulatorFactoryBeanWithCustomRandomizers() {
Populator populator = getPopulatorFromSpringContext("/application-context-with-custom-randomizers.xml");
// the populator managed by spring should be correctly configured
assertThat(populator).isNotNull();
// the populator should populate valid instances
Person person = populator.populateBean(Person.class);
assertPerson(person);
assertThat(person.getEmail())
.isNotNull()
.isNotEmpty()
.matches(".*@.*\\..*");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testJPopulatorFactoryBeanWithCustomRandomizers() {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("/application-context-with-custom-randomizers.xml");
Populator populator = (Populator) applicationContext.getBean("populator");
// the populator managed by spring should be correctly configured
assertThat(populator).isNotNull();
// the populator should populate valid instances
Person person = populator.populateBean(Person.class);
assertPerson(person);
System.out.println("person.getEmail() = " + person.getEmail());
assertThat(person.getEmail())
.isNotNull()
.isNotEmpty()
.contains("@");
}
#location 7
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testScriptString() throws Exception {
File file = tmpDir.newFile();
String line = "hello world";
executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w << '" + line +"' }" };
executeMojo.execute();
BufferedReader reader = new BufferedReader(new FileReader(file));
LineReader lineReader = new LineReader(reader);
String actualLine = lineReader.readLine();
reader.close();
Assert.assertEquals(line, actualLine);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testScriptString() throws Exception {
File file = tmpDir.newFile();
String line = "hello world";
executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w << '" + line +"' }" };
executeMojo.execute();
LineReader lineReader = new LineReader(new BufferedReader(new FileReader(file)));
String actualLine = lineReader.readLine();
Assert.assertEquals(line, actualLine);
}
#location 9
#vulnerability type RESOURCE_LEAK |
#fixed code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
Closer closer = Closer.create();
try {
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding)));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException ioe) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe);
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void execute() throws MojoExecutionException, MojoFailureException {
logGroovyVersion("execute");
try {
// get classes we need with reflection
Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell");
// create a GroovyShell to run scripts in
Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass));
// TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts?
// run the scripts
int scriptNum = 1;
for (String script : scripts) {
Closer closer = Closer.create();
try {
try {
URL url = new URL(script);
// it's a URL to a script
getLog().info("Fetching Groovy script from " + url.toString() + ".");
BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream())));
StringBuilder scriptSource = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
scriptSource.append(line).append("\n");
}
if (!scriptSource.toString().isEmpty()) {
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString());
}
} catch (MalformedURLException e) {
// it's not a URL to a script, treat as a script body
ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script);
} catch (Throwable throwable) {
throw closer.rethrow(throwable);
} finally {
closer.close();
}
} catch (IOException ioe) {
if (continueExecuting) {
getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe);
} else {
throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe);
}
}
scriptNum++;
}
} catch (ClassNotFoundException e) {
throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e);
} catch (InvocationTargetException e) {
throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e);
} catch (InstantiationException e) {
throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e);
}
}
#location 22
#vulnerability type RESOURCE_LEAK |
#fixed code
CppGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist,
File outputDirectory)
{
this.outputDirectory = outputDirectory;
mName = (new File(name)).getName();
mInclFiles = ilist;
mRecList = rlist;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
void genCode() throws IOException {
outputDirectory.mkdirs();
FileWriter cc = new FileWriter(new File(outputDirectory, mName+".cc"));
FileWriter hh = new FileWriter(new File(outputDirectory, mName+".hh"));
hh.write("#ifndef __"+mName.toUpperCase().replace('.','_')+"__\n");
hh.write("#define __"+mName.toUpperCase().replace('.','_')+"__\n");
hh.write("#include \"recordio.hh\"\n");
for (Iterator i = mInclFiles.iterator(); i.hasNext();) {
JFile f = (JFile) i.next();
hh.write("#include \""+f.getName()+".hh\"\n");
}
cc.write("#include \""+mName+".hh\"\n");
for (Iterator i = mRecList.iterator(); i.hasNext();) {
JRecord jr = (JRecord) i.next();
jr.genCppCode(hh, cc);
}
hh.write("#endif //"+mName.toUpperCase().replace('.','_')+"__\n");
hh.close();
cc.close();
}
#location 12
#vulnerability type RESOURCE_LEAK |
#fixed code
public static void getTraceMask(String host, int port) {
Socket s = null;
try {
byte[] reqBytes = new byte[12];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt());
s = new Socket();
s.setSoLinger(false, 10);
s.setSoTimeout(20000);
s.connect(new InetSocketAddress(host, port));
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
os.write(reqBytes);
byte[] resBytes = new byte[8];
int rc = is.read(resBytes);
ByteBuffer res = ByteBuffer.wrap(resBytes);
long retv = res.getLong();
System.out.println("rc=" + rc + " retv=0"
+ Long.toOctalString(retv));
} catch (IOException e) {
LOG.warn("Unexpected exception", e);
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
LOG.warn("Unexpected exception", e);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void getTraceMask(String host, int port) {
try {
byte[] reqBytes = new byte[12];
ByteBuffer req = ByteBuffer.wrap(reqBytes);
req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt());
Socket s = null;
s = new Socket();
s.setSoLinger(false, 10);
s.setSoTimeout(20000);
s.connect(new InetSocketAddress(host, port));
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
os.write(reqBytes);
byte[] resBytes = new byte[8];
int rc = is.read(resBytes);
ByteBuffer res = ByteBuffer.wrap(resBytes);
long retv = res.getLong();
System.out.println("rc=" + rc + " retv=0"
+ Long.toOctalString(retv));
} catch (IOException ioe) {
LOG.warn("Unexpected exception", ioe);
}
}
#location 20
#vulnerability type RESOURCE_LEAK |
#fixed code
private KeyValuePair rdbLoadObject(int rdbtype) throws IOException {
switch (rdbtype) {
/*
* | <content> |
* | string contents |
*/
case RDB_TYPE_STRING:
KeyStringValueString o0 = new KeyStringValueString();
EncodedString val = rdbLoadEncodedStringObject();
o0.setValueRdbType(rdbtype);
o0.setValue(val.string);
o0.setRawBytes(val.rawBytes);
return o0;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case RDB_TYPE_LIST:
long len = rdbLoadLen().len;
KeyStringValueList<String> o1 = new KeyStringValueList<>();
List<String> list = new ArrayList<>();
for (int i = 0; i < len; i++) {
String element = rdbLoadEncodedStringObject().string;
list.add(element);
}
o1.setValueRdbType(rdbtype);
o1.setValue(list);
return o1;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case RDB_TYPE_SET:
len = rdbLoadLen().len;
KeyStringValueSet o2 = new KeyStringValueSet();
Set<String> set = new LinkedHashSet<>();
for (int i = 0; i < len; i++) {
String element = rdbLoadEncodedStringObject().string;
set.add(element);
}
o2.setValueRdbType(rdbtype);
o2.setValue(set);
return o2;
/*
* | <len> | <content> | <score> |
* | 1 or 5 bytes | string contents | double content |
*/
case RDB_TYPE_ZSET:
len = rdbLoadLen().len;
KeyStringValueZSet o3 = new KeyStringValueZSet();
Set<ZSetEntry> zset = new LinkedHashSet<>();
while (len > 0) {
String element = rdbLoadEncodedStringObject().string;
double score = rdbLoadDoubleValue();
zset.add(new ZSetEntry(element, score));
len--;
}
o3.setValueRdbType(rdbtype);
o3.setValue(zset);
return o3;
/*
* | <len> | <content> | <score> |
* | 1 or 5 bytes | string contents | binary double |
*/
case RDB_TYPE_ZSET_2:
/* rdb version 8*/
len = rdbLoadLen().len;
KeyStringValueZSet o5 = new KeyStringValueZSet();
zset = new LinkedHashSet<>();
while (len > 0) {
String element = rdbLoadEncodedStringObject().string;
double score = rdbLoadBinaryDoubleValue();
zset.add(new ZSetEntry(element, score));
len--;
}
o5.setValueRdbType(rdbtype);
o5.setValue(zset);
return o5;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case RDB_TYPE_HASH:
len = rdbLoadLen().len;
KeyStringValueHash o4 = new KeyStringValueHash();
Map<String, String> map = new LinkedHashMap<>();
while (len > 0) {
String field = rdbLoadEncodedStringObject().string;
String value = rdbLoadEncodedStringObject().string;
map.put(field, value);
len--;
}
o4.setValueRdbType(rdbtype);
o4.setValue(map);
return o4;
/*
* |<zmlen> | <len> |"foo" | <len> | <free> | "bar" |<zmend> |
* | 1 byte | 1 or 5 byte | content |1 or 5 byte | 1 byte | content | 1 byte |
*/
case RDB_TYPE_HASH_ZIPMAP:
ByteArray aux = rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueHash o9 = new KeyStringValueHash();
map = new LinkedHashMap<>();
int zmlen = BaseRdbParser.LenHelper.zmlen(stream);
while (true) {
int zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream);
if (zmEleLen == 255) {
o9.setValueRdbType(rdbtype);
o9.setValue(map);
return o9;
}
String field = BaseRdbParser.StringHelper.str(stream, zmEleLen);
zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream);
if (zmEleLen == 255) {
o9.setValueRdbType(rdbtype);
o9.setValue(map);
return o9;
}
int free = BaseRdbParser.LenHelper.free(stream);
String value = BaseRdbParser.StringHelper.str(stream, zmEleLen);
BaseRdbParser.StringHelper.skip(stream, free);
map.put(field, value);
}
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
case RDB_TYPE_SET_INTSET:
aux = rdbLoadPlainStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueSet o11 = new KeyStringValueSet();
set = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
int lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (int i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
set.add(String.valueOf(stream.readInt(2)));
break;
case 4:
set.add(String.valueOf(stream.readInt(4)));
break;
case 8:
set.add(String.valueOf(stream.readLong(8)));
break;
default:
throw new AssertionError("Expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(rdbtype);
o11.setValue(set);
return o11;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case RDB_TYPE_LIST_ZIPLIST:
aux = rdbLoadPlainStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueList<String> o10 = new KeyStringValueList<>();
list = new ArrayList<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
for (int i = 0; i < zllen; i++) {
list.add(BaseRdbParser.StringHelper.zipListEntry(stream));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o10.setValueRdbType(rdbtype);
o10.setValue(list);
return o10;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case RDB_TYPE_ZSET_ZIPLIST:
aux = rdbLoadPlainStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueZSet o12 = new KeyStringValueZSet();
zset = new LinkedHashSet<>();
zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
zltail = BaseRdbParser.LenHelper.zltail(stream);
zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
String element = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
double score = Double.valueOf(BaseRdbParser.StringHelper.zipListEntry(stream));
zllen--;
zset.add(new ZSetEntry(element, score));
}
zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o12.setValueRdbType(rdbtype);
o12.setValue(zset);
return o12;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case RDB_TYPE_HASH_ZIPLIST:
aux = rdbLoadPlainStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueHash o13 = new KeyStringValueHash();
map = new LinkedHashMap<>();
zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
zltail = BaseRdbParser.LenHelper.zltail(stream);
zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
String field = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
String value = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
map.put(field, value);
}
zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o13.setValueRdbType(rdbtype);
o13.setValue(map);
return o13;
/* rdb version 7*/
case RDB_TYPE_LIST_QUICKLIST:
len = rdbLoadLen().len;
KeyStringValueList<ByteArray> o14 = new KeyStringValueList<>();
List<ByteArray> byteList = new ArrayList<>();
for (int i = 0; i < len; i++) {
ByteArray element = (ByteArray) rdbGenericLoadStringObject(RDB_LOAD_NONE);
byteList.add(element);
}
o14.setValueRdbType(rdbtype);
o14.setValue(byteList);
return o14;
case RDB_TYPE_MODULE:
/* rdb version 8*/
//|6|6|6|6|6|6|6|6|6|10|
char[] c = new char[9];
long moduleid = rdbLoadLen().len;
keyStringValueModule o6 = new keyStringValueModule();
for (int i = 0; i < c.length; i++) {
c[i] = MODULE_SET[(int) (moduleid & 63)];
moduleid >>>= 6;
}
String moduleName = new String(c);
int moduleVersion = (int) (moduleid & 1023);
ModuleHandler handler = lookupModuleHandler(moduleName,moduleVersion);
o6.setValueRdbType(rdbtype);
o6.setValue(handler.rdbLoad(in));
return o6;
default:
throw new AssertionError("Un-except value-type:" + rdbtype);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private KeyValuePair rdbLoadObject(int rdbtype) throws IOException {
switch (rdbtype) {
/*
* | <content> |
* | string contents |
*/
case REDIS_RDB_TYPE_STRING:
KeyStringValueString o0 = new KeyStringValueString();
EncodedString val = rdbLoadEncodedStringObject();
o0.setValueRdbType(rdbtype);
o0.setValue(val.string);
o0.setRawBytes(val.rawBytes);
return o0;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case REDIS_RDB_TYPE_LIST:
long len = rdbLoadLen().len;
KeyStringValueList<String> o1 = new KeyStringValueList<>();
List<String> list = new ArrayList<>();
for (int i = 0; i < len; i++) {
String element = rdbLoadEncodedStringObject().string;
list.add(element);
}
o1.setValueRdbType(rdbtype);
o1.setValue(list);
return o1;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case REDIS_RDB_TYPE_SET:
len = rdbLoadLen().len;
KeyStringValueSet o2 = new KeyStringValueSet();
Set<String> set = new LinkedHashSet<>();
for (int i = 0; i < len; i++) {
String element = rdbLoadEncodedStringObject().string;
set.add(element);
}
o2.setValueRdbType(rdbtype);
o2.setValue(set);
return o2;
/*
* | <len> | <content> | <score> |
* | 1 or 5 bytes | string contents | double content |
*/
case REDIS_RDB_TYPE_ZSET:
len = rdbLoadLen().len;
KeyStringValueZSet o3 = new KeyStringValueZSet();
Set<ZSetEntry> zset = new LinkedHashSet<>();
while (len > 0) {
String element = rdbLoadEncodedStringObject().string;
double score = rdbLoadDoubleValue();
zset.add(new ZSetEntry(element, score));
len--;
}
o3.setValueRdbType(rdbtype);
o3.setValue(zset);
return o3;
/*
* | <len> | <content> | <score> |
* | 1 or 5 bytes | string contents | binary double |
*/
case REDIS_RDB_TYPE_ZSET_2:
/* rdb version 8*/
len = rdbLoadLen().len;
KeyStringValueZSet o5 = new KeyStringValueZSet();
zset = new LinkedHashSet<>();
while (len > 0) {
String element = rdbLoadEncodedStringObject().string;
double score = rdbLoadBinaryDoubleValue();
zset.add(new ZSetEntry(element, score));
len--;
}
o5.setValueRdbType(rdbtype);
o5.setValue(zset);
return o5;
/*
* | <len> | <content> |
* | 1 or 5 bytes | string contents |
*/
case REDIS_RDB_TYPE_HASH:
len = rdbLoadLen().len;
KeyStringValueHash o4 = new KeyStringValueHash();
Map<String, String> map = new LinkedHashMap<>();
while (len > 0) {
String field = rdbLoadEncodedStringObject().string;
String value = rdbLoadEncodedStringObject().string;
map.put(field, value);
len--;
}
o4.setValueRdbType(rdbtype);
o4.setValue(map);
return o4;
/*
* |<zmlen> | <len> |"foo" | <len> | <free> | "bar" |<zmend> |
* | 1 byte | 1 or 5 byte | content |1 or 5 byte | 1 byte | content | 1 byte |
*/
case REDIS_RDB_TYPE_HASH_ZIPMAP:
ByteArray aux = rdbLoadRawStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueHash o9 = new KeyStringValueHash();
map = new LinkedHashMap<>();
int zmlen = BaseRdbParser.LenHelper.zmlen(stream);
while (true) {
int zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream);
if (zmEleLen == 255) {
o9.setValueRdbType(rdbtype);
o9.setValue(map);
return o9;
}
String field = BaseRdbParser.StringHelper.str(stream, zmEleLen);
zmEleLen = BaseRdbParser.LenHelper.zmElementLen(stream);
if (zmEleLen == 255) {
o9.setValueRdbType(rdbtype);
o9.setValue(map);
return o9;
}
int free = BaseRdbParser.LenHelper.free(stream);
String value = BaseRdbParser.StringHelper.str(stream, zmEleLen);
BaseRdbParser.StringHelper.skip(stream, free);
map.put(field, value);
}
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
case REDIS_RDB_TYPE_SET_INTSET:
aux = rdbLoadRawStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueSet o11 = new KeyStringValueSet();
set = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
int lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (int i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
set.add(String.valueOf(stream.readInt(2)));
break;
case 4:
set.add(String.valueOf(stream.readInt(4)));
break;
case 8:
set.add(String.valueOf(stream.readLong(8)));
break;
default:
throw new AssertionError("Expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(rdbtype);
o11.setValue(set);
return o11;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case REDIS_RDB_TYPE_LIST_ZIPLIST:
aux = rdbLoadRawStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueList<String> o10 = new KeyStringValueList<>();
list = new ArrayList<>();
int zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
int zltail = BaseRdbParser.LenHelper.zltail(stream);
int zllen = BaseRdbParser.LenHelper.zllen(stream);
for (int i = 0; i < zllen; i++) {
list.add(BaseRdbParser.StringHelper.zipListEntry(stream));
}
int zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o10.setValueRdbType(rdbtype);
o10.setValue(list);
return o10;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case REDIS_RDB_TYPE_ZSET_ZIPLIST:
aux = rdbLoadRawStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueZSet o12 = new KeyStringValueZSet();
zset = new LinkedHashSet<>();
zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
zltail = BaseRdbParser.LenHelper.zltail(stream);
zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
String element = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
double score = Double.valueOf(BaseRdbParser.StringHelper.zipListEntry(stream));
zllen--;
zset.add(new ZSetEntry(element, score));
}
zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o12.setValueRdbType(rdbtype);
o12.setValue(zset);
return o12;
/*
* |<zlbytes>| <zltail>| <zllen>| <entry> ...<entry> | <zlend>|
* | 4 bytes | 4 bytes | 2bytes | zipListEntry ... | 1byte |
*/
case REDIS_RDB_TYPE_HASH_ZIPLIST:
aux = rdbLoadRawStringObject();
stream = new RedisInputStream(new ByteArrayInputStream(aux));
KeyStringValueHash o13 = new KeyStringValueHash();
map = new LinkedHashMap<>();
zlbytes = BaseRdbParser.LenHelper.zlbytes(stream);
zltail = BaseRdbParser.LenHelper.zltail(stream);
zllen = BaseRdbParser.LenHelper.zllen(stream);
while (zllen > 0) {
String field = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
String value = BaseRdbParser.StringHelper.zipListEntry(stream);
zllen--;
map.put(field, value);
}
zlend = BaseRdbParser.LenHelper.zlend(stream);
if (zlend != 255) {
throw new AssertionError("zlend expected 255 but " + zlend);
}
o13.setValueRdbType(rdbtype);
o13.setValue(map);
return o13;
/* rdb version 7*/
case REDIS_RDB_TYPE_LIST_QUICKLIST:
len = rdbLoadLen().len;
KeyStringValueList<ByteArray> o14 = new KeyStringValueList<>();
List<ByteArray> byteList = new ArrayList<>();
for (int i = 0; i < len; i++) {
ByteArray element = rdbLoadRawStringObject();
byteList.add(element);
}
o14.setValueRdbType(rdbtype);
o14.setValue(byteList);
return o14;
case REDIS_RDB_TYPE_MODULE:
/* rdb version 8*/
//|6|6|6|6|6|6|6|6|6|10|
char[] c = new char[9];
long moduleid = rdbLoadLen().len;
keyStringValueModule o6 = new keyStringValueModule();
for (int i = 0; i < c.length; i++) {
c[i] = MODULE_SET[(int) (moduleid & 63)];
moduleid >>>= 6;
}
String moduleName = new String(c);
int moduleVersion = (int) (moduleid & 1023);
ModuleHandler handler = lookupModuleHandler(moduleName,moduleVersion);
o6.setValueRdbType(rdbtype);
o6.setValue(handler.rdbLoad(in));
return o6;
default:
throw new AssertionError("Un-except value-type:" + rdbtype);
}
}
#location 109
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void test() throws Exception {
String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj";
ByteArray bytes = new ByteArray(str.getBytes().length, 10);
byte[] b1 = str.getBytes();
int i = 0;
for (byte b : b1) {
bytes.set(i, b);
assertEquals(b, bytes.get(i));
i++;
}
ByteArray bytes1 = new ByteArray(str.getBytes().length - 10, 10);
ByteArray.arraycopy(bytes, 10, bytes1, 0, bytes.length - 10);
assertEquals(str.substring(10), getString(bytes1));
str = "sdajk";
ByteArray bytes2 = new ByteArray(str.getBytes().length, 10);
b1 = str.getBytes();
i = 0;
for (byte b : b1) {
bytes2.set(i, b);
assertEquals(b, bytes2.get(i));
i++;
}
assertEquals(getString(bytes2), "sdajk");
ByteArray bytes3 = new ByteArray(bytes2.length() - 1, 10);
ByteArray.arraycopy(bytes2, 1, bytes3, 0, bytes2.length() - 1);
assertEquals(str.substring(1), getString(bytes3));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void test() throws Exception {
String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj";
ByteArray bytes = new ByteArray(str.getBytes().length, 10);
byte[] b1 = str.getBytes();
int i = 0;
for (byte b : b1) {
bytes.set(i, b);
assertEquals(b, bytes.get(i));
i++;
}
ByteArray bytes1 = new ByteArray(str.getBytes().length - 10, 10);
ByteArray.arraycopy(bytes, 10, bytes1, 0, bytes.length - 10);
assertEquals(str.substring(10), new String(bytes1.first()));
str = "sdajk";
ByteArray bytes2 = new ByteArray(str.getBytes().length, 10);
b1 = str.getBytes();
i = 0;
for (byte b : b1) {
bytes2.set(i, b);
assertEquals(b, bytes2.get(i));
i++;
}
assertEquals(new String(bytes2.first()), "sdajk");
ByteArray bytes3 = new ByteArray(bytes2.length() - 1, 10);
ByteArray.arraycopy(bytes2, 1, bytes3, 0, bytes2.length() - 1);
assertEquals(str.substring(1), new String(bytes3.first()));
}
#location 15
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testSync() throws Exception {
//socket
RedisSocketReplicator replicator = new RedisSocketReplicator("127.0.0.1", 6379, Configuration.defaultSetting().setAuthPassword("test"));
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
});
replicator.open();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testSync() throws Exception {
//socket
RedisReplicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
replicator.open();
}
#location 5
#vulnerability type RESOURCE_LEAK |
#fixed code
public static void main(String[] args) throws IOException, URISyntaxException {
final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("/path/to/dump.rdb")));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save rdb from remote server
Replicator replicator = new RedisReplicator("redis://127.0.0.1:6379");
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
replicator.addRawByteListener(rawByteListener);
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.removeRawByteListener(rawByteListener);
try {
out.close();
replicator.close();
} catch (IOException ignore) {
}
}
});
replicator.open();
//check rdb file
replicator = new RedisReplicator("redis:///path/to/dump.rdb");
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
System.out.println(kv);
}
});
replicator.open();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws IOException {
final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/dump.rdb"));
final RawByteListener rawByteListener = new RawByteListener() {
@Override
public void handle(byte... rawBytes) {
try {
out.write(rawBytes);
} catch (IOException ignore) {
}
}
};
//save rdb from remote server
Replicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener() {
@Override
public void preFullSync(Replicator replicator) {
replicator.addRawByteListener(rawByteListener);
}
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
replicator.removeRawByteListener(rawByteListener);
try {
out.close();
replicator.close();
} catch (IOException ignore) {
}
}
});
replicator.open();
//check rdb file
replicator = new RedisReplicator(new File("./src/test/resources/dump.rdb"), FileType.RDB, Configuration.defaultSetting());
replicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
System.out.println(kv);
}
});
replicator.open();
}
#location 36
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public void open() throws IOException {
try {
doOpen();
} finally {
close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void open() throws IOException {
for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) {
try {
connect();
if (configuration.getAuthPassword() != null) auth(configuration.getAuthPassword());
sendSlavePort();
sendSlaveIp();
sendSlaveCapa();
//reset retries
i = 0;
logger.info("PSYNC " + configuration.getMasterRunId() + " " + String.valueOf(configuration.getOffset()));
send("PSYNC".getBytes(), configuration.getMasterRunId().getBytes(), String.valueOf(configuration.getOffset()).getBytes());
final String reply = (String) reply();
SyncMode syncMode = trySync(reply);
//bug fix.
if (syncMode == SyncMode.PSYNC && connected.get()) {
//heart beat send REPLCONF ACK ${slave offset}
synchronized (this) {
heartBeat = new Timer("heart beat");
//bug fix. in this point closed by other thread. multi-thread issue
heartBeat.schedule(new TimerTask() {
@Override
public void run() {
try {
send("REPLCONF".getBytes(), "ACK".getBytes(), String.valueOf(configuration.getOffset()).getBytes());
} catch (IOException e) {
//NOP
}
}
}, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod());
logger.info("heart beat started.");
}
}
//sync command
while (connected.get()) {
Object obj = replyParser.parse(new OffsetHandler() {
@Override
public void handle(long len) {
configuration.addOffset(len);
}
});
//command
if (obj instanceof Object[]) {
if (configuration.isVerbose() && logger.isDebugEnabled())
logger.debug(Arrays.deepToString((Object[]) obj));
Object[] command = (Object[]) obj;
CommandName cmdName = CommandName.name((String) command[0]);
Object[] params = new Object[command.length - 1];
System.arraycopy(command, 1, params, 0, params.length);
final CommandParser<? extends Command> operations;
//if command do not register. ignore
if ((operations = commands.get(cmdName)) == null) continue;
//do command replyParser
Command parsedCommand = operations.parse(cmdName, params);
//submit event
this.submitEvent(parsedCommand);
} else {
if (logger.isInfoEnabled()) logger.info("Redis reply:" + obj);
}
}
//connected = false
break;
} catch (/*bug fix*/IOException e) {
//close socket manual
if (!connected.get()) {
break;
}
logger.error("socket error", e);
//connect refused
//connect timeout
//read timeout
//connect abort
//server disconnect connection EOFException
close();
//retry psync in next loop.
logger.info("reconnect to redis-server. retry times:" + (i + 1));
try {
Thread.sleep(configuration.getRetryTimeInterval());
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
}
doCloseListener();
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void testFileV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"), FileType.RDB,
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV6");
assertEquals(132, acc.get());
}
});
redisReplicator.open();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testFileV6() throws IOException, InterruptedException {
Replicator redisReplicator = new RedisReplicator(
RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"),
Configuration.defaultSetting());
final AtomicInteger acc = new AtomicInteger(0);
redisReplicator.addRdbListener(new RdbListener.Adaptor() {
@Override
public void handle(Replicator replicator, KeyValuePair<?> kv) {
acc.incrementAndGet();
}
@Override
public void postFullSync(Replicator replicator, long checksum) {
super.postFullSync(replicator, checksum);
}
});
redisReplicator.addCloseListener(new CloseListener() {
@Override
public void handle(Replicator replicator) {
System.out.println("close testFileV6");
assertEquals(132, acc.get());
}
});
redisReplicator.open();
}
#location 26
#vulnerability type RESOURCE_LEAK |
#fixed code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, hashComparator);
List<FileState> duplicatedFiles = new ArrayList<>();
FileHash previousFileHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousFileHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousFileHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, fullHashComparator);
FileHash previousHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
}
#location 11
#vulnerability type NULL_DEREFERENCE |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS |
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 33
#vulnerability type CHECKERS_PRINTF_ARGS |
#fixed code
private Object loadContent(){
Object[] shape = getShape();
Object descr = getDescr();
byte[] data = (byte[])getData();
if(descr instanceof DType){
DType dType = (DType)descr;
descr = dType.toDescr();
}
try {
InputStream is = new ByteArrayInputStream(data);
try {
return NDArrayUtil.parseData(is, descr, shape);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Object loadContent(){
Object[] shape = getShape();
Object descr = getDescr();
byte[] data = (byte[])getData();
try {
InputStream is = new ByteArrayInputStream(data);
try {
return NDArrayUtil.parseData(is, descr, shape);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<?> data = getData();
ClassDictUtil.checkSize(1, ids, features);
final
InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment());
WildcardFeature wildcardFeature = (WildcardFeature)features.get(0);
Function<Object, String> function = new Function<Object, String>(){
@Override
public String apply(Object object){
return ValueUtil.formatValue(object);
}
};
List<String> categories = Lists.transform(data, function);
FieldDecorator decorator = new ValidValueDecorator(){
{
setInvalidValueTreatment(invalidValueTreatment);
}
};
CategoricalFeature categoricalFeature = wildcardFeature.toCategoricalFeature(categories);
encoder.addDecorator(categoricalFeature.getName(), decorator);
return Collections.<Feature>singletonList(categoricalFeature);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<?> data = getData();
if(ids.size() != 1 || features.size() != 1){
throw new IllegalArgumentException();
}
final
InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment());
WildcardFeature wildcardFeature = (WildcardFeature)features.get(0);
Function<Object, String> function = new Function<Object, String>(){
@Override
public String apply(Object object){
return ValueUtil.formatValue(object);
}
};
List<String> categories = Lists.transform(data, function);
FieldDecorator decorator = new ValidValueDecorator(){
{
setInvalidValueTreatment(invalidValueTreatment);
}
};
CategoricalFeature categoricalFeature = wildcardFeature.toCategoricalFeature(categories);
encoder.addDecorator(categoricalFeature.getName(), decorator);
return Collections.<Feature>singletonList(categoricalFeature);
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
static
public List<?> getContent(NDArray array, String key){
Map<String, ?> content = (Map<String, ?>)array.getContent();
return asJavaList(array, (List<?>)content.get(key));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
static
public List<?> getContent(NDArray array, String key){
Map<String, ?> data = (Map<String, ?>)array.getContent();
return asJavaList(array, (List<?>)data.get(key));
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
static
public List<?> getArray(ClassDict dict, String name){
Object object = dict.get(name);
if(object instanceof HasArray){
HasArray hasArray = (HasArray)object;
return hasArray.getArrayContent();
} // End if
if(object instanceof Number){
return Collections.singletonList(object);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
static
public List<?> getArray(ClassDict dict, String name){
Object object = unwrap(dict.get(name));
if(object instanceof NDArray){
NDArray array = (NDArray)object;
return NDArrayUtil.getContent(array);
} else
if(object instanceof CSRMatrix){
CSRMatrix matrix = (CSRMatrix)object;
return CSRMatrixUtil.getContent(matrix);
} else
if(object instanceof Scalar){
Scalar scalar = (Scalar)object;
return scalar.getContent();
} // End if
if(object instanceof Number){
return Collections.singletonList(object);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void test1() {
long l = System.currentTimeMillis() / 1000;
LocalDateTime localDateTime = DateUtil.fromTimeStamp(l);
System.out.print(DateUtil.localDateTimeFormatyMdHms(localDateTime));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void test1() {
long l = System.currentTimeMillis() / 1000;
LocalDateTime localDateTime = DateUtil.fromTimeStamp(l);
System.out.printf(DateUtil.localDateTimeFormatyMdHms(localDateTime));
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS |
#fixed code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
JsonObject object = element.getAsJsonObject();
String clientDataJSON = object.get("clientDataJSON").getAsString();
String authenticatorData = object.get("authenticatorData").getAsString();
String signature = object.get("signature").getAsString();
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(clientDataJSON, authenticatorData, signature);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
assertion.getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(responseData);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
assertion.getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
#location 14
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testContents() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testContents() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
#location 5
#vulnerability type RESOURCE_LEAK |
#fixed code
boolean flushEventLogByCount(int count) {
Date lastEventDate = null;
boolean cacheIsEmpty = true;
IndexWriter indexWriter = null;
long l = System.currentTimeMillis();
logger.finest("......flush eventlog cache....");
List<EventLogEntry> events = eventLogService.findEvents(count + 1,
EVENTLOG_TOPIC_ADD, EVENTLOG_TOPIC_REMOVE);
if (events != null && events.size() > 0) {
try {
indexWriter = createIndexWriter();
int _counter = 0;
for (EventLogEntry eventLogEntry : events) {
Term term = new Term("$uniqueid", eventLogEntry.getUniqueID());
// lookup the Document Entity...
org.imixs.workflow.engine.jpa.Document doc = manager
.find(org.imixs.workflow.engine.jpa.Document.class, eventLogEntry.getUniqueID());
// if the document was found we add/update the index. Otherwise we remove the
// document form the index.
if (doc != null && EVENTLOG_TOPIC_ADD.equals(eventLogEntry.getTopic())) {
// add workitem to search index....
long l2 = System.currentTimeMillis();
ItemCollection workitem = new ItemCollection();
workitem.setAllItems(doc.getData());
if (!workitem.getItemValueBoolean(DocumentService.NOINDEX)) {
indexWriter.updateDocument(term, createDocument(workitem));
logger.finest("......lucene add/update workitem '" + doc.getId() + "' to index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
} else {
long l2 = System.currentTimeMillis();
indexWriter.deleteDocuments(term);
logger.finest("......lucene remove workitem '" + term + "' from index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
// remove the eventLogEntry.
lastEventDate = eventLogEntry.getModified().getTime();
eventLogService.removeEvent(eventLogEntry);
// break?
_counter++;
if (_counter >= count) {
// we skipp the last one if the maximum was reached.
cacheIsEmpty = false;
break;
}
}
} catch (IOException luceneEx) {
logger.warning("...unable to flush lucene event log: " + luceneEx.getMessage());
// We just log a warning here and close the flush mode to no longer block the
// writer.
// NOTE: maybe throwing a IndexException would be an alternative:
//
// throw new IndexException(IndexException.INVALID_INDEX, "Unable to update
// lucene search index",
// luceneEx);
return true;
} finally {
// close writer!
if (indexWriter != null) {
logger.finest("......lucene close IndexWriter...");
try {
indexWriter.close();
} catch (CorruptIndexException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
} catch (IOException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
}
}
}
}
logger.fine("...flushEventLog - " + events.size() + " events in " + (System.currentTimeMillis() - l)
+ " ms - last log entry: " + lastEventDate);
return cacheIsEmpty;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
boolean flushEventLogByCount(int count) {
Date lastEventDate = null;
boolean cacheIsEmpty = true;
IndexWriter indexWriter = null;
long l = System.currentTimeMillis();
logger.finest("......flush eventlog cache....");
List<org.imixs.workflow.engine.jpa.Document> documentList = eventLogService.findEvents(count + 1,
EVENTLOG_TOPIC_ADD, EVENTLOG_TOPIC_REMOVE);
if (documentList != null && documentList.size() > 0) {
try {
indexWriter = createIndexWriter();
int _counter = 0;
for (org.imixs.workflow.engine.jpa.Document eventLogEntry : documentList) {
String topic = null;
String id = eventLogEntry.getId();
// cut prafix...
if (id.startsWith(EVENTLOG_TOPIC_ADD)) {
id = id.substring(EVENTLOG_TOPIC_ADD.length() + 1);
topic = EVENTLOG_TOPIC_ADD;
}
if (id.startsWith(EVENTLOG_TOPIC_REMOVE)) {
id = id.substring(EVENTLOG_TOPIC_REMOVE.length() + 1);
topic = EVENTLOG_TOPIC_REMOVE;
}
// lookup the workitem...
org.imixs.workflow.engine.jpa.Document doc = manager
.find(org.imixs.workflow.engine.jpa.Document.class, id);
Term term = new Term("$uniqueid", id);
// if the document was found we add/update the index. Otherwise we remove the
// document form the index.
if (doc != null && EVENTLOG_TOPIC_ADD.equals(topic)) {
// add workitem to search index....
long l2 = System.currentTimeMillis();
ItemCollection workitem = new ItemCollection();
workitem.setAllItems(doc.getData());
if (!workitem.getItemValueBoolean(DocumentService.NOINDEX)) {
indexWriter.updateDocument(term, createDocument(workitem));
logger.finest("......lucene add/update workitem '" + id + "' to index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
} else {
long l2 = System.currentTimeMillis();
indexWriter.deleteDocuments(term);
logger.finest("......lucene remove workitem '" + id + "' from index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
// remove the eventLogEntry.
lastEventDate = eventLogEntry.getCreated().getTime();
manager.remove(eventLogEntry);
// break?
_counter++;
if (_counter >= count) {
// we skipp the last one if the maximum was reached.
cacheIsEmpty = false;
break;
}
}
} catch (IOException luceneEx) {
logger.warning("...unable to flush lucene event log: " + luceneEx.getMessage());
// We just log a warning here and close the flush mode to no longer block the
// writer.
// NOTE: maybe throwing a IndexException would be an alternative:
//
// throw new IndexException(IndexException.INVALID_INDEX, "Unable to update
// lucene search index",
// luceneEx);
return true;
} finally {
// close writer!
if (indexWriter != null) {
logger.finest("......lucene close IndexWriter...");
try {
indexWriter.close();
} catch (CorruptIndexException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
} catch (IOException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
}
}
}
}
logger.fine("...flushEventLog - " + documentList.size() + " events in " + (System.currentTimeMillis() - l)
+ " ms - last log entry: " + lastEventDate);
return cacheIsEmpty;
}
#location 90
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
//e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
}
#location 21
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void removeWorkitem(String uniqueID) throws PluginException {
IndexWriter awriter = null;
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (LockObtainFailedException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (IOException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void removeWorkitem(String uniqueID) throws PluginException {
IndexWriter awriter = null;
Properties prop = propertyService.getProperties();
if (!prop.isEmpty()) {
try {
awriter = createIndexWriter(prop);
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (LockObtainFailedException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (IOException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
}
}
}
#location 8
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 36
#vulnerability type NULL_DEREFERENCE |
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 66
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putDocuments(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putCollection(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
#location 18
#vulnerability type NULL_DEREFERENCE |
#fixed code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// test orign ref
Assert.assertEquals(orignUniqueID,subprocess.getItemValueString(SplitAndJoinPlugin.ORIGIN_REF));
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
#location 48
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum++);
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public boolean getPaused()
{
return isPaused();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean getPaused()
{
return paused;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR");
System.out.println("默认使用TessOCR,选择后回车,不能为空");
String selection=bf.readLine();
OCR ocr = OCR_FACTORY.getOcr(Integer.valueOf((selection.length()==0)?"1":selection));
System.out.println("请选择您要进入的游戏\n1.百万英雄\n2.冲顶大会");
System.out.println("默认为百万英雄,选择后回车");
selection=bf.readLine();
Pattern pattern = PATTERN_FACTORY.getPattern(Integer.valueOf((selection.length()==0)?"1":selection), ocr, UTILS);
while (true) {
String str = bf.readLine();
if ("exit".equals(str)) {
System.out.println("ヾ( ̄▽ ̄)Bye~Bye~");
break;
} else {
if (str.length() == 0) {
System.out.print("开始答题");
pattern.run();
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR");
System.out.println("默认使用TessOCR,选择后回车");
OCR ocr = OCR_FACTORY.getOcr(Integer.valueOf(bf.readLine()));
System.out.println("请选择您要进入的游戏\n1.百万英雄\n2.冲顶大会");
System.out.println("默认为百万英雄,选择后回车");
Pattern pattern = PATTERN_FACTORY.getPattern(Integer.valueOf(bf.readLine()), ocr, UTILS);
while (true) {
String str = bf.readLine();
if ("exit".equals(str)) {
System.out.println("ヾ( ̄▽ ̄)Bye~Bye~");
break;
} else {
if (str.length() == 0) {
System.out.print("开始答题");
pattern.run();
}
}
}
}
#location 18
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void run() {
try {
LOGGER.info(I18n.UPDATE_LOADING);
URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line, pageSource = "";
while ((line = reader.readLine()) != null) {
pageSource += line + "\n";
}
reader.close();
Float gitVersion = Float.parseFloat(pageSource);
MediatorGUI.model();
if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) {
LOGGER.debug(I18n.UPDATE_UPTODATE);
} else {
LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE);
}
} catch (NumberFormatException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
} catch (IOException e) {
LOGGER.warn(I18n.UPDATE_EXCEPTION);
LOGGER.error(e, e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
getReference(ViewScopeManager.class).preDestroyView();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
if (event instanceof PreDestroyViewMapEvent) {
BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
@SuppressWarnings("unchecked")
public static <T> void destroy(BeanManager beanManager, T instance) {
if (instance instanceof Class) { // Java prefers T over Class<T> when varargs is not specified :(
destroy(beanManager, (Class<T>) instance, new Annotation[0]);
}
else {
Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass());
if (bean != null) {
destroy(beanManager, bean, instance);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
public static <T> void destroy(BeanManager beanManager, T instance) {
if (instance instanceof Class) {
destroy(beanManager, (Class<T>) instance, new Annotation[0]);
}
else if (instance instanceof Bean) {
destroy(beanManager, (Bean<T>) instance);
}
else {
Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass());
bean.destroy(instance, beanManager.createCreationalContext(bean));
}
}
#location 11
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
EagerBeansRepository.getInstance().instantiateApplicationScoped();
FacesViews.addMappings(event.getServletContext());
CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void contextInitialized(ServletContextEvent event) {
checkCDIAvailable();
BeanManager.INSTANCE.getReference(EagerBeansRepository.class).instantiateApplicationScoped();
FacesViews.addMappings(event.getServletContext());
CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext());
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public void encodeChildren(FacesContext context) throws IOException {
if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel));
}
boolean connected = isConnected();
Boolean switched = hasSwitched(context, channel, connected);
String script = null;
if (switched == null) {
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected);
}
else if (switched) {
script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel);
}
if (script != null) {
context.getResponseWriter().write(script);
}
rendered = super.isRendered();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void encodeChildren(FacesContext context) throws IOException {
if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) {
throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED);
}
String channel = getChannel();
if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) {
throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel));
}
boolean connected = isConnected();
Boolean switched = hasSwitched(context, channel, connected);
String script = null;
if (switched == null) {
Integer port = getPort();
String host = (port != null ? ":" + port : "") + getRequestContextPath(context);
String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser());
String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose();
script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected);
}
else if (switched) {
script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel);
}
if (script != null) {
context.getResponseWriter().write(script);
}
}
#location 20
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) throws IOException {
BufferedWriter svmDataFile = null;
try {
FileWriter fstream = new FileWriter(filePath);
svmDataFile = new BufferedWriter(fstream);
for (TrainingElement<BxZoneLabel> elem : trainingElements) {
svmDataFile.write(String.valueOf(elem.getLabel().ordinal()));
svmDataFile.write(" ");
Integer featureCounter = 1;
for (Double value : elem.getObservation().getFeatures()) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%d:%.5f", featureCounter++, value);
svmDataFile.write(sb.toString());
svmDataFile.write(" ");
}
svmDataFile.write("\n");
}
svmDataFile.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return;
} finally {
if(svmDataFile != null) {
svmDataFile.close();
}
}
System.out.println("Done.");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) {
try {
FileWriter fstream = new FileWriter(filePath);
BufferedWriter svmDataFile = new BufferedWriter(fstream);
for (TrainingElement<BxZoneLabel> elem : trainingElements) {
svmDataFile.write(String.valueOf(elem.getLabel().ordinal()));
svmDataFile.write(" ");
Integer featureCounter = 1;
for (Double value : elem.getObservation().getFeatures()) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%d:%.5f", featureCounter++, value);
svmDataFile.write(sb.toString());
svmDataFile.write(" ");
}
svmDataFile.write("\n");
}
svmDataFile.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return;
}
System.out.println("Done.");
}
#location 20
#vulnerability type RESOURCE_LEAK |
#fixed code
public static void main(String[] args) throws JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<String, List<Result>> results = new HashMap<String, List<Result>>();
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
List<BibEntry> testEntries = new ArrayList<BibEntry>();
for (Citation c : testCitations) {
BibEntry entry = CitationUtils.citationToBibref(c);
testEntries.add(entry);
for (String key : entry.getFieldKeys()) {
if (results.get(key) == null) {
results.put(key, new ArrayList<Result>());
}
}
}
int j = 0;
for (BibEntry orig : testEntries) {
BibEntry test = parser.parseBibReference(orig.getText());
System.out.println();
System.out.println();
System.out.println(orig.toBibTeX());
System.out.println(test.toBibTeX());
Map<String, Result> map = new HashMap<String, Result>();
for (String s : orig.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addOrig(orig.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addExtr(test.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
List<String> origVals = orig.getAllFieldValues(s);
for (String testVal : test.getAllFieldValues(s)) {
boolean found = false;
if (origVals.contains(testVal)) {
map.get(s).addSuccess();
origVals.remove(testVal);
found = true;
}
if (!found) {
System.out.println("WRONG "+s);
}
}
}
for (Map.Entry<String, Result> s : map.entrySet()) {
System.out.println("");
System.out.println(s.getKey());
System.out.println(s.getValue());
System.out.println(s.getValue().getPrecision());
System.out.println(s.getValue().getRecall());
results.get(s.getKey()).add(s.getValue());
}
j++;
System.out.println("Tested "+j+" out of "+testEntries.size());
}
}
for (Map.Entry<String, List<Result>> e : results.entrySet()) {
System.out.println("");
System.out.println(e.getKey());
System.out.println(e.getValue().size());
double precision = 0;
int precisionCount = 0;
double recall = 0;
int recallCount = 0;
for (Result r : e.getValue()) {
if (r.getPrecision() != null) {
precision += r.getPrecision();
precisionCount++;
}
if (r.getRecall() != null) {
recall += r.getRecall();
recallCount++;
}
}
System.out.println("Precision count "+precisionCount);
System.out.println("Mean precision "+(precision / precisionCount));
System.out.println("Recall count "+recallCount);
System.out.println("Mean recall "+(recall / recallCount));
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<String, List<Result>> results = new HashMap<String, List<Result>>();
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
List<BibEntry> testEntries = new ArrayList<BibEntry>();
for (Citation c : testCitations) {
BibEntry entry = CitationUtils.citationToBibref(c);
testEntries.add(entry);
for (String key : entry.getFieldKeys()) {
if (results.get(key) == null) {
results.put(key, new ArrayList<Result>());
}
}
}
int j = 0;
for (BibEntry orig : testEntries) {
BibEntry test = parser.parseBibReference(orig.getText());
System.out.println();
System.out.println();
System.out.println(orig.toBibTeX());
System.out.println(test.toBibTeX());
Map<String, Result> map = new HashMap<String, Result>();
for (String s : orig.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addOrig(orig.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addExtr(test.getAllFieldValues(s).size());
}
for (String s : test.getFieldKeys()) {
List<String> origVals = orig.getAllFieldValues(s);
for (String testVal : test.getAllFieldValues(s)) {
boolean found = false;
if (origVals.contains(testVal)) {
map.get(s).addSuccess();
origVals.remove(testVal);
found = true;
}
if (!found) {
System.out.println("WRONG "+s);
}
}
}
for (Map.Entry<String, Result> s : map.entrySet()) {
System.out.println("");
System.out.println(s.getKey());
System.out.println(s.getValue());
System.out.println(s.getValue().getPrecision());
System.out.println(s.getValue().getRecall());
results.get(s.getKey()).add(s.getValue());
}
j++;
System.out.println("Tested "+j+" out of "+testEntries.size());
}
}
for (String s : results.keySet()) {
System.out.println("");
System.out.println(s);
System.out.println(results.get(s).size());
double precision = 0;
int precisionCount = 0;
double recall = 0;
int recallCount = 0;
for (Result r : results.get(s)) {
if (r.getPrecision() != null) {
precision += r.getPrecision();
precisionCount++;
}
if (r.getRecall() != null) {
recall += r.getRecall();
recallCount++;
}
}
System.out.println("Precision count "+precisionCount);
System.out.println("Mean precision "+(precision / precisionCount));
System.out.println("Recall count "+recallCount);
System.out.println("Mean recall "+(recall / recallCount));
}
}
#location 103
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static void main(String[] args) {
AppUtil appUtil = new AppUtil();
AService service = (AService) appUtil.getComponentInstance("aService");
AggregateRootA aggregateRootA = service.getAggregateRootA("11");
DomainMessage res = service.commandA("11", aggregateRootA, 100);
long start = System.currentTimeMillis();
int result = 0;
DomainMessage res1 = (DomainMessage) res.getBlockEventResult();
if (res1 != null && res1.getBlockEventResult() != null)
result = (Integer) res1.getBlockEventResult();
long stop = System.currentTimeMillis();
Assert.assertEquals(result, 400);
System.out.print("\n ok \n" + result + " time:" + (stop - start));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) {
AppUtil appUtil = new AppUtil();
AService service = (AService) appUtil.getComponentInstance("aService");
AggregateRootA aggregateRootA = service.getAggregateRootA("11");
DomainMessage res = service.commandA("11", aggregateRootA, 100);
long start = System.currentTimeMillis();
int result = 0;
DomainMessage res1 = (DomainMessage) res.getBlockEventResult();
if (res1.getBlockEventResult() != null)
result = (Integer) res1.getBlockEventResult();
long stop = System.currentTimeMillis();
Assert.assertEquals(result, 400);
System.out.print("\n ok \n" + result + (stop - start));
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Template include(String name, Locale locale, String encoding) throws IOException, ParseException {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("include template name == null");
}
String macro = null;
int i = name.indexOf('#');
if (i > 0) {
macro = name.substring(i + 1);
name = name.substring(0, i);
}
Template template = Context.getContext().getTemplate();
if (template != null) {
if (encoding == null || encoding.length() == 0) {
encoding = template.getEncoding();
}
name = UrlUtils.relativeUrl(name, template.getName());
if (locale == null) {
locale = template.getLocale();
}
}
Template include = engine.getTemplate(name, locale, encoding);
if (macro != null && macro.length() > 0) {
include = include.getMacros().get(macro);
}
if (template != null && template == include) {
throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template.");
}
return include;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Template include(String name, Locale locale, String encoding) throws IOException, ParseException {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("include template name == null");
}
String macro = null;
int i = name.indexOf('#');
if (i > 0) {
macro = name.substring(i + 1);
name = name.substring(0, i);
}
Template template = Context.getContext().getTemplate();
if (template != null) {
if (encoding == null || encoding.length() == 0) {
encoding = template.getEncoding();
}
name = UrlUtils.relativeUrl(name, template.getName());
if (locale == null) {
locale = template.getLocale();
}
}
Template include = engine.getTemplate(name, locale, encoding);
if (macro != null && macro.length() > 0) {
include = include.getMacros().get(macro);
}
if (include == template) {
throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template.");
}
return include;
}
#location 26
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
try {
// add request, response & servletContext to thread local
Context.set(Context.webContext(request, response, filterConfig));
IOUtils.write("\nBefore chain!\n", response.getOutputStream());
final ByteArrayOutputStream os = new ByteArrayOutputStream();
System.out.println(response.getOutputStream());
final HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response);
chain.doFilter(request, wrappedResponse);
final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding()));
doProcess(reader, new OutputStreamWriter(os));
IOUtils.write(os.toByteArray(), response.getOutputStream());
response.flushBuffer();
response.getOutputStream().close();
} catch (final RuntimeException e) {
onRuntimeException(e, response, chain);
} finally {
Context.unset();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
try {
// add request, response & servletContext to thread local
Context.set(Context.webContext(request, response, filterConfig));
final ByteArrayOutputStream os = new ByteArrayOutputStream();
HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response);
chain.doFilter(req, wrappedResponse);
final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding()));
doProcess(reader, response.getWriter());
response.flushBuffer();
} catch (final RuntimeException e) {
onRuntimeException(e, response, chain);
} finally {
Context.unset();
}
}
#location 11
#vulnerability type RESOURCE_LEAK |
#fixed code
@CheckForNull
@Override
public CNode describe(T instance) throws Exception {
// Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor
// and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others
// need to be compared with default values.
// Build same object with only constructor parameters
final Constructor constructor = getDataBoundConstructor(target);
final Parameter[] parameters = constructor.getParameters();
final String[] names = ClassDescriptor.loadParameterNames(constructor);
final Attribute[] attributes = new Attribute[parameters.length];
final Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Parameter p = parameters[i];
final Attribute a = detectActualType(names[i], p.getParameterizedType());
args[i] = a.getValue(instance);
attributes[i] = a;
}
T ref = (T) constructor.newInstance(args);
// compare instance with this "default" object
Mapping mapping = compare(instance, ref);
// add constructor parameters
for (int i = 0; i < parameters.length; i++) {
final Configurator c = Configurator.lookup(attributes[i].getType());
if (args[i] == null) continue;
mapping.put(names[i], attributes[i].describe(args[i]));
}
return mapping;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@CheckForNull
@Override
public CNode describe(T instance) throws Exception {
// Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor
// and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others
// need to be compared with default values.
// Build same object with only constructor parameters
final Constructor constructor = getDataBoundConstructor(target);
final Parameter[] parameters = constructor.getParameters();
final String[] names = ClassDescriptor.loadParameterNames(constructor);
final Attribute[] attributes = new Attribute[parameters.length];
final Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Parameter p = parameters[i];
final Attribute a = detectActualType(names[i], p.getParameterizedType());
args[i] = a.getValue(instance);
attributes[i] = a;
}
T ref = (T) constructor.newInstance(args);
// compare instance with this "default" object
Mapping mapping = compare(instance, ref);
// add constructor parameters
for (int i = 0; i < parameters.length; i++) {
final Configurator c = Configurator.lookup(attributes[i].getType());
mapping.put(names[i], c.describe(args[i]));
}
return mapping;
}
#location 31
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void recover() {
final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles();
if (mappedFiles.isEmpty()) {
this.indexFileQueue.updateWherePosition(0);
this.indexFileQueue.truncateDirtyFiles(0);
return;
}
int index = mappedFiles.size() - 3;
if (index < 0) {
index = 0;
}
long firstEntryIndex = -1;
for (int i = index; i >= 0; i--) {
index = i;
MmapFile mappedFile = mappedFiles.get(index);
ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
try {
int magic = byteBuffer.getInt();
int size = byteBuffer.getInt();
long entryIndex = byteBuffer.getLong();
long entryTerm = byteBuffer.get();
PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic);
PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) );
SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE);
PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE));
indexSbr.release();
ByteBuffer indexByteBuffer = indexSbr.getByteBuffer();
int magicFromIndex = indexByteBuffer.getInt();
long posFromIndex = indexByteBuffer.getLong();
int sizeFromIndex = indexByteBuffer.getInt();
long indexFromIndex = indexByteBuffer.getLong();
long termFromIndex = indexByteBuffer.get();
PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex));
PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex));
PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex));
PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex));
PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex));
firstEntryIndex = entryIndex;
break;
} catch (Throwable t) {
logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t);
}
}
MmapFile mappedFile = mappedFiles.get(index);
ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName());
long lastEntryIndex = -1;
long lastEntryTerm = -1;
long processOffset = mappedFile.getFileFromOffset();
boolean needWriteIndex = false;
while (true) {
try {
int relativePos = byteBuffer.position();
long absolutePos = mappedFile.getFileFromOffset() + relativePos;
int magic = byteBuffer.getInt();
if (magic == MmapFileQueue.BLANK_MAGIC_CODE) {
processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize();
index++;
if (index >= mappedFiles.size()) {
logger.info("Recover data file over, the last file {}", mappedFile.getFileName());
break;
} else {
mappedFile = mappedFiles.get(index);
byteBuffer = mappedFile.sliceByteBuffer();
processOffset = mappedFile.getFileFromOffset();
logger.info("Trying to recover index file {}", mappedFile.getFileName());
continue;
}
}
int size = byteBuffer.getInt();
long entryIndex = byteBuffer.getLong();
long entryTerm = byteBuffer.get();
byteBuffer.position(relativePos + size);
String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm);
PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC));
if (lastEntryIndex != -1) {
PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex));
}
PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm));
PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) );
if (!needWriteIndex) {
try {
SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE);
PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE));
indexSbr.release();
ByteBuffer indexByteBuffer = indexSbr.getByteBuffer();
int magicFromIndex = indexByteBuffer.getInt();
long posFromIndex = indexByteBuffer.getLong();
int sizeFromIndex = indexByteBuffer.getInt();
long indexFromIndex = indexByteBuffer.getLong();
long termFromIndex = indexByteBuffer.get();
PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex));
PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex));
PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex));
PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex));
PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex));
} catch (Exception e) {
logger.warn("Compare data to index failed {}", mappedFile.getFileName());
indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE);
if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) {
logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE);
indexFileQueue.truncateDirtyFiles(0);
}
if (indexFileQueue.getMappedFiles().isEmpty()) {
indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE);
}
needWriteIndex = true;
}
}
if (needWriteIndex) {
ByteBuffer indexBuffer = localIndexBuffer.get();
DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer);
long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining());
PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex));
}
lastEntryIndex = entryIndex;
lastEntryTerm = entryTerm;
processOffset += size;
} catch (Throwable t) {
logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t);
break;
}
}
logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset);
legerEndIndex = lastEntryIndex;
legerEndTerm = lastEntryTerm;
if (lastEntryIndex != -1) {
DLegerEntry entry = get(lastEntryIndex);
PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry");
PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex));
reviseLegerBeginIndex();
} else {
processOffset = 0;
}
this.dataFileQueue.updateWherePosition(processOffset);
this.dataFileQueue.truncateDirtyFiles(processOffset);
long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE;
this.indexFileQueue.updateWherePosition(indexProcessOffset);
this.indexFileQueue.truncateDirtyFiles(indexProcessOffset);
return;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void recover() {
final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles();
if (mappedFiles.isEmpty()) {
this.indexFileQueue.updateWherePosition(0);
this.indexFileQueue.truncateDirtyFiles(0);
return;
}
int index = mappedFiles.size() - 3;
if (index < 0) {
index = 0;
}
long firstEntryIndex = -1;
for (int i = index; i >= 0; i--) {
index = i;
MmapFile mappedFile = mappedFiles.get(index);
ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
try {
int magic = byteBuffer.getInt();
int size = byteBuffer.getInt();
long entryIndex = byteBuffer.getLong();
long entryTerm = byteBuffer.get();
PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic);
PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) );
SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE);
PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE));
indexSbr.release();
ByteBuffer indexByteBuffer = indexSbr.getByteBuffer();
int magicFromIndex = indexByteBuffer.getInt();
long posFromIndex = indexByteBuffer.getLong();
int sizeFromIndex = indexByteBuffer.getInt();
long indexFromIndex = indexByteBuffer.getLong();
long termFromIndex = indexByteBuffer.get();
PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex));
PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex));
PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex));
PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex));
PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex));
firstEntryIndex = entryIndex;
break;
} catch (Throwable t) {
logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t);
}
}
MmapFile mappedFile = mappedFiles.get(index);
ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName());
long lastEntryIndex = -1;
long lastEntryTerm = -1;
long processOffset = mappedFile.getFileFromOffset();
boolean needWriteIndex = false;
while (true) {
try {
int relativePos = byteBuffer.position();
long absolutePos = mappedFile.getFileFromOffset() + relativePos;
int magic = byteBuffer.getInt();
if (magic == MmapFileQueue.BLANK_MAGIC_CODE) {
processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize();
index++;
if (index >= mappedFiles.size()) {
logger.info("Recover data file over, the last file {}", mappedFile.getFileName());
break;
} else {
mappedFile = mappedFiles.get(index);
byteBuffer = mappedFile.sliceByteBuffer();
processOffset = mappedFile.getFileFromOffset();
logger.info("Trying to recover index file {}", mappedFile.getFileName());
continue;
}
}
int size = byteBuffer.getInt();
long entryIndex = byteBuffer.getLong();
long entryTerm = byteBuffer.get();
byteBuffer.position(relativePos + size);
String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm);
PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC));
if (lastEntryIndex != -1) {
PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex));
}
PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm));
PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) );
if (!needWriteIndex) {
try {
SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE);
PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE));
indexSbr.release();
ByteBuffer indexByteBuffer = indexSbr.getByteBuffer();
int magicFromIndex = indexByteBuffer.getInt();
long posFromIndex = indexByteBuffer.getLong();
int sizeFromIndex = indexByteBuffer.getInt();
long indexFromIndex = indexByteBuffer.getLong();
long termFromIndex = indexByteBuffer.get();
PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex));
PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex));
PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex));
PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex));
PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex));
} catch (Exception e) {
logger.warn("Compare data to index failed {}", mappedFile.getFileName());
indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE);
if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) {
logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE);
indexFileQueue.truncateDirtyFiles(0);
}
if (indexFileQueue.getMappedFiles().isEmpty()) {
indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE);
}
needWriteIndex = true;
}
}
if (needWriteIndex) {
ByteBuffer indexBuffer = localIndexBuffer.get();
DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer);
long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining());
PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex));
}
lastEntryIndex = entryIndex;
lastEntryTerm = entryTerm;
processOffset += size;
} catch (Throwable t) {
logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t);
break;
}
}
logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset);
legerEndIndex = lastEntryIndex;
legerEndTerm = lastEntryTerm;
if (lastEntryIndex != -1) {
DLegerEntry entry = get(lastEntryIndex);
PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry");
PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex));
//get leger begin index
ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer();
tmpBuffer.getInt(); //magic
tmpBuffer.getInt(); //size
legerBeginIndex = byteBuffer.getLong();
} else {
processOffset = 0;
}
this.dataFileQueue.updateWherePosition(processOffset);
this.dataFileQueue.truncateDirtyFiles(processOffset);
long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE;
this.indexFileQueue.updateWherePosition(indexProcessOffset);
this.indexFileQueue.truncateDirtyFiles(indexProcessOffset);
return;
}
#location 140
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public DLegerEntry get(Long index) {
PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId());
SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE);
PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null);
indexSbr.getByteBuffer().getInt(); //magic
long pos = indexSbr.getByteBuffer().getLong();
int size = indexSbr.getByteBuffer().getInt();
indexSbr.release();
SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size);
PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null);
DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer());
dLegerEntry.setPos(pos);
dataSbr.release();
return dLegerEntry;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public DLegerEntry get(Long index) {
PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId());
SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE);
PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null);
indexSbr.getByteBuffer().getInt(); //magic
long pos = indexSbr.getByteBuffer().getLong();
int size = indexSbr.getByteBuffer().getInt();
indexSbr.release();
SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size);
PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null);
DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer());
dataSbr.release();
return dLegerEntry;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
private byte[] loadJarData(String path, String fileName) {
ZipFile zipFile;
ZipEntry entry;
int size;
try {
zipFile = new ZipFile(new File(path));
entry = zipFile.getEntry(fileName);
if (entry == null) {
zipFile.close();
return null;
}
size = (int) entry.getSize();
} catch (IOException io) {
return null;
}
InputStream stream = null;
try {
stream = zipFile.getInputStream(entry);
if (stream == null) {
zipFile.close();
return null;
}
byte[] data = new byte[size];
int pos = 0;
while (pos < size) {
int n = stream.read(data, pos, data.length - pos);
pos += n;
}
zipFile.close();
return data;
} catch (IOException e) {
} finally {
try {
if (stream != null) stream.close();
} catch (IOException e) {
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private byte[] loadJarData(String path, String fileName) {
ZipFile zipFile;
ZipEntry entry;
int size;
try {
zipFile = new ZipFile(new File(path));
entry = zipFile.getEntry(fileName);
if (entry == null) return null;
size = (int) entry.getSize();
} catch (IOException io) {
return null;
}
InputStream stream = null;
try {
stream = zipFile.getInputStream(entry);
if (stream == null) return null;
byte[] data = new byte[size];
int pos = 0;
while (pos < size) {
int n = stream.read(data, pos, data.length - pos);
pos += n;
}
zipFile.close();
return data;
} catch (IOException e) {
} finally {
try {
if (stream != null) stream.close();
} catch (IOException e) {
}
}
return null;
}
#location 19
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testConstructor2() {
NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, processor and throwable
e = new NullInputException(null, (CellProcessor) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testConstructor2() {
NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, processor and throwable
e = new NullInputException(null, (CellProcessor) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
#fixed code
private Set<T> aggregateSet() {
if (areAllInitial(changeNotifiers)) {
return ChangeNotifiers.initialEmptyDataInstance();
}
ImmutableSet.Builder<T> records = ImmutableSet.builder();
for (final ChangeNotifier<T> changeNotifier : changeNotifiers) {
records.addAll(changeNotifier.current());
}
return records.build();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Set<T> aggregateSet() {
ImmutableSet.Builder<T> records = ImmutableSet.builder();
for (final ChangeNotifier<T> changeNotifier : changeNotifiers) {
records.addAll(changeNotifier.current());
}
return records.build();
}
#location 1
#vulnerability type CHECKERS_IMMUTABLE_CAST |
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public static void main(String[] args) {
ProtocolV1Client client = new ProtocolV1Client();
client.connect("127.0.0.1", 8811, 500);
Map<String, String> head = new HashMap<>();
head.put("tracerId", "xxadadadada");
head.put("token", "adadadad");
BranchCommitRequest body = new BranchCommitRequest();
body.setBranchId(12345L);
body.setApplicationData("application");
body.setBranchType(BranchType.AT);
body.setResourceId("resource-1234");
body.setXid("xid-1234");
final int threads = 50;
final AtomicLong cnt = new AtomicLong(0);
final ThreadPoolExecutor service1 = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(), new NamedThreadFactory("client-", false));// 无队列
for (int i = 0; i < threads; i++) {
service1.execute(() -> {
while (true) {
try {
Future future = client.sendRpc(head, body);
RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.MILLISECONDS);
if (resp != null) {
cnt.incrementAndGet();
}
} catch (Exception e) {
// ignore
}
}
});
}
Thread thread = new Thread(new Runnable() {
private long last = 0;
@Override
public void run() {
while (true) {
long count = cnt.get();
long tps = count - last;
LOGGER.error("last 1s invoke: {}, queue: {}", tps, service1.getQueue().size());
last = count;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}, "Print-tps-THREAD");
thread.start();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException {
ProtocolV1Client client = new ProtocolV1Client();
client.connect("127.0.0.1", 8811, 500);
Map<String, String> head = new HashMap<>();
head.put("tracerId", "xxadadadada");
head.put("token", "adadadad");
BranchCommitRequest body = new BranchCommitRequest();
body.setBranchId(12345L);
body.setApplicationData("application");
body.setBranchType(BranchType.AT);
body.setResourceId("resource-1234");
body.setXid("xid-1234");
RpcMessage rpcMessage = new RpcMessage();
rpcMessage.setId(client.idGenerator.incrementAndGet());
rpcMessage.setCodec(CodecType.SEATA.getCode());
rpcMessage.setCompressor(ProtocolConstants.CONFIGURED_COMPRESSOR);
rpcMessage.setHeadMap(head);
rpcMessage.setBody(body);
rpcMessage.setMessageType(ProtocolConstants.MSGTYPE_RESQUEST);
Future future = client.send(rpcMessage.getId(), rpcMessage);
RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.SECONDS);
System.out.println(resp.getId() + " " + resp.getBody());
}
#location 25
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).extracting("payload").containsExactly("foo", "bar");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).hasSize(2);
assertThat(records.get(0).getPayload()).isEqualTo("foo");
assertThat(records.get(1).getPayload()).isEqualTo("bar");
}
#location 19
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error == null){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must start with field's 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field's 1 content [" + content1 + "]";
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error.length() == 0){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must starts with field 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field 1 content [" + content1 + "]";
}
return "";
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testBzip2Unarchive() throws Exception {
final File output = new File(dir, "test-entpackt.txt");
System.out.println(dir);
final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile());
final InputStream is = new FileInputStream(input);
//final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final CompressorInputStream in = new BZip2CompressorInputStream(is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 7
#vulnerability type RESOURCE_LEAK |
#fixed code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
IOUtils.closeQuietly( input );
IOUtils.closeQuietly( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
IOUtils.closeQuietly( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
shutdownStream( input );
shutdownStream( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
shutdownStream( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
}
#location 13
#vulnerability type RESOURCE_LEAK |
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 21
#vulnerability type RESOURCE_LEAK |
#fixed code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(file1);
IOUtils.copy(in, os);
os.closeArchiveEntry();
os.close();
out.close();
in.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
os2.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK |
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
FileOutputStream os = new FileOutputStream(output);
IOUtils.copy(in, os);
is.close();
os.close();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 6
#vulnerability type RESOURCE_LEAK |
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK |
#fixed code
@PreAuthorize("hasPermission(#user, 'edit')")
@Validated(BaseUser.UpdateValidation.class)
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public U updateUser(U user, @Valid U updatedUser) {
SaUtil.validate(user != null, "userNotFound");
SaUtil.validateVersion(user, updatedUser);
U loggedIn = SaUtil.getLoggedInUser();
updateUserFields(user, updatedUser, loggedIn);
userRepository.save(user);
return userForClient(loggedIn);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@PreAuthorize("hasPermission(#user, 'edit')")
@Validated(BaseUser.UpdateValidation.class)
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public U updateUser(U user, @Valid U updatedUser) {
SaUtil.validate(user != null, "userNotFound");
user.setName(updatedUser.getName());
if (user.isRolesEditable()) {
Set<String> roles = user.getRoles();
if (updatedUser.isUnverified())
roles.add(Role.UNVERIFIED);
else
roles.remove(Role.UNVERIFIED);
if (updatedUser.isAdmin())
roles.add(Role.ADMIN);
else
roles.remove(Role.ADMIN);
if (updatedUser.isBlocked())
roles.add(Role.BLOCKED);
else
roles.remove(Role.BLOCKED);
}
//user.setVersion(updatedUser.getVersion());
userRepository.save(user);
U loggedIn = SaUtil.getLoggedInUser();
if (loggedIn.equals(user)) {
loggedIn.setName(user.getName());
loggedIn.setRoles(user.getRoles());
}
return userForClient(loggedIn);
}
#location 32
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "@";
break;
default:
Util.msg("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "&";
break;
default:
System.err.println("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
#location 6
#vulnerability type NULL_DEREFERENCE |
#fixed code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getSingle().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getSingle();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getFirstNode().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getFirstNode();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
public int compareTo(@NotNull Object o) {
return getSingle().getStart() - ((Binding)o).getSingle().getStart();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public int compareTo(@NotNull Object o) {
return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart();
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
boolean checkBindingExist(List<Binding> bs, String file, int start, int end) {
if (bs == null) {
return false;
}
for (Binding b : bs) {
if (((b.getFile() == null && file == null) ||
(b.getFile() != null && file != null && b.getFile().equals(file))) &&
b.start == start && b.end == end)
{
return true;
}
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
boolean checkBindingExist(List<Binding> bs, String name, String file, int start) {
if (bs == null) {
return false;
}
for (Binding b : bs) {
String actualFile = b.getFile();
if (b.getName().equals(name) &&
actualFile.equals(file) &&
b.getStart() == start)
{
return true;
}
}
return false;
}
#location 9
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void authEnabled() throws IOException {
greenMail.getManagers().getUserManager().setAuthRequired(true);
withConnection((printStream, reader) -> {
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER [email protected]" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
});
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void authEnabled() throws IOException, UserException {
try (Socket socket = new Socket(hostAddress, port)) {
assertThat(socket.isConnected()).isTrue();
PrintStream printStream = new PrintStream(socket.getOutputStream());
final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
greenMail.getManagers().getUserManager().setAuthRequired(true);
assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v");
printStream.print("USER [email protected]" + CRLF);
assertThat(reader.readLine()).isNotEqualTo("+OK");
}
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public List<FileDto> queryFiles(@RequestBody FileDto fileDto) {
//return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class);
List<FileDto> fileDtos = new ArrayList<>();
String fileName = fileDto.getFileSaveName();
String ftpPath = java110Properties.getFtpPath();
if (fileName.contains("/")) {
ftpPath += fileName.substring(0, fileName.lastIndexOf("/")+1);
fileName = fileName.substring(fileName.lastIndexOf("/")+1, fileName.length());
}
byte[] fileImg = ftpUploadTemplate.downFileByte(ftpPath, fileName, java110Properties.getFtpServer(),
java110Properties.getFtpPort(), java110Properties.getFtpUserName(),
java110Properties.getFtpUserPassword());
try {
File file = new File("/home/hc/img/"+ UUID.randomUUID().toString()+".jpg");
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if(!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
out.write(fileImg);
}catch (Exception e){
e.printStackTrace();
}
//String context = new BASE64Encoder().encode(fileImg);
String context = Base64Convert.byteToBase64(fileImg);
fileDto.setContext(context);
fileDtos.add(fileDto);
return fileDtos;
}
#location 24
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
//JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
responseEntity = MachineResDataVo.getResData(MachineResDataVo.CODE_ERROR,"该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
JSONObject outParam = null;
ResponseEntity<String> responseEntity = null;
Map<String, String> reqHeader = context.getRequestHeaders();
String communityId = reqHeader.get("communityId");
String machineCode = reqHeader.get("machinecode");
HttpHeaders headers = new HttpHeaders();
for (String key : reqHeader.keySet()) {
if (key.toLowerCase().equals("content-length")) {
continue;
}
headers.add(key, reqHeader.get(key));
}
//根据设备编码查询 设备信息
MachineDto machineDto = new MachineDto();
machineDto.setMachineCode(machineCode);
machineDto.setCommunityId(communityId);
List<MachineDto> machineDtos = machineInnerServiceSMOImpl.queryMachines(machineDto);
if (machineDtos == null || machineDtos.size() < 1) {
outParam.put("code", -1);
outParam.put("message", "该设备【" + machineCode + "】未在该小区【" + communityId + "】注册");
responseEntity = new ResponseEntity<>(outParam.toJSONString(), headers, HttpStatus.OK);
context.setResponseEntity(responseEntity);
return;
}
//设备方向
String direction = machineDtos.get(0).getDirection();
//进入
if (MACHINE_DIRECTION_IN.equals(direction)) {
dealCarIn(event, context, reqJson, machineDtos.get(0), communityId);
} else {
dealCarOut(event, context, reqJson, machineDtos.get(0), communityId);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE |
#fixed code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final URLClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
try {
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
} finally {
try {
loader.close();
} catch (IOException e) {
System.err.println("close failed: " + e);
e.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException {
final ClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fileManager.getClassLoader(StandardLocation.CLASS_PATH));
final List<Class<?>> classes = new ArrayList<Class<?>>(classFiles.size());
for (final JavaFile classFile : classFiles) {
final Class<?> clazz = loader.loadClass(classFile.getClassName());
classes.add(clazz);
}
return classes;
}
#location 8
#vulnerability type RESOURCE_LEAK |
#fixed code
public Object call(String method, Object[] params) throws XMLRPCException {
return new Caller().call(method, params);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Object call(String method, Object[] params) throws XMLRPCException {
try {
Call c = createCall(method, params);
URLConnection conn = this.url.openConnection();
if(!(conn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("The URL is not for a http connection.");
}
HttpURLConnection http = (HttpURLConnection)conn;
http.setRequestMethod(HTTP_POST);
http.setDoOutput(true);
http.setDoInput(true);
// Set the request parameters
for(Map.Entry<String,String> param : httpParameters.entrySet()) {
http.setRequestProperty(param.getKey(), param.getValue());
}
OutputStreamWriter stream = new OutputStreamWriter(http.getOutputStream());
stream.write(c.getXML());
stream.flush();
stream.close();
InputStream istream = http.getInputStream();
if(http.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new XMLRPCException("The status code of the http response must be 200.");
}
// Check for strict parameters
if(isFlagSet(FLAGS_STRICT)) {
if(!http.getContentType().startsWith(TYPE_XML)) {
throw new XMLRPCException("The Content-Type of the response must be text/xml.");
}
}
return responseParser.parse(istream);
} catch (IOException ex) {
throw new XMLRPCException(ex);
}
}
#location 9
#vulnerability type RESOURCE_LEAK |
#fixed code
public int run() throws Throwable {
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Thread.currentThread().setContextClassLoader(setup); // or should this be 'jenkins'?
Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App");
return (int)c.getMethod("run",File.class,File.class).invoke(
c.newInstance(), warDir, pluginsDir
);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public int run() throws Throwable {
ClassLoader jenkins = createJenkinsWarClassLoader();
ClassLoader setup = createSetupClassLoader(jenkins);
Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App");
return (int)c.getMethod("run",File.class,File.class).invoke(
c.newInstance(), warDir, pluginsDir
);
}
#location 5
#vulnerability type RESOURCE_LEAK |
#fixed code
public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name,
@QueryParameter String description, @QueryParameter int executors,
@QueryParameter String remoteFsRoot, @QueryParameter String labels,
@QueryParameter String secret, @QueryParameter Node.Mode mode,
@QueryParameter(fixEmpty = true) String hash,
@QueryParameter boolean deleteExistingClients) throws IOException {
if (!getSwarmSecret().equals(secret)) {
rsp.setStatus(SC_FORBIDDEN);
return;
}
try {
Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(SlaveComputer.CREATE);
List<NodeProperty<Node>> nodeProperties = new ArrayList<>();
String[] toolLocations = req.getParameterValues("toolLocation");
if (!ArrayUtils.isEmpty(toolLocations)) {
List<ToolLocation> parsedToolLocations = parseToolLocations(toolLocations);
nodeProperties.add(new ToolLocationNodeProperty(parsedToolLocations));
}
String[] environmentVariables = req.getParameterValues("environmentVariable");
if (!ArrayUtils.isEmpty(environmentVariables)) {
List<EnvironmentVariablesNodeProperty.Entry> parsedEnvironmentVariables =
parseEnvironmentVariables(environmentVariables);
nodeProperties.add(
new EnvironmentVariablesNodeProperty(parsedEnvironmentVariables));
}
if (hash == null && jenkins.getNode(name) != null && !deleteExistingClients) {
// this is a legacy client, they won't be able to pick up the new name, so throw them away
// perhaps they can find another master to connect to
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf(
"A slave called '%s' already exists and legacy clients do not support name disambiguation%n",
name);
return;
}
if (hash != null) {
// try to make the name unique. Swarm clients are often replicated VMs, and they may have the same name.
name = name + '-' + hash;
}
// check for existing connections
{
Node n = jenkins.getNode(name);
if (n != null && !deleteExistingClients) {
Computer c = n.toComputer();
if (c != null && c.isOnline()) {
// this is an existing connection, we'll only cause issues
// if we trample over an online connection
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' is already created and on-line%n", name);
return;
}
}
}
SwarmSlave slave =
new SwarmSlave(
name,
"Swarm slave from "
+ req.getRemoteHost()
+ ((description == null || description.isEmpty())
? ""
: (": " + description)),
remoteFsRoot,
String.valueOf(executors),
mode,
"swarm " + Util.fixNull(labels),
nodeProperties);
jenkins.addNode(slave);
rsp.setContentType("text/plain; charset=iso-8859-1");
Properties props = new Properties();
props.put("name", name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
props.store(bos, "");
byte[] response = bos.toByteArray();
rsp.setContentLength(response.length);
ServletOutputStream outputStream = rsp.getOutputStream();
outputStream.write(response);
outputStream.flush();
} catch (FormException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name,
@QueryParameter String description, @QueryParameter int executors,
@QueryParameter String remoteFsRoot, @QueryParameter String labels,
@QueryParameter String secret, @QueryParameter Node.Mode mode,
@QueryParameter(fixEmpty = true) String hash,
@QueryParameter boolean deleteExistingClients) throws IOException {
if (!getSwarmSecret().equals(secret)) {
rsp.setStatus(SC_FORBIDDEN);
return;
}
try {
Jenkins jenkins = Jenkins.getInstance();
jenkins.checkPermission(SlaveComputer.CREATE);
List<NodeProperty<Node>> nodeProperties = new ArrayList<>();
String[] toolLocations = req.getParameterValues("toolLocation");
if (!ArrayUtils.isEmpty(toolLocations)) {
List<ToolLocation> parsedToolLocations = parseToolLocations(toolLocations);
nodeProperties.add(new ToolLocationNodeProperty(parsedToolLocations));
}
String[] environmentVariables = req.getParameterValues("environmentVariable");
if (!ArrayUtils.isEmpty(environmentVariables)) {
List<EnvironmentVariablesNodeProperty.Entry> parsedEnvironmentVariables =
parseEnvironmentVariables(environmentVariables);
nodeProperties.add(
new EnvironmentVariablesNodeProperty(parsedEnvironmentVariables));
}
if (hash == null && jenkins.getNode(name) != null && !deleteExistingClients) {
// this is a legacy client, they won't be able to pick up the new name, so throw them away
// perhaps they can find another master to connect to
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf(
"A slave called '%s' already exists and legacy clients do not support name disambiguation%n",
name);
return;
}
if (hash != null) {
// try to make the name unique. Swarm clients are often replicated VMs, and they may have the same name.
name = name + '-' + hash;
}
// check for existing connections
{
Node n = jenkins.getNode(name);
if (n != null && !deleteExistingClients) {
Computer c = n.toComputer();
if (c != null && c.isOnline()) {
// this is an existing connection, we'll only cause issues
// if we trample over an online connection
rsp.setStatus(SC_CONFLICT);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' is already created and on-line%n", name);
return;
}
}
}
SwarmSlave slave =
new SwarmSlave(
name,
"Swarm slave from "
+ req.getRemoteHost()
+ ((description == null || description.isEmpty())
? ""
: (": " + description)),
remoteFsRoot,
String.valueOf(executors),
mode,
"swarm " + Util.fixNull(labels),
nodeProperties);
jenkins.addNode(slave);
rsp.setContentType("text/plain; charset=iso-8859-1");
Properties props = new Properties();
props.put("name", name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
props.store(bos, "");
byte[] response = bos.toByteArray();
rsp.setContentLength(response.length);
ServletOutputStream outputStream = rsp.getOutputStream();
outputStream.write(response);
outputStream.flush();
} catch (FormException e) {
e.printStackTrace();
}
}
#location 15
#vulnerability type NULL_DEREFERENCE |
#fixed code
private Node getNodeByName(String name, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.get();
try {
Node n = jenkins.getNode(name);
if (n == null) {
rsp.setStatus(SC_NOT_FOUND);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' does not exist.%n", name);
return null;
}
return n;
} catch (NullPointerException ignored) {}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Node getNodeByName(String name, StaplerResponse rsp) throws IOException {
Jenkins jenkins = Jenkins.getInstance();
try {
Node n = jenkins.getNode(name);
if (n == null) {
rsp.setStatus(SC_NOT_FOUND);
rsp.setContentType("text/plain; UTF-8");
rsp.getWriter().printf("A slave called '%s' does not exist.%n", name);
return null;
}
return n;
} catch (NullPointerException ignored) {}
return null;
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testDeploymentFailure() throws Exception {
final long start = System.currentTimeMillis();
assertThat(testResult(TempJobFailureTestImpl.class),
hasSingleFailureContaining("AssertionError: Unexpected job state"));
final long end = System.currentTimeMillis();
assertTrue("Test should not time out", (end - start) < Jobs.TIMEOUT_MILLIS);
final byte[] testReport = Files.readAllBytes(REPORT_DIR.getRoot().listFiles()[0].toPath());
final TemporaryJobEvent[] events = Json.read(testReport, TemporaryJobEvent[].class);
for (final TemporaryJobEvent event : events) {
if (event.getStep().equals("test")) {
assertFalse("test should be reported as failed", event.isSuccess());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testDeploymentFailure() throws Exception {
final long start = System.currentTimeMillis();
assertThat(testResult(TempJobFailureTestImpl.class),
hasSingleFailureContaining("AssertionError: Unexpected job state"));
final long end = System.currentTimeMillis();
assertTrue("Test should not time out", (end-start) < Jobs.TIMEOUT_MILLIS);
final byte[] testReport = Files.readAllBytes(reportDir.getRoot().listFiles()[0].toPath());
final TemporaryJobEvent[] events = Json.read(testReport, TemporaryJobEvent[].class);
for (final TemporaryJobEvent event : events) {
if (event.getStep().equals("test")) {
assertFalse("test should be reported as failed", event.isSuccess());
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 27
#vulnerability type CHECKERS_PRINTF_ARGS |
#fixed code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
return Utils.setGoalOnHosts(client, out, json, hosts, deployment,
options.getString(tokenArg.getDest()));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected int runWithJobId(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final JobId jobId,
final BufferedReader stdin)
throws ExecutionException, InterruptedException, IOException {
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = new Deployment.Builder()
.setGoal(Goal.STOP)
.setJobId(jobId)
.build();
if (!json) {
out.printf("Stopping %s on %s%n", jobId, hosts);
}
int code = 0;
for (final String host : hosts) {
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final SetGoalResponse result = client.setGoal(deployment, host, token).get();
if (result.getStatus() == SetGoalResponse.Status.OK) {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("done%n");
}
} else {
if (json) {
out.printf(result.toJsonString());
} else {
out.printf("failed: %s%n", result);
}
code = 1;
}
}
return code;
}
#location 27
#vulnerability type CHECKERS_PRINTF_ARGS |
#fixed code
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id,
final CountDownLatch zkRegistrationSignal) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
if (config.isZooKeeperEnableAcls()) {
final String agentUser = config.getZookeeperAclAgentUser();
final String agentPassword = config.getZooKeeperAclAgentPassword();
final String masterUser = config.getZookeeperAclMasterUser();
final String masterDigest = config.getZooKeeperAclMasterDigest();
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or password not set");
}
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, masterDigest,
agentUser, digest(agentUser, agentPassword));
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", agentUser, agentPassword).getBytes()));
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
aclProvider,
authorization);
final ZooKeeperClient client = new DefaultZooKeeperClient(curator,
config.getZooKeeperClusterId());
client.start();
// Register the agent
zkRegistrar = new ZooKeeperRegistrarService(
client,
new AgentZooKeeperRegistrar(this, config.getName(),
id, config.getZooKeeperRegistrationTtlMinutes()),
zkRegistrationSignal);
return client;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id,
final CountDownLatch zkRegistrationSignal) {
ACLProvider aclProvider = null;
List<AuthInfo> authorization = null;
if (config.isZooKeeperEnableAcls()) {
final String agentUser = config.getZookeeperAclAgentUser();
final String agentPassword = config.getZooKeeperAclAgentPassword();
final String masterUser = config.getZookeeperAclMasterUser();
final String masterDigest = config.getZooKeeperAclMasterDigest();
if (isNullOrEmpty(agentUser) || isNullOrEmpty(agentPassword)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but agent username and/or password not set");
}
if (isNullOrEmpty(masterUser) || isNullOrEmpty(masterDigest)) {
throw new HeliosRuntimeException(
"ZooKeeper ACLs enabled but master username and/or digest not set");
}
aclProvider = heliosAclProvider(
masterUser, masterDigest,
agentUser, digest(agentUser, agentPassword));
authorization = Lists.newArrayList(new AuthInfo(
"digest", String.format("%s:%s", agentUser, agentPassword).getBytes()));
}
final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3);
final CuratorFramework curator = new CuratorClientFactoryImpl().newClient(
config.getZooKeeperConnectionString(),
config.getZooKeeperSessionTimeoutMillis(),
config.getZooKeeperConnectionTimeoutMillis(),
zooKeeperRetryPolicy,
config.getZooKeeperNamespace(),
aclProvider,
authorization);
final ZooKeeperClient client = new DefaultZooKeeperClient(curator,
config.getZooKeeperClusterId());
client.start();
// Register the agent
zkRegistrar = new ZooKeeperRegistrarService(
client,
new AgentZooKeeperRegistrar(this, config.getName(),
id, config.getZooKeeperRegistrationTtlMinutes()),
zkRegistrationSignal);
return client;
}
#location 30
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(super.getInputStream());
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public HttpRequest withBody() throws IOException {
body = ByteStreams.toByteArray(getInputStream());
return this;
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
public PaginationDTO list(Integer page, Integer size) {
PaginationDTO paginationDTO = new PaginationDTO();
Integer totalPage;
Integer totalCount = questionMapper.count();
if (totalCount % size == 0) {
totalPage = totalCount / size;
} else {
totalPage = totalCount / size + 1;
}
if (page < 1) {
page = 1;
}
if (page > totalPage) {
page = totalPage;
}
paginationDTO.setPagination(totalPage, page);
//size*(page-1)
Integer offset = size * (page - 1);
List<Question> questions = questionMapper.list(offset, size);
List<QuestionDTO> questionDTOList = new ArrayList<>();
for (Question question : questions) {
User user = userMapper.findById(question.getCreator());
QuestionDTO questionDTO = new QuestionDTO();
BeanUtils.copyProperties(question, questionDTO);
questionDTO.setUser(user);
questionDTOList.add(questionDTO);
}
paginationDTO.setQuestions(questionDTOList);
return paginationDTO;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public PaginationDTO list(Integer page, Integer size) {
PaginationDTO paginationDTO = new PaginationDTO();
Integer totalCount = questionMapper.count();
paginationDTO.setPagination(totalCount, page, size);
if (page < 1) {
page = 1;
}
if (page > paginationDTO.getTotalPage()) {
page = paginationDTO.getTotalPage();
}
//size*(page-1)
Integer offset = size * (page - 1);
List<Question> questions = questionMapper.list(offset, size);
List<QuestionDTO> questionDTOList = new ArrayList<>();
for (Question question : questions) {
User user = userMapper.findById(question.getCreator());
QuestionDTO questionDTO = new QuestionDTO();
BeanUtils.copyProperties(question, questionDTO);
questionDTO.setUser(user);
questionDTOList.add(questionDTO);
}
paginationDTO.setQuestions(questionDTOList);
return paginationDTO;
}
#location 12
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Index read() throws IOException {
if(version == -1) {
readVersion();
}
IndexReaderImpl reader = getReader(input, version);
if (reader == null) {
input.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Index read() throws IOException {
PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input));
if (stream.readInt() != MAGIC) {
stream.close();
throw new IllegalArgumentException("Not a jandex index");
}
byte version = stream.readByte();
IndexReaderImpl reader = getReader(stream, version);
if (reader == null) {
stream.close();
throw new UnsupportedVersion("Version: " + version);
}
return reader.read(version);
}
#location 2
#vulnerability type RESOURCE_LEAK |
#fixed code
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance();
// ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { new
// ExperimentTaskConfiguration(
// new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new KnownNIFFileDatasetConfig(
// SingletonWikipediaApi.getInstance(),
// NIFDatasets.N3_REUTERS_128), ExperimentType.D2KB,
// Matching.STRONG_ANNOTATION_MATCH) };
ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] {
new ExperimentTaskConfiguration(
new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new AIDACoNLLDatasetConfig(
AIDACoNLLChunk.TEST_A, SingletonWikipediaApi.getInstance()), ExperimentType.A2KB,
Matching.WEAK_ANNOTATION_MATCH), new ExperimentTaskConfiguration(
new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new AIDACoNLLDatasetConfig(
AIDACoNLLChunk.TEST_B, SingletonWikipediaApi.getInstance()), ExperimentType.A2KB,
Matching.WEAK_ANNOTATION_MATCH) };
Experimenter experimenter = new Experimenter(wikiAPI, new SimpleLoggingDAO4Debugging(), taskConfigs,
"BABELFY_TEST");
experimenter.run();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance();
ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { new ExperimentTaskConfiguration(
new BabelfyAnnotatorConfig(SingletonWikipediaApi.getInstance()), new KnownNIFFileDatasetConfig(
SingletonWikipediaApi.getInstance(),
NIFDatasets.N3_REUTERS_128), ExperimentType.D2KB,
Matching.STRONG_ANNOTATION_MATCH) };
Experimenter experimenter = new Experimenter(wikiAPI, new SimpleLoggingDAO4Debugging(), taskConfigs,
"BABELFY_TEST");
experimenter.run();
}
#location 10
#vulnerability type RESOURCE_LEAK |
#fixed code
public void handleReference(Reference<?> ref) {
poolLock.lock();
try {
if (ref instanceof BasicPoolEntryRef) {
// check if the GCed pool entry was still in use
//@@@ find a way to detect this without lookup
//@@@ flag in the BasicPoolEntryRef, to be reset when freed?
final boolean lost = issuedConnections.remove(ref);
if (lost) {
final HttpRoute route =
((BasicPoolEntryRef)ref).getRoute();
if (LOG.isDebugEnabled()) {
LOG.debug("Connection garbage collected. " + route);
}
handleLostEntry(route);
}
}
} finally {
poolLock.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void handleReference(Reference<?> ref) {
poolLock.lock();
try {
if (ref instanceof BasicPoolEntryRef) {
// check if the GCed pool entry was still in use
//@@@ find a way to detect this without lookup
//@@@ flag in the BasicPoolEntryRef, to be reset when freed?
final boolean lost = issuedConnections.remove(ref);
if (lost) {
final HttpRoute route =
((BasicPoolEntryRef)ref).getRoute();
if (LOG.isDebugEnabled()) {
LOG.debug("Connection garbage collected. " + route);
}
handleLostEntry(route);
}
} else if (ref instanceof ConnMgrRef) {
if (LOG.isDebugEnabled()) {
LOG.debug("Connection manager garbage collected.");
}
shutdown();
}
} finally {
poolLock.unlock();
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void shutdown() {
this.isShutDown = true;
synchronized (this) {
try {
if (uniquePoolEntry != null) // and connection open?
uniquePoolEntry.shutdown();
} catch (IOException iox) {
// ignore
log.debug("Problem while shutting down manager.", iox);
} finally {
uniquePoolEntry = null;
managedConn = null;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void shutdown() {
this.isShutDown = true;
ConnAdapter conn = managedConn;
if (conn != null)
conn.detach();
synchronized (this) {
try {
if (uniquePoolEntry != null) // and connection open?
uniquePoolEntry.shutdown();
} catch (IOException iox) {
// ignore
log.debug("Problem while shutting down manager.", iox);
} finally {
uniquePoolEntry = null;
managedConn = null;
}
}
}
#location 4
#vulnerability type UNSAFE_GUARDED_BY_ACCESS |
#fixed code
@Test
public void testReleaseConnectionWithTimeLimits() throws Exception {
final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final int rsplen = 8;
final String uri = "/random/" + rsplen;
final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);
final HttpContext context = new BasicHttpContext();
HttpClientConnection conn = getConnection(mgr, route);
mgr.connect(conn, route, 0, context);
mgr.routeComplete(conn, route, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
final HttpProcessor httpProcessor = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() });
final HttpRequestExecutor exec = new HttpRequestExecutor();
exec.preProcess(request, httpProcessor, context);
HttpResponse response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of first response entity",
rsplen, data.length);
// ignore data, but it must be read
// check that there is no auto-release by default
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (final ConnectionPoolTimeoutException e) {
// expected
}
conn.close();
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
Assert.assertFalse("connection should have been closed", conn.isOpen());
// repeat the communication, no need to prepare the request again
mgr.connect(conn, route, 0, context);
mgr.routeComplete(conn, route, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in second response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of second response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
Assert.assertTrue("connection should have been open", conn.isOpen());
// repeat the communication, no need to prepare the request again
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of third response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
Thread.sleep(150);
conn = getConnection(mgr, route);
Assert.assertTrue("connection should have been closed", !conn.isOpen());
// repeat the communication, no need to prepare the request again
mgr.connect(conn, route, 0, context);
mgr.routeComplete(conn, route, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of fourth response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.shutdown();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testReleaseConnectionWithTimeLimits() throws Exception {
final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager();
mgr.setMaxTotal(1);
final HttpHost target = getServerHttp();
final HttpRoute route = new HttpRoute(target, null, false);
final int rsplen = 8;
final String uri = "/random/" + rsplen;
final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);
final HttpContext context = new BasicHttpContext();
HttpClientConnection conn = getConnection(mgr, route);
mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
final HttpProcessor httpProcessor = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() });
final HttpRequestExecutor exec = new HttpRequestExecutor();
exec.preProcess(request, httpProcessor, context);
HttpResponse response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in first response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
byte[] data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of first response entity",
rsplen, data.length);
// ignore data, but it must be read
// check that there is no auto-release by default
try {
// this should fail quickly, connection has not been released
getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
Assert.fail("ConnectionPoolTimeoutException should have been thrown");
} catch (final ConnectionPoolTimeoutException e) {
// expected
}
conn.close();
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
Assert.assertFalse("connection should have been closed", conn.isOpen());
// repeat the communication, no need to prepare the request again
mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in second response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of second response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
conn = getConnection(mgr, route);
Assert.assertTrue("connection should have been open", conn.isOpen());
// repeat the communication, no need to prepare the request again
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of third response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.releaseConnection(conn, null, 100, TimeUnit.MILLISECONDS);
Thread.sleep(150);
conn = getConnection(mgr, route);
Assert.assertTrue("connection should have been closed", !conn.isOpen());
// repeat the communication, no need to prepare the request again
mgr.connect(conn, route.getTargetHost(), route.getLocalSocketAddress(), 0, context);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
response = exec.execute(request, conn, context);
Assert.assertEquals("wrong status in third response",
HttpStatus.SC_OK,
response.getStatusLine().getStatusCode());
data = EntityUtils.toByteArray(response.getEntity());
Assert.assertEquals("wrong length of fourth response entity",
rsplen, data.length);
// ignore data, but it must be read
mgr.shutdown();
}
#location 16
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void disconnect(int reason, String msg) throws IOException {
Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT);
buffer.putInt(reason);
buffer.putString(msg);
buffer.putString("");
WriteFuture f = writePacket(buffer);
f.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
close();
}
});
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void disconnect(int reason, String msg) throws IOException {
Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT);
buffer.putInt(reason);
buffer.putString(msg);
buffer.putString("");
WriteFuture f = writePacket(buffer);
f.join();
close();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void handleOpenFailure(Buffer buffer) {
int reason = buffer.getInt();
String msg = buffer.getString();
this.openFailureReason = reason;
this.openFailureMsg = msg;
this.openFuture.setException(new SshException(msg));
this.closeFuture.setClosed();
this.doClose();
notifyStateChanged();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void handleOpenFailure(Buffer buffer) {
int reason = buffer.getInt();
String msg = buffer.getString();
synchronized (lock) {
this.openFailureReason = reason;
this.openFailureMsg = msg;
this.openFuture.setException(new SshException(msg));
this.closeFuture.setClosed();
this.doClose();
lock.notifyAll();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected void doHandleMessage(Buffer buffer) throws Exception {
SshConstants.Message cmd = buffer.getCommand();
log.debug("Received packet {}", cmd);
switch (cmd) {
case SSH_MSG_DISCONNECT: {
int code = buffer.getInt();
String msg = buffer.getString();
log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg);
close(false);
break;
}
case SSH_MSG_UNIMPLEMENTED: {
int code = buffer.getInt();
log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code);
break;
}
case SSH_MSG_DEBUG: {
boolean display = buffer.getBoolean();
String msg = buffer.getString();
log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg);
break;
}
case SSH_MSG_IGNORE:
log.info("Received SSH_MSG_IGNORE");
break;
default:
switch (getState()) {
case ReceiveKexInit:
if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) {
log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT);
break;
}
log.info("Received SSH_MSG_KEXINIT");
receiveKexInit(buffer);
negociate();
kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]);
kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C);
setState(State.Kex);
break;
case Kex:
buffer.rpos(buffer.rpos() - 1);
if (kex.next(buffer)) {
checkHost();
sendNewKeys();
setState(State.ReceiveNewKeys);
}
break;
case ReceiveNewKeys:
if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd);
return;
}
log.info("Received SSH_MSG_NEWKEYS");
receiveNewKeys(false);
sendAuthRequest();
setState(State.AuthRequestSent);
break;
case AuthRequestSent:
if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd);
return;
}
authFuture.setAuthed(false);
setState(State.WaitForAuth);
break;
case WaitForAuth:
// We're waiting for the client to send an authentication request
// TODO: handle unexpected incoming packets
break;
case UserAuth:
if (userAuth == null) {
throw new IllegalStateException("State is userAuth, but no user auth pending!!!");
}
if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) {
String welcome = buffer.getString();
String lang = buffer.getString();
log.debug("Welcome banner: " + welcome);
UserInteraction ui = getClientFactoryManager().getUserInteraction();
if (ui != null) {
ui.welcome(welcome);
}
} else {
buffer.rpos(buffer.rpos() - 1);
processUserAuth(buffer);
}
break;
case Running:
switch (cmd) {
case SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
case SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
default:
throw new IllegalStateException("Unsupported command: " + cmd);
}
break;
default:
throw new IllegalStateException("Unsupported state: " + getState());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void doHandleMessage(Buffer buffer) throws Exception {
SshConstants.Message cmd = buffer.getCommand();
log.debug("Received packet {}", cmd);
switch (cmd) {
case SSH_MSG_DISCONNECT: {
int code = buffer.getInt();
String msg = buffer.getString();
log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg);
close(false);
break;
}
case SSH_MSG_UNIMPLEMENTED: {
int code = buffer.getInt();
log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code);
break;
}
case SSH_MSG_DEBUG: {
boolean display = buffer.getBoolean();
String msg = buffer.getString();
log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg);
break;
}
case SSH_MSG_IGNORE:
log.info("Received SSH_MSG_IGNORE");
break;
default:
switch (getState()) {
case ReceiveKexInit:
if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) {
log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT);
break;
}
log.info("Received SSH_MSG_KEXINIT");
receiveKexInit(buffer);
negociate();
kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]);
kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C);
setState(State.Kex);
break;
case Kex:
buffer.rpos(buffer.rpos() - 1);
if (kex.next(buffer)) {
checkHost();
sendNewKeys();
setState(State.ReceiveNewKeys);
}
break;
case ReceiveNewKeys:
if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd);
return;
}
log.info("Received SSH_MSG_NEWKEYS");
receiveNewKeys(false);
sendAuthRequest();
setState(State.AuthRequestSent);
break;
case AuthRequestSent:
if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd);
return;
}
setState(State.WaitForAuth);
break;
case WaitForAuth:
// We're waiting for the client to send an authentication request
// TODO: handle unexpected incoming packets
break;
case UserAuth:
if (userAuth == null) {
throw new IllegalStateException("State is userAuth, but no user auth pending!!!");
}
if (cmd == SshConstants.Message.SSH_MSG_USERAUTH_BANNER) {
String welcome = buffer.getString();
String lang = buffer.getString();
log.debug("Welcome banner: " + welcome);
UserInteraction ui = getClientFactoryManager().getUserInteraction();
if (ui != null) {
ui.welcome(welcome);
}
} else {
buffer.rpos(buffer.rpos() - 1);
switch (userAuth.next(buffer)) {
case Success:
authFuture.setAuthed(true);
username = userAuth.getUsername();
authed = true;
setState(State.Running);
startHeartBeat();
break;
case Failure:
authFuture.setAuthed(false);
userAuth = null;
setState(State.WaitForAuth);
break;
case Continued:
break;
}
}
break;
case Running:
switch (cmd) {
case SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
case SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
default:
throw new IllegalStateException("Unsupported command: " + cmd);
}
break;
default:
throw new IllegalStateException("Unsupported state: " + getState());
}
}
}
#location 92
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected void doHandleMessage(Buffer buffer) throws Exception {
SshConstants.Message cmd = buffer.getCommand();
log.debug("Received packet {}", cmd);
switch (cmd) {
case SSH_MSG_DISCONNECT: {
int code = buffer.getInt();
String msg = buffer.getString();
log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg);
close(false);
break;
}
case SSH_MSG_UNIMPLEMENTED: {
int code = buffer.getInt();
log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code);
break;
}
case SSH_MSG_DEBUG: {
boolean display = buffer.getBoolean();
String msg = buffer.getString();
log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg);
break;
}
case SSH_MSG_IGNORE:
log.info("Received SSH_MSG_IGNORE");
break;
default:
switch (getState()) {
case ReceiveKexInit:
if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) {
log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT);
break;
}
log.info("Received SSH_MSG_KEXINIT");
receiveKexInit(buffer);
negociate();
kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]);
kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C);
setState(State.Kex);
break;
case Kex:
buffer.rpos(buffer.rpos() - 1);
if (kex.next(buffer)) {
checkHost();
sendNewKeys();
setState(State.ReceiveNewKeys);
}
break;
case ReceiveNewKeys:
if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd);
return;
}
log.info("Received SSH_MSG_NEWKEYS");
receiveNewKeys(false);
sendAuthRequest();
setState(State.AuthRequestSent);
break;
case AuthRequestSent:
if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd);
return;
}
setState(State.WaitForAuth);
break;
case WaitForAuth:
// We're waiting for the client to send an authentication request
// TODO: handle unexpected incoming packets
break;
case UserAuth:
if (userAuth == null) {
throw new IllegalStateException("State is userAuth, but no user auth pending!!!");
}
buffer.rpos(buffer.rpos() - 1);
switch (userAuth.next(buffer)) {
case Success:
authFuture.setAuthed(true);
username = userAuth.getUsername();
authed = true;
setState(State.Running);
startHeartBeat();
break;
case Failure:
authFuture.setAuthed(false);
userAuth = null;
setState(State.WaitForAuth);
break;
case Continued:
break;
}
break;
case Running:
switch (cmd) {
case SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
case SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
default:
throw new IllegalStateException("Unsupported command: " + cmd);
}
break;
default:
throw new IllegalStateException("Unsupported state: " + getState());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void doHandleMessage(Buffer buffer) throws Exception {
SshConstants.Message cmd = buffer.getCommand();
log.debug("Received packet {}", cmd);
switch (cmd) {
case SSH_MSG_DISCONNECT: {
int code = buffer.getInt();
String msg = buffer.getString();
log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg);
close(false);
break;
}
case SSH_MSG_UNIMPLEMENTED: {
int code = buffer.getInt();
log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code);
break;
}
case SSH_MSG_DEBUG: {
boolean display = buffer.getBoolean();
String msg = buffer.getString();
log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg);
break;
}
case SSH_MSG_IGNORE:
log.info("Received SSH_MSG_IGNORE");
break;
default:
switch (state) {
case ReceiveKexInit:
if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) {
log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT);
break;
}
log.info("Received SSH_MSG_KEXINIT");
receiveKexInit(buffer);
negociate();
kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]);
kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C);
setState(State.Kex);
break;
case Kex:
buffer.rpos(buffer.rpos() - 1);
if (kex.next(buffer)) {
checkHost();
sendNewKeys();
setState(State.ReceiveNewKeys);
}
break;
case ReceiveNewKeys:
if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd);
return;
}
log.info("Received SSH_MSG_NEWKEYS");
receiveNewKeys(false);
sendAuthRequest();
setState(State.AuthRequestSent);
break;
case AuthRequestSent:
if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) {
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd);
return;
}
setState(State.WaitForAuth);
break;
case WaitForAuth:
// We're waiting for the client to send an authentication request
// TODO: handle unexpected incoming packets
break;
case UserAuth:
if (userAuth == null) {
throw new IllegalStateException("State is userAuth, but no user auth pending!!!");
}
buffer.rpos(buffer.rpos() - 1);
switch (userAuth.next(buffer)) {
case Success:
authFuture.setAuthed(true);
username = userAuth.getUsername();
authed = true;
setState(State.Running);
startHeartBeat();
break;
case Failure:
authFuture.setAuthed(false);
userAuth = null;
setState(State.WaitForAuth);
break;
case Continued:
break;
}
break;
case Running:
switch (cmd) {
case SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
case SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
default:
throw new IllegalStateException("Unsupported command: " + cmd);
}
break;
default:
throw new IllegalStateException("Unsupported state: " + state);
}
}
}
#location 134
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public OutputStream createOutputStream(final long offset)
throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + file.getName());
}
// move to the appropriate offset and create output stream
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
raf.setLength(offset);
raf.seek(offset);
// The IBM jre needs to have both the stream and the random access file
// objects closed to actually close the file
return new FileOutputStream(raf.getFD()) {
public void close() throws IOException {
super.close();
raf.close();
}
};
} catch (IOException e) {
raf.close();
throw e;
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public OutputStream createOutputStream(final long offset)
throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + file.getName());
}
// create output stream
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(offset);
raf.seek(offset);
// The IBM jre needs to have both the stream and the random access file
// objects closed to actually close the file
return new FileOutputStream(raf.getFD()) {
public void close() throws IOException {
super.close();
raf.close();
}
};
}
#location 16
#vulnerability type RESOURCE_LEAK |
#fixed code
public void handleEof() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id);
eof = true;
notifyStateChanged();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void handleEof() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id);
synchronized (lock) {
eof = true;
lock.notifyAll();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void check(int maxFree) throws IOException {
synchronized (lock) {
if ((size < maxFree) && (maxFree - size > packetSize * 3 || size < maxFree / 2)) {
if (log.isDebugEnabled()) {
log.debug("Increase " + name + " by " + (maxFree - size) + " up to " + maxFree);
}
channel.sendWindowAdjust(maxFree - size);
size = maxFree;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void check(int maxFree) throws IOException {
int threshold = Math.min(packetSize * 8, maxSize / 4);
synchronized (lock) {
if ((maxFree - size) > packetSize && (maxFree - size > threshold || size < threshold)) {
if (log.isDebugEnabled()) {
log.debug("Increase " + name + " by " + (maxFree - size) + " up to " + maxFree);
}
channel.sendWindowAdjust(maxFree - size);
size = maxFree;
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void handleClose() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id);
closedByOtherSide = !closing.get();
if (closedByOtherSide) {
close(false);
} else {
close(false).setClosed();
notifyStateChanged();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void handleClose() throws IOException {
log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id);
synchronized (lock) {
closedByOtherSide = !closing;
if (closedByOtherSide) {
close(false);
} else {
close(false).setClosed();
doClose();
lock.notifyAll();
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void freemarkerEngineTest() {
// 字符串模板
TemplateEngine engine = TemplateUtil.createEngine(
new TemplateConfig("templates", ResourceMode.STRING).setCustomEngine(FreemarkerEngine.class));
Template template = engine.getTemplate("hello,${name}");
String result = template.render(Dict.create().set("name", "hutool"));
Assert.assertEquals("hello,hutool", result);
//ClassPath模板
engine = TemplateUtil.createEngine(
new TemplateConfig("templates", ResourceMode.CLASSPATH).setCustomEngine(FreemarkerEngine.class));
template = engine.getTemplate("freemarker_test.ftl");
result = template.render(Dict.create().set("name", "hutool"));
Assert.assertEquals("hello,hutool", result);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void freemarkerEngineTest() {
// 字符串模板
TemplateEngine engine = new FreemarkerEngine(new TemplateConfig("templates", ResourceMode.STRING));
Template template = engine.getTemplate("hello,${name}");
String result = template.render(Dict.create().set("name", "hutool"));
Assert.assertEquals("hello,hutool", result);
//ClassPath模板
engine = new FreemarkerEngine(new TemplateConfig("templates", ResourceMode.CLASSPATH));
template = engine.getTemplate("freemarker_test.ftl");
result = template.render(Dict.create().set("name", "hutool"));
Assert.assertEquals("hello,hutool", result);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.