output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public Key<?> exists(final Object entityOrKey) {
final Query<?> query = buildExistsQuery(entityOrKey);
return query.getKey();
} | #vulnerable code
public Key<?> exists(final Object entityOrKey) {
final Object unwrapped = ProxyHelper.unwrap(entityOrKey);
final Key<?> key = mapper.getKey(unwrapped);
final Object id = key.getId();
if (id == null) {
throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
}
String collName = key.getKind();
if (collName == null) {
collName = getCollection(key.getKindClass()).getName();
}
return find(collName, key.getKindClass()).filter(Mapper.ID_KEY, key.getId()).getKey();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) {
//TODO: Do this without creating another iterator
DBCollection dbColl = getCollection(entities.iterator().next());
return insert(dbColl, entities, wc);
} | #vulnerable code
public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) {
ArrayList<DBObject> ents = entities instanceof List ? new ArrayList<DBObject>(((List<T>)entities).size()) : new ArrayList<DBObject>();
Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
T lastEntity = null;
for (T ent : entities) {
ents.add(entityToDBObj(ent, involvedObjects));
lastEntity = ent;
}
DBCollection dbColl = getCollection(lastEntity);
WriteResult wr = null;
DBObject[] dbObjs = new DBObject[ents.size()];
dbColl.insert(ents.toArray(dbObjs), wc);
throwOnError(wc, wr);
ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>();
Iterator<T> entitiesIT = entities.iterator();
Iterator<DBObject> dbObjsIT = ents.iterator();
while (entitiesIT.hasNext()) {
T entity = entitiesIT.next();
DBObject dbObj = dbObjsIT.next();
savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
}
return savedKeys;
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getCollectionName(Object object) {
if (object == null) throw new IllegalArgumentException();
MappedClass mc = getMappedClass(object);
return mc.getCollectionName();
} | #vulnerable code
public String getCollectionName(Object object) {
MappedClass mc = getMappedClass(object);
return mc.getCollectionName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
V2_AsciiTable at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "URL", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
at.addRow(key, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
V2_AsciiTableRenderer rend = new V2_AsciiTableRenderer();
rend.setTheme(V2_E_TableThemes.UTF_LIGHT.get());
rend.setWidth(new WidthLongestLine());
RenderedTable rt = rend.render(at);
System.out.println(rt);
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
} | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id ="";
if(!groupId.equals("org.walkmod")){
id = groupId+":";
}
id+= artifactId.substring("walkmod-".length(), artifactId.length()-"-plugin".length());
if (Character.isLowerCase(description.charAt(0))){
description = Character.toUpperCase(description.charAt(0))+ description.substring(1, description.length());
}
if(!description.endsWith(".")){
description = description +".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for(int j = 0; j < max; j++){
String name = nList.item(j).getNodeName();
if(name.equals("url")){
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
String line = "";
for (int i = 0; i < 2 + 23 +63 + 103; i++) {
line = line + "-";
}
System.out.println(line);
System.out.printf("| %-20s | %-60s | %-100s |%n", StringUtils.center("PLUGIN NAME (ID)", 20),
StringUtils.center("URL", 60), StringUtils.center("DESCRIPTION", 100));
System.out.println(line);
for(String key: sortedKeys){
System.out.printf("| %-20s | %-60s | %-100s |%n", fill(key, 20), fill(pluginsURLs.get(key), 60), pluginsList.get(key));
}
System.out.println(line);
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
}
#location 88
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = null;
if(cfg != null){
installedPlugins = cfg.getPlugins();
}
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>();
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
PluginConfig equivalentPluginCfg = new PluginConfigImpl();
equivalentPluginCfg.setGroupId(groupId);
equivalentPluginCfg.setArtifactId(artifactId);
boolean isInstalled = (installedPlugins != null && installedPlugins
.contains(equivalentPluginCfg));
installedList.put(id, isInstalled);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
String installed = "";
if (installedList.get(key)) {
installed = "*";
}
at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
} | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = cfg.getPlugins();
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>();
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
PluginConfig equivalentPluginCfg = new PluginConfigImpl();
equivalentPluginCfg.setGroupId(groupId);
equivalentPluginCfg.setArtifactId(artifactId);
boolean isInstalled = (installedPlugins != null && installedPlugins
.contains(equivalentPluginCfg));
installedList.put(id, isInstalled);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
String installed = "";
if (installedList.get(key)) {
installed = "*";
}
at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void load() throws ConfigurationException {
Collection<PluginConfig> plugins = configuration.getPlugins();
PluginConfig plugin = null;
Collection<File> jarsToLoad = new LinkedList<File>();
ConfigurationException ce = null;
try {
if (plugins != null) {
Iterator<PluginConfig> it = plugins.iterator();
initIvy();
while (it.hasNext()) {
plugin = it.next();
addArtifact(plugin.getGroupId(), plugin.getArtifactId(),
plugin.getVersion());
}
jarsToLoad = resolveArtifacts();
URL[] urls = new URL[jarsToLoad.size()];
int i = 0;
for (File jar : jarsToLoad) {
urls[i] = jar.toURI().toURL();
i++;
}
URLClassLoader childClassLoader = new URLClassLoader(urls,
configuration.getClassLoader());
configuration.setClassLoader(childClassLoader);
}
} catch (Exception e) {
if (!(e instanceof ConfigurationException)) {
if (plugin == null) {
ce = new ConfigurationException(
"Unable to initialize ivy configuration:"
+ e.getMessage());
} else {
ce = new ConfigurationException(
"Unable to resolve the plugin: "
+ plugin.getGroupId() + " : "
+ plugin.getArtifactId() + " : "
+ plugin.getVersion() + ". Reason : "
+ e.getMessage());
}
} else {
ce = (ConfigurationException) e;
}
throw ce;
}
} | #vulnerable code
@Override
public void load() throws ConfigurationException {
Collection<PluginConfig> plugins = configuration.getPlugins();
PluginConfig plugin = null;
Collection<File> jarsToLoad = new LinkedList<File>();
try {
if (plugins != null) {
Iterator<PluginConfig> it = plugins.iterator();
initIvy();
while (it.hasNext()) {
plugin = it.next();
addArtifact(plugin.getGroupId(), plugin.getArtifactId(),
plugin.getVersion());
}
jarsToLoad = resolveArtifacts();
URL[] urls = new URL[jarsToLoad.size()];
int i = 0;
for (File jar : jarsToLoad) {
urls[i] = jar.toURI().toURL();
i++;
}
URLClassLoader childClassLoader = new URLClassLoader(urls,
configuration.getClassLoader());
configuration.setClassLoader(childClassLoader);
}
} catch (ConfigurationException e) {
throw e;
} catch (Exception e) {
if (plugin == null) {
throw new ConfigurationException(
"Unable to initialize ivy configuration", e);
} else {
throw new ConfigurationException(
"Unable to resolve the plugin: " + plugin.getGroupId()
+ " : " + plugin.getArtifactId() + " : "
+ plugin.getVersion(), e);
}
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
V2_AsciiTable at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "URL", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
at.addRow(key, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
V2_AsciiTableRenderer rend = new V2_AsciiTableRenderer();
rend.setTheme(V2_E_TableThemes.UTF_LIGHT.get());
rend.setWidth(new WidthLongestLine());
RenderedTable rt = rend.render(at);
System.out.println(rt);
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
} | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id ="";
if(!groupId.equals("org.walkmod")){
id = groupId+":";
}
id+= artifactId.substring("walkmod-".length(), artifactId.length()-"-plugin".length());
if (Character.isLowerCase(description.charAt(0))){
description = Character.toUpperCase(description.charAt(0))+ description.substring(1, description.length());
}
if(!description.endsWith(".")){
description = description +".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for(int j = 0; j < max; j++){
String name = nList.item(j).getNodeName();
if(name.equals("url")){
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
String line = "";
for (int i = 0; i < 2 + 23 +63 + 103; i++) {
line = line + "-";
}
System.out.println(line);
System.out.printf("| %-20s | %-60s | %-100s |%n", StringUtils.center("PLUGIN NAME (ID)", 20),
StringUtils.center("URL", 60), StringUtils.center("DESCRIPTION", 100));
System.out.println(line);
for(String key: sortedKeys){
System.out.printf("| %-20s | %-60s | %-100s |%n", fill(key, 20), fill(pluginsURLs.get(key), 60), pluginsList.get(key));
}
System.out.println(line);
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
}
#location 93
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void write(Object n, VisitorContext vc) throws Exception {
File out = null;
boolean createdEmptyFile = false;
if (vc != null) {
out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY);
}
if (out == null) {
log.debug("Creating the target source file. This is not the original source file.");
out = createOutputDirectory(n);
createdEmptyFile = true;
} else {
log.debug("The system will overwrite the original source file.");
}
boolean write = true;
if (out != null) {
log.debug("Analyzing exclude and include rules");
String aux = FilenameUtils.normalize(out.getAbsolutePath(), true);
if (excludes != null) {
for (int i = 0; i < excludes.length && write; i++) {
if (!excludes[i].startsWith(normalizedOutputDirectory)) {
excludes[i] = normalizedOutputDirectory + "/"
+ excludes[i];
if (excludes[i].endsWith("\\*\\*")) {
excludes[i] = excludes[i].substring(0,
excludes[i].length() - 2);
}
}
write = !(excludes[i].startsWith(aux) || FilenameUtils
.wildcardMatch(aux, excludes[i]));
}
}
if (includes != null && write) {
write = false;
for (int i = 0; i < includes.length && !write; i++) {
if (!includes[i].startsWith(normalizedOutputDirectory)) {
includes[i] = normalizedOutputDirectory + "/"
+ includes[i];
if (includes[i].endsWith("\\*\\*")) {
includes[i] = includes[i].substring(0,
includes[i].length() - 2);
}
}
write = includes[i].startsWith(aux)
|| FilenameUtils.wildcardMatch(aux, includes[i]);
}
}
if (write) {
Writer writer = null;
try {
vc.put("outFile", out);
String content = getContent(n, vc);
vc.remove("outFile");
if (content != null && !"".equals(content)) {
char endLineChar = getEndLineChar(out);
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), getEncoding()));
if (vc.get("append") == null) {
write(content, writer, endLineChar);
} else {
if (Boolean.TRUE.equals(vc.get("append"))) {
append(content, writer, endLineChar);
} else {
write(content, writer, endLineChar);
}
}
Summary.getInstance().addFile(out);
log.debug(out.getPath() + " written ");
} else {
log.error(out.getPath()
+ " does not have valid content");
throw new WalkModException("blank code is returned");
}
} finally {
if (writer != null) {
writer.close();
}
}
} else {
if (createdEmptyFile && out != null && out.isFile()) {
out.delete();
}
log.debug("skipping " + out.getParent());
}
} else {
log.debug("There is no place where to write.");
}
} | #vulnerable code
public void write(Object n, VisitorContext vc) throws Exception {
File out = null;
boolean createdEmptyFile = false;
if (vc != null) {
out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY);
}
if (out == null) {
log.debug("Creating the target source file. This is not the original source file.");
out = createOutputDirectory(n);
createdEmptyFile = true;
} else {
log.debug("The system will overwrite the original source file.");
}
boolean write = true;
if (out != null) {
log.debug("Analyzing exclude and include rules");
String aux = FilenameUtils.normalize(out.getAbsolutePath(), true);
if (excludes != null) {
for (int i = 0; i < excludes.length && write; i++) {
if (!excludes[i].startsWith(normalizedOutputDirectory)) {
excludes[i] = normalizedOutputDirectory + "/"
+ excludes[i];
if (excludes[i].endsWith("\\*\\*")) {
excludes[i] = excludes[i].substring(0,
excludes[i].length() - 2);
}
}
write = !(excludes[i].startsWith(aux) || FilenameUtils
.wildcardMatch(aux, excludes[i]));
}
}
if (includes != null && write) {
write = false;
for (int i = 0; i < includes.length && !write; i++) {
if (!includes[i].startsWith(normalizedOutputDirectory)) {
includes[i] = normalizedOutputDirectory + "/"
+ includes[i];
if (includes[i].endsWith("\\*\\*")) {
includes[i] = includes[i].substring(0,
includes[i].length() - 2);
}
}
write = includes[i].startsWith(aux)
|| FilenameUtils.wildcardMatch(aux, includes[i]);
}
}
if (write) {
Writer writer = null;
try {
String content = getContent(n, vc);
if (content != null && !"".equals(content)) {
char endLineChar = getEndLineChar(out);
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), getEncoding()));
if (vc.get("append") == null) {
write(content, writer, endLineChar);
} else {
if (Boolean.TRUE.equals(vc.get("append"))) {
append(content, writer, endLineChar);
} else {
write(content, writer, endLineChar);
}
}
Summary.getInstance().addFile(out);
log.debug(out.getPath() + " written ");
} else {
log.error(out.getPath()
+ " does not have valid content");
throw new WalkModException("blank code is returned");
}
} finally {
if (writer != null) {
writer.close();
}
}
} else {
if (createdEmptyFile && out != null && out.isFile()) {
out.delete();
}
log.debug("skipping " + out.getParent());
}
} else {
log.debug("There is no place where to write.");
}
}
#location 59
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static List<File> findFiles(final File parent, boolean recurse) {
final List<File> result = new ArrayList<File>();
if (parent.isDirectory()) {
File[] files = parent.listFiles();
files = (files != null ? files : new File[0]);
for (File child : files) {
if (child.isFile() && child.getName().endsWith(".java")) {
result.add(child);
}
}
if (recurse) {
for (File child : files) {
if (child.isDirectory() && child.getName().startsWith(".") == false) {
result.addAll(findFiles(child, recurse));
}
}
}
} else {
if (parent.getName().endsWith(".java")) {
result.add(parent);
}
}
return result;
} | #vulnerable code
private static List<File> findFiles(final File parent, boolean recurse) {
final List<File> result = new ArrayList<File>();
if (parent.isDirectory()) {
File[] files = parent.listFiles();
for (File child : files) {
if (child.isFile() && child.getName().endsWith(".java")) {
result.add(child);
}
}
if (recurse) {
for (File child : files) {
if (child.isDirectory() && child.getName().startsWith(".") == false) {
result.addAll(findFiles(child, recurse));
}
}
}
} else {
if (parent.getName().endsWith(".java")) {
result.add(parent);
}
}
return result;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception {
Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME);
Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME);
if (rowsAttr != null && columnsAttr != null) {
iterable.dimensions(new int[] {Integer.parseInt(rowsAttr.getValue()), Integer.parseInt(columnsAttr.getValue())});
}
XMLEvent event = nextEvent(">iter ");
while (event.isEndElement() == false) {
if (event.isStartElement()) {
StartElement start = event.asStartElement();
QName expectedType = iterable.category() == SerCategory.MAP ? ENTRY_QNAME : ITEM_QNAME;
if (start.getName().equals(expectedType) == false) {
throw new IllegalArgumentException("Expected '" + expectedType.getLocalPart() + "' but found '" + start.getName() + "'");
}
int count = 1;
Object key = null;
Object column = null;
Object value = null;
if (iterable.category() == SerCategory.COUNTED) {
Attribute countAttr = start.getAttributeByName(COUNT_QNAME);
if (countAttr != null) {
count = Integer.parseInt(countAttr.getValue());
}
value = parseValue(iterable, start);
} else if (iterable.category() == SerCategory.TABLE || iterable.category() == SerCategory.GRID) {
Attribute rowAttr = start.getAttributeByName(ROW_QNAME);
Attribute colAttr = start.getAttributeByName(COL_QNAME);
if (rowAttr == null || colAttr == null) {
throw new IllegalArgumentException("Unable to read table as row/col attribute missing");
}
String rowStr = rowAttr.getValue();
if (iterable.keyType() != null) {
key = settings.getConverter().convertFromString(iterable.keyType(), rowStr);
} else {
key = rowStr;
}
String colStr = colAttr.getValue();
if (iterable.columnType() != null) {
column = settings.getConverter().convertFromString(iterable.columnType(), colStr);
} else {
column = colStr;
}
value = parseValue(iterable, start);
} else if (iterable.category() == SerCategory.MAP) {
Attribute keyAttr = start.getAttributeByName(KEY_QNAME);
if (keyAttr != null) {
// item is value with a key attribute
String keyStr = keyAttr.getValue();
if (iterable.keyType() != null) {
key = settings.getConverter().convertFromString(iterable.keyType(), keyStr);
} else {
key = keyStr;
}
value = parseValue(iterable, start);
} else {
// two items nested in this entry
event = nextEvent(">>map ");
int loop = 0;
while (event.isEndElement() == false) {
if (event.isStartElement()) {
start = event.asStartElement();
if (start.getName().equals(ITEM_QNAME) == false) {
throw new IllegalArgumentException("Expected 'item' but found '" + start.getName() + "'");
}
if (key == null) {
key = parseKey(iterable, start);
} else {
value = parseValue(iterable, start);
}
loop++;
}
event = nextEvent("..map ");
}
if (loop != 2) {
throw new IllegalArgumentException("Expected 2 'item's but found " + loop);
}
}
} else { // COLLECTION
value = parseValue(iterable, start);
}
iterable.add(key, column, value, count);
}
event = nextEvent(".iter ");
}
return iterable.build();
} | #vulnerable code
private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception {
Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME);
Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME);
if (rowsAttr != null && columnsAttr != null) {
iterable.dimensions(new int[] {Integer.parseInt(rowsAttr.getValue()), Integer.parseInt(columnsAttr.getValue())});
}
XMLEvent event = nextEvent(">iter ");
while (event.isEndElement() == false) {
if (event.isStartElement()) {
StartElement start = event.asStartElement();
QName expectedType = iterable.category() == SerCategory.MAP ? ENTRY_QNAME : ITEM_QNAME;
if (start.getName().equals(expectedType) == false) {
throw new IllegalArgumentException("Expected '" + expectedType.getLocalPart() + "' but found '" + start.getName() + "'");
}
int count = 1;
Object key = null;
Object column = null;
Object value = null;
if (iterable.category() == SerCategory.COUNTED) {
Attribute countAttr = start.getAttributeByName(COUNT_QNAME);
if (countAttr != null) {
count = Integer.parseInt(countAttr.getValue());
}
value = parseValue(iterable, start);
} else if (iterable.category() == SerCategory.TABLE || iterable.category() == SerCategory.GRID) {
Attribute rowAttr = start.getAttributeByName(ROW_QNAME);
Attribute colAttr = start.getAttributeByName(COL_QNAME);
if (rowAttr == null || colAttr == null) {
throw new IllegalArgumentException("Unable to read table as row/col attribute missing");
}
String rowStr = rowAttr.getValue();
if (iterable.keyType() != null) {
key = settings.getConverter().convertFromString(iterable.keyType(), rowStr);
} else {
key = rowStr;
}
String colStr = colAttr.getValue();
if (iterable.columnType() != null) {
column = settings.getConverter().convertFromString(iterable.columnType(), colStr);
} else {
column = colStr;
}
value = parseValue(iterable, start);
} else if (iterable.category() == SerCategory.MAP) {
Attribute keyAttr = start.getAttributeByName(KEY_QNAME);
if (keyAttr != null) {
// item is value with a key attribute
String keyStr = keyAttr.getValue();
if (iterable.keyType() != null) {
key = settings.getConverter().convertFromString(iterable.keyType(), keyStr);
} else {
key = keyStr;
}
value = parseValue(iterable, start);
} else {
// two items nested in this entry
if (Bean.class.isAssignableFrom(iterable.keyType()) == false) {
throw new IllegalArgumentException("Unable to read map as declared key type is neither a bean nor a simple type: " + iterable.keyType().getName());
}
event = nextEvent(">>map ");
int loop = 0;
while (event.isEndElement() == false) {
if (event.isStartElement()) {
start = event.asStartElement();
if (start.getName().equals(ITEM_QNAME) == false) {
throw new IllegalArgumentException("Expected 'item' but found '" + start.getName() + "'");
}
if (key == null) {
key = parseKey(iterable, start);
} else {
value = parseValue(iterable, start);
}
loop++;
}
event = nextEvent("..map ");
}
if (loop != 2) {
throw new IllegalArgumentException("Expected 2 'item's but found " + loop);
}
}
} else { // COLLECTION
value = parseValue(iterable, start);
}
iterable.add(key, column, value, count);
}
event = nextEvent(".iter ");
}
return iterable.build();
}
#location 61
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static BeanCodeGen createFromArgs(String[] args) {
if (args == null) {
throw new IllegalArgumentException("Arguments must not be null");
}
String indent = " ";
String prefix = "";
boolean recurse = false;
int verbosity = 1;
boolean write = true;
File file = null;
BeanGenConfig config = null;
if (args.length == 0) {
throw new IllegalArgumentException("No arguments specified");
}
for (int i = 0; i < args.length - 1; i++) {
String arg = args[i];
if (arg == null) {
throw new IllegalArgumentException("Argument must not be null: " + Arrays.toString(args));
}
if (arg.startsWith("-indent=tab")) {
indent = "\t";
} else if (arg.startsWith("-indent=")) {
indent = " ".substring(0, Integer.parseInt(arg.substring(8)));
} else if (arg.startsWith("-prefix=")) {
prefix = arg.substring(8);
} else if (arg.equals("-R")) {
recurse = true;
} else if (arg.startsWith("-config=")) {
if (config != null) {
throw new IllegalArgumentException("Argument 'config' must not be specified twice: " + Arrays.toString(args));
}
config = BeanGenConfig.parse(arg.substring(8));
} else if (arg.startsWith("-verbose=")) {
verbosity = Integer.parseInt(arg.substring(9));
} else if (arg.startsWith("-v=")) {
System.out.println("Deprecated command line argument -v (use -verbose instead)");
verbosity = Integer.parseInt(arg.substring(3));
} else if (arg.equals("-nowrite")) {
write = false;
} else {
throw new IllegalArgumentException("Unknown argument: " + arg);
}
}
file = new File(args[args.length - 1]);
List<File> files = findFiles(file, recurse);
if (config == null) {
config = BeanGenConfig.parse("guava");
}
config.setIndent(indent);
config.setPrefix(prefix);
return new BeanCodeGen(files, config, verbosity, write);
} | #vulnerable code
public static BeanCodeGen createFromArgs(String[] args) {
if (args == null) {
throw new IllegalArgumentException("Arguments must not be null");
}
String indent = " ";
String prefix = "";
boolean recurse = false;
int verbosity = 1;
boolean write = true;
File file = null;
BeanGenConfig config = null;
if (args.length == 0) {
throw new IllegalArgumentException("No arguments specified");
}
for (int i = 0; i < args.length - 1; i++) {
String arg = args[i];
if (arg == null) {
throw new IllegalArgumentException("Argument must not be null: " + Arrays.toString(args));
}
if (arg.startsWith("-indent=tab")) {
indent = "\t";
} else if (arg.startsWith("-indent=")) {
indent = " ".substring(0, Integer.parseInt(arg.substring(8)));
} else if (arg.startsWith("-prefix=")) {
prefix = arg.substring(8);
} else if (arg.equals("-R")) {
recurse = true;
} else if (arg.equals("-config=")) {
if (config != null) {
throw new IllegalArgumentException("Argument 'config' must not be specified twice: " + Arrays.toString(args));
}
config = BeanGenConfig.parse(arg.substring(8));
} else if (arg.startsWith("-verbose=")) {
verbosity = Integer.parseInt(arg.substring(9));
} else if (arg.startsWith("-v=")) {
System.out.println("Deprecated command line argument -v (use -verbose instead)");
verbosity = Integer.parseInt(arg.substring(3));
} else if (arg.equals("-nowrite")) {
write = false;
} else {
throw new IllegalArgumentException("Unknown argument: " + arg);
}
}
file = new File(args[args.length - 1]);
List<File> files = findFiles(file, recurse);
if (config == null) {
config = BeanGenConfig.parse("guava");
}
config.setIndent(indent);
config.setPrefix(prefix);
return new BeanCodeGen(files, config, verbosity, write);
}
#location 50
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void writeElements(final String currentIndent, final SerIterator itemIterator) {
// find converter once for performance, and before checking if key is bean
StringConverter<Object> keyConverter = null;
StringConverter<Object> rowConverter = null;
StringConverter<Object> columnConverter = null;
boolean keyBean = false;
if (itemIterator.category() == SerCategory.TABLE || itemIterator.category() == SerCategory.GRID) {
try {
rowConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
} catch (RuntimeException ex) {
throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName(), ex);
}
try {
columnConverter = settings.getConverter().findConverterNoGenerics(itemIterator.columnType());
} catch (RuntimeException ex) {
throw new IllegalArgumentException("Unable to write map as declared column type is neither a bean nor a simple type: " + itemIterator.columnType().getName(), ex);
}
} else if (itemIterator.category() == SerCategory.MAP) {
// if key type is known and convertible use short key format, else use full bean format
if (settings.getConverter().isConvertible(itemIterator.keyType())) {
keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
} else {
keyBean = true;
}
}
// output each item
while (itemIterator.hasNext()) {
itemIterator.next();
StringBuilder attr = new StringBuilder(32);
if (keyConverter != null) {
String keyStr = convertToString(keyConverter, itemIterator.key(), "map key");
appendAttribute(attr, KEY, keyStr);
}
if (rowConverter != null) {
String rowStr = convertToString(rowConverter, itemIterator.key(), "table row");
appendAttribute(attr, ROW, rowStr);
String colStr = convertToString(columnConverter, itemIterator.column(), "table column");
appendAttribute(attr, COL, colStr);
}
if (itemIterator.count() != 1) {
appendAttribute(attr, COUNT, Integer.toString(itemIterator.count()));
}
if (keyBean) {
Object key = itemIterator.key();
builder.append(currentIndent).append('<').append(ENTRY).append(attr).append('>').append(settings.getNewLine());
writeKeyElement(currentIndent + settings.getIndent(), key, itemIterator);
writeValueElement(currentIndent + settings.getIndent(), ITEM, new StringBuilder(), itemIterator);
builder.append(currentIndent).append('<').append('/').append(ENTRY).append('>').append(settings.getNewLine());
} else {
String tagName = itemIterator.category() == SerCategory.MAP ? ENTRY : ITEM;
writeValueElement(currentIndent, tagName, attr, itemIterator);
}
}
} | #vulnerable code
private void writeElements(final String currentIndent, final SerIterator itemIterator) {
// find converter once for performance, and before checking if key is bean
StringConverter<Object> keyConverter = null;
StringConverter<Object> rowConverter = null;
StringConverter<Object> columnConverter = null;
boolean keyBean = false;
if (itemIterator.category() == SerCategory.TABLE || itemIterator.category() == SerCategory.GRID) {
try {
rowConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
} catch (RuntimeException ex) {
throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName(), ex);
}
try {
columnConverter = settings.getConverter().findConverterNoGenerics(itemIterator.columnType());
} catch (RuntimeException ex) {
throw new IllegalArgumentException("Unable to write map as declared column type is neither a bean nor a simple type: " + itemIterator.columnType().getName(), ex);
}
} else if (itemIterator.category() == SerCategory.MAP) {
if (settings.getConverter().isConvertible(itemIterator.keyType())) {
keyConverter = settings.getConverter().findConverterNoGenerics(itemIterator.keyType());
} else if (Bean.class.isAssignableFrom(itemIterator.keyType())) {
keyBean = true;
} else {
throw new IllegalArgumentException("Unable to write map as declared key type is neither a bean nor a simple type: " + itemIterator.keyType().getName());
}
}
// output each item
while (itemIterator.hasNext()) {
itemIterator.next();
StringBuilder attr = new StringBuilder(32);
if (keyConverter != null) {
String keyStr = convertToString(keyConverter, itemIterator.key(), "map key");
appendAttribute(attr, KEY, keyStr);
}
if (rowConverter != null) {
String rowStr = convertToString(rowConverter, itemIterator.key(), "table row");
appendAttribute(attr, ROW, rowStr);
String colStr = convertToString(columnConverter, itemIterator.column(), "table column");
appendAttribute(attr, COL, colStr);
}
if (itemIterator.count() != 1) {
appendAttribute(attr, COUNT, Integer.toString(itemIterator.count()));
}
if (keyBean) {
Object key = itemIterator.key();
if (key == null) {
throw new IllegalArgumentException("Unable to write map key as it cannot be null: " + key);
}
builder.append(currentIndent).append('<').append(ENTRY).append(attr).append('>').append(settings.getNewLine());
writeKeyValueElement(currentIndent + settings.getIndent(), key, itemIterator);
builder.append(currentIndent).append('<').append('/').append(ENTRY).append('>').append(settings.getNewLine());
} else {
String tagName = itemIterator.category() == SerCategory.MAP ? ENTRY : ITEM;
writeValueElement(currentIndent, tagName, attr, itemIterator);
}
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_global.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.075863, 0.0000001));
assertThat("number of errors", handler.getCount(), is(0));
} | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_global.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.075863, 0.0000001));
assertThat("number of errors", handler.getCount(), is(0));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
DataReader dataReader = null;
long nextPos = 0;
String chunkOfLastLine = null;
int attemptCount = 0;
while (attemptCount < MAX_ATTEMPT_COUNT) {
in.mark(FOUR_KB + (int) nextPos);
if (nextPos > 0) {
long skipped = in.skip(nextPos);
if (skipped != nextPos) {
break;
}
}
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.reset();
if (length <= 0) {
break;
}
nextPos += length;
String s = new String(buf, 0, length, "ASCII");
if (chunkOfLastLine != null && chunkOfLastLine.length() > 0) {
s = chunkOfLastLine + s;
}
dataReader = getDataReaderBySample(s, in);
if (dataReader != null) {
break;
}
int index = s.lastIndexOf('\n');
if (index >= 0) {
chunkOfLastLine = s.substring(index + 1, s.length());
} else {
chunkOfLastLine = "";
}
attemptCount++;
}
if (dataReader == null) {
if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed"));
throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed"));
}
return dataReader;
} | #vulnerable code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
in.mark(FOUR_KB);
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.reset();
String s = new String(buf, 0, length, "ASCII");
if (s.indexOf("[memory ] ") != -1) {
if ((s.indexOf("[memory ] [YC") != -1) ||(s.indexOf("[memory ] [OC") != -1)) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.6");
return new DataReaderJRockit1_6_0(in);
} else {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.4.2");
return new DataReaderJRockit1_4_2(in);
}
} else if (s.indexOf("since last AF or CON>") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.4.2");
return new DataReaderIBM1_4_2(in);
} else if (s.indexOf("GC cycle started") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.3.1");
return new DataReaderIBM1_3_1(in);
} else if (s.indexOf("<AF") != -1) {
// this should be an IBM JDK < 1.3.0
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM <1.3.0");
return new DataReaderIBM1_3_0(in);
} else if (s.indexOf("pause (young)") > 0) {
// G1 logger usually starts with "<timestamp>: [GC pause (young)...]"
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x G1 collector");
return new DataReaderSun1_6_0G1(in);
} else if (s.indexOf("[Times:") > 0) {
// all 1.6 lines end with a block like this "[Times: user=1.13 sys=0.08, real=0.95 secs]"
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf("CMS-initial-mark") != -1 || s.indexOf("PSYoungGen") != -1) {
// format is 1.5, but datareader for 1_6_0 can handle it
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.5.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf(": [") != -1) {
// format is 1.4, but datareader for 1_6_0 can handle it
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.4.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf("[GC") != -1 || s.indexOf("[Full GC") != -1 || s.indexOf("[Inc GC")!=-1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.3.1");
return new DataReaderSun1_3_1(in);
} else if (s.indexOf("<GC: managing allocation failure: need ") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.2.2");
return new DataReaderSun1_2_2(in);
} else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 20) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.2/1.3/1.4.0");
return new DataReaderHPUX1_2(in);
} else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 22) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.4.1/1.4.2");
return new DataReaderHPUX1_4_1(in);
} else if (s.indexOf("<verbosegc version=\"") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM J9 5.0");
return new DataReaderIBM_J9_5_0(in);
} else if (s.indexOf("starting collection, threshold allocation reached.") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM i5/OS 1.4.2");
return new DataReaderIBMi5OS1_4_2(in);
} else
if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed"));
throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed"));
}
#location 62
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free"))));
} | #vulnerable code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free"))));
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException, InterruptedException {
IntData performanceData = new IntData();
for (int i=0; i<10; i++) {
long start = System.currentTimeMillis();
DataReader dataReader = new DataReaderFactory().getDataReader(new FileInputStream(args[0]));
dataReader.read();
performanceData.add((int)(System.currentTimeMillis() - start));
}
printIntData(args[0], performanceData);
} | #vulnerable code
public static void main(String[] args) throws IOException, InterruptedException {
IntData performanceData = new IntData();
for (int i=0; i<50; i++) {
long start = System.currentTimeMillis();
DataReader dataReader = new DataReaderSun1_6_0(new FileInputStream(args[0]));
dataReader.read();
performanceData.add((int)(System.currentTimeMillis() - start));
}
printIntData(args[0], performanceData);
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(3));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001));
assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001));
assertThat("number of errors", handler.getCount(), is(1));
} | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_full_header.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(3));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001));
assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001));
assertThat("number of errors", handler.getCount(), is(1));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException {
event.setType(Type.lookup(getAttributeValue(startElement, "type")));
if (event.getExtendedType() == null) {
LOG.warning("could not determine type of event " + startElement.toString());
return;
}
String currentElementName = "";
while (eventReader.hasNext() && !currentElementName.equals(GC_START)) {
XMLEvent xmlEvent = eventReader.nextEvent();
if (xmlEvent.isStartElement()) {
StartElement startEl = xmlEvent.asStartElement();
if (startEl.getName().getLocalPart().equals("mem-info")) {
setTotalAndPreUsed(event, startEl);
}
else if (startEl.getName().getLocalPart().equals("mem")) {
switch (getAttributeValue(startEl, "type")) {
case "nursery":
GCEvent young = new GCEvent();
young.setType(Type.lookup("nursery"));
setTotalAndPreUsed(young, startEl);
event.add(young);
break;
case "tenure":
GCEvent tenured = new GCEvent();
tenured.setType(Type.lookup("tenure"));
setTotalAndPreUsed(tenured, startEl);
event.add(tenured);
break;
// all other are ignored
}
}
}
else if (xmlEvent.isEndElement()) {
EndElement endElement = xmlEvent.asEndElement();
currentElementName = endElement.getName().getLocalPart();
}
}
} | #vulnerable code
private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException {
event.setType(Type.lookup(getAttributeValue(startElement, "type")));
if (event.getExtendedType() == null) {
LOG.warning("could not determine type of event " + startElement.toString());
return;
}
String currentElementName = "";
while (eventReader.hasNext() && !currentElementName.equals(GC_START)) {
XMLEvent xmlEvent = eventReader.nextEvent();
if (xmlEvent.isStartElement()) {
StartElement startEl = xmlEvent.asStartElement();
if (startEl.getName().getLocalPart().equals("mem-info")) {
event.setTotal(NumberParser.parseInt(getAttributeValue(startEl, "total")) / 1024);
event.setPreUsed(event.getTotal() - (NumberParser.parseInt(getAttributeValue(startEl, "free")) / 1024));
}
else if (startEl.getName().getLocalPart().equals("mem")) {
switch (getAttributeValue(startEl, "type")) {
case "nursery":
// TODO read young
break;
}
}
}
else if (xmlEvent.isEndElement()) {
EndElement endElement = xmlEvent.asEndElement();
currentElementName = endElement.getName().getLocalPart();
}
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(3));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001));
assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001));
assertThat("number of errors", handler.getCount(), is(1));
} | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_full_header.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(3));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001));
assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001));
assertThat("number of errors", handler.getCount(), is(1));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R28_full_header.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(2));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(536870912)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001));
assertThat("number of errors", handler.getCount(), is(0));
} | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R28_full_header.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(2));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.025388, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(536870912)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(536870912 - 401882552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(536870912 - 457545744)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(134217728)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(134217728)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(134217728 - 55663192)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 401882552)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 401882552)));
assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001));
assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.272, 0.0001));
assertThat("number of errors", handler.getCount(), is(0));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean isParseablePhaseEvent(String line) {
Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null;
if (phaseStringMatcher != null && phaseStringMatcher.find()) {
String phaseType = phaseStringMatcher.group(GROUP_DECORATORS_GC_TYPE);
if (phaseType != null && AbstractGCEvent.Type.lookup(phaseType) != null) {
return true;
}
}
return false;
} | #vulnerable code
private boolean isParseablePhaseEvent(String line) {
Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null;
if (phaseStringMatcher.find()) {
String phaseType = phaseStringMatcher.group(GROUP_DECORATORS_GC_TYPE);
if (phaseType != null && AbstractGCEvent.Type.lookup(phaseType) != null) {
return true;
}
}
return false;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_full_header.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.00529, 0.0000001));
assertThat("number of errors", handler.getCount(), is(1));
} | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_full_header.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.00529, 0.0000001));
assertThat("number of errors", handler.getCount(), is(1));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_global.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(514064384)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840)));
assertThat("number of errors", handler.getCount(), is(0));
} | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_global.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(514064384)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840)));
assertThat("number of errors", handler.getCount(), is(0));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free"))));
} | #vulnerable code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free"))));
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R28_global.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.097756, 0.0000001));
assertThat("number of errors", handler.getCount(), is(0));
} | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R28_global.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.097756, 0.0000001));
assertThat("number of errors", handler.getCount(), is(0));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_global.txt");
gcResource.getLogger().addHandler(handler);
DataReader reader = getDataReader(gcResource);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(514064384)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840)));
assertThat("number of errors", handler.getCount(), is(0));
} | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R26_GAFP1_global.txt");
DataReader reader = new DataReaderIBM_J9_R28(in);
GCModel model = reader.read();
assertThat("model size", model.size(), is(1));
GCEvent event = (GCEvent) model.get(0);
assertThat("pause", event.getPause(), closeTo(0.036392, 0.0000001));
assertThat("total before", event.getTotal(), is(toKiloBytes(514064384)));
assertThat("free before", event.getPreUsed(), is(toKiloBytes(514064384 - 428417552)));
assertThat("free after", event.getPostUsed(), is(toKiloBytes(514064384 - 479900360)));
assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(111411200)));
assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(111411200 - 29431656)));
assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(111411200 - 80831520)));
assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(402653184)));
assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(402653184 - 398985896)));
assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(402653184 - 399068840)));
assertThat("number of errors", handler.getCount(), is(0));
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
DataReader dataReader = null;
long nextPos = 0;
String chunkOfLastLine = null;
int attemptCount = 0;
while (attemptCount < MAX_ATTEMPT_COUNT) {
in.mark(FOUR_KB + (int) nextPos);
if (nextPos > 0) {
long skipped = in.skip(nextPos);
if (skipped != nextPos) {
break;
}
}
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.reset();
if (length <= 0) {
break;
}
nextPos += length;
String s = new String(buf, 0, length, "ASCII");
if (chunkOfLastLine != null && chunkOfLastLine.length() > 0) {
s = chunkOfLastLine + s;
}
dataReader = getDataReaderBySample(s, in);
if (dataReader != null) {
break;
}
int index = s.lastIndexOf('\n');
if (index >= 0) {
chunkOfLastLine = s.substring(index + 1, s.length());
} else {
chunkOfLastLine = "";
}
attemptCount++;
}
if (dataReader == null) {
if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed"));
throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed"));
}
return dataReader;
} | #vulnerable code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
in.mark(FOUR_KB);
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.reset();
String s = new String(buf, 0, length, "ASCII");
if (s.indexOf("[memory ] ") != -1) {
if ((s.indexOf("[memory ] [YC") != -1) ||(s.indexOf("[memory ] [OC") != -1)) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.6");
return new DataReaderJRockit1_6_0(in);
} else {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: JRockit 1.4.2");
return new DataReaderJRockit1_4_2(in);
}
} else if (s.indexOf("since last AF or CON>") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.4.2");
return new DataReaderIBM1_4_2(in);
} else if (s.indexOf("GC cycle started") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM 1.3.1");
return new DataReaderIBM1_3_1(in);
} else if (s.indexOf("<AF") != -1) {
// this should be an IBM JDK < 1.3.0
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM <1.3.0");
return new DataReaderIBM1_3_0(in);
} else if (s.indexOf("pause (young)") > 0) {
// G1 logger usually starts with "<timestamp>: [GC pause (young)...]"
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x G1 collector");
return new DataReaderSun1_6_0G1(in);
} else if (s.indexOf("[Times:") > 0) {
// all 1.6 lines end with a block like this "[Times: user=1.13 sys=0.08, real=0.95 secs]"
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.6.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf("CMS-initial-mark") != -1 || s.indexOf("PSYoungGen") != -1) {
// format is 1.5, but datareader for 1_6_0 can handle it
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.5.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf(": [") != -1) {
// format is 1.4, but datareader for 1_6_0 can handle it
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.4.x");
return new DataReaderSun1_6_0(in);
} else if (s.indexOf("[GC") != -1 || s.indexOf("[Full GC") != -1 || s.indexOf("[Inc GC")!=-1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.3.1");
return new DataReaderSun1_3_1(in);
} else if (s.indexOf("<GC: managing allocation failure: need ") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: Sun 1.2.2");
return new DataReaderSun1_2_2(in);
} else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 20) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.2/1.3/1.4.0");
return new DataReaderHPUX1_2(in);
} else if (s.indexOf("<GC: ") == 0 && s.indexOf('>') != -1 && new StringTokenizer(s.substring(0, s.indexOf('>')+1), " ").countTokens() == 22) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: HP-UX 1.4.1/1.4.2");
return new DataReaderHPUX1_4_1(in);
} else if (s.indexOf("<verbosegc version=\"") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM J9 5.0");
return new DataReaderIBM_J9_5_0(in);
} else if (s.indexOf("starting collection, threshold allocation reached.") != -1) {
if (LOG.isLoggable(Level.INFO)) LOG.info("File format: IBM i5/OS 1.4.2");
return new DataReaderIBMi5OS1_4_2(in);
} else
if (LOG.isLoggable(Level.SEVERE)) LOG.severe(localStrings.getString("datareaderfactory_instantiation_failed"));
throw new IOException(localStrings.getString("datareaderfactory_instantiation_failed"));
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) {
return createListBoxModel(credentialsId);
} | #vulnerable code
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(
ACL.SYSTEM,
Jenkins.getInstance(),
StringCredentials.class,
Collections.emptyList(),
CredentialsMatchers.always()
);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static SonarQubeWebHook get() {
return Jenkins.get().getExtensionList(RootAction.class).get(SonarQubeWebHook.class);
} | #vulnerable code
public static SonarQubeWebHook get() {
return Jenkins.getInstance().getExtensionList(RootAction.class).get(SonarQubeWebHook.class);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
if (!SonarInstallation.isValid(getInstallationName(), listener)) {
return false;
}
ArgumentListBuilder args = new ArgumentListBuilder();
EnvVars env = BuilderUtils.getEnvAndBuildVars(run, listener);
SonarRunnerInstallation sri = getSonarRunnerInstallation();
if (sri == null) {
args.add(launcher.isUnix() ? "sonar-runner" : "sonar-runner.bat");
} else {
sri = BuilderUtils.getBuildTool(sri, env, listener);
String exe = sri.getExecutable(launcher);
if (exe == null) {
Logger.printFailureMessage(listener);
listener.fatalError(Messages.SonarRunner_ExecutableNotFound(sri.getName()));
return false;
}
args.add(exe);
env.put("SONAR_RUNNER_HOME", sri.getHome());
}
SonarInstallation sonarInst = getSonarInstallation();
addTaskArgument(args);
addAdditionalArguments(args, sonarInst);
ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix());
if (!populateConfiguration(argsBuilder, run, workspace, listener, env, sonarInst)) {
return false;
}
// Java
computeJdkToUse(run, workspace, listener, env);
// Java options
env.put("SONAR_RUNNER_OPTS", getJavaOpts());
long startTime = System.currentTimeMillis();
int r;
try {
r = executeSonarRunner(run, workspace, launcher, listener, args, env);
} catch (IOException e) {
handleErrors(run, listener, sri, startTime, e);
r = -1;
}
return r == 0;
} | #vulnerable code
private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
if (!SonarInstallation.isValid(getInstallationName(), listener)) {
return false;
}
ArgumentListBuilder args = new ArgumentListBuilder();
EnvVars env = run.getEnvironment(listener);
if (run instanceof AbstractBuild) {
env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables());
}
SonarRunnerInstallation sri = getSonarRunnerInstallation();
if (sri == null) {
args.add(launcher.isUnix() ? "sonar-runner" : "sonar-runner.bat");
} else {
sri = sri.forNode(getComputer(workspace).getNode(), listener);
sri = sri.forEnvironment(env);
String exe = sri.getExecutable(launcher);
if (exe == null) {
Logger.printFailureMessage(listener);
listener.fatalError(Messages.SonarRunner_ExecutableNotFound(sri.getName()));
return false;
}
args.add(exe);
env.put("SONAR_RUNNER_HOME", sri.getHome());
}
SonarInstallation sonarInst = getSonarInstallation();
addTaskArgument(args);
addAdditionalArguments(args, sonarInst);
ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix());
if (!populateConfiguration(argsBuilder, run, workspace, listener, env, sonarInst)) {
return false;
}
// Java
computeJdkToUse(run, workspace, listener, env);
// Java options
env.put("SONAR_RUNNER_OPTS", getJavaOpts());
long startTime = System.currentTimeMillis();
int r;
try {
r = executeSonarRunner(run, workspace, launcher, listener, args, env);
} catch (IOException e) {
handleErrors(run, listener, sri, startTime, e);
r = -1;
}
return r == 0;
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unused")
public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {
return createListBoxModel(webhookSecretId);
} | #vulnerable code
@SuppressWarnings("unused")
public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return new StandardListBoxModel().includeCurrentValue(webhookSecretId);
}
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(
ACL.SYSTEM,
Jenkins.getInstance(),
StringCredentials.class,
Collections.emptyList(),
CredentialsMatchers.always()
);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String getIconFileName() {
PluginWrapper wrapper = Jenkins.getInstanceOrNull().getPluginManager()
.getPlugin(SonarPlugin.class);
return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png";
} | #vulnerable code
@Override
public String getIconFileName() {
PluginWrapper wrapper = Jenkins.getInstance().getPluginManager()
.getPlugin(SonarPlugin.class);
return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png";
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
if (!cd.hasSelectedDevice ())
return;
if (!this.showDevices)
{
cd.setSelectedParameterPageInBank (index);
return;
}
if (cd.getPositionInBank () != index)
{
cd.selectSibling (index);
return;
}
final ModeManager modeManager = this.surface.getModeManager ();
if (!cd.hasLayers ())
{
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false);
return;
}
final ChannelData layer = cd.getSelectedLayerOrDrumPad ();
if (layer == null)
cd.selectLayerOrDrumPad (0);
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
return;
}
// LONG press - move upwards
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
this.moveUp ();
} | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.getModeManager ();
if (event == ButtonEvent.UP)
{
if (!cd.hasSelectedDevice ())
return;
if (!this.showDevices)
{
cd.setSelectedParameterPageInBank (index);
return;
}
if (cd.getPositionInBank () != index)
{
cd.selectSibling (index);
return;
}
final boolean isContainer = cd.hasLayers ();
if (!isContainer)
{
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false);
return;
}
final ChannelData layer = cd.getSelectedLayerOrDrumPad ();
if (layer == null)
cd.selectLayerOrDrumPad (0);
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
return;
}
// LONG press - move upwards
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
// There is no device on the track move upwards to the track view
if (!cd.hasSelectedDevice ())
{
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
return;
}
// Parameter banks are shown -> show devices
final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS);
if (!deviceParamsMode.isShowDevices ())
{
deviceParamsMode.setShowDevices (true);
return;
}
// Devices are shown, if nested show the layers otherwise move up to the tracks
if (cd.isNested ())
{
cd.selectParent ();
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
deviceParamsMode.setShowDevices (false);
cd.selectChannel ();
return;
}
// Move up to the track
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
}
#location 48
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
if (l == null)
return;
this.isKnobTouched[index] = isTouched;
if (isTouched)
{
if (this.surface.isDeletePressed ())
{
this.surface.setButtonConsumed (this.surface.getDeleteButtonId ());
switch (index)
{
case 0:
cd.resetLayerOrDrumPadVolume (l.getIndex ());
break;
case 1:
cd.resetLayerOrDrumPadPan (l.getIndex ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.resetLayerSend (l.getIndex (), sendIndex);
break;
}
return;
}
switch (index)
{
case 0:
this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ());
break;
case 1:
this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank ();
final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName ();
if (!name.isEmpty ())
this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ());
break;
}
}
switch (index)
{
case 0:
cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched);
break;
case 1:
cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched);
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched);
break;
}
this.checkStopAutomationOnKnobRelease (isTouched);
} | #vulnerable code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
this.isKnobTouched[index] = isTouched;
if (isTouched)
{
if (this.surface.isDeletePressed ())
{
this.surface.setButtonConsumed (this.surface.getDeleteButtonId ());
switch (index)
{
case 0:
cd.resetLayerOrDrumPadVolume (l.getIndex ());
break;
case 1:
cd.resetLayerOrDrumPadPan (l.getIndex ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.resetLayerSend (l.getIndex (), sendIndex);
break;
}
return;
}
switch (index)
{
case 0:
this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ());
break;
case 1:
this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank ();
final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName ();
if (!name.isEmpty ())
this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ());
break;
}
}
switch (index)
{
case 0:
cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched);
break;
case 1:
cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched);
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched);
break;
}
this.checkStopAutomationOnKnobRelease (isTouched);
}
#location 55
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
if (!cd.hasSelectedDevice ())
return;
final int offset = getDrumPadIndex (cd);
final ChannelData layer = cd.getLayerOrDrumPad (offset + index);
if (!layer.doesExist ())
return;
final int layerIndex = layer.getIndex ();
if (!layer.isSelected ())
{
cd.selectLayerOrDrumPad (layerIndex);
return;
}
cd.enterLayerOrDrumPad (layer.getIndex ());
cd.selectFirstDeviceInLayerOrDrumPad (layer.getIndex ());
final ModeManager modeManager = this.surface.getModeManager ();
modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS);
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true);
return;
}
// LONG press
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
this.moveUp ();
} | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.getModeManager ();
if (event == ButtonEvent.UP)
{
if (!cd.hasSelectedDevice ())
return;
final int offset = getDrumPadIndex (cd);
final ChannelData layer = cd.getLayerOrDrumPad (offset + index);
if (!layer.doesExist ())
return;
final int layerIndex = layer.getIndex ();
if (!layer.isSelected ())
{
cd.selectLayerOrDrumPad (layerIndex);
return;
}
cd.enterLayerOrDrumPad (layer.getIndex ());
cd.selectFirstDeviceInLayerOrDrumPad (layer.getIndex ());
modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS);
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true);
return;
}
// LONG press
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
// There is no device on the track move upwards to the track view
if (!cd.hasSelectedDevice ())
{
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
return;
}
modeManager.setActiveMode (Modes.MODE_DEVICE_PARAMS);
cd.selectChannel ();
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (true);
}
#location 42
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void sendDisplayData ()
{
if (this.hidDevice == null)
return;
synchronized (this.busySendingDisplay)
{
final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer ();
for (int row = 0; row < 3; row++)
{
fillHeader (displayBuffer, row);
if (row == 0)
{
for (int j = 0; j < 72; j++)
{
final int col = j / 8;
displayBuffer.put ((byte) this.bars[col][j - col * 8]);
if (j % 8 == 7)
{
displayBuffer.put ((byte) this.bars[col][8]);
}
else
{
if (this.dots[0][j] && this.dots[1][j])
displayBuffer.put ((byte) 255);
else if (this.dots[0][j])
displayBuffer.put ((byte) 253);
else if (this.dots[1][j])
displayBuffer.put ((byte) 254);
else
displayBuffer.put ((byte) 0);
}
}
// Padding
for (int j = 0; j < 96; j++)
displayBuffer.put ((byte) 0);
}
else
{
for (int j = 0; j < 72; j++)
displayBuffer.put (this.getCharacter (row - 1, j));
// Padding
for (int j = 0; j < 96; j++)
displayBuffer.put ((byte) 0);
}
// TODO Use Memory object for interface; also rewind on createByteBuffer with Reaper
displayBuffer.rewind ();
final byte [] data = new byte [DATA_SZ];
displayBuffer.get (data);
this.hidDevice.sendOutputReport ((byte) 0xE0, data, DATA_SZ);
}
}
} | #vulnerable code
public void sendDisplayData ()
{
if (this.usbEndpointDisplay == null)
return;
synchronized (this.busySendingDisplay)
{
final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer ();
displayBuffer.rewind ();
for (int row = 0; row < 3; row++)
{
fillHeader (displayBuffer, row);
if (row == 0)
{
for (int j = 0; j < 72; j++)
{
final int col = j / 8;
displayBuffer.put ((byte) this.bars[col][j - col * 8]);
if (j % 8 == 7)
{
displayBuffer.put ((byte) this.bars[col][8]);
}
else
{
if (this.dots[0][j] && this.dots[1][j])
displayBuffer.put ((byte) 255);
else if (this.dots[0][j])
displayBuffer.put ((byte) 253);
else if (this.dots[1][j])
displayBuffer.put ((byte) 254);
else
displayBuffer.put ((byte) 0);
}
}
// Padding
for (int j = 0; j < 96; j++)
displayBuffer.put ((byte) 0);
}
else
{
for (int j = 0; j < 72; j++)
displayBuffer.put (this.getCharacter (row - 1, j));
// Padding
for (int j = 0; j < 96; j++)
displayBuffer.put ((byte) 0);
}
// TODO TEST
final byte [] data = new byte [DATA_SZ];
displayBuffer.get (data);
this.hidDevice.sendOutputReport ((byte) 0, data, DATA_SZ);
// this.usbEndpointDisplay.send (this.displayBlock, TIMEOUT);
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void execute (final ButtonEvent event)
{
if (event != ButtonEvent.DOWN)
return;
final ViewManager viewManager = this.surface.getViewManager ();
final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank ();
final TrackData sel = tb.getSelectedTrack ();
if (sel == null)
{
viewManager.setActiveView (Views.VIEW_SESSION);
return;
}
if (Views.isNoteView (viewManager.getActiveViewId ()))
{
if (this.surface.isShiftPressed ())
this.seqSelect.executeNormal (event);
else
this.playSelect.executeNormal (event);
}
else
{
final Integer viewID = viewManager.getPreferredView (sel.getPosition ());
if (viewID == null)
this.seqSelect.executeNormal (event);
else
viewManager.setActiveView (viewID);
}
viewManager.setPreferredView (sel.getPosition (), viewManager.getActiveViewId ());
this.surface.getDisplay ().notify (viewManager.getActiveView ().getName ());
} | #vulnerable code
@Override
public void execute (final ButtonEvent event)
{
if (event != ButtonEvent.DOWN)
return;
final ViewManager viewManager = this.surface.getViewManager ();
final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank ();
final TrackData sel = tb.getSelectedTrack ();
if (sel == null)
{
viewManager.setActiveView (Views.VIEW_SESSION);
return;
}
Integer viewID;
if (Views.isNoteView (viewManager.getActiveViewId ()))
{
if (this.surface.isShiftPressed ())
viewID = viewManager.isActiveView (Views.VIEW_SEQUENCER) ? Views.VIEW_RAINDROPS : Views.VIEW_SEQUENCER;
else
viewID = viewManager.isActiveView (Views.VIEW_PLAY) ? Views.VIEW_DRUM : Views.VIEW_PLAY;
}
else
{
viewID = viewManager.getPreferredView (sel.getPosition ());
if (viewID == null)
viewID = this.surface.isShiftPressed () ? Views.VIEW_SEQUENCER : Views.VIEW_PLAY;
}
viewManager.setActiveView (viewID);
viewManager.setPreferredView (sel.getPosition (), viewID);
}
#location 30
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onGridNote (final int note, final int velocity)
{
if (velocity == 0)
return;
final ICursorDevice cursorDevice = this.model.getCursorDevice ();
final int n = this.surface.getPadGrid ().translateToController (note);
switch (n)
{
// Flip views
case 56:
this.switchToView (Views.VIEW_SESSION);
break;
case 57:
this.switchToView (Views.VIEW_PLAY);
break;
case 58:
this.switchToView (Views.VIEW_DRUM);
break;
case 59:
this.switchToView (Views.VIEW_SEQUENCER);
break;
case 60:
this.switchToView (Views.VIEW_RAINDROPS);
break;
// Last row transport
case 63:
this.playCommand.executeNormal (ButtonEvent.DOWN);
this.surface.getDisplay ().notify ("Start/Stop");
break;
case 55:
this.model.getTransport ().record ();
this.surface.getDisplay ().notify ("Record");
break;
case 47:
this.model.getTransport ().toggleLoop ();
this.surface.getDisplay ().notify ("Toggle Loop");
break;
case 39:
this.model.getTransport ().toggleMetronome ();
this.surface.getDisplay ().notify ("Toggle Click");
break;
// Navigation
case 62:
this.onNew ();
this.surface.getDisplay ().notify ("New clip");
break;
case 54:
this.model.getTransport ().toggleLauncherOverdub ();
this.surface.getDisplay ().notify ("Toggle Launcher Overdub");
break;
case 46:
this.model.getCursorClip ().quantize (this.surface.getConfiguration ().getQuantizeAmount () / 100.0);
this.surface.getDisplay ().notify ("Quantize");
break;
case 38:
this.model.getApplication ().undo ();
this.surface.getDisplay ().notify ("Undo");
break;
// Device Parameters up/down
case 24:
if (cursorDevice.hasPreviousParameterPage ())
{
cursorDevice.previousParameterPage ();
this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ());
}
break;
case 25:
if (cursorDevice.hasNextParameterPage ())
{
cursorDevice.nextParameterPage ();
this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ());
}
break;
// Device up/down
case 32:
if (cursorDevice.canSelectPreviousFX ())
{
cursorDevice.selectPrevious ();
this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ());
}
break;
case 33:
if (cursorDevice.canSelectNextFX ())
{
cursorDevice.selectNext ();
this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ());
}
break;
// Change the scale
case 35:
this.scales.prevScale ();
final String name = this.scales.getScale ().getName ();
this.surface.getConfiguration ().setScale (name);
this.surface.getDisplay ().notify (name);
break;
case 36:
this.scales.nextScale ();
final String name2 = this.scales.getScale ().getName ();
this.surface.getConfiguration ().setScale (name2);
this.surface.getDisplay ().notify (name2);
break;
case 27:
this.scales.toggleChromatic ();
this.surface.getDisplay ().notify (this.scales.isChromatic () ? "Chromatc" : "In Key");
break;
// Scale Base note selection
default:
if (n > 15)
return;
final int pos = TRANSLATE[n];
if (pos == -1)
return;
this.scales.setScaleOffset (pos);
this.surface.getConfiguration ().setScaleBase (Scales.BASES[pos]);
this.surface.getDisplay ().notify (Scales.BASES[pos]);
this.surface.getViewManager ().getActiveView ().updateNoteMapping ();
break;
}
} | #vulnerable code
@Override
public void onGridNote (final int note, final int velocity)
{
if (velocity == 0)
return;
final ICursorDevice cursorDevice = this.model.getCursorDevice ();
switch (this.surface.getPadGrid ().translateToController (note))
{
// Flip views
case 56:
this.switchToView (Views.VIEW_SESSION);
break;
case 57:
this.switchToView (Views.VIEW_PLAY);
break;
case 58:
this.switchToView (Views.VIEW_DRUM);
break;
case 59:
this.switchToView (Views.VIEW_SEQUENCER);
break;
case 60:
this.switchToView (Views.VIEW_RAINDROPS);
break;
// Last row transport
case 63:
this.playCommand.executeNormal (ButtonEvent.DOWN);
this.surface.getDisplay ().notify ("Start/Stop");
break;
case 55:
this.model.getTransport ().record ();
this.surface.getDisplay ().notify ("Record");
break;
case 47:
this.model.getTransport ().toggleLoop ();
this.surface.getDisplay ().notify ("Toggle Loop");
break;
case 39:
this.model.getTransport ().toggleMetronome ();
this.surface.getDisplay ().notify ("Toggle Click");
break;
// Navigation
case 62:
this.onNew ();
this.surface.getDisplay ().notify ("New clip");
break;
case 54:
this.model.getTransport ().toggleLauncherOverdub ();
this.surface.getDisplay ().notify ("Toggle Launcher Overdub");
break;
case 46:
this.model.getCursorClip ().quantize (this.surface.getConfiguration ().getQuantizeAmount () / 100.0);
this.surface.getDisplay ().notify ("Quantize");
break;
case 38:
this.model.getApplication ().undo ();
this.surface.getDisplay ().notify ("Undo");
break;
// Device Parameters up/down
case 24:
if (cursorDevice.hasPreviousParameterPage ())
{
cursorDevice.previousParameterPage ();
this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ());
}
break;
case 25:
if (cursorDevice.hasNextParameterPage ())
{
cursorDevice.nextParameterPage ();
this.surface.getDisplay ().notify ("Bank: " + cursorDevice.getSelectedParameterPageName ());
}
break;
// Device up/down
case 32:
if (cursorDevice.canSelectPreviousFX ())
{
cursorDevice.selectPrevious ();
this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ());
}
break;
case 33:
if (cursorDevice.canSelectNextFX ())
{
cursorDevice.selectNext ();
this.surface.getDisplay ().notify ("Device: " + cursorDevice.getName ());
}
break;
// Change the scale
case 35:
this.scales.prevScale ();
final String name = this.scales.getScale ().getName ();
this.surface.getConfiguration ().setScale (name);
this.surface.getDisplay ().notify (name);
break;
case 36:
this.scales.nextScale ();
final String name2 = this.scales.getScale ().getName ();
this.surface.getConfiguration ().setScale (name2);
this.surface.getDisplay ().notify (name2);
break;
case 27:
this.scales.toggleChromatic ();
this.surface.getDisplay ().notify (this.scales.isChromatic () ? "Chromatc" : "In Key");
break;
// Scale Base note selection
default:
if (note > 15)
return;
final int pos = TRANSLATE[note];
if (pos == -1)
return;
this.scales.setScaleOffset (pos);
this.surface.getConfiguration ().setScaleBase (Scales.BASES[pos]);
this.surface.getDisplay ().notify (Scales.BASES[pos]);
this.surface.getViewManager ().getActiveView ().updateNoteMapping ();
break;
}
}
#location 123
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void moveUp ()
{
// There is no device on the track move upwards to the track view
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final View activeView = this.surface.getViewManager ().getActiveView ();
if (!cd.hasSelectedDevice ())
{
activeView.executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
return;
}
// Parameter banks are shown -> show devices
final ModeManager modeManager = this.surface.getModeManager ();
final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS);
if (!deviceParamsMode.isShowDevices ())
{
deviceParamsMode.setShowDevices (true);
return;
}
// Devices are shown, if nested show the layers otherwise move up to the tracks
if (cd.isNested ())
{
cd.selectParent ();
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
deviceParamsMode.setShowDevices (false);
cd.selectChannel ();
return;
}
// Move up to the track
if (this.model.isCursorDeviceOnMasterTrack ())
{
activeView.executeTriggerCommand (Commands.COMMAND_MASTERTRACK, ButtonEvent.DOWN);
activeView.executeTriggerCommand (Commands.COMMAND_MASTERTRACK, ButtonEvent.UP);
}
else
activeView.executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
} | #vulnerable code
protected void moveUp ()
{
// There is no device on the track move upwards to the track view
final CursorDeviceProxy cd = this.model.getCursorDevice ();
if (!cd.hasSelectedDevice ())
{
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
return;
}
// Parameter banks are shown -> show devices
final ModeManager modeManager = this.surface.getModeManager ();
final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS);
if (!deviceParamsMode.isShowDevices ())
{
deviceParamsMode.setShowDevices (true);
return;
}
// Devices are shown, if nested show the layers otherwise move up to the tracks
if (cd.isNested ())
{
cd.selectParent ();
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
deviceParamsMode.setShowDevices (false);
cd.selectChannel ();
return;
}
// Move up to the track
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
if (l == null)
return;
this.isKnobTouched[index] = isTouched;
if (isTouched)
{
if (this.surface.isDeletePressed ())
{
this.surface.setButtonConsumed (this.surface.getDeleteButtonId ());
switch (index)
{
case 0:
cd.resetLayerOrDrumPadVolume (l.getIndex ());
break;
case 1:
cd.resetLayerOrDrumPadPan (l.getIndex ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.resetLayerSend (l.getIndex (), sendIndex);
break;
}
return;
}
switch (index)
{
case 0:
this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ());
break;
case 1:
this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank ();
final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName ();
if (!name.isEmpty ())
this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ());
break;
}
}
switch (index)
{
case 0:
cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched);
break;
case 1:
cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched);
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched);
break;
}
this.checkStopAutomationOnKnobRelease (isTouched);
} | #vulnerable code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
this.isKnobTouched[index] = isTouched;
if (isTouched)
{
if (this.surface.isDeletePressed ())
{
this.surface.setButtonConsumed (this.surface.getDeleteButtonId ());
switch (index)
{
case 0:
cd.resetLayerOrDrumPadVolume (l.getIndex ());
break;
case 1:
cd.resetLayerOrDrumPadPan (l.getIndex ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.resetLayerSend (l.getIndex (), sendIndex);
break;
}
return;
}
switch (index)
{
case 0:
this.surface.getDisplay ().notify ("Volume: " + l.getVolumeStr ());
break;
case 1:
this.surface.getDisplay ().notify ("Pan: " + l.getPanStr ());
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
final EffectTrackBankProxy fxTrackBank = this.model.getEffectTrackBank ();
final String name = fxTrackBank == null ? l.getSends ()[sendIndex].getName () : fxTrackBank.getTrack (sendIndex).getName ();
if (!name.isEmpty ())
this.surface.getDisplay ().notify ("Send " + name + ": " + l.getSends ()[sendIndex].getDisplayedValue ());
break;
}
}
switch (index)
{
case 0:
cd.touchLayerOrDrumPadVolume (l.getIndex (), isTouched);
break;
case 1:
cd.touchLayerOrDrumPadPan (l.getIndex (), isTouched);
break;
default:
if (this.isPush2 && index < 4)
break;
final int sendIndex = index - (this.isPush2 ? this.surface.getConfiguration ().isSendsAreToggled () ? 0 : 4 : 2);
cd.touchLayerOrDrumPadSend (l.getIndex (), sendIndex, isTouched);
break;
}
this.checkStopAutomationOnKnobRelease (isTouched);
}
#location 58
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
if (!cd.hasSelectedDevice ())
return;
if (!this.showDevices)
{
cd.setSelectedParameterPageInBank (index);
return;
}
if (cd.getPositionInBank () != index)
{
cd.selectSibling (index);
return;
}
final ModeManager modeManager = this.surface.getModeManager ();
if (!cd.hasLayers ())
{
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false);
return;
}
final ChannelData layer = cd.getSelectedLayerOrDrumPad ();
if (layer == null)
cd.selectLayerOrDrumPad (0);
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
return;
}
// LONG press - move upwards
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
this.moveUp ();
} | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.getModeManager ();
if (event == ButtonEvent.UP)
{
if (!cd.hasSelectedDevice ())
return;
if (!this.showDevices)
{
cd.setSelectedParameterPageInBank (index);
return;
}
if (cd.getPositionInBank () != index)
{
cd.selectSibling (index);
return;
}
final boolean isContainer = cd.hasLayers ();
if (!isContainer)
{
((DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS)).setShowDevices (false);
return;
}
final ChannelData layer = cd.getSelectedLayerOrDrumPad ();
if (layer == null)
cd.selectLayerOrDrumPad (0);
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
return;
}
// LONG press - move upwards
this.surface.setButtonConsumed (PushControlSurface.PUSH_BUTTON_ROW1_1 + index);
// There is no device on the track move upwards to the track view
if (!cd.hasSelectedDevice ())
{
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
return;
}
// Parameter banks are shown -> show devices
final DeviceParamsMode deviceParamsMode = (DeviceParamsMode) modeManager.getMode (Modes.MODE_DEVICE_PARAMS);
if (!deviceParamsMode.isShowDevices ())
{
deviceParamsMode.setShowDevices (true);
return;
}
// Devices are shown, if nested show the layers otherwise move up to the tracks
if (cd.isNested ())
{
cd.selectParent ();
modeManager.setActiveMode (Modes.MODE_DEVICE_LAYER);
deviceParamsMode.setShowDevices (false);
cd.selectChannel ();
return;
}
// Move up to the track
this.surface.getViewManager ().getActiveView ().executeTriggerCommand (Commands.COMMAND_TRACK, ButtonEvent.DOWN);
}
#location 48
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Artifact chooseBinaryBits() throws MojoExecutionException {
String plat;
String os = System.getProperty("os.name");
getLog().debug("OS = " + os);
// See here for possible values of os.name:
// http://lopica.sourceforge.net/os.html
if (os.startsWith("Windows")) {
plat = "win32";
} else if ("Linux".equals(os)) {
plat = "linux";
} else if ("Solaris".equals(os) || "SunOS".equals(os)) {
plat = "solaris";
} else if ("Mac OS X".equals(os) || "Darwin".equals(os)) {
plat = isBelowMacOSX_10_8() ? "mac" : "osx";
} else {
throw new MojoExecutionException("Sorry, Launch4j doesn't support the '" + os + "' OS.");
}
return factory.createArtifactWithClassifier(LAUNCH4J_GROUP_ID, LAUNCH4J_ARTIFACT_ID,
getLaunch4jVersion(), "jar", "workdir-" + plat);
} | #vulnerable code
private Artifact chooseBinaryBits() throws MojoExecutionException {
String plat;
String os = System.getProperty("os.name");
getLog().debug("OS = " + os);
// See here for possible values of os.name:
// http://lopica.sourceforge.net/os.html
if (os.startsWith("Windows")) {
plat = "win32";
} else if ("Linux".equals(os)) {
plat = "linux";
} else if ("Solaris".equals(os) || "SunOS".equals(os)) {
plat = "solaris";
} else if ("Mac OS X".equals(os) || "Darwin".equals(os)) {
plat = (isBelow10_8(System.getProperty("os.version"))) ? "mac" : "osx";
} else {
throw new MojoExecutionException("Sorry, Launch4j doesn't support the '" + os + "' OS.");
}
return factory.createArtifactWithClassifier(LAUNCH4J_GROUP_ID, LAUNCH4J_ARTIFACT_ID,
getLaunch4jVersion(), "jar", "workdir-" + plat);
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
try {
new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor();
new ProcessBuilder("chmod", "755", workdir + "/bin/windres").start().waitFor();
} catch (InterruptedException e) {
getLog().warn("Interrupted while chmodding platform-specific binaries", e);
} catch (IOException e) {
getLog().warn("Unable to set platform-specific binaries to 755", e);
}
}
} | #vulnerable code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
Runtime r = Runtime.getRuntime();
try {
r.exec("chmod 755 " + workdir + "/bin/ld").waitFor();
r.exec("chmod 755 " + workdir + "/bin/windres").waitFor();
} catch (InterruptedException e) {
getLog().warn("Interrupted while chmodding platform-specific binaries", e);
} catch (IOException e) {
getLog().warn("Unable to set platform-specific binaries to 755", e);
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
try {
new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor();
new ProcessBuilder("chmod", "755", workdir + "/bin/windres").start().waitFor();
} catch (InterruptedException e) {
getLog().warn("Interrupted while chmodding platform-specific binaries", e);
} catch (IOException e) {
getLog().warn("Unable to set platform-specific binaries to 755", e);
}
}
} | #vulnerable code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
Runtime r = Runtime.getRuntime();
try {
r.exec("chmod 755 " + workdir + "/bin/ld").waitFor();
r.exec("chmod 755 " + workdir + "/bin/windres").waitFor();
} catch (InterruptedException e) {
getLog().warn("Interrupted while chmodding platform-specific binaries", e);
} catch (IOException e) {
getLog().warn("Unable to set platform-specific binaries to 755", e);
}
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static Set<Annotation> parameterAnnotations(Member member) {
Annotation[][] annotations =
member instanceof Method ? ((Method) member).getParameterAnnotations() :
member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null;
return Arrays.stream(annotations).flatMap(Arrays::stream).collect(Collectors.toSet());
} | #vulnerable code
private static Set<Annotation> parameterAnnotations(Member member) {
Set<Annotation> result = new HashSet<>();
Annotation[][] annotations =
member instanceof Method ? ((Method) member).getParameterAnnotations() :
member instanceof Constructor ? ((Constructor) member).getParameterAnnotations() : null;
for (Annotation[] annotation : annotations) Collections.addAll(result, annotation);
return result;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount);
FileInputStream fin = new FileInputStream(baseFile);
for (int i=0; i<piecesCount; i++){
byte[] piece = new byte[pieceSize];
fin.read(piece);
piecesList.add(piece);
}
fin.close();
final long torrentFileLength = baseFile.length();
Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i=0; i<numSeeders; i++){
final File baseDir = tempFiles.createTempDir();
final File seederPiecesFile = new File(baseDir, baseFile.getName());
RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw");
raf.setLength(torrentFileLength);
for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){
raf.seek(pieceIdx*pieceSize);
raf.write(piecesList.get(pieceIdx));
}
Client client = createClient();
clientList.add(client);
client.addTorrent(new SharedTorrent(torrent, baseDir, false));
client.start(InetAddress.getLocalHost());
}
} | #vulnerable code
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount);
FileInputStream fin = new FileInputStream(baseFile);
for (int i=0; i<piecesCount; i++){
byte[] piece = new byte[pieceSize];
fin.read(piece);
piecesList.add(piece);
}
fin.close();
final long torrentFileLength = baseFile.length();
Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i=0; i<numSeeders; i++){
final File baseDir = tempFiles.createTempDir();
final File seederPiecesFile = new File(baseDir, baseFile.getName());
RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw");
raf.setLength(torrentFileLength);
for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){
raf.seek(pieceIdx*pieceSize);
raf.write(piecesList.get(pieceIdx));
}
Client client = createClient();
clientList.add(client);
client.addTorrent(new SharedTorrent(torrent, baseDir, false));
client.share();
}
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
URLConnection conn = null;
try {
HTTPAnnounceRequestMessage request =
this.buildAnnounceRequest(event);
// Send announce request (HTTP GET)
URL target = request.buildAnnounceURL(this.tracker.toURL());
conn = target.openConnection();
InputStream is = new AutoCloseInputStream(conn.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(is);
// Parse and handle the response
HTTPTrackerMessage message =
HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
this.handleTrackerAnnounceResponse(message, inhibitEvents);
} catch (MalformedURLException mue) {
throw new AnnounceException("Invalid announce URL (" +
mue.getMessage() + ")", mue);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} catch (IOException ioe) {
throw new AnnounceException(ioe.getMessage(), ioe);
} finally {
if (conn != null && conn instanceof HttpURLConnection) {
InputStream err = ((HttpURLConnection) conn).getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.warn("Problem ensuring error stream closed!", ioe);
}
}
}
}
} | #vulnerable code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
try {
HTTPAnnounceRequestMessage request =
this.buildAnnounceRequest(event);
// Send announce request (HTTP GET)
URL target = request.buildAnnounceURL(this.tracker.toURL());
URLConnection conn = target.openConnection();
InputStream is = new AutoCloseInputStream(conn.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(is);
// Parse and handle the response
HTTPTrackerMessage message =
HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
this.handleTrackerAnnounceResponse(message, inhibitEvents);
} catch (MalformedURLException mue) {
throw new AnnounceException("Invalid announce URL (" +
mue.getMessage() + ")", mue);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} catch (IOException ioe) {
throw new AnnounceException(ioe.getMessage(), ioe);
}
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public long getDownloaded() {
return myTorrentStatistic.getDownloadedBytes();
} | #vulnerable code
public long getDownloaded() {
return this.downloaded;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to {}...", peer);
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to {}: {}", peer, ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from {}: {}",
this.socketRepr(socket), pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: {}", ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
} | #vulnerable code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to " + peer + "...");
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to " + peer + ": " +
ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from " + this.socketRepr(socket) +
": " + pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: " + ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
long start = System.nanoTime();
long hashTime = 0L;
MessageDigest md = MessageDigest.getInstance("SHA-1");
InputStream is = new BufferedInputStream(new FileInputStream(source));
StringBuffer pieces = new StringBuffer();
byte[] data = new byte[Torrent.PIECE_LENGTH];
int read;
while ((read = is.read(data)) > 0) {
md.reset();
md.update(data, 0, read);
long hashStart = System.nanoTime();
pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING));
hashTime += (System.nanoTime() - hashStart);
}
is.close();
int n_pieces = new Double(Math.ceil((double)source.length() /
Torrent.PIECE_LENGTH)).intValue();
logger.info("Hashed {} ({} bytes) in {} pieces (total: {}ms, " +
"{}ms hashing).",
new Object[] {
source.getName(),
source.length(),
n_pieces,
String.format("%.1f", (System.nanoTime() - start) / 1024),
String.format("%.1f", hashTime / 1024),
});
return pieces.toString();
} | #vulnerable code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
FileInputStream fis = new FileInputStream(source);
StringBuffer pieces = new StringBuffer();
byte[] data = new byte[Torrent.PIECE_LENGTH];
int read;
while ((read = fis.read(data)) > 0) {
md.reset();
md.update(data, 0, read);
pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING));
}
fis.close();
int n_pieces = new Double(Math.ceil((double)source.length() /
Torrent.PIECE_LENGTH)).intValue();
logger.debug("Hashed {} ({} bytes) in {} pieces.",
new Object[] {
source.getName(),
source.length(),
n_pieces
});
return pieces.toString();
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) {
checkHashingResultIsNotSet();
filesPaths.add(path);
dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild));
return this;
} | #vulnerable code
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) {
sources.add(new Source(dataSource, path, closeAfterBuild));
return this;
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(ClientState.ERROR);
return;
} catch (IOException ioe) {
logger.error("Could not initialize torrent file data!", ioe);
this.setState(ClientState.ERROR);
return;
}
// Initial completion test
if (this.torrent.isComplete()) {
this.seed();
} else {
this.setState(ClientState.SHARING);
}
this.announce.start();
this.service.start();
int optimisticIterations = 0;
int rateComputationIterations = 0;
while (!this.stop) {
optimisticIterations =
(optimisticIterations == 0 ?
Client.OPTIMISTIC_UNCHOKE_ITERATIONS :
optimisticIterations - 1);
rateComputationIterations =
(rateComputationIterations == 0 ?
Client.RATE_COMPUTATION_ITERATIONS :
rateComputationIterations - 1);
try {
this.unchokePeers(optimisticIterations == 0);
this.info();
if (rateComputationIterations == 0) {
this.resetPeerRates();
}
} catch (Exception e) {
logger.error("An exception occurred during the BitTorrent " +
"client main loop execution!", e);
}
try {
Thread.sleep(Client.UNCHOKING_FREQUENCY*1000);
} catch (InterruptedException ie) {
logger.trace("BitTorrent main loop interrupted.");
}
}
logger.debug("Stopping BitTorrent client connection service " +
"and announce threads...");
this.service.stop();
this.announce.stop();
// Close all peer connections
logger.debug("Closing all remaining peer connections...");
for (SharingPeer peer : this.connected.values()) {
peer.unbind(true);
}
this.torrent.close();
// Determine final state
if (this.torrent.isComplete()) {
this.setState(ClientState.DONE);
} else {
this.setState(ClientState.ERROR);
}
logger.info("BitTorrent client signing off.");
} | #vulnerable code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(ClientState.ERROR);
return;
} catch (IOException ioe) {
logger.error("Could not initialize torrent file data!", ioe);
this.setState(ClientState.ERROR);
return;
}
// Initial completion test
if (this.torrent.isComplete()) {
this.seed();
} else {
this.setState(ClientState.SHARING);
}
this.announce.start();
this.service.start();
int optimisticIterations = 0;
int rateComputationIterations = 0;
while (!this.stop) {
optimisticIterations =
(optimisticIterations == 0 ?
Client.OPTIMISTIC_UNCHOKE_ITERATIONS :
optimisticIterations - 1);
rateComputationIterations =
(rateComputationIterations == 0 ?
Client.RATE_COMPUTATION_ITERATIONS :
rateComputationIterations - 1);
try {
this.unchokePeers(optimisticIterations == 0);
this.info();
if (rateComputationIterations == 0) {
this.resetPeerRates();
}
} catch (Exception e) {
logger.error("An exception occurred during the BitTorrent " +
"client main loop execution!", e);
}
try {
Thread.sleep(Client.UNCHOKING_FREQUENCY*1000);
} catch (InterruptedException ie) {
logger.trace("BitTorrent main loop interrupted.");
}
}
logger.debug("Stopping BitTorrent client connection service " +
"and announce threads...");
this.service.stop();
this.announce.stop();
// Close all peer connections
logger.debug("Closing all remaining peer connections...");
for (SharingPeer peer : this.connected.values()) {
peer.unbind(true);
}
// Determine final state
if (this.torrent.isComplete()) {
this.setState(ClientState.DONE);
} else {
this.setState(ClientState.ERROR);
}
logger.info("BitTorrent client signing off.");
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
try {
State state = State.CONNECT_REQUEST;
int tries = 0;
while (tries <= UDP_MAX_TRIES) {
if (this.lastConnectionTime != null &&
new Date().before(this.lastConnectionTime)) {
state = State.ANNOUNCE_REQUEST;
}
tries++;
}
ByteBuffer data = null;
UDPTrackerMessage.UDPTrackerResponseMessage message =
UDPTrackerMessage.UDPTrackerResponseMessage.parse(data);
this.handleTrackerResponse(message, inhibitEvents);
} catch (MessageValidationException mve) {
logger.error("Tracker message violates expected protocol: {}!",
mve.getMessage(), mve);
}
} | #vulnerable code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
try {
ByteBuffer data = null;
UDPTrackerMessage.UDPTrackerResponseMessage message =
UDPTrackerMessage.UDPTrackerResponseMessage.parse(data);
this.handleTrackerResponse(message, inhibitEvents);
} catch (MessageValidationException mve) {
logger.error("Tracker message violates expected protocol: {}!",
mve.getMessage(), mve);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = null;
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket = new Socket("127.0.0.1", serverPort);
if (socket.isConnected()) break;
} catch (ConnectException ignored) {}
serverPort++;
}
if (socket == null || !socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
} | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = new Socket();
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket.connect(new InetSocketAddress("127.0.0.1", serverPort));
if (socket.isConnected()) break;
} catch (ConnectException ignored) {}
serverPort++;
}
if (!socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
final AtomicBoolean isInterrupted,
final long maxTimeForConnectMs,
DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException {
String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true);
final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash);
if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found");
SharedTorrent torrent = new TorrentLoaderImpl(torrentsStorage).loadTorrent(announceableTorrent);
long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
torrent.addDownloadProgressListener(listener);
final long startDownloadAt = System.currentTimeMillis();
long currentLeft = torrent.getLeft();
while (torrent.getClientState() != ClientState.SEEDING &&
torrent.getClientState() != ClientState.ERROR &&
(torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) &&
(System.currentTimeMillis() <= maxIdleTime)) {
if (Thread.currentThread().isInterrupted() || isInterrupted.get())
throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted");
if (currentLeft > torrent.getLeft()) {
currentLeft = torrent.getLeft();
maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
}
if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) {
if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) {
break;
}
}
Thread.sleep(100);
}
if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) {
removeAndDeleteTorrent(hash, torrent);
final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash);
int connectedPeersForTorrent = peersForTorrent.size();
for (SharingPeer peer : peersForTorrent) {
peer.unbind(true);
}
final String errorMsg;
if (System.currentTimeMillis() > maxIdleTime) {
int completedPieces = torrent.getCompletedPieces().cardinality();
int totalPieces = torrent.getPieceCount();
errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d"
, idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent);
} else if (connectedPeersForTorrent < minSeedersCount) {
errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent);
} else if (torrent.getClientState() == ClientState.ERROR) {
errorMsg = "Torrent state is ERROR";
} else {
errorMsg = "Unknown error";
}
throw new IOException("Unable to download torrent completely - " + errorMsg);
}
} | #vulnerable code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
final AtomicBoolean isInterrupted,
final long maxTimeForConnectMs,
DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException {
String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true);
final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash);
if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found");
final SharedTorrent torrent = SharedTorrent.fromFile(new File(dotTorrentPath),
new File(downloadDirPath),
false,
false,
true,
announceableTorrent);
torrentsStorage.putIfAbsentActiveTorrent(torrent.getHexInfoHash(), torrent);
long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
torrent.addDownloadProgressListener(listener);
final long startDownloadAt = System.currentTimeMillis();
long currentLeft = torrent.getLeft();
while (torrent.getClientState() != ClientState.SEEDING &&
torrent.getClientState() != ClientState.ERROR &&
(torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) &&
(System.currentTimeMillis() <= maxIdleTime)) {
if (Thread.currentThread().isInterrupted() || isInterrupted.get())
throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted");
if (currentLeft > torrent.getLeft()) {
currentLeft = torrent.getLeft();
maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
}
if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) {
if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) {
break;
}
}
Thread.sleep(100);
}
if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) {
removeAndDeleteTorrent(hash, torrent);
final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash);
int connectedPeersForTorrent = peersForTorrent.size();
for (SharingPeer peer : peersForTorrent) {
peer.unbind(true);
}
final String errorMsg;
if (System.currentTimeMillis() > maxIdleTime) {
int completedPieces = torrent.getCompletedPieces().cardinality();
int totalPieces = torrent.getPieceCount();
errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d"
, idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent);
} else if (connectedPeersForTorrent < minSeedersCount) {
errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent);
} else if (torrent.getClientState() == ClientState.ERROR) {
errorMsg = "Torrent state is ERROR";
} else {
errorMsg = "Unknown error";
}
throw new IOException("Unable to download torrent completely - " + errorMsg);
}
}
#location 60
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = null;
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket = new Socket("127.0.0.1", serverPort);
if (socket.isConnected()) break;
} catch (ConnectException ignored) {}
serverPort++;
}
if (socket == null || !socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
} | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = new Socket();
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket.connect(new InetSocketAddress("127.0.0.1", serverPort));
if (socket.isConnected()) break;
} catch (ConnectException ignored) {}
serverPort++;
}
if (!socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
#location 103
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public long getUploaded() {
return myTorrentStatistic.getUploadedBytes();
} | #vulnerable code
public long getUploaded() {
return this.uploaded;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
// Parse and handle the response
return HTTPTrackerMessage.parse(in);
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
} | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while ((len=in.read(buf)) > 0){
baos.write(buf, 0, len);
}
// Parse and handle the response
return HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher,
TorrentStatisticProvider torrentStatisticProvider)
throws IOException, NoSuchAlgorithmException {
byte[] data = FileUtils.readFileToByteArray(source);
return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider);
} | #vulnerable code
public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher,
TorrentStatisticProvider torrentStatisticProvider)
throws IOException, NoSuchAlgorithmException {
FileInputStream fis = new FileInputStream(source);
byte[] data = new byte[(int) source.length()];
fis.read(data);
fis.close();
return new SharedTorrent(data, parent, multiThreadHash, seeder, leecher, DEFAULT_REQUEST_STRATEGY, torrentStatisticProvider);
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to {}...", peer);
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to {}: {}", peer, ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from {}: {}",
this.socketRepr(socket), pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: {}", ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
} | #vulnerable code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to " + peer + "...");
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to " + peer + ": " +
ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from " + this.socketRepr(socket) +
": " + pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: " + ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Torrent load(File torrent, File parent, boolean seeder)
throws IOException, NoSuchAlgorithmException {
FileInputStream fis = null;
try {
fis = new FileInputStream(torrent);
byte[] data = new byte[(int)torrent.length()];
fis.read(data);
return new Torrent(data, parent, seeder);
} finally {
if (fis != null) {
fis.close();
}
}
} | #vulnerable code
public static Torrent load(File torrent, File parent, boolean seeder)
throws IOException {
FileInputStream fis = new FileInputStream(torrent);
byte[] data = new byte[(int)torrent.length()];
fis.read(data);
fis.close();
return new Torrent(data, parent, seeder);
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
} finally {
myLock.writeLock().unlock();
}
} | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
myConnectionManager.initAndRunWorker();
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = myConnectionManager.getBindAddress().getPort();
Socket socket = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
this.myConnectionManager.close(true);
} | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = null;
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket = new Socket("127.0.0.1", serverPort);
if (socket.isConnected()) break;
} catch (ConnectException ignored) {}
serverPort++;
}
if (socket == null || !socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
#location 44
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)openConnectionCheckRedirects(url);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
// Parse and handle the response
return HTTPTrackerMessage.parse(in);
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
} | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
// Parse and handle the response
return HTTPTrackerMessage.parse(in);
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
}
#location 41
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break;
case CHOKE:
this.choked = true;
this.firePeerChoked();
this.cancelPendingRequests();
break;
case UNCHOKE:
this.choked = false;
logger.trace("Peer {} is now accepting requests.", this);
this.firePeerReady();
break;
case INTERESTED:
this.interested = true;
break;
case NOT_INTERESTED:
this.interested = false;
break;
case HAVE:
// Record this peer has the given piece
PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg;
Piece havePiece = this.torrent.getPiece(have.getPieceIndex());
synchronized (this.availablePiecesLock) {
this.availablePieces.set(havePiece.getIndex());
logger.trace("Peer {} now has {} [{}/{}].",
new Object[]{
this,
havePiece,
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.firePieceAvailabity(havePiece);
break;
case BITFIELD:
// Augment the hasPiece bit field from this BITFIELD message
PeerMessage.BitfieldMessage bitfield =
(PeerMessage.BitfieldMessage) msg;
synchronized (this.availablePiecesLock) {
this.availablePieces.or(bitfield.getBitfield());
logger.trace("Recorded bitfield from {} with {} " +
"pieces(s) [{}/{}].",
new Object[]{
this,
bitfield.getBitfield().cardinality(),
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.fireBitfieldAvailabity();
break;
case REQUEST:
PeerMessage.RequestMessage request =
(PeerMessage.RequestMessage) msg;
logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
request.getPiece(),
request.getLength(),
request.getOffset(),
this
});
Piece rp = this.torrent.getPiece(request.getPiece());
// If we are choking from this peer and it still sends us
// requests, it is a violation of the BitTorrent protocol.
// Similarly, if the peer requests a piece we don't have, it
// is a violation of the BitTorrent protocol. In these
// situation, terminate the connection.
if (this.isChoking() || !rp.isValid()) {
logger.warn("Peer {} violated protocol, terminating exchange.", this);
this.unbind(true);
break;
}
if (request.getLength() >
PeerMessage.RequestMessage.MAX_REQUEST_SIZE) {
logger.warn("Peer {} requested a block too big, " +
"terminating exchange.", this);
this.unbind(true);
break;
}
// At this point we agree to send the requested piece block to
// the remote peer, so let's queue a message with that block
try {
ByteBuffer block = rp.read(request.getOffset(),
request.getLength());
this.send(PeerMessage.PieceMessage.craft(request.getPiece(),
request.getOffset(), block));
this.upload.add(block.capacity());
if (request.getOffset() + request.getLength() == rp.size()) {
this.firePieceSent(rp);
}
} catch (IOException ioe) {
logger.error("error", ioe);
this.fireIOException(new IOException(
"Error while sending piece block request!", ioe));
}
break;
case PIECE:
// Record the incoming piece block.
// Should we keep track of the requested pieces and act when we
// get a piece we didn't ask for, or should we just stay
// greedy?
PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg;
Piece p = this.torrent.getPiece(piece.getPiece());
logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
p.getIndex(),
p.size(),
piece.getOffset(),
this
});
// Remove the corresponding request from the request queue to
// make room for next block requests.
this.removeBlockRequest(piece.getPiece(), piece.getOffset());
this.download.add(piece.getBlock().capacity());
try {
synchronized (p) {
if (p.isValid()) {
this.cancelPendingRequests(p);
this.firePeerReady();
logger.debug("Discarding block for already completed " + p);
break;
}
//TODO add proper catch for IOException
p.record(piece.getBlock(), piece.getOffset());
// If the block offset equals the piece size and the block
// length is 0, it means the piece has been entirely
// downloaded. In this case, we have nothing to save, but
// we should validate the piece.
if (getRemainingRequestedPieces(p).size() == 0) {
p.finish();
p.validate(torrent, p);
this.firePieceCompleted(p);
myRequestedPieces.remove(p);
this.firePeerReady();
} else {
if (piece.getOffset() + piece.getBlock().capacity()
== p.size()) { // final request reached
for (PeerMessage.RequestMessage requestMessage : getRemainingRequestedPieces(p)) {
send(requestMessage);
}
} else {
this.requestNextBlocksForPiece(p);
}
}
}
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
this.fireIOException(new IOException(
"Error while storing received piece block!", ioe));
break;
}
break;
case CANCEL:
// No need to support
break;
}
} | #vulnerable code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break;
case CHOKE:
this.choked = true;
this.firePeerChoked();
this.cancelPendingRequests();
break;
case UNCHOKE:
this.choked = false;
logger.trace("Peer {} is now accepting requests.", this);
this.firePeerReady();
break;
case INTERESTED:
this.interested = true;
break;
case NOT_INTERESTED:
this.interested = false;
break;
case HAVE:
// Record this peer has the given piece
PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg;
Piece havePiece = this.torrent.getPiece(have.getPieceIndex());
synchronized (this.availablePiecesLock) {
this.availablePieces.set(havePiece.getIndex());
logger.trace("Peer {} now has {} [{}/{}].",
new Object[]{
this,
havePiece,
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.firePieceAvailabity(havePiece);
break;
case BITFIELD:
// Augment the hasPiece bit field from this BITFIELD message
PeerMessage.BitfieldMessage bitfield =
(PeerMessage.BitfieldMessage) msg;
synchronized (this.availablePiecesLock) {
this.availablePieces.or(bitfield.getBitfield());
logger.trace("Recorded bitfield from {} with {} " +
"pieces(s) [{}/{}].",
new Object[]{
this,
bitfield.getBitfield().cardinality(),
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.fireBitfieldAvailabity();
break;
case REQUEST:
PeerMessage.RequestMessage request =
(PeerMessage.RequestMessage) msg;
logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
request.getPiece(),
request.getLength(),
request.getOffset(),
this
});
Piece rp = this.torrent.getPiece(request.getPiece());
// If we are choking from this peer and it still sends us
// requests, it is a violation of the BitTorrent protocol.
// Similarly, if the peer requests a piece we don't have, it
// is a violation of the BitTorrent protocol. In these
// situation, terminate the connection.
if (this.isChoking() || !rp.isValid()) {
logger.warn("Peer {} violated protocol, terminating exchange.", this);
this.unbind(true);
break;
}
if (request.getLength() >
PeerMessage.RequestMessage.MAX_REQUEST_SIZE) {
logger.warn("Peer {} requested a block too big, " +
"terminating exchange.", this);
this.unbind(true);
break;
}
// At this point we agree to send the requested piece block to
// the remote peer, so let's queue a message with that block
try {
ByteBuffer block = rp.read(request.getOffset(),
request.getLength());
this.send(PeerMessage.PieceMessage.craft(request.getPiece(),
request.getOffset(), block));
this.upload.add(block.capacity());
if (request.getOffset() + request.getLength() == rp.size()) {
this.firePieceSent(rp);
}
} catch (IOException ioe) {
logger.error("error", ioe);
this.fireIOException(new IOException(
"Error while sending piece block request!", ioe));
}
break;
case PIECE:
// Record the incoming piece block.
// Should we keep track of the requested pieces and act when we
// get a piece we didn't ask for, or should we just stay
// greedy?
PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg;
Piece p = this.torrent.getPiece(piece.getPiece());
logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
p.getIndex(),
p.size(),
piece.getOffset(),
this
});
// Remove the corresponding request from the request queue to
// make room for next block requests.
this.removeBlockRequest(piece);
this.download.add(piece.getBlock().capacity());
try {
synchronized (p) {
if (p.isValid()) {
this.requestedPiece = null;
this.cancelPendingRequests();
this.firePeerReady();
logger.debug("Discarding block for already completed " + p);
break;
}
//TODO add proper catch for IOException
p.record(piece.getBlock(), piece.getOffset());
// If the block offset equals the piece size and the block
// length is 0, it means the piece has been entirely
// downloaded. In this case, we have nothing to save, but
// we should validate the piece.
if (requests==null || requests.size() == 0) {
p.finish();
p.validate(torrent, p);
this.firePieceCompleted(p);
this.requestedPiece = null;
this.firePeerReady();
} else {
if (piece.getOffset() + piece.getBlock().capacity()
== p.size()) { // final request reached
for (PeerMessage.RequestMessage requestMessage : requests) {
send(requestMessage);
}
} else {
this.requestNextBlocks();
}
}
}
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
this.fireIOException(new IOException(
"Error while storing received piece block!", ioe));
break;
}
break;
case CANCEL:
// No need to support
break;
}
}
#location 163
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
if (this.seeder) {
logger.trace("Skipping validation of {} (seeder mode).", this);
this.valid = true;
return true;
}
logger.trace("Validating {}...", this);
this.valid = false;
try {
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
ByteBuffer buffer = this._read(0, this.length);
byte[] data = new byte[(int)this.length];
buffer.get(data);
final byte[] calculatedHash = Torrent.hash(data);
this.valid = Arrays.equals(calculatedHash, this.hash);
} catch (NoSuchAlgorithmException nsae) {
logger.error("{}", nsae);
}
return this.isValid();
} | #vulnerable code
public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
if (this.seeder) {
logger.trace("Skipping validation of {} (seeder mode).", this);
this.valid = true;
return true;
}
logger.trace("Validating {}...", this);
this.valid = false;
try {
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
ByteBuffer buffer = this._read(0, this.length);
byte[] data = new byte[(int)this.length];
buffer.get(data);
final byte[] calculatedHash = Torrent.hash(data);
this.valid = Arrays.equals(calculatedHash, this.hash);
if (torrent != null && piece != null){
final File file;
if (torrent.getParentFile().isDirectory()) {
file = new File(torrent.getParentFile(), String.format("%d.txt", piece.getIndex()));
} else {
file = new File(torrent.getParentFile().getCanonicalFile().getParentFile(), String.format("%s.%d.txt", torrent.getName(), piece.getIndex()));
}
if (!valid) {
logger.debug("Piece {} invalid. Expected hash {} when actual is {}", new Object[]{
piece.getIndex(), HexBin.encode(hash), HexBin.encode(calculatedHash)});
//saving data:
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(data);
fOut.close();
} else {
if (file.exists()){
File correctFile;
if (torrent.getParentFile().isDirectory()) {
correctFile = new File(torrent.getParentFile(), String.format("%d.correct.txt", piece.getIndex()));
} else {
correctFile = new File(torrent.getParentFile().getCanonicalFile().getParentFile(), String.format("%s.%d.correct.txt", torrent.getName(), piece.getIndex()));
}
FileOutputStream fOut = new FileOutputStream(correctFile);
fOut.write(data);
fOut.close();
}
}
}
} catch (NoSuchAlgorithmException nsae) {
logger.error("{}", nsae);
}
/*
if (valid){
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
*/
logger.trace("Validation of {} {}", this, this.isValid() ? "succeeded" : "failed");
return this.isValid();
}
#location 48
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start(final InetAddress... bindAddresses) throws IOException {
start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null, new SelectorFactoryImpl());
} | #vulnerable code
public void start(final InetAddress... bindAddresses) throws IOException {
start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
} | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
#location 71
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
} finally {
myLock.writeLock().unlock();
}
} | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BitSet getCompletedPieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
} | #vulnerable code
public BitSet getCompletedPieces() {
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void run() {
try {
init();
Peer self = peersStorageFactory.getPeersStorage().getSelf();
logger.info("BitTorrent client [{}] started and " +
"listening at {}:{}...",
new Object[]{
self.getShortHexPeerId(),
self.getIp(),
self.getPort()
});
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "error in initialization server channel", e);
return;
}
while (!Thread.interrupted()) {
int selected = -1;
try {
selected = selector.select();// TODO: 11/13/17 timeout
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "unable to select channel keys", e);
}
logger.trace("select keys from selector. Keys count is " + selected);
if (selected < 0) {
logger.info("selected count less that zero");
}
if (selected == 0) {
continue;
}
processSelectedKeys();
}
try {
close();
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "unable to close connection receiver", e);
}
} | #vulnerable code
@Override
public void run() {
try {
init();
Peer self = client.peersStorage.getSelf();
logger.info("BitTorrent client [{}] started and " +
"listening at {}:{}...",
new Object[]{
self.getShortHexPeerId(),
self.getIp(),
self.getPort()
});
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "error in initialization server channel", e);
return;
}
while (!Thread.interrupted()) {
int selected = -1;
try {
selected = selector.select();// TODO: 11/13/17 timeout
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "unable to select channel keys", e);
}
logger.trace("select keys from selector. Keys count is " + selected);
if (selected < 0) {
logger.info("selected count less that zero");
}
if (selected == 0) {
continue;
}
processSelectedKeys();
}
try {
close();
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "unable to close connection receiver", e);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
piece.finish();
// Send a HAVE message to all connected peers, which don't have the piece
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash) &&
!remote.getAvailablePieces().get(piece.getIndex()))
remote.send(have);
}
final boolean isTorrentComplete;
synchronized (torrent) {
torrent.removeValidationFuture(piece);
torrent.notifyPieceDownloaded(piece, peer);
boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount();
//if it's seeder we will send not interested message when we download full file
if (!isCurrentPeerSeeder) {
if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) {
peer.notInteresting();
}
}
isTorrentComplete = torrent.isComplete();
if (isTorrentComplete) {
logger.debug("Download of {} complete.", torrent.getDirectoryName());
torrent.finish();
}
}
if (isTorrentComplete) {
LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash);
if (announceableTorrent == null) return;
AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation();
try {
announce.getCurrentTrackerClient(announceableInformation)
.announceAllInterfaces(COMPLETED, true, announceableInformation);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
for (SharingPeer remote : getPeersForTorrent(torrentHash)) {
remote.notInteresting();
}
}
} else {
torrent.markUncompleted(piece);
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
}
} catch (Throwable e) {
torrent.markUncompleted(piece);
logger.warn("unhandled exception in piece {} validation task", e);
}
torrent.handlePeerReady(peer);
} | #vulnerable code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
piece.finish();
// Send a HAVE message to all connected peers, which don't have the piece
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash) &&
!remote.getAvailablePieces().get(piece.getIndex()))
remote.send(have);
}
final boolean isTorrentComplete;
synchronized (torrent) {
torrent.removeValidationFuture(piece);
torrent.notifyPieceDownloaded(piece, peer);
boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount();
//if it's seeder we will send not interested message when we download full file
if (!isCurrentPeerSeeder) {
if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) {
peer.notInteresting();
}
}
isTorrentComplete = torrent.isComplete();
if (isTorrentComplete) {
logger.debug("Download of {} complete.", torrent.getDirectoryName());
torrent.finish();
}
}
if (isTorrentComplete) {
LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash);
if (announceableTorrent == null) return;
AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation();
try {
announce.getCurrentTrackerClient(announceableInformation)
.announceAllInterfaces(COMPLETED, true, announceableInformation);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
for (SharingPeer remote : getPeersForTorrent(torrentHash)) {
remote.notInteresting();
}
}
} else {
torrent.markUncompleted(piece);
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
}
} catch (Throwable e) {
torrent.markUncompleted(piece);
logger.warn("unhandled exception in piece {} validation task", e);
}
}
#location 51
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
URL target = null;
try {
HTTPAnnounceRequestMessage request =
this.buildAnnounceRequest(event, torrentInfo);
target = request.buildAnnounceURL(this.tracker.toURL());
} catch (MalformedURLException mue) {
throw new AnnounceException("Invalid announce URL (" +
mue.getMessage() + ")", mue);
} catch (MessageValidationException mve) {
throw new AnnounceException("Announce request creation violated " +
"expected protocol (" + mve.getMessage() + ")", mve);
} catch (IOException ioe) {
throw new AnnounceException("Error building announce request (" +
ioe.getMessage() + ")", ioe);
}
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)target.openConnection();
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while ((len=in.read(buf)) > 0){
baos.write(buf, 0, len);
}
// Parse and handle the response
HTTPTrackerMessage message =
HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash());
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.warn("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.warn("Problem ensuring error stream closed!", ioe);
}
}
}
} | #vulnerable code
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
URL target = null;
try {
HTTPAnnounceRequestMessage request =
this.buildAnnounceRequest(event, torrentInfo);
target = request.buildAnnounceURL(this.tracker.toURL());
} catch (MalformedURLException mue) {
throw new AnnounceException("Invalid announce URL (" +
mue.getMessage() + ")", mue);
} catch (MessageValidationException mve) {
throw new AnnounceException("Announce request creation violated " +
"expected protocol (" + mve.getMessage() + ")", mve);
} catch (IOException ioe) {
throw new AnnounceException("Error building announce request (" +
ioe.getMessage() + ")", ioe);
}
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)target.openConnection();
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(in);
// Parse and handle the response
HTTPTrackerMessage message =
HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash());
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.warn("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.warn("Problem ensuring error stream closed!", ioe);
}
}
}
}
#location 61
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
} | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
#location 46
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MetadataBuilder addFile(@NotNull File source) {
return addFile(source, source.getName());
} | #vulnerable code
public MetadataBuilder addFile(@NotNull File source) {
sources.add(new Source(source));
return this;
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
} finally {
myLock.writeLock().unlock();
}
} | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = new Socket();
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket.connect(new InetSocketAddress("127.0.0.1", serverPort));
} catch (ConnectException ignored) {}
serverPort++;
}
if (!socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
} | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
Socket socket = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
}
#location 66
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash;
synchronized (torrent) {
torrentHash = torrent.getHexInfoHash();
if (piece.isValid()) {
// Make sure the piece is marked as completed in the torrent
// Note: this is required because the order the
// PeerActivityListeners are called is not defined, and we
// might be called before the torrent's piece completion
// handler is.
torrent.markCompleted(piece);
logger.debug("Completed download of {} from {}, now has {}/{} pieces.",
new Object[]{
piece,
peer,
torrent.getCompletedPieces().cardinality(),
torrent.getPieceCount()
});
BitSet completed = new BitSet();
completed.or(torrent.getCompletedPieces());
completed.and(peer.getAvailablePieces());
if (completed.equals(peer.getAvailablePieces())) {
// send not interested when have no interested pieces;
peer.send(PeerMessage.NotInterestedMessage.craft());
}
} else {
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
if (torrent.isComplete()) {
//close connection with all peers for this torrent
logger.info("Download of {} complete.", torrent.getName());
torrent.finish();
try {
this.announce.getCurrentTrackerClient(torrent)
.announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
}
}
// Send a HAVE message to all connected peers
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash))
remote.send(have);
}
} | #vulnerable code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
synchronized (torrent) {
if (piece.isValid()) {
// Make sure the piece is marked as completed in the torrent
// Note: this is required because the order the
// PeerActivityListeners are called is not defined, and we
// might be called before the torrent's piece completion
// handler is.
torrent.markCompleted(piece);
logger.debug("Completed download of {} from {}, now has {}/{} pieces.",
new Object[]{
piece,
peer,
torrent.getCompletedPieces().cardinality(),
torrent.getPieceCount()
});
// Send a HAVE message to all connected peers
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
final String torrentHash = torrent.getHexInfoHash();
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash))
remote.send(have);
}
BitSet completed = new BitSet();
completed.or(torrent.getCompletedPieces());
completed.and(peer.getAvailablePieces());
if (completed.equals(peer.getAvailablePieces())) {
// send not interested when have no interested pieces;
peer.send(PeerMessage.NotInterestedMessage.craft());
}
} else {
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
if (torrent.isComplete()) {
//close connection with all peers for this torrent
logger.info("Download of {} complete.", torrent.getName());
torrent.finish();
try {
this.announce.getCurrentTrackerClient(torrent)
.announceAllInterfaces(TrackerMessage.AnnounceRequestMessage.RequestEvent.COMPLETED, true, torrent);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
}
}
}
#location 50
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash = torrent.getHexInfoHash();
if (piece.isValid()) {
// Send a HAVE message to all connected peers
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash))
remote.send(have);
}
}
synchronized (torrent) {
if (piece.isValid()) {
// Make sure the piece is marked as completed in the torrent
// Note: this is required because the order the
// PeerActivityListeners are called is not defined, and we
// might be called before the torrent's piece completion
// handler is.
torrent.markCompleted(piece);
logger.debug("Completed download of {} from {}, now has {}/{} pieces.",
new Object[]{
piece,
peer,
torrent.getCompletedPieces().cardinality(),
torrent.getPieceCount()
});
BitSet completed = new BitSet();
completed.or(torrent.getCompletedPieces());
completed.and(peer.getAvailablePieces());
if (completed.equals(peer.getAvailablePieces())) {
// send not interested when have no interested pieces;
peer.send(PeerMessage.NotInterestedMessage.craft());
}
} else {
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
if (torrent.isComplete()) {
//close connection with all peers for this torrent
logger.debug("Download of {} complete.", torrent.getDirectoryName());
torrent.finish();
AnnounceableTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(torrentHash);
if (announceableTorrent == null) return;
try {
this.announce.getCurrentTrackerClient(announceableTorrent)
.announceAllInterfaces(COMPLETED, true, announceableTorrent);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
}
}
} | #vulnerable code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash = torrent.getHexInfoHash();
if (piece.isValid()) {
// Send a HAVE message to all connected peers
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash))
remote.send(have);
}
}
synchronized (torrent) {
if (piece.isValid()) {
// Make sure the piece is marked as completed in the torrent
// Note: this is required because the order the
// PeerActivityListeners are called is not defined, and we
// might be called before the torrent's piece completion
// handler is.
torrent.markCompleted(piece);
logger.debug("Completed download of {} from {}, now has {}/{} pieces.",
new Object[]{
piece,
peer,
torrent.getCompletedPieces().cardinality(),
torrent.getPieceCount()
});
BitSet completed = new BitSet();
completed.or(torrent.getCompletedPieces());
completed.and(peer.getAvailablePieces());
if (completed.equals(peer.getAvailablePieces())) {
// send not interested when have no interested pieces;
peer.send(PeerMessage.NotInterestedMessage.craft());
}
} else {
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
if (torrent.isComplete()) {
//close connection with all peers for this torrent
logger.debug("Download of {} complete.", torrent.getName());
torrent.finish();
try {
this.announce.getCurrentTrackerClient(torrent)
.announceAllInterfaces(COMPLETED, true, torrent);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
}
}
}
#location 51
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException {
if (!torrentContainsManyFiles) {
final BEValue md5Sum = infoTable.get(MD5_SUM);
return Collections.singletonList(new TorrentFile(
Collections.singletonList(name),
getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(),
md5Sum == null ? null : md5Sum.getString()
));
}
List<TorrentFile> result = new ArrayList<TorrentFile>();
for (BEValue file : infoTable.get(FILES).getList()) {
Map<String, BEValue> fileInfo = file.getMap();
List<String> path = new ArrayList<String>();
BEValue filePathList = fileInfo.get(FILE_PATH_UTF8);
if (filePathList == null) {
filePathList = fileInfo.get(FILE_PATH);
}
for (BEValue pathElement : filePathList.getList()) {
path.add(pathElement.getString());
}
final BEValue md5Sum = infoTable.get(MD5_SUM);
result.add(new TorrentFile(
path,
fileInfo.get(FILE_LENGTH).getLong(),
md5Sum == null ? null : md5Sum.getString()));
}
return result;
} | #vulnerable code
private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException {
if (!torrentContainsManyFiles) {
final BEValue md5Sum = infoTable.get(MD5_SUM);
return Collections.singletonList(new TorrentFile(
Collections.singletonList(name),
getRequiredValueOrThrowException(infoTable, FILE_LENGTH).getLong(),
md5Sum == null ? null : md5Sum.getString()
));
}
List<TorrentFile> result = new ArrayList<TorrentFile>();
for (BEValue file : infoTable.get(FILES).getList()) {
Map<String, BEValue> fileInfo = file.getMap();
List<String> path = new ArrayList<String>();
for (BEValue pathElement : fileInfo.get(FILE_PATH).getList()) {
path.add(pathElement.getString());
}
final BEValue md5Sum = infoTable.get(MD5_SUM);
result.add(new TorrentFile(
path,
fileInfo.get(FILE_LENGTH).getLong(),
md5Sum == null ? null : md5Sum.getString()));
}
return result;
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
} finally {
myLock.writeLock().unlock();
}
} | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void save(File output) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(output);
fos.write(this.getEncoded());
logger.info("Wrote torrent file {}.", output.getAbsolutePath());
} finally {
if (fos != null) {
fos.close();
}
}
} | #vulnerable code
public void save(File output) throws IOException {
FileOutputStream fos = new FileOutputStream(output);
fos.write(this.getEncoded());
fos.close();
logger.info("Wrote torrent file {}.", output.getAbsolutePath());
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
} | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders + 7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
final Client firstClient = clientsList.get(0);
new WaitFor(10 * 1000) {
@Override
protected boolean condition() {
return firstClient.getTorrentsStorage().activeTorrents().size() >= 1;
}
};
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) {
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()) {
fail("All seeders didn't get their files");
}
Thread.sleep(10 * 1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
#location 46
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void cleanUp() {
// temporary ignore until I figure out how to handle this in more robust way.
/*
for (PeerMessage.RequestMessage request : myRequests) {
if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){
send(request);
request.renew();
}
}
*/
} | #vulnerable code
@Override
public void cleanUp() {
for (PeerMessage.RequestMessage request : myRequests) {
if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){
send(request);
request.renew();
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
// Parse and handle the response
return HTTPTrackerMessage.parse(in);
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
} | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
in = conn.getInputStream();
} catch (IOException ioe) {
if (conn != null) {
in = conn.getErrorStream();
}
}
// At this point if the input stream is null it means we have neither a
// response body nor an error stream from the server. No point in going
// any further.
if (in == null) {
throw new AnnounceException("No response or unreachable tracker!");
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len;
while ((len=in.read(buf)) > 0){
baos.write(buf, 0, len);
}
// Parse and handle the response
return HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
} catch (IOException ioe) {
throw new AnnounceException("Error reading tracker response!", ioe);
} catch (MessageValidationException mve) {
throw new AnnounceException("Tracker message violates expected " +
"protocol (" + mve.getMessage() + ")", mve);
} finally {
// Make sure we close everything down at the end to avoid resource
// leaks.
try {
in.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
// This means trying to close the error stream as well.
InputStream err = conn.getErrorStream();
if (err != null) {
try {
err.close();
} catch (IOException ioe) {
logger.info("Problem ensuring error stream closed!");
logger.debug("Problem ensuring error stream closed!", ioe);
}
}
}
}
#location 32
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BitSet getAvailablePieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availablePieces;
} | #vulnerable code
public BitSet getAvailablePieces() {
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availablePieces;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
} finally {
myLock.writeLock().unlock();
}
} | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else if (!this.target.exists()) {
logger.debug("Downloading new file to {}...",
this.partial.getAbsolutePath());
this.current = this.partial;
} else {
logger.debug("Using existing file {}.",
this.target.getAbsolutePath());
this.current = this.target;
}
this.raf = new RandomAccessFile(this.current, "rw");
// Set the file length to the appropriate size, eventually truncating
// or extending the file if it already exists with a different size.
this.raf.setLength(this.size);
this.channel = raf.getChannel();
logger.debug("Opened byte storage file at {} " +
"({}+{} byte(s)).",
new Object[] {
this.current.getAbsolutePath(),
this.offset,
this.size,
});
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, InterruptedException, IOException {
ExecutorService executor = Executors.newFixedThreadPool(
getHashingThreadsCount());
List<Future<String>> results = new LinkedList<Future<String>>();
byte[] data = new byte[Torrent.PIECE_LENGTH];
int pieces = 0;
int read;
logger.info("Analyzing local data for {} with {} threads...",
source.getName(), getHashingThreadsCount());
long start = System.nanoTime();
InputStream is = new BufferedInputStream(new FileInputStream(source));
while ((read = is.read(data)) > 0) {
results.add(executor.submit(new CallableChunkHasher(data, read)));
pieces++;
}
is.close();
// Request orderly executor shutdown and wait for hashing tasks to
// complete.
executor.shutdown();
while (!executor.isTerminated()) {
Thread.sleep(10);
}
long elapsed = System.nanoTime() - start;
StringBuffer hashes = new StringBuffer();
try {
for (Future<String> chunk : results) {
hashes.append(chunk.get());
}
} catch (ExecutionException ee) {
throw new IOException("Error while hashing the torrent data!", ee);
}
int expectedPieces = new Double(Math.ceil((double)source.length() /
Torrent.PIECE_LENGTH)).intValue();
logger.info("Hashed {} ({} bytes) in {} pieces ({} expected) in {}ms.",
new Object[] {
source.getName(),
source.length(),
pieces,
expectedPieces,
String.format("%.1f", elapsed/1024.0/1024.0),
});
return hashes.toString();
} | #vulnerable code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
long start = System.nanoTime();
long hashTime = 0L;
MessageDigest md = MessageDigest.getInstance("SHA-1");
InputStream is = new BufferedInputStream(new FileInputStream(source));
StringBuffer pieces = new StringBuffer();
byte[] data = new byte[Torrent.PIECE_LENGTH];
int read;
while ((read = is.read(data)) > 0) {
md.reset();
md.update(data, 0, read);
long hashStart = System.nanoTime();
pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING));
hashTime += (System.nanoTime() - hashStart);
}
is.close();
int n_pieces = new Double(Math.ceil((double)source.length() /
Torrent.PIECE_LENGTH)).intValue();
logger.info("Hashed {} ({} bytes) in {} pieces (total: {}ms, " +
"{}ms hashing).",
new Object[] {
source.getName(),
source.length(),
n_pieces,
String.format("%.1f", (System.nanoTime() - start) / 1024),
String.format("%.1f", hashTime / 1024),
});
return pieces.toString();
}
#location 34
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException {
Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent"));
assertEquals("http://localhost:6969/announce", t.getAnnounceList().get(0).get(0));
assertEquals("B92D38046C76D73948E14C42DF992CAF25489D08", t.getHexInfoHash());
assertEquals("uTorrent/3130", t.getCreatedBy());
} | #vulnerable code
public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException {
Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent"));
assertEquals(new URI("http://localhost:6969/announce"), t.getAnnounceList().get(0).get(0));
assertEquals("B92D38046C76D73948E14C42DF992CAF25489D08", t.getHexInfoHash());
assertEquals("uTorrent/3130", t.getCreatedBy());
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
saveTorrent(torrent, torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent());
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null, new SelectorFactoryImpl());
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")) {
count++;
partItems.add(s);
}
}
if (count < 5) {
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
} | #vulnerable code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
saveTorrent(torrent, torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent());
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null);
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")) {
count++;
partItems.add(s);
}
}
if (count < 5) {
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
}
#location 35
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void process(final String uri, final String hostAddress, RequestHandler requestHandler)
throws IOException {
// Prepare the response headers.
/**
* Parse the query parameters into an announce request message.
*
* We need to rely on our own query parsing function because
* SimpleHTTP's Query map will contain UTF-8 decoded parameters, which
* doesn't work well for the byte-encoded strings we expect.
*/
HTTPAnnounceRequestMessage announceRequest = null;
try {
announceRequest = this.parseQuery(uri, hostAddress);
} catch (MessageValidationException mve) {
LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve);
serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler);
return;
}
AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent();
if (event == null) {
event = AnnounceRequestMessage.RequestEvent.NONE;
}
TrackedTorrent torrent = myTorrentsRepository.getTorrent(announceRequest.getHexInfoHash());
// The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false
if (!this.myAcceptForeignTorrents && torrent == null) {
logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash());
serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler);
return;
}
final boolean isSeeder = (event == AnnounceRequestMessage.RequestEvent.COMPLETED)
|| (announceRequest.getLeft() == 0);
if (myAddressChecker.isBadAddress(announceRequest.getIp())) {
if (torrent == null) {
writeEmptyResponse(announceRequest, requestHandler);
} else {
writeAnnounceResponse(torrent, null, isSeeder, requestHandler);
}
return;
}
final Peer peer = new Peer(announceRequest.getIp(), announceRequest.getPort());
try {
torrent = myTorrentsRepository.putIfAbsentAndUpdate(announceRequest.getHexInfoHash(), new TrackedTorrent(announceRequest.getInfoHash()),event,
ByteBuffer.wrap(announceRequest.getPeerId()),
announceRequest.getHexPeerId(),
announceRequest.getIp(),
announceRequest.getPort(),
announceRequest.getUploaded(),
announceRequest.getDownloaded(),
announceRequest.getLeft());
} catch (IllegalArgumentException iae) {
LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae);
serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler);
return;
}
// Craft and output the answer
writeAnnounceResponse(torrent, peer, isSeeder, requestHandler);
} | #vulnerable code
public void process(final String uri, final String hostAddress, RequestHandler requestHandler)
throws IOException {
// Prepare the response headers.
/**
* Parse the query parameters into an announce request message.
*
* We need to rely on our own query parsing function because
* SimpleHTTP's Query map will contain UTF-8 decoded parameters, which
* doesn't work well for the byte-encoded strings we expect.
*/
HTTPAnnounceRequestMessage announceRequest = null;
try {
announceRequest = this.parseQuery(uri, hostAddress);
} catch (MessageValidationException mve) {
LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve);
serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler);
return;
}
// The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false
final ConcurrentMap<String, TrackedTorrent> torrentsMap = requestHandler.getTorrentsMap();
TrackedTorrent torrent = torrentsMap.get(announceRequest.getHexInfoHash());
if (!this.myAcceptForeignTorrents && torrent == null) {
logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash());
serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler);
return;
}
if (torrent == null) {
torrent = new TrackedTorrent(announceRequest.getInfoHash());
TrackedTorrent oldTorrent = requestHandler.getTorrentsMap().putIfAbsent(torrent.getHexInfoHash(), torrent);
if (oldTorrent != null) {
torrent = oldTorrent;
}
}
AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent();
PeerUID peerUID = new PeerUID(new InetSocketAddress(announceRequest.getIp(), announceRequest.getPort()), announceRequest.getHexInfoHash());
// When no event is specified, it's a periodic update while the client
// is operating. If we don't have a peer for this announce, it means
// the tracker restarted while the client was running. Consider this
// announce request as a 'started' event.
if ((event == null ||
AnnounceRequestMessage.RequestEvent.NONE.equals(event)) &&
torrent.getPeer(peerUID) == null) {
event = AnnounceRequestMessage.RequestEvent.STARTED;
}
if (myAddressChecker.isBadAddress(announceRequest.getIp())) {
writeAnnounceResponse(torrent, null, requestHandler);
return;
}
if (event != null && torrent.getPeer(peerUID) == null &&
AnnounceRequestMessage.RequestEvent.STOPPED.equals(event)) {
writeAnnounceResponse(torrent, null, requestHandler);
return;
}
// If an event other than 'started' is specified and we also haven't
// seen the peer on this torrent before, something went wrong. A
// previous 'started' announce request should have been made by the
// client that would have had us register that peer on the torrent this
// request refers to.
if (event != null && torrent.getPeer(peerUID) == null &&
!(AnnounceRequestMessage.RequestEvent.STARTED.equals(event) ||
AnnounceRequestMessage.RequestEvent.COMPLETED.equals(event))) {
serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler);
return;
}
// Update the torrent according to the announce event
TrackedPeer peer = null;
try {
peer = torrent.update(event,
ByteBuffer.wrap(announceRequest.getPeerId()),
announceRequest.getHexPeerId(),
announceRequest.getIp(),
announceRequest.getPort(),
announceRequest.getUploaded(),
announceRequest.getDownloaded(),
announceRequest.getLeft());
} catch (IllegalArgumentException iae) {
LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae);
serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler);
return;
}
// Craft and output the answer
writeAnnounceResponse(torrent, peer, requestHandler);
}
#location 77
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void removeTorrent(TorrentHash torrentHash) {
logger.info("Stopping seeding " + torrentHash.getHexInfoHash());
final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash());
SharedTorrent torrent = torrentsPair.getSharedTorrent();
if (torrent != null) {
torrent.setClientState(ClientState.DONE);
torrent.close();
} else {
logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash()));
}
sendStopEvent(torrentsPair.getAnnounceableFileTorrent(), torrentHash.getHexInfoHash());
} | #vulnerable code
public void removeTorrent(TorrentHash torrentHash) {
logger.info("Stopping seeding " + torrentHash.getHexInfoHash());
final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash());
SharedTorrent torrent = torrentsPair.getSharedTorrent();
if (torrent != null) {
torrent.setClientState(ClientState.DONE);
torrent.close();
} else {
logger.warn(String.format("Torrent %s already removed from myTorrents", torrentHash.getHexInfoHash()));
}
final AnnounceableFileTorrent announceableFileTorrent = torrentsPair.getAnnounceableFileTorrent();
if (announceableFileTorrent == null) {
logger.info("Announceable torrent {} not found in storage on removing torrent", torrentHash.getHexInfoHash());
}
try {
this.announce.forceAnnounce(announceableFileTorrent, this, STOPPED);
} catch (IOException e) {
LoggerUtils.warnAndDebugDetails(logger, "can not send force stop announce event on delete torrent {}", torrentHash.getHexInfoHash(), e);
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initAndRunWorker() throws IOException {
myServerSocketChannel = selector.provider().openServerSocketChannel();
myServerSocketChannel.configureBlocking(false);
for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) {
try {
InetSocketAddress tryAddress = new InetSocketAddress(inetAddress, port);
myServerSocketChannel.socket().bind(tryAddress);
myServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
this.myBindAddress = tryAddress;
break;
} catch (IOException e) {
//try next port
logger.debug("Could not bind to port {}, trying next port...", port);
}
}
if (this.myBindAddress == null) {
throw new IOException("No available port for the BitTorrent client!");
}
myWorkerFuture = myExecutorService.submit(this);// TODO: 11/22/17 move runnable part to separate class e.g. ConnectionWorker
} | #vulnerable code
public void initAndRunWorker() throws IOException {
myServerSocketChannel = selector.provider().openServerSocketChannel();
myServerSocketChannel.configureBlocking(false);
for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) {
try {
InetSocketAddress tryAddress = new InetSocketAddress(inetAddress, port);
myServerSocketChannel.socket().bind(tryAddress);
myServerSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
this.myBindAddress = tryAddress;
break;
} catch (IOException e) {
//try next port
logger.debug("Could not bind to port {}, trying next port...", port);
}
}
if (this.myBindAddress == null) {
throw new IOException("No available port for the BitTorrent client!");
}
final String id = Client.BITTORRENT_ID_PREFIX + UUID.randomUUID().toString().split("-")[4];
byte[] idBytes = id.getBytes(Torrent.BYTE_ENCODING);
Peer self = new Peer(this.myBindAddress, ByteBuffer.wrap(idBytes));
peersStorageProvider.getPeersStorage().setSelf(self);
myWorkerFuture = myExecutorService.submit(this);// TODO: 11/22/17 move runnable part to separate class e.g. ConnectionWorker
logger.info("BitTorrent client [{}] started and " +
"listening at {}:{}...",
new Object[]{
self.getShortHexPeerId(),
self.getIp(),
self.getPort()
});
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePeerDisconnected(SharingPeer peer) {
final SharedTorrent peerTorrent = peer.getTorrent();
Peer p = new Peer(peer.getIp(), peer.getPort());
p.setPeerId(peer.getPeerId());
p.setTorrentHash(peer.getHexInfoHash());
PeerUID peerUID = new PeerUID(p.getAddress(), p.getHexInfoHash());
SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID);
logger.debug("Peer {} disconnected, [{}/{}].",
new Object[]{
peer,
getConnectedPeers().size(),
this.peersStorage.getSharingPeers().size()
});
} | #vulnerable code
@Override
public void handlePeerDisconnected(SharingPeer peer) {
final SharedTorrent peerTorrent = peer.getTorrent();
Peer p = new Peer(peer.getIp(), peer.getPort());
p.setPeerId(peer.getPeerId());
p.setTorrentHash(peer.getHexInfoHash());
PeerUID peerUID = new PeerUID(p.getStringPeerId(), p.getHexInfoHash());
SharingPeer sharingPeer = this.peersStorage.removeSharingPeer(peerUID);
logger.debug("Peer {} disconnected, [{}/{}].",
new Object[]{
peer,
getConnectedPeers().size(),
this.peersStorage.getSharingPeers().size()
});
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int read(ByteBuffer buffer, long offset) throws IOException {
try {
myLock.readLock().lock();
int requested = buffer.remaining();
if (offset + requested > this.size) {
throw new IllegalArgumentException("Invalid storage read request!");
}
int bytes = this.channel.read(buffer, offset);
if (bytes < requested) {
throw new IOException("Storage underrun!");
}
return bytes;
} finally {
myLock.readLock().unlock();
}
} | #vulnerable code
@Override
public int read(ByteBuffer buffer, long offset) throws IOException {
int requested = buffer.remaining();
if (offset + requested > this.size) {
throw new IllegalArgumentException("Invalid storage read request!");
}
int bytes = this.channel.read(buffer, offset);
if (bytes < requested) {
throw new IOException("Storage underrun!");
}
return bytes;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void unbind(boolean force) {
if (!force) {
// Cancel all outgoing requests, and send a NOT_INTERESTED message to
// the peer.
this.cancelPendingRequests();
this.send(PeerMessage.NotInterestedMessage.craft());
}
PeerExchange exchangeCopy;
synchronized (this.exchangeLock) {
exchangeCopy = exchange;
}
if (exchangeCopy != null) {
exchangeCopy.close();
}
synchronized (this.exchangeLock) {
this.exchange = null;
}
this.firePeerDisconnected();
myRequestedPieces.clear();
} | #vulnerable code
public void unbind(boolean force) {
if (!force) {
// Cancel all outgoing requests, and send a NOT_INTERESTED message to
// the peer.
this.cancelPendingRequests();
this.send(PeerMessage.NotInterestedMessage.craft());
}
PeerExchange exchangeCopy;
synchronized (this.exchangeLock) {
exchangeCopy = exchange;
}
if (exchangeCopy != null) {
exchangeCopy.close();
}
synchronized (this.exchangeLock) {
this.exchange = null;
}
this.firePeerDisconnected();
this.requestedPiece = null;
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void accept() throws IOException, SocketTimeoutException {
Socket socket = this.socket.accept();
try {
logger.debug("New incoming connection ...");
Handshake hs = this.validateHandshake(socket, null);
this.sendHandshake(socket);
this.fireNewPeerConnection(socket, hs.getPeerId());
} catch (ParseException pe) {
logger.info("Invalid handshake from {}: {}",
this.socketRepr(socket), pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: {}", ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
} | #vulnerable code
private void accept() throws IOException, SocketTimeoutException {
Socket socket = this.socket.accept();
try {
logger.debug("New incoming connection ...");
Handshake hs = this.validateHandshake(socket, null);
this.sendHandshake(socket);
this.fireNewPeerConnection(socket, hs.getPeerId());
} catch (ParseException pe) {
logger.info("Invalid handshake from " + this.socketRepr(socket) +
": " + pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: " + ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException {
if (pstrLength == -1) {
ByteBuffer len = ByteBuffer.allocate(1);
int readBytes = -1;
try {
readBytes = socketChannel.read(len);
} catch (IOException ignored) {
}
if (readBytes == -1) {
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (readBytes == 0) {
return this;
}
len.rewind();
byte pstrLen = len.get();
this.pstrLength = pstrLen;
messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH);
messageBytes.put(pstrLen);
}
int readBytes = -1;
try {
readBytes = socketChannel.read(messageBytes);
} catch (IOException e) {
e.printStackTrace();
}
if (readBytes == -1) {
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (messageBytes.remaining() != 0) {
return this;
}
Handshake hs;
try {
messageBytes.rewind();
hs = Handshake.parse(messageBytes, pstrLength);
} catch (ParseException e) {
logger.debug("incorrect handshake message from " + socketChannel.toString(), e);
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (!torrentsStorageFactory.getTorrentsStorage().hasTorrent(hs.getHexInfoHash())) {
logger.debug("peer {} try download torrent with hash {}, but it's unknown torrent for self",
Arrays.toString(hs.getPeerId()),
hs.getHexInfoHash());
return new ShutdownProcessor(uid, peersStorageFactory);
}
logger.debug("get handshake {} from {}", Arrays.toString(messageBytes.array()), socketChannel);
Peer peer = peersStorageFactory.getPeersStorage().getPeer(uid);
ByteBuffer wrap = ByteBuffer.wrap(hs.getPeerId());
wrap.rewind();
peer.setPeerId(wrap);
peer.setTorrentHash(hs.getHexInfoHash());
logger.trace("set peer id to peer " + peer);
ConnectionUtils.sendHandshake(socketChannel, hs.getInfoHash(), peersStorageFactory.getPeersStorage().getSelf().getPeerIdArray());
SharedTorrent torrent = torrentsStorageFactory.getTorrentsStorage().getTorrent(hs.getHexInfoHash());
SharingPeer sharingPeer = new SharingPeer(peer.getIp(), peer.getPort(), peer.getPeerId(), torrent);
sharingPeer.register(torrent);
sharingPeer.register(myPeerActivityListener);
sharingPeer.bind(socketChannel, true);
SharingPeer old = peersStorageFactory.getPeersStorage().tryAddSharingPeer(peer, sharingPeer);
if (old != null) {
logger.debug("$$$ already connected to " + peer);
return new ShutdownProcessor(uid, peersStorageFactory);
}
return new WorkingReceiver(this.uid, peersStorageFactory, torrentsStorageFactory);
} | #vulnerable code
@Override
public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException {
if (pstrLength == -1) {
ByteBuffer len = ByteBuffer.allocate(1);
int readBytes = -1;
try {
readBytes = socketChannel.read(len);
} catch (IOException ignored) {
}
if (readBytes == -1) {
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (readBytes == 0) {
return this;
}
len.rewind();
byte pstrLen = len.get();
this.pstrLength = pstrLen;
messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH);
messageBytes.put(pstrLen);
}
int readBytes = -1;
try {
readBytes = socketChannel.read(messageBytes);
} catch (IOException e) {
e.printStackTrace();
}
if (readBytes == -1) {
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (messageBytes.remaining() != 0) {
return this;
}
Handshake hs;
try {
messageBytes.rewind();
hs = Handshake.parse(messageBytes, pstrLength);
} catch (ParseException e) {
logger.debug("incorrect handshake message from " + socketChannel.toString(), e);
return new ShutdownProcessor(uid, peersStorageFactory);
}
if (!torrentsStorageFactory.getTorrentsStorage().hasTorrent(hs.getHexInfoHash())) {
logger.debug("peer {} try download torrent with hash {}, but it's unknown torrent for self",
Arrays.toString(hs.getPeerId()),
hs.getHexInfoHash());
return new ShutdownProcessor(uid, peersStorageFactory);
}
Peer peer = peersStorageFactory.getPeersStorage().getPeer(uid);
logger.trace("set peer id to peer " + peer);
peer.setPeerId(ByteBuffer.wrap(hs.getPeerId()));
peer.setTorrentHash(hs.getHexInfoHash());
ConnectionUtils.sendHandshake(socketChannel, hs.getInfoHash(), peersStorageFactory.getPeersStorage().getSelf().getPeerIdArray());
SharedTorrent torrent = torrentsStorageFactory.getTorrentsStorage().getTorrent(hs.getHexInfoHash());
SharingPeer sharingPeer = new SharingPeer(peer.getIp(), peer.getPort(), peer.getPeerId(), torrent);
sharingPeer.register(torrent);
sharingPeer.bind(socketChannel, true);
peersStorageFactory.getPeersStorage().addSharingPeer(peer, sharingPeer);
return new WorkingReceiver(this.uid, peersStorageFactory, torrentsStorageFactory);
}
#location 57
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() {
@Override
public void onWriteFailed(String message, Throwable e) {
logger.debug(message, e);
unbind(true);
}
@Override
public void onWriteDone() {
}
}), 1, TimeUnit.SECONDS);
} else {
logger.info("Attempting to send a message to non-connected peer {}!", this);
unbind(true);
}
} | #vulnerable code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
boolean writeTaskAdded = connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() {
@Override
public void onWriteFailed(String message, Throwable e) {
logger.debug(message, e);
unbind(true);
}
@Override
public void onWriteDone() {
}
}), 1, TimeUnit.SECONDS);
if (!writeTaskAdded) {
unbind(true);
}
} else {
logger.info("Attempting to send a message to non-connected peer {}!", this);
unbind(true);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void init(String fileName) throws IOException {
List<WxImgCreateTemplateCell> list = new CopyOnWriteArrayList<>();
BufferedReader reader = FileReadUtil.createLineRead(fileName);
String line = reader.readLine();
String[] temps;
while (line != null) {
temps = StringUtils.split(line, "|");
list.add(new WxImgCreateTemplateCell(temps[0], temps[1]));
line = reader.readLine();
}
cellList = list;
} | #vulnerable code
private void init(String fileName) throws IOException {
cellList.clear();
BufferedReader reader = FileReadUtil.createLineRead(fileName);
String line = reader.readLine();
String[] temps;
while (line != null) {
temps = StringUtils.split(line, "|");
cellList.add(new WxImgCreateTemplateCell(temps[0], temps[1]));
}
}
#location 4
#vulnerability type RESOURCE_LEAK | 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.