input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
private PackageDescriptor createPackageDescriptor(File file, BigInteger pDataSize) throws IOException, ParseException {
PackageDescriptor packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
// override the Version if the DEBVERSION environment variable is defined
final String debVersion = System.getenv("DEBVERSION");
if (debVersion != null) {
packageDescriptor.set("Version", debVersion);
console.info("Using version'" + debVersion + "' from the environment variables.");
}
// override the Maintainer field if the DEBFULLNAME and DEBEMAIL environment variables are defined
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.info("Using maintainer '" + maintainer + "' from the environment variables.");
}
return packageDescriptor;
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
private PackageDescriptor createPackageDescriptor(File file, BigInteger pDataSize) throws IOException, ParseException {
FilteredConfigurationFile controlFile = new FilteredConfigurationFile(file.getName(), new FileInputStream(file), resolver);
PackageDescriptor packageDescriptor = new PackageDescriptor(new ByteArrayInputStream(controlFile.toString().getBytes()));
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
// override the Version if the DEBVERSION environment variable is defined
final String debVersion = System.getenv("DEBVERSION");
if (debVersion != null) {
packageDescriptor.set("Version", debVersion);
console.info("Using version'" + debVersion + "' from the environment variables.");
}
// override the Maintainer field if the DEBFULLNAME and DEBEMAIL environment variables are defined
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.info("Using maintainer '" + maintainer + "' from the environment variables.");
}
return packageDescriptor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void produce( final DataConsumer receiver ) {
TarInputStream archiveInputStream = null;
try {
archiveInputStream = new TarInputStream(new GZIPInputStream(new FileInputStream(archive)));
while(true) {
TarEntry entry = archiveInputStream.getNextEntry();
if (entry == null) {
break;
}
if (!isIncluded(entry.getName())) {
continue;
}
entry = map(entry);
if (entry.isDirectory()) {
receiver.onEachDir(entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
continue;
}
receiver.onEachFile(archiveInputStream, entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (archiveInputStream != null) {
try {
archiveInputStream.close();
} catch (IOException e) {
}
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public void produce( final DataConsumer receiver ) {
TarInputStream archiveInputStream = null;
try {
archiveInputStream = new TarInputStream(getCompressedInputStream(new FileInputStream(archive)));
while(true) {
TarEntry entry = archiveInputStream.getNextEntry();
if (entry == null) {
break;
}
if (!isIncluded(entry.getName())) {
continue;
}
entry = map(entry);
if (entry.isDirectory()) {
receiver.onEachDir(entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
continue;
}
receiver.onEachFile(archiveInputStream, entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (archiveInputStream != null) {
try {
archiveInputStream.close();
} catch (IOException e) {
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(in);
while ((tar.getNextEntry()) != null);
} else {
// skip to the next entry
in.skip(entry.getLength());
}
}
assertTrue("tar file not found", found);
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(in);
while ((tar.getNextEntry()) != null);
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
assertTrue("tar file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("bz2 file not found", found);
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("bz2 file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null) {
;
}
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while (skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("bz2 file not found", found);
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
final AtomicBoolean found = new AtomicBoolean(false);
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArchiveWalker.walk(in, new ArchiveVisitor<ArArchiveEntry>() {
public void visit(ArArchiveEntry entry, byte[] content) throws IOException {
if (entry.getName().equals("data.tar.bz2")) {
found.set(true);
assertEquals("header 0", (byte) 'B', content[0]);
assertEquals("header 1", (byte) 'Z', content[1]);
TarInputStream tar = new TarInputStream(new BZip2CompressorInputStream(new ByteArrayInputStream(content)));
while ((tar.getNextEntry()) != null) ;
tar.close();
}
}
});
assertTrue("bz2 file not found", found.get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreation() throws Exception {
final Processor processor = new Processor(new Console() {
public void println(String s) {
}
}, null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip");
assertTrue(packageDescriptor.isValid());
final Set filesInDeb = new HashSet();
FileInputStream in = new FileInputStream(deb);
final ArInputStream ar = new ArInputStream(in);
while(true) {
final ArEntry arEntry = ar.getNextEntry();
if (arEntry == null) {
break;
}
if ("data.tar.gz".equals(arEntry.getName())) {
final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar));
while(true) {
final TarEntry tarEntry = tar.getNextEntry();
if (tarEntry == null) {
break;
}
filesInDeb.add(tarEntry.getName());
}
tar.close();
break;
}
for (int i = 0; i < arEntry.getLength(); i++) {
ar.read();
}
}
in.close();
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3"));
assertTrue("Cannot delete the file " + deb, deb.delete());
}
#location 37
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCreation() throws Exception {
final Processor processor = new Processor(new Console() {
public void println(String s) {
}
}, null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip");
assertTrue(packageDescriptor.isValid());
final Set filesInDeb = new HashSet();
final ArInputStream ar = new ArInputStream(new FileInputStream(deb));
while(true) {
final ArEntry arEntry = ar.getNextEntry();
if (arEntry == null) {
break;
}
if ("data.tar.gz".equals(arEntry.getName())) {
final TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(ar)));
while(true) {
final TarEntry tarEntry = tar.getNextEntry();
if (tarEntry == null) {
break;
}
filesInDeb.add(tarEntry.getName());
}
tar.close();
break;
}
for (int i = 0; i < arEntry.getLength(); i++) {
ar.read();
}
}
ar.close();
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3"));
assertTrue("Cannot delete the file " + deb, deb.delete());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public BinaryPackageControlFile createDeb(Compression compression) throws PackagingException {
File tempData = null;
File tempControl = null;
try {
tempData = File.createTempFile("deb", "data");
tempControl = File.createTempFile("deb", "control");
console.info("Building data");
DataBuilder dataBuilder = new DataBuilder(console);
final StringBuilder md5s = new StringBuilder();
final BigInteger size = dataBuilder.buildData(dataProducers, tempData, md5s, compression);
console.info("Building control");
ControlBuilder controlBuilder = new ControlBuilder(console, variableResolver);
final BinaryPackageControlFile packageControlFile = controlBuilder.buildControl(control.listFiles(), size, md5s, tempControl);
if (!packageControlFile.isValid()) {
throw new PackagingException("Control file fields are invalid " + packageControlFile.invalidFields() +
". The following fields are mandatory: " + packageControlFile.getMandatoryFields() +
". Please check your pom.xml/build.xml and your control file.");
}
deb.getParentFile().mkdirs();
ArArchiveOutputStream ar = new ArArchiveOutputStream(new FileOutputStream(deb));
addTo(ar, "debian-binary", "2.0\n");
addTo(ar, "control.tar.gz", tempControl);
addTo(ar, "data.tar" + compression.getExtension(), tempData);
ar.close();
return packageControlFile;
} catch (Exception e) {
throw new PackagingException("Could not create deb package", e);
} finally {
if (tempData != null) {
if (!tempData.delete()) {
console.warn("Could not delete the temporary file " + tempData);
}
}
if (tempControl != null) {
if (!tempControl.delete()) {
console.warn("Could not delete the temporary file " + tempControl);
}
}
}
}
#location 38
#vulnerability type RESOURCE_LEAK | #fixed code
public BinaryPackageControlFile createDeb(Compression compression) throws PackagingException {
File tempData = null;
File tempControl = null;
try {
tempData = File.createTempFile("deb", "data");
tempControl = File.createTempFile("deb", "control");
console.info("Building data");
DataBuilder dataBuilder = new DataBuilder(console);
StringBuilder md5s = new StringBuilder();
BigInteger size = dataBuilder.buildData(dataProducers, tempData, md5s, compression);
console.info("Building control");
ControlBuilder controlBuilder = new ControlBuilder(console, variableResolver);
BinaryPackageControlFile packageControlFile = controlBuilder.createPackageControlFile(new File(control, "control"), size);
if (packageControlFile.get("Description") == null) {
packageControlFile.set("Description", description);
}
if (packageControlFile.get("Homepage") == null) {
packageControlFile.set("Homepage", homepage);
}
controlBuilder.buildControl(packageControlFile, control.listFiles(), md5s, tempControl);
if (!packageControlFile.isValid()) {
throw new PackagingException("Control file fields are invalid " + packageControlFile.invalidFields() +
". The following fields are mandatory: " + packageControlFile.getMandatoryFields() +
". Please check your pom.xml/build.xml and your control file.");
}
deb.getParentFile().mkdirs();
ArArchiveOutputStream ar = new ArArchiveOutputStream(new FileOutputStream(deb));
addTo(ar, "debian-binary", "2.0\n");
addTo(ar, "control.tar.gz", tempControl);
addTo(ar, "data.tar" + compression.getExtension(), tempData);
ar.close();
return packageControlFile;
} catch (Exception e) {
throw new PackagingException("Could not create deb package", e);
} finally {
if (tempData != null) {
if (!tempData.delete()) {
console.warn("Could not delete the temporary file " + tempData);
}
}
if (tempControl != null) {
if (!tempControl.delete()) {
console.warn("Could not delete the temporary file " + tempControl);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuilder pChecksums, final File pOutput ) throws IOException, ParseException {
if (!pOutput.canWrite()) {
throw new IOException("Cannot write control file at '" + pOutput + "'");
}
final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
// create a descriptor out of the "control" file, copy all other files, ignore directories
PackageDescriptor packageDescriptor = null;
for (int i = 0; i < pControlFiles.length; i++) {
final File file = pControlFiles[i];
if (file.isDirectory()) {
console.println("Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?");
continue;
}
final TarEntry entry = new TarEntry(file);
final String name = file.getName();
entry.setName("./" + name);
entry.setNames("root", "root");
entry.setMode(PermMapper.toMode("755"));
if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.println("Using maintainer '" + maintainer + "' from the environment variables.");
}
} else {
// FIXME: usually the control directory should only have text files/shell scripts
// we convert all of them to unix line endings here. This could screw up binaries.
// better to have binary/text detection here.
final byte[] data = Utils.toUnixLineEndings(new FileInputStream(file));
entry.setSize(data.length);
outputStream.putNextEntry(entry);
outputStream.write(data);
outputStream.closeEntry();
}
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No 'control' found in " + Arrays.toString(pControlFiles));
}
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
}
#location 62
#vulnerability type RESOURCE_LEAK | #fixed code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuilder pChecksums, final File pOutput ) throws IOException, ParseException {
if (!pOutput.canWrite()) {
throw new IOException("Cannot write control file at '" + pOutput + "'");
}
final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
// create a descriptor out of the "control" file, copy all other files, ignore directories
PackageDescriptor packageDescriptor = null;
for (int i = 0; i < pControlFiles.length; i++) {
final File file = pControlFiles[i];
if (file.isDirectory()) {
console.println("Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?");
continue;
}
final TarEntry entry = new TarEntry(file);
final String name = file.getName();
entry.setName("./" + name);
entry.setNames("root", "root");
entry.setMode(PermMapper.toMode("755"));
if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.println("Using maintainer '" + maintainer + "' from the environment variables.");
}
} else {
final InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));
outputStream.putNextEntry(entry);
Utils.copy(infoStream, outputStream);
outputStream.closeEntry();
if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {
console.println("WARNING: The file '" + file + "' does not use Unix line endings. Please convert and check your VCS settings.");
}
}
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No 'control' found in " + Arrays.toString(pControlFiles));
}
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void produce( final DataConsumer pReceiver ) throws IOException {
TarInputStream archiveInputStream = null;
try {
archiveInputStream = new TarInputStream(getCompressedInputStream(new FileInputStream(archive)));
while(true) {
TarEntry entry = archiveInputStream.getNextEntry();
if (entry == null) {
break;
}
if (!isIncluded(entry.getName())) {
continue;
}
entry = map(entry);
if (entry.isDirectory()) {
pReceiver.onEachDir(entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
continue;
}
pReceiver.onEachFile(archiveInputStream, entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
}
} finally {
if (archiveInputStream != null) {
archiveInputStream.close();
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public void produce( final DataConsumer pReceiver ) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(archive));
CompressorInputStream compressorInputStream = null;
try {
// FIXME remove once commons 1.1 is out
final String fn = archive.getName();
if (fn.endsWith("gz")) {
compressorInputStream = new CompressorStreamFactory().createCompressorInputStream("gz", is);
} else if (fn.endsWith("bz2")){
compressorInputStream = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
}
// compressorInputStream = new CompressorStreamFactory().createCompressorInputStream(is);
} catch(CompressorException e) {
}
if (compressorInputStream != null) {
is = new BufferedInputStream(compressorInputStream);
}
ArchiveInputStream archiveInputStream = null;
try {
archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream(is);
} catch(ArchiveException e) {
throw new IOException("Unsupported archive format : " + archive, e);
}
EntryConverter converter = null;
if (archiveInputStream instanceof TarArchiveInputStream) {
converter = new EntryConverter() {
public TarEntry convert(ArchiveEntry entry) {
TarArchiveEntry src = (TarArchiveEntry)entry;
TarEntry dst = new TarEntry(entry.getName());
dst.setSize(src.getSize());
dst.setGroupName(src.getGroupName());
dst.setGroupId(src.getGroupId());
dst.setUserId(src.getUserId());
dst.setMode(src.getMode());
dst.setModTime(src.getModTime());
return dst;
}
};
} else {
throw new IOException("Unsupported archive format : " + archive);
}
try {
while(true) {
ArchiveEntry archiveEntry = archiveInputStream.getNextEntry();
if (archiveEntry == null) {
break;
}
if (!isIncluded(archiveEntry.getName())) {
continue;
}
TarEntry entry = converter.convert(archiveEntry);
entry = map(entry);
if (entry.isDirectory()) {
pReceiver.onEachDir(entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
continue;
}
pReceiver.onEachFile(archiveInputStream, entry.getName(), entry.getLinkName(), entry.getUserName(), entry.getUserId(), entry.getGroupName(), entry.getGroupId(), entry.getMode(), entry.getSize());
}
} finally {
if (archiveInputStream != null) {
archiveInputStream.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testTarFileSet() throws Exception {
project.executeTarget("tarfileset");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in)));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
assertTrue("prefix", tarentry.getName().startsWith("./foo/"));
if (tarentry.isDirectory()) {
assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode());
} else {
assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode());
}
assertEquals("user", "ebourg", tarentry.getUserName());
assertEquals("group", "ebourg", tarentry.getGroupName());
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
public void testTarFileSet() throws Exception {
project.executeTarget("tarfileset");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in)));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
assertTrue("prefix", tarentry.getName().startsWith("./foo/"));
if (tarentry.isDirectory()) {
assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode());
} else {
assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode());
}
assertEquals("user", "ebourg", tarentry.getUserName());
assertEquals("group", "ebourg", tarentry.getGroupName());
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreation() throws Exception {
final Processor processor = new Processor(new Console() {
public void println(String s) {
}
}, null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip");
assertTrue(packageDescriptor.isValid());
final Set filesInDeb = new HashSet();
final ArInputStream ar = new ArInputStream(new FileInputStream(deb));
while(true) {
final ArEntry arEntry = ar.getNextEntry();
if (arEntry == null) {
break;
}
if ("data.tar.gz".equals(arEntry.getName())) {
final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar));
while(true) {
final TarEntry tarEntry = tar.getNextEntry();
if (tarEntry == null) {
break;
}
filesInDeb.add(tarEntry.getName());
}
break;
}
for (int i = 0; i < arEntry.getLength(); i++) {
ar.read();
}
}
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3"));
deb.delete();
}
#location 40
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCreation() throws Exception {
final Processor processor = new Processor(new Console() {
public void println(String s) {
}
}, null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip");
assertTrue(packageDescriptor.isValid());
final Set filesInDeb = new HashSet();
final ArInputStream ar = new ArInputStream(new FileInputStream(deb));
while(true) {
final ArEntry arEntry = ar.getNextEntry();
if (arEntry == null) {
break;
}
if ("data.tar.gz".equals(arEntry.getName())) {
final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar));
while(true) {
final TarEntry tarEntry = tar.getNextEntry();
if (tarEntry == null) {
break;
}
filesInDeb.add(tarEntry.getName());
}
tar.close();
break;
}
for (int i = 0; i < arEntry.getLength(); i++) {
ar.read();
}
}
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2"));
assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3"));
assertTrue(deb.delete());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuilder pChecksums, final File pOutput ) throws IOException, ParseException {
final File dir = pOutput.getParentFile();
if (dir != null && (!dir.exists() || !dir.isDirectory())) {
throw new IOException("Cannot write control file at '" + pOutput.getAbsolutePath() + "'");
}
final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
// create a descriptor out of the "control" file, copy all other files, ignore directories
PackageDescriptor packageDescriptor = null;
for (File file : pControlFiles) {
if (file.isDirectory()) {
// warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)
boolean isDefaultExcludes = false;
for (String pattern : DirectoryScanner.getDefaultExcludes()) {
isDefaultExcludes = DirectoryScanner.match(pattern, file.getAbsolutePath().replace("\\", "/"));
if (isDefaultExcludes) {
break;
}
}
if (!isDefaultExcludes) {
console.info("Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?");
}
continue;
}
final TarEntry entry = new TarEntry(file);
final String name = file.getName();
entry.setName("./" + name);
entry.setNames("root", "root");
entry.setMode(PermMapper.toMode("755"));
if (CONFIGURATION_FILENAMES.contains(name)) {
FilteredConfigurationFile configurationFile = new FilteredConfigurationFile(file.getName(), new FileInputStream(file), resolver);
configurationFiles.add(configurationFile);
} else if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.info("Using maintainer '" + maintainer + "' from the environment variables.");
}
} else {
InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));
Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
infoStream.close();
InputStream in = new FileInputStream(file);
if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {
// fix the line endings automatically
byte[] buf = Utils.toUnixLineEndings(in);
entry.setSize(buf.length);
in = new ByteArrayInputStream(buf);
}
outputStream.putNextEntry(entry);
Utils.copy(in, outputStream);
outputStream.closeEntry();
in.close();
}
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No 'control' found in " + Arrays.toString(pControlFiles));
}
for (FilteredConfigurationFile configurationFile : configurationFiles) {
addControlEntry(configurationFile.getName(), configurationFile.toString(), outputStream);
}
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
}
#location 94
#vulnerability type RESOURCE_LEAK | #fixed code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuilder pChecksums, final File pOutput ) throws IOException, ParseException {
final File dir = pOutput.getParentFile();
if (dir != null && (!dir.exists() || !dir.isDirectory())) {
throw new IOException("Cannot write control file at '" + pOutput.getAbsolutePath() + "'");
}
final TarArchiveOutputStream outputStream = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
// create a descriptor out of the "control" file, copy all other files, ignore directories
PackageDescriptor packageDescriptor = null;
for (File file : pControlFiles) {
if (file.isDirectory()) {
// warn about the misplaced directory, except for directories ignored by default (.svn, cvs, etc)
boolean isDefaultExcludes = false;
for (String pattern : DirectoryScanner.getDefaultExcludes()) {
isDefaultExcludes = DirectoryScanner.match(pattern, file.getAbsolutePath().replace("\\", "/"));
if (isDefaultExcludes) {
break;
}
}
if (!isDefaultExcludes) {
console.info("Found directory '" + file + "' in the control directory. Maybe you are pointing to wrong dir?");
}
continue;
}
final TarArchiveEntry entry = new TarArchiveEntry(file);
final String name = file.getName();
entry.setName("./" + name);
entry.setNames("root", "root");
entry.setMode(PermMapper.toMode("755"));
if (CONFIGURATION_FILENAMES.contains(name)) {
FilteredConfigurationFile configurationFile = new FilteredConfigurationFile(file.getName(), new FileInputStream(file), resolver);
configurationFiles.add(configurationFile);
} else if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
// Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822)
SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
packageDescriptor.set("Date", fmt.format(new Date()));
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString());
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
final String maintainer = debFullName + " <" + debEmail + ">";
packageDescriptor.set("Maintainer", maintainer);
console.info("Using maintainer '" + maintainer + "' from the environment variables.");
}
} else {
InformationInputStream infoStream = new InformationInputStream(new FileInputStream(file));
Utils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
infoStream.close();
InputStream in = new FileInputStream(file);
if (infoStream.isShell() && !infoStream.hasUnixLineEndings()) {
// fix the line endings automatically
byte[] buf = Utils.toUnixLineEndings(in);
entry.setSize(buf.length);
in = new ByteArrayInputStream(buf);
}
outputStream.putArchiveEntry(entry);
Utils.copy(in, outputStream);
outputStream.closeArchiveEntry();
in.close();
}
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No 'control' found in " + Arrays.toString(pControlFiles));
}
for (FilteredConfigurationFile configurationFile : configurationFiles) {
addControlEntry(configurationFile.getName(), configurationFile.toString(), outputStream);
}
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException {
int digest = PGPUtil.SHA1;
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);
ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
armoredOutput.beginClearText(digest);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1)
byte[] data = trim(line).getBytes("UTF-8");
armoredOutput.write(data);
armoredOutput.write(EOL);
signatureGenerator.update(data);
signatureGenerator.update(EOL);
}
armoredOutput.endClearText();
PGPSignature signature = signatureGenerator.generate();
signature.encode(new BCPGOutputStream(armoredOutput));
armoredOutput.close();
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException {
int digest = PGPUtil.SHA1;
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);
ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
armoredOutput.beginClearText(digest);
LineIterator iterator = new LineIterator(new InputStreamReader(input));
while (iterator.hasNext()) {
String line = iterator.nextLine();
// trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1)
byte[] data = trim(line).getBytes("UTF-8");
armoredOutput.write(data);
armoredOutput.write(EOL);
signatureGenerator.update(data);
if (iterator.hasNext()) {
signatureGenerator.update(EOL);
}
}
armoredOutput.endClearText();
PGPSignature signature = signatureGenerator.generate();
signature.encode(new BCPGOutputStream(armoredOutput));
armoredOutput.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testWrite() throws Exception {
final File out1 = File.createTempFile("jdeb", ".ar");
final ArOutputStream os = new ArOutputStream(new FileOutputStream(out1));
os.putNextEntry(new ArEntry("data", 4));
os.write("data".getBytes());
os.close();
assertTrue(out1.delete());
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
public void testWrite() throws Exception {
final File out1 = File.createTempFile("jdeb", ".ar");
final ArArchiveOutputStream os = new ArArchiveOutputStream(new FileOutputStream(out1));
os.putArchiveEntry(new ArArchiveEntry("data", 4));
os.write("data".getBytes());
os.closeArchiveEntry();
os.close();
assertTrue(out1.delete());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(in);
while ((tar.getNextEntry()) != null);
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
assertTrue("tar file not found", found);
}
#location 31
#vulnerability type RESOURCE_LEAK | #fixed code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(new NonClosingInputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("tar file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testControlFilesPermissions() throws Exception {
File deb = new File("target/test-classes/test-control.deb");
if (deb.exists() && !deb.delete()) {
fail("Couldn't delete " + deb);
}
Processor processor = new Processor(new NullConsole(), new MapVariableResolver(Collections.<String, String>emptyMap()));
File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control");
DataProducer[] producers = {new EmptyDataProducer()};
processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE);
// now reopen the package and check the control files
assertTrue("package not build", deb.exists());
boolean controlFound = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
try {
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("control.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in)));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
controlFound = true;
assertFalse("directory found in the control archive", tarentry.isDirectory());
assertTrue("prefix", tarentry.getName().startsWith("./"));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
tar.copyEntryContents(bout);
InformationInputStream infoStream = new InformationInputStream(new ByteArrayInputStream(bout.toByteArray()));
IOUtils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
if (infoStream.isShell()) {
assertTrue("Permissions on " + tarentry.getName() + " should be 755", tarentry.getMode() == 0755);
} else {
assertTrue("Permissions on " + tarentry.getName() + " should be 644", tarentry.getMode() == 0644);
}
assertTrue(tarentry.getName() + " doesn't have Unix line endings", infoStream.hasUnixLineEndings());
assertEquals("user", "root", tarentry.getUserName());
assertEquals("group", "root", tarentry.getGroupName());
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while (skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
} finally {
in.close();
}
assertTrue("Control files not found in the package", controlFound);
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
public void testControlFilesPermissions() throws Exception {
File deb = new File("target/test-classes/test-control.deb");
if (deb.exists() && !deb.delete()) {
fail("Couldn't delete " + deb);
}
Processor processor = new Processor(new NullConsole(), new MapVariableResolver(Collections.<String, String>emptyMap()));
File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control");
DataProducer[] producers = {new EmptyDataProducer()};
processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE);
// now reopen the package and check the control files
assertTrue("package not build", deb.exists());
final AtomicBoolean controlFound = new AtomicBoolean(false);
ArchiveWalker.walkControlFiles(deb, new ArchiveVisitor<TarArchiveEntry>() {
public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
controlFound.set(true);
assertFalse("directory found in the control archive", entry.isDirectory());
assertTrue("prefix", entry.getName().startsWith("./"));
InformationInputStream infoStream = new InformationInputStream(new ByteArrayInputStream(content));
IOUtils.copy(infoStream, NullOutputStream.NULL_OUTPUT_STREAM);
if (infoStream.isShell()) {
assertTrue("Permissions on " + entry.getName() + " should be 755", entry.getMode() == 0755);
} else {
assertTrue("Permissions on " + entry.getName() + " should be 644", entry.getMode() == 0644);
}
assertTrue(entry.getName() + " doesn't have Unix line endings", infoStream.hasUnixLineEndings());
assertEquals("user", "root", entry.getUserName());
assertEquals("group", "root", entry.getGroupName());
}
});
assertTrue("Control files not found in the package", controlFound.get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreateParentDirectories() throws Exception {
File archive = new File("target/data.tar");
if (archive.exists()) {
archive.delete();
}
DataBuilder builder = new DataBuilder(new NullConsole());
DataProducer producer = new DataProducerFile(new File("pom.xml"), "/usr/share/myapp/pom.xml", null, null, null);
builder.buildData(Arrays.asList(producer), archive, new StringBuilder(), Compression.NONE);
int count = 0;
TarArchiveInputStream in = new TarArchiveInputStream(new FileInputStream(archive));
while (in.getNextTarEntry() != null) {
count++;
}
assertEquals("entries", 4, count);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCreateParentDirectories() throws Exception {
File archive = new File("target/data.tar");
if (archive.exists()) {
archive.delete();
}
DataBuilder builder = new DataBuilder(new NullConsole());
DataProducer producer = new DataProducerFile(new File("pom.xml"), "/usr/share/myapp/pom.xml", null, null, null);
builder.buildData(Arrays.asList(producer), archive, new StringBuilder(), Compression.NONE);
int count = 0;
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(archive));
while (in.getNextTarEntry() != null) {
count++;
}
} finally {
if (in != null) {
in.close();
}
}
assertEquals("entries", 4, count);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("bz2 file not found", found);
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("bz2 file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
break;
} else {
// skip to the next entry
in.skip(entry.getLength());
}
}
assertTrue("bz2 file not found", found);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBZip2Compression() throws Exception {
project.executeTarget("bzip2-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.bz2")) {
found = true;
assertEquals("header 0", (byte) 'B', in.read());
assertEquals("header 1", (byte) 'Z', in.read());
TarInputStream tar = new TarInputStream(new CBZip2InputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
break;
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
assertTrue("bz2 file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testControlFilesVariables() throws Exception {
File deb = new File("target/test-classes/test-control.deb");
if (deb.exists() && !deb.delete()) {
fail("Couldn't delete " + deb);
}
Map<String, String> variables = new HashMap<String, String>();
variables.put("name", "jdeb");
variables.put("version", "1.0");
Processor processor = new Processor(new NullConsole(), new MapVariableResolver(variables));
File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control");
DataProducer[] producers = {new EmptyDataProducer()};
processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE);
// now reopen the package and check the control files
assertTrue("package not build", deb.exists());
boolean controlFound = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
try {
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("control.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in)));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
controlFound = true;
if (tarentry.getName().contains("postinst") || tarentry.getName().contains("prerm")) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
tar.copyEntryContents(bout);
String content = bout.toString("ISO-8859-1");
assertFalse("Variables not replaced in the control file " + tarentry.getName(), content.contains("[[name]] [[version]]"));
assertTrue("Expected variables not found in the control file " + tarentry.getName(), content.contains("jdeb 1.0"));
}
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while (skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
} finally {
in.close();
}
assertTrue("Control files not found in the package", controlFound);
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
public void testControlFilesVariables() throws Exception {
File deb = new File("target/test-classes/test-control.deb");
if (deb.exists() && !deb.delete()) {
fail("Couldn't delete " + deb);
}
Map<String, String> variables = new HashMap<String, String>();
variables.put("name", "jdeb");
variables.put("version", "1.0");
Processor processor = new Processor(new NullConsole(), new MapVariableResolver(variables));
File controlDir = new File("target/test-classes/org/vafer/jdeb/deb/control");
DataProducer[] producers = {new EmptyDataProducer()};
processor.createDeb(controlDir.listFiles(), producers, deb, Compression.NONE);
// now reopen the package and check the control files
assertTrue("package not build", deb.exists());
final AtomicBoolean controlFound = new AtomicBoolean(false);
ArchiveWalker.walkControlFiles(deb, new ArchiveVisitor<TarArchiveEntry>() {
public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
controlFound.set(true);
if (entry.getName().contains("postinst") || entry.getName().contains("prerm")) {
String body = new String(content, "ISO-8859-1");
assertFalse("Variables not replaced in the control file " + entry.getName(), body.contains("[[name]] [[version]]"));
assertTrue("Expected variables not found in the control file " + entry.getName(), body.contains("jdeb 1.0"));
}
}
});
assertTrue("Control files not found in the package", controlFound.get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static byte[] toUnixLineEndings(InputStream input) throws IOException {
final Charset UTF8 = Charset.forName("UTF-8");
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
String line;
while((line = reader.readLine()) != null) {
dataStream.write(line.getBytes(UTF8));
dataStream.write('\n');
}
reader.close();
return dataStream.toByteArray();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
public static byte[] toUnixLineEndings(InputStream input) throws IOException {
String encoding = "ISO-8859-1";
FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));
filter.setEol(FixCrLfFilter.CrLf.newInstance("unix"));
ByteArrayOutputStream filteredFile = new ByteArrayOutputStream();
Utils.copy(new ReaderInputStream(filter, encoding), filteredFile);
return filteredFile.toByteArray();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void parse( final InputStream pInput ) throws IOException, ParseException {
final BufferedReader br = new BufferedReader(new InputStreamReader(pInput));
StringBuilder buffer = new StringBuilder();
String key = null;
int linenr = 0;
while (true) {
final String line = br.readLine();
if (line == null) {
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = null;
}
break;
}
linenr++;
if (line.length() == 0) {
throw new ParseException("Empty line", linenr);
}
final char first = line.charAt(0);
if (Character.isLetter(first)) {
// new key
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = new StringBuilder();
}
final int i = line.indexOf(':');
if (i < 0) {
throw new ParseException("Line misses ':' delimiter", linenr);
}
key = line.substring(0, i);
buffer.append(line.substring(i + 1).trim());
continue;
}
// continuing old value
buffer.append('\n').append(line.substring(1));
}
br.close();
}
#location 39
#vulnerability type RESOURCE_LEAK | #fixed code
protected void parse( final InputStream pInput ) throws IOException, ParseException {
final BufferedReader br = new BufferedReader(new InputStreamReader(pInput, "UTF-8"));
StringBuilder buffer = new StringBuilder();
String key = null;
int linenr = 0;
while (true) {
final String line = br.readLine();
if (line == null) {
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = null;
}
break;
}
linenr++;
if (line.length() == 0) {
throw new ParseException("Empty line", linenr);
}
final char first = line.charAt(0);
if (Character.isLetter(first)) {
// new key
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = new StringBuilder();
}
final int i = line.indexOf(':');
if (i < 0) {
throw new ParseException("Line misses ':' delimiter", linenr);
}
key = line.substring(0, i);
buffer.append(line.substring(i + 1).trim());
continue;
}
// continuing old value
buffer.append('\n').append(line.substring(1));
}
br.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void execute() {
if (control == null || !control.isDirectory()) {
throw new BuildException("You need to point the 'control' attribute to the control directory.");
}
if (changesIn != null) {
if (!changesIn.isFile() || !changesIn.canRead()) {
throw new BuildException("The 'changesIn' attribute needs to point to a readable file. " + changesIn + " was not found/readable.");
}
if (changesOut == null) {
throw new BuildException("A 'changesIn' without a 'changesOut' does not make much sense.");
}
if (!isPossibleOutput(changesOut)) {
throw new BuildException("Cannot write the output for 'changesOut' to " + changesOut);
}
if (changesSave != null && !isPossibleOutput(changesSave)) {
throw new BuildException("Cannot write the output for 'changesSave' to " + changesSave);
}
} else {
if (changesOut != null || changesSave != null) {
throw new BuildException("The 'changesOut' or 'changesSave' attributes may only be used when there is a 'changesIn' specified.");
}
}
if (dataProducers.size() == 0) {
throw new BuildException("You need to provide at least one reference to a tgz or directory with data.");
}
if (deb == null) {
throw new BuildException("You need to point the 'destfile' attribute to where the deb is supposed to be created.");
}
final File[] controlFiles = control.listFiles();
final DataProducer[] data = new DataProducer[dataProducers.size()];
dataProducers.toArray(data);
final Processor processor = new Processor(new Console() {
public void println(String s) {
if (verbose) {
log(s);
}
}
}, null);
final PackageDescriptor packageDescriptor;
try {
packageDescriptor = processor.createDeb(controlFiles, data, deb);
log("Created " + deb);
} catch (Exception e) {
throw new BuildException("Failed to create debian package " + deb, e);
}
final TextfileChangesProvider changesProvider;
try {
if (changesOut == null) {
return;
}
// for now only support reading the changes form a textfile provider
changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor);
processor.createChanges(packageDescriptor, changesProvider, (keyring!=null)?new FileInputStream(keyring):null, key, passphrase, new FileOutputStream(changesOut));
log("Created changes file " + changesOut);
} catch (Exception e) {
throw new BuildException("Failed to create debian changes file " + changesOut, e);
}
try {
if (changesSave == null) {
return;
}
changesProvider.save(new FileOutputStream(changesSave));
log("Saved changes to file " + changesSave);
} catch (Exception e) {
throw new BuildException("Failed to save debian changes file " + changesSave, e);
}
}
#location 59
#vulnerability type RESOURCE_LEAK | #fixed code
public void execute() {
if (control == null || !control.isDirectory()) {
throw new BuildException("You need to point the 'control' attribute to the control directory.");
}
if (changesIn != null) {
if (!changesIn.isFile() || !changesIn.canRead()) {
throw new BuildException("The 'changesIn' attribute needs to point to a readable file. " + changesIn + " was not found/readable.");
}
if (changesOut == null) {
throw new BuildException("A 'changesIn' without a 'changesOut' does not make much sense.");
}
if (!isPossibleOutput(changesOut)) {
throw new BuildException("Cannot write the output for 'changesOut' to " + changesOut);
}
if (changesSave != null && !isPossibleOutput(changesSave)) {
throw new BuildException("Cannot write the output for 'changesSave' to " + changesSave);
}
} else {
if (changesOut != null || changesSave != null) {
throw new BuildException("The 'changesOut' or 'changesSave' attributes may only be used when there is a 'changesIn' specified.");
}
}
if (dataProducers.size() == 0) {
throw new BuildException("You need to provide at least one reference to a tgz or directory with data.");
}
if (deb == null) {
throw new BuildException("You need to point the 'destfile' attribute to where the deb is supposed to be created.");
}
final File[] controlFiles = control.listFiles();
final DataProducer[] data = new DataProducer[dataProducers.size()];
dataProducers.toArray(data);
final Processor processor = new Processor(new Console() {
public void println(String s) {
if (verbose) {
log(s);
}
}
}, null);
final PackageDescriptor packageDescriptor;
try {
log("Creating debian package: " + deb);
packageDescriptor = processor.createDeb(controlFiles, data, deb);
} catch (Exception e) {
throw new BuildException("Failed to create debian package " + deb, e);
}
final TextfileChangesProvider changesProvider;
try {
if (changesOut == null) {
return;
}
log("Creating changes file: " + changesOut);
// for now only support reading the changes form a textfile provider
changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor);
processor.createChanges(packageDescriptor, changesProvider, (keyring!=null)?new FileInputStream(keyring):null, key, passphrase, new FileOutputStream(changesOut));
} catch (Exception e) {
throw new BuildException("Failed to create debian changes file " + changesOut, e);
}
try {
if (changesSave == null) {
return;
}
log("Saving changes to file: " + changesSave);
changesProvider.save(new FileOutputStream(changesSave));
} catch (Exception e) {
throw new BuildException("Failed to save debian changes file " + changesSave, e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testRead() throws Exception {
final File archive = new File(getClass().getResource("data.ar").toURI());
final ArInputStream ar = new ArInputStream(new FileInputStream(archive));
final ArEntry entry1 = ar.getNextEntry();
assertEquals("data.tgz", entry1.getName());
assertEquals(148, entry1.getLength());
for (int i = 0; i < entry1.getLength(); i++) {
ar.read();
}
final ArEntry entry2 = ar.getNextEntry();
assertNull(entry2);
ar.close();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
public void testRead() throws Exception {
final File archive = new File(getClass().getResource("data.ar").toURI());
final ArArchiveInputStream ar = new ArArchiveInputStream(new FileInputStream(archive));
final ArArchiveEntry entry1 = ar.getNextArEntry();
assertEquals("data.tgz", entry1.getName());
assertEquals(148, entry1.getLength());
for (int i = 0; i < entry1.getLength(); i++) {
ar.read();
}
final ArArchiveEntry entry2 = ar.getNextArEntry();
assertNull(entry2);
ar.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public PackageDescriptor createDeb( final File[] pControlFiles, final DataProducer[] pData, final File pOutput, String compression ) throws PackagingException, InvalidDescriptorException {
File tempData = null;
File tempControl = null;
try {
tempData = File.createTempFile("deb", "data");
tempControl = File.createTempFile("deb", "control");
console.println("Building data");
final StringBuffer md5s = new StringBuffer();
final BigInteger size = buildData(pData, tempData, md5s, compression);
console.println("Building control");
final PackageDescriptor packageDescriptor = buildControl(pControlFiles, size, md5s, tempControl);
if (!packageDescriptor.isValid()) {
throw new InvalidDescriptorException(packageDescriptor);
}
final InformationOutputStream output = new InformationOutputStream(new FileOutputStream(pOutput), MessageDigest.getInstance("MD5"));
final ArOutputStream ar = new ArOutputStream(output);
addTo(ar, "debian-binary", "2.0\n");
addTo(ar, "control.tar.gz", tempControl);
addTo(ar, "data.tar" + getExtension(compression), tempData);
ar.close();
// intermediate values
packageDescriptor.set("MD5", output.getMd5());
packageDescriptor.set("Size", "" + output.getSize());
packageDescriptor.set("File", pOutput.getName());
return packageDescriptor;
} catch(InvalidDescriptorException e) {
throw e;
} catch(Exception e) {
throw new PackagingException("Could not create deb package", e);
} finally {
if (tempData != null) {
if (!tempData.delete()) {
throw new PackagingException("Could not delete " + tempData);
}
}
if (tempControl != null) {
if (!tempControl.delete()) {
throw new PackagingException("Could not delete " + tempControl);
}
}
}
}
#location 38
#vulnerability type RESOURCE_LEAK | #fixed code
public PackageDescriptor createDeb( final File[] pControlFiles, final DataProducer[] pData, final File pOutput, String compression ) throws PackagingException, InvalidDescriptorException {
File tempData = null;
File tempControl = null;
try {
tempData = File.createTempFile("deb", "data");
tempControl = File.createTempFile("deb", "control");
console.println("Building data");
final StringBuffer md5s = new StringBuffer();
final BigInteger size = buildData(pData, tempData, md5s, compression);
console.println("Building control");
final PackageDescriptor packageDescriptor = buildControl(pControlFiles, size, md5s, tempControl);
if (!packageDescriptor.isValid()) {
throw new InvalidDescriptorException(packageDescriptor);
}
final InformationOutputStream output = new InformationOutputStream(new FileOutputStream(pOutput), MessageDigest.getInstance("MD5"));
final ArArchiveOutputStream ar = new ArArchiveOutputStream(output);
addTo(ar, "debian-binary", "2.0\n");
addTo(ar, "control.tar.gz", tempControl);
addTo(ar, "data.tar" + getExtension(compression), tempData);
ar.close();
// intermediate values
packageDescriptor.set("MD5", output.getMd5());
packageDescriptor.set("Size", "" + output.getSize());
packageDescriptor.set("File", pOutput.getName());
return packageDescriptor;
} catch(InvalidDescriptorException e) {
throw e;
} catch(Exception e) {
throw new PackagingException("Could not create deb package", e);
} finally {
if (tempData != null) {
if (!tempData.delete()) {
throw new PackagingException("Could not delete " + tempData);
}
}
if (tempControl != null) {
if (!tempControl.delete()) {
throw new PackagingException("Could not delete " + tempControl);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testTarFileSet() throws Exception {
project.executeTarget("tarfileset");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(in));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
assertTrue("prefix", tarentry.getName().startsWith("/foo/"));
if (tarentry.isDirectory()) {
assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode());
} else {
assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode());
}
assertEquals("user", "ebourg", tarentry.getUserName());
assertEquals("group", "ebourg", tarentry.getGroupName());
}
} else {
// skip to the next entry
in.skip(entry.getLength());
}
}
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public void testTarFileSet() throws Exception {
project.executeTarget("tarfileset");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar.gz")) {
TarInputStream tar = new TarInputStream(new GZIPInputStream(in));
TarEntry tarentry;
while ((tarentry = tar.getNextEntry()) != null) {
assertTrue("prefix", tarentry.getName().startsWith("/foo/"));
if (tarentry.isDirectory()) {
assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode());
} else {
assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode());
}
assertEquals("user", "ebourg", tarentry.getUserName());
assertEquals("group", "ebourg", tarentry.getGroupName());
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(new NonClosingInputStream(in));
while ((tar.getNextEntry()) != null) {
;
}
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while (skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("tar file not found", found);
}
#location 26
#vulnerability type RESOURCE_LEAK | #fixed code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
final AtomicBoolean found = new AtomicBoolean(false);
ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() {
public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
found.set(true);
}
}, Compression.NONE);
assertTrue("tar file not found", found.get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException {
int digest = PGPUtil.SHA1;
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);
ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
armoredOutput.beginClearText(digest);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1)
byte[] data = trim(line).getBytes("UTF-8");
armoredOutput.write(data);
armoredOutput.write(EOL);
signatureGenerator.update(data);
signatureGenerator.update(EOL);
}
armoredOutput.endClearText();
PGPSignature signature = signatureGenerator.generate();
signature.encode(new BCPGOutputStream(armoredOutput));
armoredOutput.close();
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException {
int digest = PGPUtil.SHA1;
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);
ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
armoredOutput.beginClearText(digest);
LineIterator iterator = new LineIterator(new InputStreamReader(input));
while (iterator.hasNext()) {
String line = iterator.nextLine();
// trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1)
byte[] data = trim(line).getBytes("UTF-8");
armoredOutput.write(data);
armoredOutput.write(EOL);
signatureGenerator.update(data);
if (iterator.hasNext()) {
signatureGenerator.update(EOL);
}
}
armoredOutput.endClearText();
PGPSignature signature = signatureGenerator.generate();
signature.encode(new BCPGOutputStream(armoredOutput));
armoredOutput.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArInputStream in = new ArInputStream(new FileInputStream(deb));
ArEntry entry;
while ((entry = in.getNextEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(new NonClosingInputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("tar file not found", found);
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
public void testNoCompression() throws Exception {
project.executeTarget("no-compression");
File deb = new File("target/test-classes/test.deb");
assertTrue("package not build", deb.exists());
boolean found = false;
ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb));
ArArchiveEntry entry;
while ((entry = in.getNextArEntry()) != null) {
if (entry.getName().equals("data.tar")) {
found = true;
TarInputStream tar = new TarInputStream(new NonClosingInputStream(in));
while ((tar.getNextEntry()) != null);
tar.close();
} else {
// skip to the next entry
long skip = entry.getLength();
while(skip > 0) {
long skipped = in.skip(skip);
if (skipped == -1) {
throw new IOException("Failed to skip");
}
skip -= skipped;
}
}
}
in.close();
assertTrue("tar file not found", found);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void makeDeb() throws PackagingException {
if (control == null || !control.isDirectory()) {
throw new PackagingException(
"\"" + control + "\" is not a valid 'control' directory)");
}
if (changesIn != null) {
if (!changesIn.isFile() || !changesIn.canRead()) {
throw new PackagingException(
"The 'changesIn' setting needs to point to a readable file. "
+ changesIn + " was not found/readable.");
}
if (changesOut == null) {
throw new PackagingException(
"A 'changesIn' without a 'changesOut' does not make much sense.");
}
if (!isPossibleOutput(changesOut)) {
throw new PackagingException(
"Cannot write the output for 'changesOut' to "
+ changesOut);
}
if (changesSave != null && !isPossibleOutput(changesSave)) {
throw new PackagingException(
"Cannot write the output for 'changesSave' to "
+ changesSave);
}
} else {
if (changesOut != null || changesSave != null) {
throw new PackagingException(
"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.");
}
}
if (!"gzip".equals(compression) && !"bzip2".equals(compression)
&& !"none".equals(compression)) {
throw new PackagingException("The compression method '"
+ compression + "' is not supported");
}
if (dataProducers.size() == 0) {
throw new PackagingException(
"You need to provide at least one reference to a tgz or directory with data.");
}
if (deb == null) {
throw new PackagingException(
"You need to specify where the deb file is supposed to be created.");
}
final File[] controlFiles = control.listFiles();
console.println("control dir:" + control);
for(File file : controlFiles) {
console.println("-" + file);
}
final DataProducer[] data = new DataProducer[dataProducers.size()];
dataProducers.toArray(data);
final Processor processor = new Processor(console, variableResolver);
final PackageDescriptor packageDescriptor;
try {
console.println("Creating debian package: " + deb);
packageDescriptor = processor.createDeb(controlFiles, data, deb, compression);
} catch (Exception e) {
throw new PackagingException("Failed to create debian package " + deb, e);
}
final TextfileChangesProvider changesProvider;
try {
if (changesOut == null) {
return;
}
console.println("Creating changes file: " + changesOut);
// for now only support reading the changes form a textfile provider
changesProvider = new TextfileChangesProvider(new FileInputStream(
changesIn), packageDescriptor);
processor.createChanges(packageDescriptor, changesProvider,
(keyring != null) ? new FileInputStream(keyring) : null,
key, passphrase, new FileOutputStream(changesOut));
} catch (Exception e) {
throw new PackagingException(
"Failed to create debian changes file " + changesOut, e);
}
try {
if (changesSave == null) {
return;
}
console.println("Saving changes to file: " + changesSave);
changesProvider.save(new FileOutputStream(changesSave));
} catch (Exception e) {
throw new PackagingException("Failed to save debian changes file " + changesSave, e);
}
}
#location 59
#vulnerability type NULL_DEREFERENCE | #fixed code
public void makeDeb() throws PackagingException {
if (control == null || !control.isDirectory()) {
throw new PackagingException(
"\"" + control + "\" is not a valid 'control' directory)");
}
if (changesIn != null) {
if (!changesIn.isFile() || !changesIn.canRead()) {
throw new PackagingException(
"The 'changesIn' setting needs to point to a readable file. "
+ changesIn + " was not found/readable.");
}
if (changesOut == null) {
throw new PackagingException(
"A 'changesIn' without a 'changesOut' does not make much sense.");
}
if (!isPossibleOutput(changesOut)) {
throw new PackagingException(
"Cannot write the output for 'changesOut' to "
+ changesOut);
}
if (changesSave != null && !isPossibleOutput(changesSave)) {
throw new PackagingException(
"Cannot write the output for 'changesSave' to "
+ changesSave);
}
} else {
if (changesOut != null || changesSave != null) {
throw new PackagingException(
"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.");
}
}
if (!"gzip".equals(compression) && !"bzip2".equals(compression)
&& !"none".equals(compression)) {
throw new PackagingException("The compression method '"
+ compression + "' is not supported");
}
if (dataProducers.size() == 0) {
throw new PackagingException(
"You need to provide at least one reference to a tgz or directory with data.");
}
if (deb == null) {
throw new PackagingException(
"You need to specify where the deb file is supposed to be created.");
}
final File[] controlFiles = control.listFiles();
final DataProducer[] data = new DataProducer[dataProducers.size()];
dataProducers.toArray(data);
final Processor processor = new Processor(console, variableResolver);
final PackageDescriptor packageDescriptor;
try {
console.println("Creating debian package: " + deb);
packageDescriptor = processor.createDeb(controlFiles, data, deb, compression);
} catch (Exception e) {
throw new PackagingException("Failed to create debian package " + deb, e);
}
final TextfileChangesProvider changesProvider;
try {
if (changesOut == null) {
return;
}
console.println("Creating changes file: " + changesOut);
// for now only support reading the changes form a textfile provider
changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor);
processor.createChanges(packageDescriptor, changesProvider,
(keyring != null) ? new FileInputStream(keyring) : null,
key, passphrase, new FileOutputStream(changesOut));
} catch (Exception e) {
throw new PackagingException(
"Failed to create debian changes file " + changesOut, e);
}
try {
if (changesSave == null) {
return;
}
console.println("Saving changes to file: " + changesSave);
changesProvider.save(new FileOutputStream(changesSave));
} catch (Exception e) {
throw new PackagingException("Failed to save debian changes file " + changesSave, e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuffer pChecksums, final File pOutput ) throws FileNotFoundException, IOException, ParseException {
PackageDescriptor packageDescriptor = null;
final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
for (int i = 0; i < pControlFiles.length; i++) {
final File file = pControlFiles[i];
if (file.isDirectory()) {
continue;
}
final TarEntry entry = new TarEntry(file);
final String name = file.getName();
entry.setName(name);
if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file));
if (packageDescriptor.get("Date") == null) {
packageDescriptor.set("Date", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date())); // Mon, 26 Mar 2007 11:44:04 +0200
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
if (packageDescriptor.get("Maintainer") == null) {
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
packageDescriptor.set("Maintainer", debFullName + " <" + debEmail + ">");
}
}
continue;
}
final InputStream inputStream = new FileInputStream(file);
outputStream.putNextEntry(entry);
Utils.copy(inputStream, outputStream);
outputStream.closeEntry();
inputStream.close();
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No control file in " + Arrays.toString(pControlFiles));
}
packageDescriptor.set("Installed-Size", pDataSize.toString());
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuffer pChecksums, final File pOutput ) throws FileNotFoundException, IOException, ParseException {
PackageDescriptor packageDescriptor = null;
final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput)));
outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU);
for (int i = 0; i < pControlFiles.length; i++) {
final File file = pControlFiles[i];
if (file.isDirectory()) {
continue;
}
final TarEntry entry = new TarEntry(file);
final String name = file.getName();
entry.setName(name);
if ("control".equals(name)) {
packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver);
if (packageDescriptor.get("Date") == null) {
packageDescriptor.set("Date", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date())); // Mon, 26 Mar 2007 11:44:04 +0200
}
if (packageDescriptor.get("Distribution") == null) {
packageDescriptor.set("Distribution", "unknown");
}
if (packageDescriptor.get("Urgency") == null) {
packageDescriptor.set("Urgency", "low");
}
if (packageDescriptor.get("Maintainer") == null) {
final String debFullName = System.getenv("DEBFULLNAME");
final String debEmail = System.getenv("DEBEMAIL");
if (debFullName != null && debEmail != null) {
packageDescriptor.set("Maintainer", debFullName + " <" + debEmail + ">");
}
}
continue;
}
final InputStream inputStream = new FileInputStream(file);
outputStream.putNextEntry(entry);
Utils.copy(inputStream, outputStream);
outputStream.closeEntry();
inputStream.close();
}
if (packageDescriptor == null) {
throw new FileNotFoundException("No control file in " + Arrays.toString(pControlFiles));
}
packageDescriptor.set("Installed-Size", pDataSize.toString());
addEntry("control", packageDescriptor.toString(), outputStream);
addEntry("md5sums", pChecksums.toString(), outputStream);
outputStream.close();
return packageDescriptor;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCreation() throws Exception {
final Processor processor = new Processor(new NullConsole(), null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File archive3 = new File(getClass().getResource("deb/data.zip").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerArchive(archive3, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null),
new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, Compression.GZIP);
assertTrue(packageDescriptor.isValid());
final Map<String, TarEntry> filesInDeb = new HashMap<String, TarEntry>();
final ArArchiveInputStream ar = new ArArchiveInputStream(new FileInputStream(deb));
while (true) {
final ArArchiveEntry arEntry = ar.getNextArEntry();
if (arEntry == null) {
break;
}
if ("data.tar.gz".equals(arEntry.getName())) {
final TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(ar)));
while (true) {
final TarEntry tarEntry = tar.getNextEntry();
if (tarEntry == null) {
break;
}
filesInDeb.put(tarEntry.getName(), tarEntry);
}
tar.close();
break;
}
for (int i = 0; i < arEntry.getLength(); i++) {
ar.read();
}
}
ar.close();
assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile"));
assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2"));
assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3"));
assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4"));
assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext"));
assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName());
assertTrue("Cannot delete the file " + deb, deb.delete());
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCreation() throws Exception {
final Processor processor = new Processor(new NullConsole(), null);
final File control = new File(getClass().getResource("deb/control/control").toURI());
final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI());
final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI());
final File archive3 = new File(getClass().getResource("deb/data.zip").toURI());
final File directory = new File(getClass().getResource("deb/data").toURI());
final DataProducer[] data = new DataProducer[] {
new DataProducerArchive(archive1, null, null, null),
new DataProducerArchive(archive2, null, null, null),
new DataProducerArchive(archive3, null, null, null),
new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null),
new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null)
};
final File deb = File.createTempFile("jdeb", ".deb");
final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, Compression.GZIP);
assertTrue(packageDescriptor.isValid());
final Map<String, TarArchiveEntry> filesInDeb = new HashMap<String, TarArchiveEntry>();
ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() {
public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
filesInDeb.put(entry.getName(), entry);
}
}, Compression.GZIP);
assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile"));
assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2"));
assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3"));
assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4"));
assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext"));
assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName());
assertTrue("Cannot delete the file " + deb, deb.delete());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void parse( final InputStream pInput ) throws IOException, ParseException {
final BufferedReader br = new BufferedReader(new InputStreamReader(pInput));
StringBuilder buffer = new StringBuilder();
String key = null;
int linenr = 0;
while (true) {
final String line = br.readLine();
if (line == null) {
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = null;
}
break;
}
linenr++;
if (line.length() == 0) {
throw new ParseException("Empty line", linenr);
}
final char first = line.charAt(0);
if (Character.isLetter(first)) {
// new key
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = new StringBuilder();
}
final int i = line.indexOf(':');
if (i < 0) {
throw new ParseException("Line misses ':' delimiter", linenr);
}
key = line.substring(0, i);
buffer.append(line.substring(i + 1).trim());
continue;
}
// continuing old value
buffer.append('\n').append(line.substring(1));
}
br.close();
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
protected void parse( final InputStream pInput ) throws IOException, ParseException {
final BufferedReader br = new BufferedReader(new InputStreamReader(pInput, "UTF-8"));
StringBuilder buffer = new StringBuilder();
String key = null;
int linenr = 0;
while (true) {
final String line = br.readLine();
if (line == null) {
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = null;
}
break;
}
linenr++;
if (line.length() == 0) {
throw new ParseException("Empty line", linenr);
}
final char first = line.charAt(0);
if (Character.isLetter(first)) {
// new key
if (buffer.length() > 0) {
// flush value of previous key
set(key, buffer.toString());
buffer = new StringBuilder();
}
final int i = line.indexOf(':');
if (i < 0) {
throw new ParseException("Line misses ':' delimiter", linenr);
}
key = line.substring(0, i);
buffer.append(line.substring(i + 1).trim());
continue;
}
// continuing old value
buffer.append('\n').append(line.substring(1));
}
br.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void unpackDependencies() throws MojoExecutionException {
try {
// get plugin JAR
String pluginJarPath = getPluginJarPath();
JarFile pluginJar = new JarFile(new File(pluginJarPath));
// extract loader JAR from plugin JAR
JarEntry pluginJarloaderJarEntry = pluginJar.getJarEntry(LOADER_JAR);
InputStream loaderJarInputStream = pluginJar.getInputStream(pluginJarloaderJarEntry);
File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "EeBootLoader");
if (!tmpDirectory.exists()) {
tmpDirectory.mkdir();
}
chmod777(tmpDirectory);
File tmpLoaderJarFile = File.createTempFile(TEMP_DIR_NAME_PREFIX, null, tmpDirectory);
tmpLoaderJarFile.deleteOnExit();
chmod777(tmpLoaderJarFile);
FileUtils.copyInputStreamToFile(loaderJarInputStream, tmpLoaderJarFile);
// extract loader JAR contents
JarFile loaderJar = new JarFile(tmpLoaderJarFile);
loaderJar
.stream()
.parallel()
.filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX))
.forEach(loaderJarEntry -> {
try {
File file = new File(mavenProject.getBuild().getDirectory(), "classes/" + loaderJarEntry.getName());
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
InputStream inputStream = loaderJar.getInputStream(loaderJarEntry);
FileUtils.copyInputStreamToFile(inputStream, file);
} catch (IOException e) {
// ignore
}
});
loaderJar.close();
} catch (IOException e) {
throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + ".");
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
private void unpackDependencies() throws MojoExecutionException {
ExecutionEnvironment executionEnvironment = executionEnvironment(mavenProject, mavenSession, buildPluginManager);
// try {
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("3.0.1")
),
goal("unpack"),
configuration(
element("artifact", LOADER_JAR_GAV),
element("excludes", "META-INF/**"),
element("outputDirectory", "${project.build.directory}/classes")
),
executionEnvironment
);
// } catch (MojoExecutionException e) {
// unpackDependenciesFallback();
// }
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void unpackDependencies() throws MojoExecutionException {
getLog().info("Unpacking kumuluzee-loader dependency.");
try {
// get plugin JAR
String pluginJarPath = getPluginJarPath();
JarFile pluginJar = new JarFile(new File(pluginJarPath));
// extract loader JAR from plugin JAR
JarEntry pluginJarloaderJarEntry = pluginJar.getJarEntry(LOADER_JAR);
InputStream loaderJarInputStream = pluginJar.getInputStream(pluginJarloaderJarEntry);
File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "EeBootLoader");
if (!tmpDirectory.exists()) {
tmpDirectory.mkdir();
}
chmod777(tmpDirectory);
File tmpLoaderJarFile = File.createTempFile(TEMP_DIR_NAME_PREFIX, null, tmpDirectory);
tmpLoaderJarFile.deleteOnExit();
chmod777(tmpLoaderJarFile);
FileUtils.copyInputStreamToFile(loaderJarInputStream, tmpLoaderJarFile);
// extract loader JAR contents
JarFile loaderJar = new JarFile(tmpLoaderJarFile);
loaderJar
.stream()
.parallel()
.filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX))
.forEach(loaderJarEntry -> {
try {
File file = new File(outputDirectory, "classes" + File.separator + loaderJarEntry.getName());
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
InputStream inputStream = loaderJar.getInputStream(loaderJarEntry);
FileUtils.copyInputStreamToFile(inputStream, file);
} catch (IOException e) {
// ignore
}
});
loaderJar.close();
} catch (IOException e) {
throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + ".");
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
private void unpackDependencies() throws MojoExecutionException {
getLog().info("Unpacking kumuluzee-loader dependency.");
try {
// get plugin JAR
String pluginJarPath = getPluginJarPath();
Path pluginJarFile = Paths.get(pluginJarPath);
FileSystem pluginJarFs = FileSystems.newFileSystem(pluginJarFile, null);
Path loaderJarFile = pluginJarFs.getPath(LOADER_JAR);
Path tmpJar = Files.createTempFile(TEMP_DIR_NAME_PREFIX, ".tmp");
Files.copy(loaderJarFile, tmpJar, StandardCopyOption.REPLACE_EXISTING);
JarFile loaderJar = new JarFile(tmpJar.toFile());
loaderJar.stream().parallel()
.filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX))
.forEach(loaderJarEntry -> {
try {
Path outputPath = Paths.get(outputDirectory, loaderJarEntry.getName());
Path outputPathParent = outputPath.getParent();
if (outputPathParent != null) {
Files.createDirectories(outputPathParent);
}
InputStream inputStream = loaderJar.getInputStream(loaderJarEntry);
Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
inputStream.close();
} catch (IOException ignored) {
}
});
loaderJar.close();
Files.delete(tmpJar);
} catch (IOException e) {
throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + ".");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void sendError(final int sc, final String msg) throws IOException {
if (exchange.getExchange().isResponseStarted()) {
throw UndertowServletMessages.MESSAGES.responseAlreadyCommited();
}
if (servletOutputStream != null) {
servletOutputStream.resetBuffer();
}
writer = null;
responseState = ResponseState.NONE;
exchange.getExchange().setResponseCode(sc);
//todo: is this the best way to handle errors?
final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc);
if (location != null) {
RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext);
try {
requestDispatcher.error(exchange.getExchange().getAttachment(HttpServletRequestImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(HttpServletResponseImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(ServletInitialHandler.CURRENT_SERVLET).getName(), msg);
} catch (ServletException e) {
throw new RuntimeException(e);
}
responseDone(exchange.getCompletionHandler());
} else if (msg != null) {
setContentType("text/html");
getWriter().write(msg);
getWriter().close();
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void sendError(final int sc, final String msg) throws IOException {
if (exchange.getExchange().isResponseStarted()) {
throw UndertowServletMessages.MESSAGES.responseAlreadyCommited();
}
resetBuffer();
writer = null;
responseState = ResponseState.NONE;
exchange.getExchange().setResponseCode(sc);
//todo: is this the best way to handle errors?
final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc);
if (location != null) {
RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext);
try {
requestDispatcher.error(exchange.getExchange().getAttachment(HttpServletRequestImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(HttpServletResponseImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(ServletInitialHandler.CURRENT_SERVLET).getName(), msg);
} catch (ServletException e) {
throw new RuntimeException(e);
}
} else if (msg != null) {
setContentType("text/html");
getWriter().write(msg);
getWriter().close();
}
responseDone(exchange.getCompletionHandler());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected StreamSinkFrameChannel create(StreamSinkChannel channel, WebSocketFrameType type, long payloadSize) {
return new WebSocket08FrameSinkChannel(channel, this, type, payloadSize);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected StreamSinkFrameChannel create(StreamSinkChannel channel, WebSocketFrameType type, long payloadSize) {
switch (type) {
case TEXT:
return new WebSocket08TextFrameSinkChannel(channel, this, payloadSize);
case BINARY:
return new WebSocket08BinaryFrameSinkChannel(channel, this, payloadSize);
case CLOSE:
return new WebSocket08CloseFrameSinkChannel(channel, this, payloadSize);
case PONG:
return new WebSocket08PongFrameSinkChannel(channel, this, payloadSize);
case PING:
return new WebSocket08PingFrameSinkChannel(channel, this, payloadSize);
case CONTINUATION:
return new WebSocket08ContinuationFrameSinkChannel(channel, this, payloadSize);
default:
throw new IllegalArgumentException("WebSocketFrameType " + type + " is not supported by this WebSocketChannel");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HttpSession getSession(final boolean create) {
if (httpSession == null) {
Session session = exchange.getExchange().getAttachment(Session.ATTACHMENT_KEY);
if (session != null) {
httpSession = new HttpSessionImpl(session, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), false);
} else if (create) {
final SessionManager sessionManager = exchange.getExchange().getAttachment(SessionManager.ATTACHMENT_KEY);
try {
Session newSession = sessionManager.getOrCreateSession(exchange.getExchange()).get();
httpSession = new HttpSessionImpl(newSession, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), true);
servletContext.getDeployment().getApplicationListeners().sessionCreated(httpSession);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return httpSession;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HttpSession getSession(final boolean create) {
return servletContext.getSession(exchange.getExchange(), create);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("/start")
@Metric(HTTP_STOP_OTA)
public Response startOTA(@QueryParam("fileName") String filename,
@QueryParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int dashId = tokenValue.dashId;
int deviceId = tokenValue.deviceId;
if (user == null) {
return badRequest("Invalid auth credentials.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename);
String body = otaManager.buildOTAInitCommandBody(otaFile);
if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
DashBoard dash = user.profile.getDashById(dashId);
Device device = dash.getDeviceById(deviceId);
device.updateOTAInfo(user.email);
return ok();
}
#location 35
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("/start")
@Metric(HTTP_STOP_OTA)
public Response startOTA(@QueryParam("fileName") String filename,
@QueryParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int deviceId = tokenValue.deviceId;
if (user == null) {
return badRequest("Invalid auth credentials.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename);
String body = otaManager.buildOTAInitCommandBody(otaFile);
if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
Device device = tokenValue.dash.getDeviceById(deviceId);
device.updateOTAInfo(user.email);
return ok();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGetWithFakeToken() throws Exception {
String token = "4ae3851817194e2596cf1b7103603ef8";
HttpGet request = new HttpGet(httpsServerUrl + token + "/project");
InputStream is = getClass().getResourceAsStream("/profiles/[email protected]");
User user = JsonParser.mapper.readValue(is, User.class);
Integer dashId = user.getDashIdByToken(token);
dashBoard = user.profile.getDashById(dashId);
try (CloseableHttpResponse response = httpclient.execute(request)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals(dashBoard.toString(), consumeText(response));
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGetWithFakeToken() throws Exception {
String token = "4ae3851817194e2596cf1b7103603ef8";
HttpGet request = new HttpGet(httpsServerUrl + token + "/project");
InputStream is = getClass().getResourceAsStream("/profiles/[email protected]");
User user = JsonParser.mapper.readValue(is, User.class);
Integer dashId = getDashIdByToken(user.dashTokens, token, 0);
dashBoard = user.profile.getDashById(dashId);
try (CloseableHttpResponse response = httpclient.execute(request)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals(dashBoard.toString(), consumeText(response));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void channelRead0(ChannelHandlerContext ctx, SaveProfileMessage message) throws Exception {
String userProfileString = message.body;
//expecting message with 2 parts
if (userProfileString == null || userProfileString.equals("")) {
log.error("Save Profile Handler. Income profile message is empty.");
ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT));
return;
}
log.info("Trying to parseProfile user profile : {}", userProfileString);
UserProfile userProfile = JsonParser.parseProfile(userProfileString);
if (userProfile == null) {
log.error("Register Handler. Wrong user profile message format.");
ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT));
return;
}
log.info("Trying save user profile.");
User authUser = Session.findUserByChannel(ctx.channel());
authUser.setUserProfile(userProfile);
boolean profileSaved = fileManager.overrideUserFile(authUser);
if (profileSaved) {
ctx.writeAndFlush(produce(message.id, OK));
} else {
ctx.writeAndFlush(produce(message.id, SERVER_ERROR));
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void channelRead0(ChannelHandlerContext ctx, SaveProfileMessage message) throws Exception {
String userProfileString = message.body;
//expecting message with 2 parts
if (userProfileString == null || userProfileString.equals("")) {
throw new InvalidCommandFormatException("Save Profile Handler. Income profile message is empty.", message.id);
}
log.info("Trying to parseProfile user profile : {}", userProfileString);
UserProfile userProfile = JsonParser.parseProfile(userProfileString);
if (userProfile == null) {
throw new InvalidCommandFormatException("Register Handler. Wrong user profile message format.", message.id);
}
log.info("Trying save user profile.");
User authUser = Session.findUserByChannel(ctx.channel(), message.id);
authUser.setUserProfile(userProfile);
boolean profileSaved = fileManager.overrideUserFile(authUser);
if (profileSaved) {
ctx.writeAndFlush(produce(message.id, OK));
} else {
ctx.writeAndFlush(produce(message.id, SERVER_ERROR));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void messageReceived(ChannelHandlerContext ctx, Message message) {
String token = message.body;
User userThatShared = userDao.sharedTokenManager.getUserByToken(token);
if (userThatShared == null) {
throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id);
}
Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token);
if (dashId == null) {
throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id);
}
DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId);
cleanPrivateData(dashBoard);
ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString()));
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
public void messageReceived(ChannelHandlerContext ctx, Message message) {
String token = message.body;
User userThatShared = userDao.sharedTokenManager.getUserByToken(token);
if (userThatShared == null) {
throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id);
}
Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token);
if (dashId == null) {
throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id);
}
DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId, message.id);
cleanPrivateData(dashBoard);
ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void channelRead0(ChannelHandlerContext ctx, GetTokenMessage message) throws Exception {
String dashBoardIdString = message.body;
Long dashBoardId;
try {
dashBoardId = Long.parseLong(dashBoardIdString);
} catch (NumberFormatException ex) {
log.error("Dash board id {} not valid.", dashBoardIdString);
ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT));
return;
}
User user = Session.findUserByChannel(ctx.channel());
String token = userRegistry.getToken(user, dashBoardId);
ctx.writeAndFlush(produce(message.id, message.command, token));
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void channelRead0(ChannelHandlerContext ctx, GetTokenMessage message) throws Exception {
String dashBoardIdString = message.body;
Long dashBoardId;
try {
dashBoardId = Long.parseLong(dashBoardIdString);
} catch (NumberFormatException ex) {
throw new InvalidCommandFormatException(String.format("Dash board id %s not valid.", dashBoardIdString), message.id);
}
User user = Session.findUserByChannel(ctx.channel(), message.id);
String token = userRegistry.getToken(user, dashBoardId);
ctx.writeAndFlush(produce(message.id, message.command, token));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void messageReceived(ChannelHandlerContext ctx, HardwareStateHolder state, StringMessage message) {
Session session = sessionDao.userSession.get(state.user);
String[] bodyParts = message.body.split(StringUtils.BODY_SEPARATOR_STRING);
if (bodyParts.length != 3) {
throw new IllegalCommandException("SetWidgetProperty command body has wrong format.");
}
byte pin = ParseUtil.parseByte(bodyParts[0]);
String property = bodyParts[1];
String propertyValue = bodyParts[2];
if (property.length() == 0 || propertyValue.length() == 0) {
throw new IllegalCommandException("SetWidgetProperty command body has wrong format.");
}
DashBoard dash = state.user.profile.getDashByIdOrThrow(state.dashId);
//for now supporting only virtual pins
Widget widget = dash.findWidgetByPin(pin, PinType.VIRTUAL);
boolean isChanged;
try {
isChanged = ReflectionUtil.setProperty(widget, property, propertyValue);
} catch (Exception e) {
log.error("Error setting widget property. Reason : {}", e.getMessage());
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
return;
}
if (isChanged) {
if (dash.isActive) {
session.sendToApps(SET_WIDGET_PROPERTY, message.id, dash.id + StringUtils.BODY_SEPARATOR_STRING + message.body);
}
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
} else {
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
public void messageReceived(ChannelHandlerContext ctx, HardwareStateHolder state, StringMessage message) {
Session session = sessionDao.userSession.get(state.user);
String[] bodyParts = message.body.split(StringUtils.BODY_SEPARATOR_STRING);
if (bodyParts.length != 3) {
log.error("SetWidgetProperty command body has wrong format. {}", message.body);
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
return;
}
byte pin = ParseUtil.parseByte(bodyParts[0]);
String property = bodyParts[1];
String propertyValue = bodyParts[2];
if (property.length() == 0 || propertyValue.length() == 0) {
log.error("SetWidgetProperty command body has wrong format. {}", message.body);
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
return;
}
DashBoard dash = state.user.profile.getDashByIdOrThrow(state.dashId);
//for now supporting only virtual pins
Widget widget = dash.findWidgetByPin(pin, PinType.VIRTUAL);
if (widget == null) {
log.error("No widget for SetWidgetProperty command. {}", message.body);
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
return;
}
boolean isChanged;
try {
isChanged = ReflectionUtil.setProperty(widget, property, propertyValue);
} catch (Exception e) {
log.error("Error setting widget property. Reason : {}", e.getMessage());
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
return;
}
if (isChanged) {
if (dash.isActive) {
session.sendToApps(SET_WIDGET_PROPERTY, message.id, dash.id + StringUtils.BODY_SEPARATOR_STRING + message.body);
}
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
} else {
ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, "");
String email = "[email protected]";
String pass = "b";
String appName = AppName.BLYNK;
User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false);
user.purchaseEnergy(98000);
int count = 300;
user.profile.dashBoards = new DashBoard[count];
for (int i = 1; i <= count; i++) {
DashBoard dash = new DashBoard();
dash.id = i;
dash.theme = Theme.Blynk;
dash.isActive = true;
user.profile.dashBoards[i - 1] = dash;
}
List<String> tokens = new ArrayList<>();
for (int i = 1; i <= count; i++) {
tokens.add(tokenManager.refreshToken(user, i, 0));
}
write("/path/300_tokens.txt", tokens);
write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user));
//scp /path/[email protected] root@IP:/root/data/
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) throws Exception {
TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, "");
String email = "[email protected]";
String pass = "b";
String appName = AppName.BLYNK;
User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false);
user.purchaseEnergy(98000);
int count = 300;
user.profile.dashBoards = new DashBoard[count];
for (int i = 1; i <= count; i++) {
DashBoard dash = new DashBoard();
dash.id = i;
dash.theme = Theme.Blynk;
dash.isActive = true;
user.profile.dashBoards[i - 1] = dash;
}
List<String> tokens = new ArrayList<>();
for (int i = 1; i <= count; i++) {
//tokens.add(tokenManager.refreshToken(user, i, 0));
}
write("/path/300_tokens.txt", tokens);
write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user));
//scp /path/[email protected] root@IP:/root/data/
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int dashId = tokenValue.dash.id;
int deviceId = tokenValue.deviceId;
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String body = otaManager.buildOTAInitCommandBody(path);
if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
Device device = tokenValue.dash.getDeviceById(deviceId);
User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
if (initiator != null) {
device.updateOTAInfo(initiator.email);
}
return ok(path);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int dashId = tokenValue.dash.id;
int deviceId = tokenValue.device.id;
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String body = otaManager.buildOTAInitCommandBody(path);
if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
if (initiator != null) {
tokenValue.device.updateOTAInfo(initiator.email);
}
return ok(path);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void messageReceived(ChannelHandlerContext ctx, Message message) {
String token = message.body;
User userThatShared = userRegistry.sharedTokenManager.getUserByToken(token);
if (userThatShared == null) {
throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id);
}
Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token);
if (dashId == null) {
throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id);
}
DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId);
ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString()));
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
public void messageReceived(ChannelHandlerContext ctx, Message message) {
String token = message.body;
User userThatShared = userRegistry.sharedTokenManager.getUserByToken(token);
if (userThatShared == null) {
throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id);
}
Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token);
if (dashId == null) {
throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id);
}
DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId);
cleanPrivateData(dashBoard);
ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDeleteCommand() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null));
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
when(properties.getProperty("data.folder")).thenReturn(System.getProperty("java.io.tmpdir"));
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY))));
new ReportingDao(reportingFolder, null, properties).delete("test", 1, PinType.ANALOG, (byte) 1);
assertFalse(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDeleteCommand() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager());
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
when(properties.getProperty("data.folder")).thenReturn(System.getProperty("java.io.tmpdir"));
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY))));
new ReportingDao(reportingFolder, null, properties).delete("test", 1, PinType.ANALOG, (byte) 1);
assertFalse(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendPushNotification(DashBoard dashBoard, Notification notification, int dashId, int deviceId) {
Device device = dashBoard.getDeviceById(deviceId);
final String dashName = dashBoard.name == null ? "" : dashBoard.name;
final String deviceName = device.name == null ? "device" : device.name;
String message = "Your " + deviceName + " went offline. \"" + dashName + "\" project is disconnected.";
notification.push(gcmWrapper,
message,
dashId
);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
private void sendPushNotification(DashBoard dashBoard, Notification notification, int dashId, int deviceId) {
Device device = dashBoard.getDeviceById(deviceId);
final String dashName = dashBoard.name == null ? "" : dashBoard.name;
final String deviceName = ((device == null || device.name == null) ? "device" : device.name);
String message = "Your " + deviceName + " went offline. \"" + dashName + "\" project is disconnected.";
notification.push(gcmWrapper,
message,
dashId
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
String assignToken(User user, int dashId, int deviceId, String newToken) {
// Clean old token from cache if exists.
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device device = dash.getDeviceById(deviceId);
String oldToken = deleteDeviceToken(device);
//assign new token
device.token = newToken;
cache.put(newToken, new TokenValue(user, dash, device));
user.lastModifiedTs = System.currentTimeMillis();
log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.email, dashId, deviceId, newToken);
return oldToken;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
RegularTokenManager(Iterable<User> users) {
this.cache = new ConcurrentHashMap<String, TokenValue>() {{
for (User user : users) {
if (user.profile != null) {
for (DashBoard dashBoard : user.profile.dashBoards) {
for (Device device : dashBoard.devices) {
if (device.token != null) {
put(device.token, new TokenValue(user, dashBoard, device));
}
}
}
}
}
}};
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@POST
@Path("{token}/email")
@Consumes(value = MediaType.APPLICATION_JSON)
public Response email(@PathParam("token") String token,
EmailPojo message) {
globalStats.mark(HTTP_EMAIL);
User user = tokenManager.getUserByToken(token);
if (user == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
Integer dashId = user.getDashIdByToken(token);
if (dashId == null) {
log.debug("Dash id for token {} not found. User {}", token, user.name);
return Response.badRequest("Didn't find dash id for token.");
}
DashBoard dash = user.profile.getDashById(dashId);
if (!dash.isActive) {
log.debug("Project is not active.");
return Response.badRequest("Project is not active.");
}
Mail mail = dash.getWidgetByType(Mail.class);
if (mail == null) {
log.debug("No email widget.");
return Response.badRequest("No email widget.");
}
if (message == null ||
message.subj == null || message.subj.equals("") ||
message.to == null || message.to.equals("")) {
log.debug("Email body empty. '{}'", message);
return Response.badRequest("Email body is wrong. Missing or empty fields 'to', 'subj'.");
}
log.trace("Sending Mail for user {}, with message : '{}'.", user.name, message.subj);
mail(user.name, message.to, message.subj, message.title);
return Response.ok();
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@POST
@Path("{token}/email")
@Consumes(value = MediaType.APPLICATION_JSON)
public Response email(@PathParam("token") String token,
EmailPojo message) {
globalStats.mark(HTTP_EMAIL);
TokenValue tokenValue = tokenManager.getUserByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
DashBoard dash = tokenValue.user.profile.getDashById(tokenValue.dashId);
if (dash == null || !dash.isActive) {
log.debug("Project is not active.");
return Response.badRequest("Project is not active.");
}
Mail mail = dash.getWidgetByType(Mail.class);
if (mail == null) {
log.debug("No email widget.");
return Response.badRequest("No email widget.");
}
if (message == null ||
message.subj == null || message.subj.equals("") ||
message.to == null || message.to.equals("")) {
log.debug("Email body empty. '{}'", message);
return Response.badRequest("Email body is wrong. Missing or empty fields 'to', 'subj'.");
}
log.trace("Sending Mail for user {}, with message : '{}'.", tokenValue.user.name, message.subj);
mail(tokenValue.user.name, message.to, message.subj, message.title);
return Response.ok();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("{token}/pin/{pin}")
@Metric(HTTP_GET_PIN_DATA)
public Response getWidgetPinData(@PathParam("token") String token,
@PathParam("pin") String pinString) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
final int deviceId = tokenValue.deviceId;
DashBoard dashBoard = user.profile.getDashById(dashId);
PinType pinType;
byte pin;
try {
pinType = PinType.getPinType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException | IllegalCommandBodyException e) {
log.debug("Wrong pin format. {}", pinString);
return Response.badRequest("Wrong pin format.");
}
Widget widget = dashBoard.findWidgetByPin(deviceId, pin, pinType);
if (widget == null) {
String value = dashBoard.pinsStorage.get(new PinStorageKey(deviceId, pinType, pin));
if (value == null) {
log.debug("Requested pin {} not found. User {}", pinString, user.email);
return Response.badRequest("Requested pin doesn't exist in the app.");
}
return ok(JsonParser.valueToJsonAsString(value.split(StringUtils.BODY_SEPARATOR_STRING)));
}
return ok(widget.getJsonValue());
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("{token}/pin/{pin}")
@Metric(HTTP_GET_PIN_DATA)
public Response getWidgetPinData(@PathParam("token") String token,
@PathParam("pin") String pinString) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
User user = tokenValue.user;
int deviceId = tokenValue.deviceId;
DashBoard dashBoard = tokenValue.dash;
PinType pinType;
byte pin;
try {
pinType = PinType.getPinType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException | IllegalCommandBodyException e) {
log.debug("Wrong pin format. {}", pinString);
return Response.badRequest("Wrong pin format.");
}
Widget widget = dashBoard.findWidgetByPin(deviceId, pin, pinType);
if (widget == null) {
String value = dashBoard.pinsStorage.get(new PinStorageKey(deviceId, pinType, pin));
if (value == null) {
log.debug("Requested pin {} not found. User {}", pinString, user.email);
return Response.badRequest("Requested pin doesn't exist in the app.");
}
return ok(JsonParser.valueToJsonAsString(value.split(StringUtils.BODY_SEPARATOR_STRING)));
}
return ok(widget.getJsonValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("{token}/project")
@Metric(HTTP_GET_PROJECT)
public Response getDashboard(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
DashBoard dashBoard = user.profile.getDashById(dashId);
return ok(dashBoard.toString());
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("{token}/project")
@Metric(HTTP_GET_PROJECT)
public Response getDashboard(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
return ok(tokenValue.dash.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) {
String[] split = StringUtils.split2(message.body);
int dashId = ParseUtil.parseInt(split[0]);
int deviceId = 0;
//new value for multi devices
if (split.length == 2) {
deviceId = ParseUtil.parseInt(split[1]);
}
DashBoard dashBoard = user.profile.getDashByIdOrThrow(dashId);
Device device = dashBoard.getDeviceById(deviceId);
String token = device.token;
if (token == null) {
throw new IllegalCommandBodyException("Wrong device id.");
}
String to = user.name;
String dashName = dashBoard.name == null ? "New Project" : dashBoard.name;
String deviceName = device.name == null ? "" : device.name;
String subj = "Auth Token for " + dashName + " project and device " + deviceName;
String body = String.format(BODY, dashName, token);
log.trace("Sending Mail for user {}, with token : '{}'.", user.name, token);
mail(ctx.channel(), user.name, to, subj, body, message.id);
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) {
String[] split = StringUtils.split2(message.body);
int dashId = ParseUtil.parseInt(split[0]);
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
if (split.length == 2) {
int deviceId = ParseUtil.parseInt(split[1]);
Device device = dash.getDeviceById(deviceId);
if (device == null || device.token == null) {
throw new IllegalCommandBodyException("Wrong device id.");
}
makeSingleTokenEmail(ctx, dash, device, user.name, message.id);
} else {
if (dash.devices.length == 1) {
makeSingleTokenEmail(ctx, dash, dash.devices[0], user.name, message.id);
} else {
sendMultiTokenEmail(ctx, dash, user.name, message.id);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@PUT
@Path("/{token}/widget/{pin}")
@Consumes(value = MediaType.APPLICATION_JSON)
public Response updateWidgetPinData(@PathParam("token") String token,
@PathParam("pin") String pinString,
String[] pinValues) {
User user = userDao.tokenManager.getUserByToken(token);
if (user == null) {
log.error("Requested token {} not found.", token);
return Response.notFound();
}
Integer dashId = user.getDashIdByToken(token);
if (dashId == null) {
log.error("Dash id for token {} not found. User {}", token, user.name);
return Response.notFound();
}
DashBoard dashBoard = user.profile.getDashById(dashId);
PinType pinType;
byte pin;
try {
pinType = PinType.getPingType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException e) {
log.error("Wrong pin format. {}", pinString);
return Response.badRequest();
}
Widget widget = dashBoard.findWidgetByPin(pin, pinType);
if (widget == null) {
log.error("Requested pin {} not found. User {}", pinString, user.name);
return Response.notFound();
}
widget.updateIfSame(new HardwareBody(pinType, pin, pinValues));
return Response.noContent();
}
#location 35
#vulnerability type NULL_DEREFERENCE | #fixed code
@PUT
@Path("/{token}/widget/{pin}")
@Consumes(value = MediaType.APPLICATION_JSON)
public Response updateWidgetPinData(@PathParam("token") String token,
@PathParam("pin") String pinString,
String[] pinValues) {
User user = userDao.tokenManager.getUserByToken(token);
if (user == null) {
log.error("Requested token {} not found.", token);
return Response.notFound();
}
Integer dashId = user.getDashIdByToken(token);
if (dashId == null) {
log.error("Dash id for token {} not found. User {}", token, user.name);
return Response.notFound();
}
DashBoard dashBoard = user.profile.getDashById(dashId);
PinType pinType;
byte pin;
try {
pinType = PinType.getPingType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException e) {
log.error("Wrong pin format. {}", pinString);
return Response.badRequest();
}
Widget widget = dashBoard.findWidgetByPin(pin, pinType);
if (widget == null) {
log.error("Requested pin {} not found. User {}", pinString, user.name);
return Response.notFound();
}
widget.updateIfSame(new HardwareBody(pinType, pin, pinValues));
String body = widget.makeHardwareBody();
if (body != null) {
Session session = sessionDao.getUserSession().get(user);
session.sendMessageToHardware(dashId, new HardwareMessage(111, body));
}
return Response.noContent();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Response updateWidgetProperty(String token,
String pinString,
String property,
String... values) {
if (values.length == 0) {
log.debug("No properties for update provided.");
return Response.badRequest("No properties for update provided.");
}
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
final int deviceId = tokenValue.deviceId;
DashBoard dash = user.profile.getDashById(dashId);
//todo add test for this use case
if (!dash.isActive) {
return Response.badRequest("Project is not active.");
}
PinType pinType;
byte pin;
try {
pinType = PinType.getPinType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException | IllegalCommandBodyException e) {
log.debug("Wrong pin format. {}", pinString);
return Response.badRequest("Wrong pin format.");
}
//for now supporting only virtual pins
Widget widget = dash.findWidgetByPin(deviceId, pin, pinType);
if (widget == null || pinType != PinType.VIRTUAL) {
log.debug("No widget for SetWidgetProperty command.");
return Response.badRequest("No widget for SetWidgetProperty command.");
}
try {
//todo for now supporting only single property
widget.setProperty(property, values[0]);
} catch (Exception e) {
log.debug("Error setting widget property. Reason : {}", e.getMessage());
return Response.badRequest("Error setting widget property.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
session.sendToApps(SET_WIDGET_PROPERTY, 111, dash.id, deviceId, "" + pin + BODY_SEPARATOR + property + BODY_SEPARATOR + values[0]);
return Response.ok();
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
public Response updateWidgetProperty(String token,
String pinString,
String property,
String... values) {
if (values.length == 0) {
log.debug("No properties for update provided.");
return Response.badRequest("No properties for update provided.");
}
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int deviceId = tokenValue.deviceId;
DashBoard dash = tokenValue.dash;
//todo add test for this use case
if (!dash.isActive) {
return Response.badRequest("Project is not active.");
}
PinType pinType;
byte pin;
try {
pinType = PinType.getPinType(pinString.charAt(0));
pin = Byte.parseByte(pinString.substring(1));
} catch (NumberFormatException | IllegalCommandBodyException e) {
log.debug("Wrong pin format. {}", pinString);
return Response.badRequest("Wrong pin format.");
}
//for now supporting only virtual pins
Widget widget = dash.findWidgetByPin(deviceId, pin, pinType);
if (widget == null || pinType != PinType.VIRTUAL) {
log.debug("No widget for SetWidgetProperty command.");
return Response.badRequest("No widget for SetWidgetProperty command.");
}
try {
//todo for now supporting only single property
widget.setProperty(property, values[0]);
} catch (Exception e) {
log.debug("Error setting widget property. Reason : {}", e.getMessage());
return Response.badRequest("Error setting widget property.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
session.sendToApps(SET_WIDGET_PROPERTY, 111, dash.id, deviceId, "" + pin + BODY_SEPARATOR + property + BODY_SEPARATOR + values[0]);
return Response.ok();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void parseHardwareInfo(ChannelHandlerContext ctx, String[] messageParts, HardwareStateHolder state, int msgId) {
HardwareInfo hardwareInfo = new HardwareInfo(messageParts);
int newHardwareInterval = hardwareInfo.heartbeatInterval;
log.trace("Info command. heartbeat interval {}", newHardwareInterval);
if (hardwareIdleTimeout != 0 && newHardwareInterval > 0) {
int newReadTimeout = (int) Math.ceil(newHardwareInterval * 2.3D);
log.debug("Changing read timeout interval to {}", newReadTimeout);
ctx.pipeline().replace(ReadTimeoutHandler.class, "H_ReadTimeout", new ReadTimeoutHandler(newReadTimeout));
}
DashBoard dashBoard = state.user.profile.getDashByIdOrThrow(state.dashId);
Device device = dashBoard.getDeviceById(state.deviceId);
if (otaManager.isUpdateRequired(hardwareInfo)) {
otaManager.sendOtaCommand(ctx, device);
log.info("Ota command is sent for user {} and device {}:{}.", state.user.email, device.name, device.id);
}
device.hardwareInfo = hardwareInfo;
dashBoard.updatedAt = System.currentTimeMillis();
ctx.writeAndFlush(ok(msgId), ctx.voidPromise());
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
private void parseHardwareInfo(ChannelHandlerContext ctx, String[] messageParts, HardwareStateHolder state, int msgId) {
HardwareInfo hardwareInfo = new HardwareInfo(messageParts);
int newHardwareInterval = hardwareInfo.heartbeatInterval;
log.trace("Info command. heartbeat interval {}", newHardwareInterval);
if (hardwareIdleTimeout != 0 && newHardwareInterval > 0) {
int newReadTimeout = (int) Math.ceil(newHardwareInterval * 2.3D);
log.debug("Changing read timeout interval to {}", newReadTimeout);
ctx.pipeline().replace(ReadTimeoutHandler.class, "H_ReadTimeout", new ReadTimeoutHandler(newReadTimeout));
}
DashBoard dashBoard = state.user.profile.getDashByIdOrThrow(state.dashId);
Device device = dashBoard.getDeviceById(state.deviceId);
if (device != null) {
if (otaManager.isUpdateRequired(hardwareInfo)) {
otaManager.sendOtaCommand(ctx, device);
log.info("Ota command is sent for user {} and device {}:{}.", state.user.email, device.name, device.id);
}
device.hardwareInfo = hardwareInfo;
dashBoard.updatedAt = System.currentTimeMillis();
}
ctx.writeAndFlush(ok(msgId), ctx.voidPromise());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void testGetTestString() {
RealRedisClient redisClient = new RealRedisClient("localhost", "123", 6378);
String result = redisClient.getServerByToken("test");
assertEquals("It's working!", result);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@Ignore
public void testGetTestString() {
RedisClient redisClient = new RedisClient("localhost", "123", 6378, false);
String result = redisClient.getServerByToken("test");
assertEquals("It's working!", result);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int dashId = tokenValue.dashId;
int deviceId = tokenValue.deviceId;
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String body = otaManager.buildOTAInitCommandBody(path);
if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
DashBoard dash = user.profile.getDashById(dashId);
Device device = dash.getDeviceById(deviceId);
User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
if (initiator != null) {
device.updateOTAInfo(initiator.email);
}
return ok(path);
}
#location 26
#vulnerability type NULL_DEREFERENCE | #fixed code
private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int dashId = tokenValue.dash.id;
int deviceId = tokenValue.deviceId;
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String body = otaManager.buildOTAInitCommandBody(path);
if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
Device device = tokenValue.dash.getDeviceById(deviceId);
User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
if (initiator != null) {
device.updateOTAInfo(initiator.email);
}
return ok(path);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
String assignToken(User user, int dashId, int deviceId, String newToken) {
// Clean old token from cache if exists.
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device device = dash.getDeviceById(deviceId);
String oldToken = removeOldToken(device);
//assign new token
device.token = newToken;
cache.put(newToken, new TokenValue(user, dashId, deviceId));
user.lastModifiedTs = System.currentTimeMillis();
log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.name, dashId, deviceId, newToken);
return oldToken;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
String assignToken(User user, int dashId, int deviceId, String newToken) {
// Clean old token from cache if exists.
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device device = dash.getDeviceById(deviceId);
String oldToken = removeOldToken(device);
//todo should never happen. but due to back compatibility
if (device == null) {
throw new IllegalCommandBodyException("Error refreshing token for user + " + user.name);
}
//assign new token
device.token = newToken;
cache.put(newToken, new TokenValue(user, dashId, deviceId));
user.lastModifiedTs = System.currentTimeMillis();
log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.name, dashId, deviceId, newToken);
return oldToken;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testStore2() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null));
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 2);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
//take less
byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 1, GraphType.HOURLY);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(16, data.length);
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
//take more
data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 24, GraphType.HOURLY);
byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(48, data.length);
assertEquals(200.0, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 2) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(150.54, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testStore2() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager());
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 2);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
//take less
byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 1, GraphType.HOURLY);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(16, data.length);
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
//take more
data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 24, GraphType.HOURLY);
byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(48, data.length);
assertEquals(200.0, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 2) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(150.54, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("/start")
@Metric(HTTP_STOP_OTA)
public Response startOTA(@QueryParam("fileName") String filename,
@QueryParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
int deviceId = tokenValue.deviceId;
if (user == null) {
return badRequest("Invalid auth credentials.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename);
String body = otaManager.buildOTAInitCommandBody(otaFile);
if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
Device device = tokenValue.dash.getDeviceById(deviceId);
device.updateOTAInfo(user.email);
return ok();
}
#location 35
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("/start")
@Metric(HTTP_STOP_OTA)
public Response startOTA(@QueryParam("fileName") String filename,
@QueryParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return badRequest("Invalid token.");
}
User user = tokenValue.user;
if (user == null) {
return badRequest("Invalid auth credentials.");
}
Session session = sessionDao.userSession.get(new UserKey(user));
if (session == null) {
log.debug("No session for user {}.", user.email);
return badRequest("Device wasn't connected yet.");
}
String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename);
String body = otaManager.buildOTAInitCommandBody(otaFile);
if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) {
log.debug("No device in session.");
return badRequest("No device in session.");
}
tokenValue.device.updateOTAInfo(user.email);
return ok();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("{token}/rtc")
@Metric(HTTP_GET_PIN_DATA)
public Response getWidgetPinData(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
DashBoard dashBoard = user.profile.getDashById(dashId);
RTC rtc = dashBoard.getWidgetByType(RTC.class);
if (rtc == null) {
log.debug("Requested rtc widget not found. User {}", user.email);
return Response.badRequest("Requested rtc not exists in app.");
}
return ok(rtc.getJsonValue());
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("{token}/rtc")
@Metric(HTTP_GET_PIN_DATA)
public Response getWidgetPinData(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
User user = tokenValue.user;
RTC rtc = tokenValue.dash.getWidgetByType(RTC.class);
if (rtc == null) {
log.debug("Requested rtc widget not found. User {}", user.email);
return Response.badRequest("Requested rtc not exists in app.");
}
return ok(rtc.getJsonValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void add(Set<String> doNotRemovePaths, DashBoard dash, EnhancedHistoryGraph graph) {
for (GraphDataStream graphDataStream : graph.dataStreams) {
if (graphDataStream != null && graphDataStream.dataStream != null && graphDataStream.dataStream.isValid()) {
DataStream dataStream = graphDataStream.dataStream;
Target target = dash.getTarget(graphDataStream.targetId);
for (int deviceId : target.getAssignedDeviceIds()) {
for (GraphGranularityType type : GraphGranularityType.values()) {
String filename = ReportingDao.generateFilename(dash.id,
deviceId,
dataStream.pinType.pintTypeChar, dataStream.pin, type.label);
doNotRemovePaths.add(filename);
}
}
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void add(Set<String> doNotRemovePaths, DashBoard dash, EnhancedHistoryGraph graph) {
for (GraphDataStream graphDataStream : graph.dataStreams) {
if (graphDataStream != null && graphDataStream.dataStream != null && graphDataStream.dataStream.isValid()) {
DataStream dataStream = graphDataStream.dataStream;
Target target = dash.getTarget(graphDataStream.targetId);
if (target != null) {
for (int deviceId : target.getAssignedDeviceIds()) {
for (GraphGranularityType type : GraphGranularityType.values()) {
String filename = ReportingDao.generateFilename(dash.id,
deviceId,
dataStream.pinType.pintTypeChar, dataStream.pin, type.label);
doNotRemovePaths.add(filename);
}
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static List<String> find(String staticResourcesFolder) throws Exception {
CodeSource src = ServerLauncher.class.getProtectionDomain().getCodeSource();
List<String> staticResources = new ArrayList<>();
if (src != null) {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry ze;
while((ze = zip.getNextEntry()) != null) {
String entryName = ze.getName();
if (entryName.startsWith(staticResourcesFolder) &&
(entryName.endsWith(".js") ||
entryName.endsWith(".css") ||
entryName.endsWith(".html")) ||
entryName.endsWith(".ico") ||
entryName.endsWith(".png")) {
staticResources.add(entryName);
}
}
}
return staticResources;
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
public static List<String> find(String staticResourcesFolder) throws Exception {
CodeSource src = ServerLauncher.class.getProtectionDomain().getCodeSource();
List<String> staticResources = new ArrayList<>();
if (src != null) {
URL jar = src.getLocation();
try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
ZipEntry ze;
while ((ze = zip.getNextEntry()) != null) {
String entryName = ze.getName();
if (entryName.startsWith(staticResourcesFolder) &&
(entryName.endsWith(".js") ||
entryName.endsWith(".css") ||
entryName.endsWith(".html")) ||
entryName.endsWith(".ico") ||
entryName.endsWith(".png")) {
staticResources.add(entryName);
}
}
}
}
return staticResources;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
List<FlashedToken> flashedTokens = generateTokens(10, AppName.BLYNK, 1);
DBManager dbManager = new DBManager("db-test.properties", new BlockingIOProcessor(1, 100, null));
dbManager.insertFlashedTokens(flashedTokens);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception{
List<FlashedToken> flashedTokens = generateTokens(100, "Grow", 2);
DBManager dbManager = new DBManager("db-test.properties", new BlockingIOProcessor(1, 100, null));
dbManager.insertFlashedTokens(flashedTokens);
for (FlashedToken token : flashedTokens) {
Path path = Paths.get("/home/doom369/Downloads/grow", token.token + "_" + token.deviceId + ".jpg");
generateQR(token.token, path);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) {
String[] split = split2(message.body);
if (split.length < 2) {
throw new IllegalCommandException("Wrong income message format.");
}
int dashId = ParseUtil.parseInt(split[0]) ;
String deviceString = split[1];
if (deviceString == null || deviceString.equals("")) {
throw new IllegalCommandException("Income device message is empty.");
}
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device newDevice = JsonParser.parseDevice(deviceString);
log.debug("Updating new device {}.", deviceString);
Device existingDevice = dash.getDeviceById(newDevice.id);
existingDevice.update(newDevice);
dash.updatedAt = System.currentTimeMillis();
user.lastModifiedTs = dash.updatedAt;
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) {
String[] split = split2(message.body);
if (split.length < 2) {
throw new IllegalCommandException("Wrong income message format.");
}
int dashId = ParseUtil.parseInt(split[0]) ;
String deviceString = split[1];
if (deviceString == null || deviceString.equals("")) {
throw new IllegalCommandException("Income device message is empty.");
}
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device newDevice = JsonParser.parseDevice(deviceString);
log.debug("Updating new device {}.", deviceString);
Device existingDevice = dash.getDeviceById(newDevice.id);
if (existingDevice == null) {
throw new IllegalCommandException("Attempt to update device with non existing id.");
}
existingDevice.update(newDevice);
dash.updatedAt = System.currentTimeMillis();
user.lastModifiedTs = dash.updatedAt;
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testStore() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null));
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY))));
byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 2, GraphType.HOURLY);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(32, data.length);
assertEquals(150.54, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
data = ReportingDao.getAllFromDisk(reportingFolder, "test2", 2, PinType.ANALOG, (byte) 2, 1, GraphType.HOURLY);
byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(16, data.length);
assertEquals(200.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testStore() throws IOException {
StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager());
ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>();
long ts = getTS() / AverageAggregator.HOUR;
AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts);
AggregationValue aggregationValue = new AggregationValue();
aggregationValue.update(100);
AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1);
AggregationValue aggregationValue2 = new AggregationValue();
aggregationValue2.update(150.54);
AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts);
AggregationValue aggregationValue3 = new AggregationValue();
aggregationValue3.update(200);
map.put(aggregationKey, aggregationValue);
map.put(aggregationKey2, aggregationValue2);
map.put(aggregationKey3, aggregationValue3);
when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>());
when(averageAggregator.getHourly()).thenReturn(map);
when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>());
storageWorker.run();
assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY))));
assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY))));
byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 2, GraphType.HOURLY);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(32, data.length);
assertEquals(150.54, byteBuffer.getDouble(), 0.001);
assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong());
assertEquals(100.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
data = ReportingDao.getAllFromDisk(reportingFolder, "test2", 2, PinType.ANALOG, (byte) 2, 1, GraphType.HOURLY);
byteBuffer = ByteBuffer.wrap(data);
assertNotNull(data);
assertEquals(16, data.length);
assertEquals(200.0, byteBuffer.getDouble(), 0.001);
assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void testIOS() throws Exception {
GCMWrapper gcmWrapper = new GCMWrapper(null, null);
gcmWrapper.send(new IOSGCMMessage("to", Priority.normal, "yo!!!", 1), null, null);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
@Ignore
public void testIOS() throws Exception {
GCMWrapper gcmWrapper = new GCMWrapper(props, client);
gcmWrapper.send(new IOSGCMMessage("to", Priority.normal, "yo!!!", 1), null, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("/{projectId}")
public Response getProject(@Context User user,
@PathParam("projectId") int projectId) {
DashBoard project = user.profile.getDashById(projectId);
project.token = user.dashTokens.get(projectId);
return ok(project);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("/{projectId}")
public Response getProject(@Context User user,
@PathParam("projectId") int projectId) {
DashBoard project = user.profile.getDashById(projectId);
//project.token = user.dashTokens.get(projectId);
return ok(project);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GET
@Path("{token}/isAppConnected")
@Metric(HTTP_IS_APP_CONNECTED)
public Response isAppConnected(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
final DashBoard dashBoard = user.profile.getDashById(dashId);
final Session session = sessionDao.userSession.get(new UserKey(user));
return ok(dashBoard.isActive && session.isAppConnected());
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@GET
@Path("{token}/isAppConnected")
@Metric(HTTP_IS_APP_CONNECTED)
public Response isAppConnected(@PathParam("token") String token) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
User user = tokenValue.user;
Session session = sessionDao.userSession.get(new UserKey(user));
return ok(tokenValue.dash.isActive && session.isAppConnected());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void channelRead0(ChannelHandlerContext ctx, LoadProfileMessage message) throws Exception {
User authUser = Session.findUserByChannel(ctx.channel());
String body = authUser.getUserProfile() == null ? "{}" : authUser.getUserProfile().toString();
ctx.writeAndFlush(produce(message.id, message.command, body));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void channelRead0(ChannelHandlerContext ctx, LoadProfileMessage message) throws Exception {
User authUser = Session.findUserByChannel(ctx.channel(), message.id);
String body = authUser.getUserProfile() == null ? "{}" : authUser.getUserProfile().toString();
ctx.writeAndFlush(produce(message.id, message.command, body));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@POST
@Path("{token}/notify")
@Consumes(value = MediaType.APPLICATION_JSON)
@Metric(HTTP_NOTIFY)
public Response notify(@PathParam("token") String token,
PushMessagePojo message) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
final int dashId = tokenValue.dashId;
if (message == null || Notification.isWrongBody(message.body)) {
log.debug("Notification body is wrong. '{}'", message == null ? "" : message.body);
return Response.badRequest("Body is empty or larger than 255 chars.");
}
DashBoard dash = user.profile.getDashById(dashId);
if (!dash.isActive) {
log.debug("Project is not active.");
return Response.badRequest("Project is not active.");
}
Notification notification = dash.getWidgetByType(Notification.class);
if (notification == null || notification.hasNoToken()) {
log.debug("No notification tokens.");
if (notification == null) {
return Response.badRequest("No notification widget.");
} else {
return Response.badRequest("Notification widget not initialized.");
}
}
log.trace("Sending push for user {}, with message : '{}'.", user.email, message.body);
notification.push(gcmWrapper, message.body, dash.id);
return Response.ok();
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@POST
@Path("{token}/notify")
@Consumes(value = MediaType.APPLICATION_JSON)
@Metric(HTTP_NOTIFY)
public Response notify(@PathParam("token") String token,
PushMessagePojo message) {
TokenValue tokenValue = tokenManager.getTokenValueByToken(token);
if (tokenValue == null) {
log.debug("Requested token {} not found.", token);
return Response.badRequest("Invalid token.");
}
final User user = tokenValue.user;
if (message == null || Notification.isWrongBody(message.body)) {
log.debug("Notification body is wrong. '{}'", message == null ? "" : message.body);
return Response.badRequest("Body is empty or larger than 255 chars.");
}
DashBoard dash = tokenValue.dash;
if (!dash.isActive) {
log.debug("Project is not active.");
return Response.badRequest("Project is not active.");
}
Notification notification = dash.getWidgetByType(Notification.class);
if (notification == null || notification.hasNoToken()) {
log.debug("No notification tokens.");
if (notification == null) {
return Response.badRequest("No notification widget.");
} else {
return Response.badRequest("Notification widget not initialized.");
}
}
log.trace("Sending push for user {}, with message : '{}'.", user.email, message.body);
notification.push(gcmWrapper, message.body, dash.id);
return Response.ok();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void testAndroid() throws Exception {
GCMWrapper gcmWrapper = new GCMWrapper(null, null);
gcmWrapper.send(new AndroidGCMMessage("", Priority.normal, "yo!!!", 1), null, null);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
@Ignore
public void testAndroid() throws Exception {
when(props.getProperty("gcm.api.key")).thenReturn("");
when(props.getProperty("gcm.server")).thenReturn("");
GCMWrapper gcmWrapper = new GCMWrapper(props, client);
gcmWrapper.send(new AndroidGCMMessage("", Priority.normal, "yo!!!", 1), null, null);
Thread.sleep(5000);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
ByteArrayInputStream in = new ByteArrayInputStream(str
.getBytes("UTF-8"));
// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n = 0;
while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write(buffer, 0, n);
}
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("UTF-8");
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
try (
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(StrConst.DEFAULT_CHARSET_NAME));
// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream(in);) {
byte[] buffer = new byte[256];
int n = 0;
// 将未压缩数据读入字节数组
while ((n = gzip.read(buffer)) >= 0) {
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write(buffer, 0, n);
}
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString(StrConst.DEFAULT_CHARSET_NAME);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
ByteArrayInputStream in = new ByteArrayInputStream(str
.getBytes("UTF-8"));
// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n = 0;
while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write(buffer, 0, n);
}
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString("UTF-8");
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public static String unCompress(String str) throws IOException {
if (null == str || str.length() <= 0) {
return str;
}
try (
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(StrConst.DEFAULT_CHARSET_NAME));
// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream(in);) {
byte[] buffer = new byte[256];
int n = 0;
// 将未压缩数据读入字节数组
while ((n = gzip.read(buffer)) >= 0) {
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write(buffer, 0, n);
}
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
return out.toString(StrConst.DEFAULT_CHARSET_NAME);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
void testThrowsExceptionWithNullTestInstance() throws Exception {
Object optionsFromAnnotatedField = annotationsReader
.getOptionsFromAnnotatedField(null, Options.class);
assertThat(optionsFromAnnotatedField, nullValue());
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
void testThrowsExceptionWithNullTestInstance() throws Exception {
assertThrows(NullPointerException.class, () -> {
annotationsReader.getOptionsFromAnnotatedField(null, Options.class);
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String startContainer(DockerContainer dockerContainer)
throws DockerException, InterruptedException {
String imageId = dockerContainer.getImageId();
log.info("Starting Docker container {}", imageId);
com.spotify.docker.client.messages.HostConfig.Builder hostConfigBuilder = HostConfig
.builder();
com.spotify.docker.client.messages.ContainerConfig.Builder containerConfigBuilder = ContainerConfig
.builder();
boolean privileged = dockerContainer.isPrivileged();
if (privileged) {
log.trace("Using privileged mode");
hostConfigBuilder.privileged(true);
}
Optional<String> network = dockerContainer.getNetwork();
if (network.isPresent()) {
log.trace("Using network: {}", network.get());
hostConfigBuilder.networkMode(network.get());
}
Optional<Map<String, List<PortBinding>>> portBindings = dockerContainer
.getPortBindings();
if (portBindings.isPresent()) {
log.trace("Using port bindings: {}", portBindings.get());
hostConfigBuilder.portBindings(portBindings.get());
containerConfigBuilder.exposedPorts(portBindings.get().keySet());
}
Optional<List<String>> binds = dockerContainer.getBinds();
if (binds.isPresent()) {
log.trace("Using binds: {}", binds.get());
hostConfigBuilder.binds(binds.get());
}
Optional<List<String>> envs = dockerContainer.getEnvs();
if (envs.isPresent()) {
log.trace("Using envs: {}", envs.get());
containerConfigBuilder.env(envs.get());
}
Optional<List<String>> cmd = dockerContainer.getCmd();
if (cmd.isPresent()) {
log.trace("Using cmd: {}", cmd.get());
containerConfigBuilder.cmd(cmd.get());
}
Optional<List<String>> entryPoint = dockerContainer.getEntryPoint();
if (entryPoint.isPresent()) {
log.trace("Using entryPoint: {}", entryPoint.get());
containerConfigBuilder.entrypoint(entryPoint.get());
}
ContainerConfig createContainer = containerConfigBuilder.image(imageId)
.hostConfig(hostConfigBuilder.build()).build();
String containerId = dockerClient.createContainer(createContainer).id();
dockerClient.startContainer(containerId);
boolean isPrivileged = dockerClient.inspectContainer(containerId)
.hostConfig().privileged();
log.debug("Docker container {} is running in privileged mode: {}",
imageId, isPrivileged);
return containerId;
}
#location 54
#vulnerability type NULL_DEREFERENCE | #fixed code
public String startContainer(DockerContainer dockerContainer)
throws DockerException, InterruptedException {
String imageId = dockerContainer.getImageId();
log.info("Starting Docker container {}", imageId);
com.spotify.docker.client.messages.HostConfig.Builder hostConfigBuilder = HostConfig
.builder();
com.spotify.docker.client.messages.ContainerConfig.Builder containerConfigBuilder = ContainerConfig
.builder();
boolean privileged = dockerContainer.isPrivileged();
if (privileged) {
log.trace("Using privileged mode");
hostConfigBuilder.privileged(true);
}
Optional<String> network = dockerContainer.getNetwork();
if (network.isPresent()) {
log.trace("Using network: {}", network.get());
hostConfigBuilder.networkMode(network.get());
}
Optional<Map<String, List<PortBinding>>> portBindings = dockerContainer
.getPortBindings();
if (portBindings.isPresent()) {
log.trace("Using port bindings: {}", portBindings.get());
hostConfigBuilder.portBindings(portBindings.get());
containerConfigBuilder.exposedPorts(portBindings.get().keySet());
}
Optional<List<String>> binds = dockerContainer.getBinds();
if (binds.isPresent()) {
log.trace("Using binds: {}", binds.get());
hostConfigBuilder.binds(binds.get());
}
Optional<List<String>> envs = dockerContainer.getEnvs();
if (envs.isPresent()) {
log.trace("Using envs: {}", envs.get());
containerConfigBuilder.env(envs.get());
}
Optional<List<String>> cmd = dockerContainer.getCmd();
if (cmd.isPresent()) {
log.trace("Using cmd: {}", cmd.get());
containerConfigBuilder.cmd(cmd.get());
}
Optional<List<String>> entryPoint = dockerContainer.getEntryPoint();
if (entryPoint.isPresent()) {
log.trace("Using entryPoint: {}", entryPoint.get());
containerConfigBuilder.entrypoint(entryPoint.get());
}
ContainerConfig createContainer = containerConfigBuilder.image(imageId)
.hostConfig(hostConfigBuilder.build()).build();
String containerId = dockerClient.createContainer(createContainer).id();
dockerClient.startContainer(containerId);
return containerId;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("unchecked")
private DriverHandler getDriverHandler(ExtensionContext extensionContext,
Parameter parameter, Class<?> type, Integer index,
Class<?> constructorClass, boolean isRemote)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
DriverHandler driverHandler;
String contextId = extensionContext.getUniqueId();
if (isRemote && !browserListMap.isEmpty()) {
List<Browser> browserListFromContextId = (List<Browser>) getValueFromContextId(
browserListMap, contextId);
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class, Browser.class)
.newInstance(parameter, extensionContext,
browserListFromContextId.get(index));
} else if (constructorClass.equals(OtherDriverHandler.class)
&& !browserListMap.isEmpty()) {
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class, Class.class)
.newInstance(parameter, extensionContext, type);
} else {
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class)
.newInstance(parameter, extensionContext);
}
return driverHandler;
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@SuppressWarnings("unchecked")
private DriverHandler getDriverHandler(ExtensionContext extensionContext,
Parameter parameter, Class<?> type, Integer index,
Class<?> constructorClass, boolean isRemote)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
DriverHandler driverHandler = null;
String contextId = extensionContext.getUniqueId();
if (isRemote && !browserListMap.isEmpty()) {
List<Browser> browserListFromContextId = (List<Browser>) getValueFromContextId(
browserListMap, contextId);
if (browserListFromContextId == null) {
log.warn("Browser list for context id {} not found", contextId);
} else {
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class, Browser.class)
.newInstance(parameter, extensionContext,
browserListFromContextId.get(index));
}
} else if (constructorClass.equals(OtherDriverHandler.class)
&& !browserListMap.isEmpty()) {
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class, Class.class)
.newInstance(parameter, extensionContext, type);
} else {
driverHandler = (DriverHandler) constructorClass
.getDeclaredConstructor(Parameter.class,
ExtensionContext.class)
.newInstance(parameter, extensionContext);
}
return driverHandler;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stopService() {
this.stop = true;
writer.stopService();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stopService() {
this.stop = true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-client").build();
Req<Ping> req = new Req<Ping>(
"ping",
new HashMap<String, String>() {
{
put("some", "header");
}
},
new Ping("{'key': 'ping?'}")
);
for (int i = 0; i < this.requests; i++) {
Promise<Res<Pong>> f = tchannel.makeRequest(
this.host,
this.port,
"service",
ArgScheme.JSON.getScheme(),
Pong.class,
req
);
f.addListener(new GenericFutureListener<Future<? super Res<Pong>>>() {
@Override
public void operationComplete(Future<? super Res<Pong>> future) throws Exception {
if (future.isSuccess()) {
Res<Pong> res = (Res<Pong>) future.get();
System.out.println(res);
}
}
});
}
tchannel.shutdown();
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-client").build();
Map<String, String> headers = new HashMap<String, String>() {
{
put("some", "header");
}
};
Request<Ping> request = new Request.Builder<>(new Ping("{'key': 'ping?'}"))
.setEndpoint("ping")
.setHeaders(headers)
.build();
for (int i = 0; i < this.requests; i++) {
Promise<Response<Pong>> f = tchannel.makeRequest(
this.host,
this.port,
"service",
ArgScheme.JSON,
request,
Pong.class
);
final int iteration = i;
f.addListener(new GenericFutureListener<Future<? super Response<Pong>>>() {
@Override
public void operationComplete(Future<? super Response<Pong>> future) throws Exception {
Response<?> response = (Response<?>) future.get(100, TimeUnit.MILLISECONDS);
if (iteration % 1000 == 0) {
System.out.println(response);
}
}
});
}
tchannel.shutdown();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-server")
.register("ping", new PingRequestHandler())
.setPort(this.port)
.build();
tchannel.listen().channel().closeFuture().sync();
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() throws Exception {
TChannel tchannel = new TChannel.Builder("ping-server")
.register("ping", new PingRequestHandler())
.setServerPort(this.port)
.build();
tchannel.listen().channel().closeFuture().sync();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long missCount()
{
return missCount;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long removeCount()
{
return removeCount;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE));
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
lruCompactions = 0L;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket, throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long size()
{
return size;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree)
{
this.capacity = capacity;
this.freeCapacity = capacity;
this.cleanUpTriggerFree = cleanUpTriggerFree;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = new Table(roundUpToPowerOf2(hts));
double lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75d;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long rehashes()
{
return rehashes;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree)
{
this.capacity = capacity;
this.freeCapacity = capacity;
this.cleanUpTriggerFree = cleanUpTriggerFree;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = new Table(roundUpToPowerOf2(hts));
double lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75d;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long missCount()
{
return missCount;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket, throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long cleanUpCount()
{
return cleanUpCount;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree, long cleanUpTargetFree)
{
this.capacity = capacity;
this.freeCapacity = capacity;
this.cleanUpTriggerFree = cleanUpTriggerFree;
this.cleanUpTargetFree = cleanUpTargetFree;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = new Table(roundUpToPowerOf2(hts));
double lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75d;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long putReplaceCount()
{
return putReplaceCount;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE));
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
lruCompactions = 0L;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long evictedEntries()
{
return evictedEntries;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
lruCompactions = 0L;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
lruCompactions = 0L;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket, throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
int hashTableSize()
{
return table.size();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity)
{
this.freeCapacity = freeCapacity;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
int bl = builder.getBucketLength();
if (bl <= 0)
bl = 8;
int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE);
entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE);
table = Table.create(buckets, entriesPerBucket);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
if (lf >= 1d)
throw new IllegalArgumentException("load factor must not be greater that 1");
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean replaceEntry(long hash, long oldHashEntryAdr, long newHashEntryAdr, long bytes)
{
LongArrayList derefList = null;
lock.lock();
try
{
long prevEntryAdr = 0L;
for (long hashEntryAdr = table.getFirst(hash);
hashEntryAdr != 0L;
prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr))
{
if (hashEntryAdr != oldHashEntryAdr)
continue;
// remove existing entry
replaceInternal(oldHashEntryAdr, prevEntryAdr, newHashEntryAdr);
while (freeCapacity < bytes)
{
long eldestHashAdr = removeEldest();
if (eldestHashAdr == 0L)
{
return false;
}
if (derefList == null)
derefList = new LongArrayList();
derefList.add(eldestHashAdr);
}
return true;
}
return false;
}
finally
{
lock.unlock();
if (derefList != null)
for (int i = 0; i < derefList.size(); i++)
HashEntries.dereference(derefList.getLong(i));
}
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long freeCapacity()
{
return freeCapacity;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree)
{
this.capacity = capacity;
this.freeCapacity = capacity;
this.cleanUpTriggerFree = cleanUpTriggerFree;
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = new Table(roundUpToPowerOf2(hts));
double lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75d;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void resetStatistics()
{
rehashes = 0L;
evictedEntries = 0L;
hitCount = 0L;
missCount = 0L;
putAddCount = 0L;
putReplaceCount = 0L;
removeCount = 0L;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
OffHeapMap(OHCacheBuilder builder, long freeCapacity)
{
this.freeCapacity = freeCapacity;
this.throwOOME = builder.isThrowOOME();
this.lock = builder.isUnlocked() ? null : new ReentrantLock();
int hts = builder.getHashTableSize();
if (hts <= 0)
hts = 8192;
if (hts < 256)
hts = 256;
table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME);
if (table == null)
throw new RuntimeException("unable to allocate off-heap memory for segment");
float lf = builder.getLoadFactor();
if (lf <= .0d)
lf = .75f;
this.loadFactor = lf;
threshold = (long) ((double) table.size() * loadFactor);
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.