input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code private Map<String, Set<String>> readIndexFiles() { // checking cache if (entries != null) { return entries; } entries = new HashMap<String, Set<String>>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions index file for plugin '{}'", pluginId); Set<String> entriesPerPlugin = new HashSet<String>(); try { URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE); log.debug("Read '{}'", url.getFile()); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); ExtensionsIndexer.readIndex(reader, entriesPerPlugin); if (entriesPerPlugin.isEmpty()) { log.debug("No extensions found"); } else { log.debug("Found possible {} extensions:", entriesPerPlugin.size()); for (String entry : entriesPerPlugin) { log.debug(" " + entry); } } entries.put(pluginId, entriesPerPlugin); } catch (IOException e) { log.error(e.getMessage(), e); } } return entries; } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code private Map<String, Set<String>> readIndexFiles() { // checking cache if (entries != null) { return entries; } entries = new LinkedHashMap<String, Set<String>>(); readClasspathIndexFiles(); readPluginsIndexFiles(); return entries; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists removeDirectory(destination); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } fos.close(); } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } zipInputStream.close(); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists if (destination.exists() && destination.isDirectory()) { FileUtils.delete(destination.toPath()); } try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length; try (FileOutputStream fos = new FileOutputStream(file)) { while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } } } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Manifest readManifest(Path pluginPath) throws PluginException { if (FileUtils.isJarFile(pluginPath)) { try { Manifest manifest = new JarFile(pluginPath.toFile()).getManifest(); if (manifest != null) { return manifest; } } catch (IOException e) { throw new PluginException(e); } } Path manifestPath = getManifestPath(pluginPath); if (manifestPath == null) { throw new PluginException("Cannot find the manifest path"); } log.debug("Lookup plugin descriptor in '{}'", manifestPath); if (Files.notExists(manifestPath)) { throw new PluginException("Cannot find '{}' path", manifestPath); } try (InputStream input = Files.newInputStream(manifestPath)) { return new Manifest(input); } catch (IOException e) { throw new PluginException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected Manifest readManifest(Path pluginPath) throws PluginException { if (FileUtils.isJarFile(pluginPath)) { try(JarFile jar = new JarFile(pluginPath.toFile())) { Manifest manifest = jar.getManifest(); if (manifest != null) { return manifest; } } catch (IOException e) { throw new PluginException(e); } } Path manifestPath = getManifestPath(pluginPath); if (manifestPath == null) { throw new PluginException("Cannot find the manifest path"); } log.debug("Lookup plugin descriptor in '{}'", manifestPath); if (Files.notExists(manifestPath)) { throw new PluginException("Cannot find '{}' path", manifestPath); } try (InputStream input = Files.newInputStream(manifestPath)) { return new Manifest(input); } catch (IOException e) { throw new PluginException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; } for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) { // check if @Extension is put on class and not on method or constructor if (!(element instanceof TypeElement)) { continue; } // check if class extends/implements an extension point if (!isExtension(element.asType())) { continue; } TypeElement extensionElement = (TypeElement) element; // Extension annotation = element.getAnnotation(Extension.class); List<TypeElement> extensionPointElements = findExtensionPoints(extensionElement); if (extensionPointElements.isEmpty()) { // TODO throw error ? continue; } String extension = getBinaryName(extensionElement); for (TypeElement extensionPointElement : extensionPointElements) { String extensionPoint = getBinaryName(extensionPointElement); Set<String> extensionPoints = extensions.get(extensionPoint); if (extensionPoints == null) { extensionPoints = new TreeSet<>(); extensions.put(extensionPoint, extensionPoints); } extensionPoints.add(extension); } } /* if (!roundEnv.processingOver()) { return false; } */ // read old extensions oldExtensions = storage.read(); for (Map.Entry<String, Set<String>> entry : oldExtensions.entrySet()) { String extensionPoint = entry.getKey(); if (extensions.containsKey(extensionPoint)) { extensions.get(extensionPoint).addAll(entry.getValue()); } else { extensions.put(extensionPoint, entry.getValue()); } } // write extensions storage.write(extensions); return false; // return true; // no further processing of this annotation type } #location 56 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; } for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) { // check if @Extension is put on class and not on method or constructor if (!(element instanceof TypeElement)) { continue; } // check if class extends/implements an extension point if (!isExtension(element.asType())) { continue; } TypeElement extensionElement = (TypeElement) element; // Extension annotation = element.getAnnotation(Extension.class); List<TypeElement> extensionPointElements = findExtensionPoints(extensionElement); if (extensionPointElements.isEmpty()) { // TODO throw error ? continue; } String extension = getBinaryName(extensionElement); for (TypeElement extensionPointElement : extensionPointElements) { String extensionPoint = getBinaryName(extensionPointElement); Set<String> extensionPoints = extensions.get(extensionPoint); if (extensionPoints == null) { extensionPoints = new TreeSet<>(); extensions.put(extensionPoint, extensionPoints); } extensionPoints.add(extension); } } /* if (!roundEnv.processingOver()) { return false; } */ // read old extensions oldExtensions = storage.read(); for (Map.Entry<String, Set<String>> entry : oldExtensions.entrySet()) { String extensionPoint = entry.getKey(); if (extensions.containsKey(extensionPoint)) { extensions.get(extensionPoint).addAll(entry.getValue()); } else { extensions.put(extensionPoint, entry.getValue()); } } // write extensions storage.write(extensions); return false; // return true; // no further processing of this annotation type }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Map<String, Set<String>> readPluginsStorages() { log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storage from plugin '{}'", pluginId); Set<String> bucket = new HashSet<>(); try { URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource()); if (url != null) { log.debug("Read '{}'", url.getFile()); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); LegacyExtensionStorage.read(reader, bucket); } else { log.debug("Cannot find '{}'", getExtensionsResource()); } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } } return result; } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Map<String, Set<String>> readPluginsStorages() { log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storage from plugin '{}'", pluginId); Set<String> bucket = new HashSet<>(); try { URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource()); if (url != null) { log.debug("Read '{}'", url.getFile()); try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) { LegacyExtensionStorage.read(reader, bucket); } } else { log.debug("Cannot find '{}'", getExtensionsResource()); } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createEnabledFile() throws IOException { File file = testFolder.newFile("enabled.txt"); file.createNewFile(); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) { writer.write("plugin-1\r\n"); writer.write("plugin-2\r\n"); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void createEnabledFile() throws IOException { List<String> plugins = new ArrayList<>(); plugins.add("plugin-1"); plugins.add("plugin-2"); writeLines(plugins, "enabled.txt"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Map<String, Set<String>> readClasspathStorages() { log.debug("Reading extensions storages from classpath"); Map<String, Set<String>> result = new LinkedHashMap<>(); Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = getClass().getClassLoader().getResources(getExtensionsResource()); while (urls.hasMoreElements()) { URL url = urls.nextElement(); log.debug("Read '{}'", url.getFile()); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); LegacyExtensionStorage.read(reader, bucket); } debugExtensions(bucket); result.put(null, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } return result; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Map<String, Set<String>> readClasspathStorages() { log.debug("Reading extensions storages from classpath"); Map<String, Set<String>> result = new LinkedHashMap<>(); Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = getClass().getClassLoader().getResources(getExtensionsResource()); while (urls.hasMoreElements()) { URL url = urls.nextElement(); log.debug("Read '{}'", url.getFile()); try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) { LegacyExtensionStorage.read(reader, bucket); } } debugExtensions(bucket); result.put(null, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String loadPlugin(File pluginArchiveFile) { if (pluginArchiveFile == null || !pluginArchiveFile.exists()) { throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginArchiveFile)); } File pluginDirectory = null; try { pluginDirectory = expandPluginArchive(pluginArchiveFile); } catch (IOException e) { log.error(e.getMessage(), e); } if (pluginDirectory == null || !pluginDirectory.exists()) { throw new IllegalArgumentException(String.format("Failed to expand %s", pluginArchiveFile)); } try { PluginWrapper pluginWrapper = loadPluginDirectory(pluginDirectory); // TODO uninstalled plugin dependencies? unresolvedPlugins.remove(pluginWrapper); resolvedPlugins.add(pluginWrapper); compoundClassLoader.addLoader(pluginWrapper.getPluginClassLoader()); extensionFinder.reset(); return pluginWrapper.getDescriptor().getPluginId(); } catch (PluginException e) { log.error(e.getMessage(), e); } return null; } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String loadPlugin(File pluginArchiveFile) { if (pluginArchiveFile == null || !pluginArchiveFile.exists()) { throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginArchiveFile)); } File pluginDirectory = null; try { pluginDirectory = expandPluginArchive(pluginArchiveFile); } catch (IOException e) { log.error(e.getMessage(), e); } if (pluginDirectory == null || !pluginDirectory.exists()) { throw new IllegalArgumentException(String.format("Failed to expand %s", pluginArchiveFile)); } try { PluginWrapper pluginWrapper = loadPluginDirectory(pluginDirectory); // TODO uninstalled plugin dependencies? unresolvedPlugins.remove(pluginWrapper); resolvedPlugins.add(pluginWrapper); extensionFinder.reset(); return pluginWrapper.getDescriptor().getPluginId(); } catch (PluginException e) { log.error(e.getMessage(), e); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getTitle() throws IOException, ParseException { if (title != null) { return title; } if (url == null) throw new IOException("URL needs to be present"); return info(url).get("title").toString(); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public String getTitle() { return title; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_mod").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_mod").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double created() throws IOException, ParseException { return Double.parseDouble(info().get("created").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double created() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(info().get("created_utc").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created_utc").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mail").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_mod").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_mod").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double created() throws IOException, ParseException { return Double.parseDouble(info().get("created").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double created() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_gold").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_gold").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); } return submissions; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; Submission submission; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submission = new Submission(data); submission.setUser(user); submissions.add(submission); } return submissions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String id() throws IOException, ParseException { return info().get("id").toString(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public String id() throws IOException, ParseException { return getUserInformation().get("id").toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void parseRecursive(List<Comment> comments, JSONObject object) throws RetrievalFailedException, RedditError { assert comments != null : "List of comments must be instantiated."; assert object != null : "JSON Object must be instantiated."; // Get the comments in an array JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the submission results JSONObject data; Comment comment; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind.equals(Kind.COMMENT.value())) { // Contents of the comment data = ((JSONObject) data.get("data")); // Create and add the new comment comment = new Comment(data); comments.add(comment); Object o = data.get("replies"); if (o instanceof JSONObject) { // Dig towards the replies JSONObject replies = (JSONObject) o; parseRecursive(comment.getReplies(), replies); } } else if (kind.equals(Kind.MORE.value())) { //data = (JSONObject) data.get("data"); //JSONArray children = (JSONArray) data.get("children"); //System.out.println("\t+ More children: " + children); } } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code protected void parseRecursive(List<Comment> comments, JSONObject object) throws RetrievalFailedException, RedditError { assert comments != null : "List of comments must be instantiated."; assert object != null : "JSON Object must be instantiated."; // Get the comments in an array JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the submission results JSONObject data; Comment comment; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind != null) { if (kind.equals(Kind.COMMENT.value())) { // Contents of the comment data = ((JSONObject) data.get("data")); // Create and add the new comment comment = new Comment(data); comments.add(comment); Object o = data.get("replies"); if (o instanceof JSONObject) { // Dig towards the replies JSONObject replies = (JSONObject) o; parseRecursive(comment.getReplies(), replies); } } else if (kind.equals(Kind.MORE.value())) { //data = (JSONObject) data.get("data"); //JSONArray children = (JSONArray) data.get("children"); //System.out.println("\t+ More children: " + children); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getSubreddit() throws IOException, ParseException { if (subreddit != null) { return subreddit; } if (url == null) throw new IOException("URL needs to be present"); return info(url).get("subreddit").toString(); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public String getSubreddit() { return subreddit; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mod_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mod_mail").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int linkKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(info().get("link_karma"))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public int linkKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(getUserInformation().get("link_karma"))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Subreddit> parse(String url) throws RetrievalFailedException, RedditError { // Determine cookie String cookie = (user == null) ? null : user.getCookie(); // List of subreddits List<Subreddit> subreddits = new LinkedList<Subreddit>(); // Send request to reddit server via REST client Object response = restClient.get(url, cookie).getResponseObject(); if (response instanceof JSONObject) { JSONObject object = (JSONObject) response; JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the subreddit results JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind.equals(Kind.SUBREDDIT.value())) { // Create and add subreddit data = ((JSONObject) data.get("data")); subreddits.add(new Subreddit(data)); } } } else { System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); } // Finally return list of subreddits return subreddits; } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code public List<Subreddit> parse(String url) throws RetrievalFailedException, RedditError { // Determine cookie String cookie = (user == null) ? null : user.getCookie(); // List of subreddits List<Subreddit> subreddits = new LinkedList<Subreddit>(); // Send request to reddit server via REST client Object response = restClient.get(url, cookie).getResponseObject(); if (response instanceof JSONObject) { JSONObject object = (JSONObject) response; JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the subreddit results JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind != null) { if (kind.equals(Kind.SUBREDDIT.value())) { // Create and add subreddit data = ((JSONObject) data.get("data")); subreddits.add(new Subreddit(data)); } } } } else { System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); } // Finally return list of subreddits return subreddits; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getAuthor() throws IOException, ParseException { if (author != null) { return author; } if (url == null) throw new IOException("URL needs to be present"); return info(url).get("author").toString(); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public String getAuthor() { return author; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String id() throws IOException, ParseException { return info().get("id").toString(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public String id() throws IOException, ParseException { return getUserInformation().get("id").toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; RestClient restClient = new Utils(); switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; for (int i = 0; i < array.size(); i++) { data = (JSONObject) array.get(i); data = ((JSONObject) data.get("data")); submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); } return submissions; } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code public static LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; RestClient restClient = new HttpRestClient(); switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; for (int i = 0; i < array.size(); i++) { data = (JSONObject) array.get(i); data = ((JSONObject) data.get("data")); submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); } return submissions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_gold").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_gold").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Submission> parse(String url) throws RetrievalFailedException, RedditError { // Determine cookie String cookie = (user == null) ? null : user.getCookie(); // List of submissions List<Submission> submissions = new LinkedList<Submission>(); // Send request to reddit server via REST client Object response = restClient.get(url, cookie).getResponseObject(); if (response instanceof JSONObject) { JSONObject object = (JSONObject) response; if (object.get("error") != null) { throw new RedditError("Response contained error code " + object.get("error") + "."); } JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the submission results JSONObject data; Submission submission; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind.equals(Kind.LINK.value())) { // Create and add submission data = ((JSONObject) data.get("data")); submission = new Submission(data); submission.setUser(user); submissions.add(submission); } } } else { System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); } // Finally return list of submissions return submissions; } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public List<Submission> parse(String url) throws RetrievalFailedException, RedditError { // Determine cookie String cookie = (user == null) ? null : user.getCookie(); // List of submissions List<Submission> submissions = new LinkedList<Submission>(); // Send request to reddit server via REST client Object response = restClient.get(url, cookie).getResponseObject(); if (response instanceof JSONObject) { JSONObject object = (JSONObject) response; if (object.get("error") != null) { throw new RedditError("Response contained error code " + object.get("error") + "."); } JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); // Iterate over the submission results JSONObject data; Submission submission; for (Object anArray : array) { data = (JSONObject) anArray; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); if (kind != null) { if (kind.equals(Kind.LINK.value())) { // Create and add submission data = ((JSONObject) data.get("data")); submission = new Submission(data); submission.setUser(user); submissions.add(submission); } } } } else { System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'"); } // Finally return list of submissions return submissions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(info().get("created_utc").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created_utc").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); } return submissions; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; Submission submission; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submission = new Submission(data); submission.setUser(user); submissions.add(submission); } return submissions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mod_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mod_mail").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int commentKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(info().get("comment_karma"))); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public int commentKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(getUserInformation().get("comment_karma"))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString()))); } return submissions; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public LinkedList<Submission> getSubmissions(String redditName, Popularity type, Page frontpage, User user) throws IOException, ParseException { LinkedList<Submission> submissions = new LinkedList<Submission>(); String urlString = "/r/" + redditName; switch (type) { case NEW: urlString += "/new"; break; default: break; } //TODO Implement Pages urlString += ".json"; JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject(); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children"); JSONObject data; Submission submission; for (Object anArray : array) { data = (JSONObject) anArray; data = ((JSONObject) data.get("data")); submission = new Submission(data); submission.setUser(user); submissions.add(submission); } return submissions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double getCreatedUTC() throws IOException, ParseException { createdUTC = Double.parseDouble(info(url).get("created_utc").toString()); return createdUTC; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public double getCreatedUTC() { return createdUTC; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mail").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} deleteWithCheck(fileHandle); } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 3); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 3); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithMultipleContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "1"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithMultipleContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "0"); message.addHeader("Content-Length", "1"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public DefaultNHttpServerConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); CharsetDecoder chardecoder = null; CharsetEncoder charencoder = null; final Charset charset = this.config.getCharset(); final CodingErrorAction malformedInputAction = this.config.getMalformedInputAction() != null ? this.config.getMalformedInputAction() : CodingErrorAction.REPORT; final CodingErrorAction unmappableInputAction = this.config.getUnmappableInputAction() != null ? this.config.getUnmappableInputAction() : CodingErrorAction.REPORT; if (charset != null) { chardecoder = charset.newDecoder(); chardecoder.onMalformedInput(malformedInputAction); chardecoder.onUnmappableCharacter(unmappableInputAction); charencoder = charset.newEncoder(); charencoder.onMalformedInput(malformedInputAction); charencoder.onUnmappableCharacter(unmappableInputAction); } return new DefaultNHttpServerConnection(ssliosession, this.config.getBufferSize(), this.config.getFragmentSizeHint(), this.allocator, chardecoder, charencoder, this.config.getMessageConstraints(), null, null, this.requestParserFactory, null); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code public DefaultNHttpServerConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); return new DefaultNHttpServerConnection(ssliosession, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), null, null, this.requestParserFactory, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMalformedChunkSizeDecoding() throws Exception { String s = "5\r\n01234\r\n5zz\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMalformedChunkSizeDecoding() throws Exception { String s = "5\r\n01234\r\n5zz\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); HttpVersion ver = request.getRequestLine().getHttpVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); connState.resetInput(); connState.setRequest(request); connState.setInputState(ServerConnState.REQUEST_RECEIVED); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.expectContinue()) { try { HttpResponse ack = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); ack.getParams().setDefaults(this.params); if (this.expectationVerifier != null) { this.expectationVerifier.verify(request, ack, context); } conn.submitResponse(ack); } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex); } return; } } // Create a wrapper entity instead of the original one if (entityReq.getEntity() != null) { entityReq.setEntity(new BufferedContent( entityReq.getEntity(), connState.getInbuffer())); } } this.executor.execute(new Runnable() { public void run() { try { HttpContext context = new HttpExecutionContext(conn.getContext()); context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); handleRequest(connState, context); commitResponse(connState, conn); } catch (IOException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalIOException(ex); } } catch (HttpException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalProtocolException(ex); } } } }); } #location 40 #vulnerability type RESOURCE_LEAK
#fixed code public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); connState.resetInput(); connState.setRequest(request); connState.setInputState(ServerConnState.REQUEST_RECEIVED); this.executor.execute(new Runnable() { public void run() { try { HttpContext context = new HttpExecutionContext(conn.getContext()); context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); handleRequest(connState, context); commitResponse(connState, conn); } catch (IOException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalIOException(ex); } } catch (HttpException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalProtocolException(ex); } } } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ContentInputBuffer buffer = connState.getInbuffer(); // Update connection state connState.setInputState(ServerConnState.REQUEST_BODY_STREAM); try { buffer.consumeContent(decoder); if (decoder.isCompleted()) { // Request entity has been fully received connState.setInputState(ServerConnState.REQUEST_BODY_DONE); // Create a wrapper entity instead of the original one HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.getEntity() != null) { entityReq.setEntity(new BufferedContent( entityReq.getEntity(), connState.getInbuffer())); } conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ContentInputBuffer buffer = connState.getInbuffer(); // Update connection state connState.setInputState(ServerConnState.REQUEST_BODY_STREAM); try { buffer.consumeContent(decoder); if (decoder.isCompleted()) { // Request entity has been fully received connState.setInputState(ServerConnState.REQUEST_BODY_DONE); // Create a wrapper entity instead of the original one HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.getEntity() != null) { entityReq.setEntity(new ContentBufferEntity( entityReq.getEntity(), connState.getInbuffer())); } conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithMultipleContentLengthSomeWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "1"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithMultipleContentLengthSomeWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "1"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConstructors() throws Exception { new IdentityOutputStream(new SessionOutputBufferMock()); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConstructors() throws Exception { new IdentityOutputStream(new SessionOutputBufferMock()).close(); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void validate(final Set keys) { long currentTime = System.currentTimeMillis(); if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) { this.lastTimeoutCheck = currentTime; if (keys != null) { for (Iterator it = keys.iterator(); it.hasNext();) { SelectionKey key = (SelectionKey) it.next(); timeoutCheck(key, currentTime); } } } synchronized (this.bufferingSessions) { if (!this.bufferingSessions.isEmpty()) { for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) { IOSession session = (IOSession) it.next(); SessionBufferStatus bufStatus = session.getBufferStatus(); if (bufStatus != null) { if (!bufStatus.hasBufferedInput()) { it.remove(); continue; } } try { int ops = session.getEventMask(); if ((ops & EventMask.READ) > 0) { this.eventDispatch.inputReady(session); if (bufStatus != null) { if (!bufStatus.hasBufferedInput()) { it.remove(); } } } } catch (CancelledKeyException ex) { it.remove(); } } } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void validate(final Set keys) { long currentTime = System.currentTimeMillis(); if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) { this.lastTimeoutCheck = currentTime; if (keys != null) { for (Iterator it = keys.iterator(); it.hasNext();) { SelectionKey key = (SelectionKey) it.next(); timeoutCheck(key, currentTime); } } } if (!this.bufferingSessions.isEmpty()) { for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) { IOSession session = (IOSession) it.next(); SessionBufferStatus bufStatus = session.getBufferStatus(); if (bufStatus != null) { if (!bufStatus.hasBufferedInput()) { it.remove(); continue; } } try { int ops = session.getEventMask(); if ((ops & EventMask.READ) > 0) { this.eventDispatch.inputReady(session); if (bufStatus != null) { if (!bufStatus.hasBufferedInput()) { it.remove(); } } } } catch (CancelledKeyException ex) { it.remove(); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testChunkedConsistence() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testChunkedConsistence() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAvailable() throws IOException { final InputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {1, 2, 3}), 10L); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(2, in.available()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAvailable() throws IOException { final InputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {1, 2, 3}), 3L); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(2, in.available()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } try { in.close(); } catch (TruncatedChunkException expected) { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRequestExpectContinueGenerated() throws Exception { HttpContext context = new BasicHttpContext(null); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); String s = "whatever"; StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); RequestExpectContinue interceptor = new RequestExpectContinue(); interceptor.process(request, context); Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.EXPECT_CONTINUE, header.getValue()); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRequestExpectContinueGenerated() throws Exception { HttpContext context = new BasicHttpContext(null); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); String s = "whatever"; StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); RequestExpectContinue interceptor = new RequestExpectContinue(); interceptor.process(request, context); Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.EXPECT_CONTINUE, header.getValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpPostsHTTP10() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s, HttpVersion.HTTP_1_0); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testSimpleHttpPostsHTTP10() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s, HttpVersion.HTTP_1_0); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicWrite() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.write(new byte[] {'a', 'b'}, 0, 2); outstream.write('c'); outstream.flush(); final byte[] input = transmitter.getData(); Assert.assertNotNull(input); final byte[] expected = new byte[] {'a', 'b', 'c'}; Assert.assertEquals(expected.length, input.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], input[i]); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBasicWrite() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.write(new byte[] {'a', 'b'}, 0, 2); outstream.write('c'); outstream.flush(); final byte[] input = transmitter.getData(); Assert.assertNotNull(input); final byte[] expected = new byte[] {'a', 'b', 'c'}; Assert.assertEquals(expected.length, input.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], input[i]); } outstream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Future<BasicNIOPoolEntry> lease( final HttpHost route, final Object state, final FutureCallback<BasicNIOPoolEntry> callback) { int connectTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0); return super.lease(route, state, connectTimeout, TimeUnit.MILLISECONDS, callback); } #location 6 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Future<BasicNIOPoolEntry> lease( final HttpHost route, final Object state, final FutureCallback<BasicNIOPoolEntry> callback) { return super.lease(route, state, this.connectTimeout, this.tunit, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Assert.assertTrue(decoder.isCompleted()); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Assert.assertTrue(decoder.isCompleted()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpPostsChunked() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testSimpleHttpPostsChunked() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; HttpEntity entity = this.response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE); response.setEntity(new ContentBufferEntity(entity, this.buf)); } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIncompleteChunkDecoding() throws Exception { String[] chunks = { "10;", "key=\"value\"\r", "\n123456789012345", "6\r\n5\r\n12", "345\r\n6\r", "\nabcdef\r", "\n0\r\nFoot", "er1: abcde\r\nFooter2: f", "ghij\r\n\r\n" }; ReadableByteChannel channel = new ReadableByteChannelMockup( chunks, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ByteBuffer dst = ByteBuffer.allocate(1024); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(27, bytesRead); Assert.assertEquals("123456789012345612345abcdef", convert(dst)); Assert.assertTrue(decoder.isCompleted()); Header[] footers = decoder.getFooters(); Assert.assertEquals(2, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde", footers[0].getValue()); Assert.assertEquals("Footer2", footers[1].getName()); Assert.assertEquals("fghij", footers[1].getValue()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testIncompleteChunkDecoding() throws Exception { String[] chunks = { "10;", "key=\"value\"\r", "\n123456789012345", "6\r\n5\r\n12", "345\r\n6\r", "\nabcdef\r", "\n0\r\nFoot", "er1: abcde\r\nFooter2: f", "ghij\r\n\r\n" }; ReadableByteChannel channel = new ReadableByteChannelMock( chunks, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ByteBuffer dst = ByteBuffer.allocate(1024); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(27, bytesRead); Assert.assertEquals("123456789012345612345abcdef", convert(dst)); Assert.assertTrue(decoder.isCompleted()); Header[] footers = decoder.getFooters(); Assert.assertEquals(2, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde", footers[0].getValue()); Assert.assertEquals("Footer2", footers[1].getName()); Assert.assertEquals("fghij", footers[1].getValue()); dst.clear(); bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpHeads() throws Exception { int connNo = 3; int reqNo = 20; TestJob[] jobs = new TestJob[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new TestJob(); } Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("HEAD", s); } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener(new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.getFailureMessage() != null) { fail(testjob.getFailureMessage()); } assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertNull(testjob.getResult()); } } #location 61 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testSimpleHttpHeads() throws Exception { int connNo = 3; int reqNo = 20; Job[] jobs = new Job[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); } Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("HEAD", s); } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener(new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.getFailureMessage() != null) { fail(testjob.getFailureMessage()); } assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertNull(testjob.getResult()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; HttpEntity entity = this.response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE); response.setEntity(new ContentBufferEntity(entity, this.buf)); } } #location 6 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void processResponse( final NHttpClientConnection conn, final ClientConnState connState) throws IOException, HttpException { HttpContext context = conn.getContext(); HttpResponse response = connState.getResponse(); if (response.getEntity() != null) { response.setEntity(new BufferedContent( response.getEntity(), connState.getInbuffer())); } context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); this.execHandler.handleResponse(response, context); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready for another request connState.resetInput(); conn.requestOutput(); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void processResponse( final NHttpClientConnection conn, final ClientConnState connState) throws IOException, HttpException { HttpContext context = conn.getContext(); HttpResponse response = connState.getResponse(); if (response.getEntity() != null) { response.setEntity(new ContentBufferEntity( response.getEntity(), connState.getInbuffer())); } context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); this.execHandler.handleResponse(response, context); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready for another request connState.resetInput(); conn.requestOutput(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMalformedChunkEndingDecoding() throws Exception { String s = "5\r\n01234\r\n5\r\n56789\n\r6\r\nabcdef\r\n0\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMalformedChunkEndingDecoding() throws Exception { String s = "5\r\n01234\r\n5\r\n56789\n\r6\r\nabcdef\r\n0\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCodingBeyondContentLimitFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] { "stuff;", "more stuff; and a lot more stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", ".txt"); FileChannel fchannel = new FileOutputStream(tmpFile).getChannel(); long bytesRead = decoder.transfer(fchannel, 0, 6); assertEquals(6, bytesRead); assertEquals("stuff;", readFromFile(tmpFile, 6)); assertFalse(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel,0 , 10); assertEquals(10, bytesRead); assertEquals("more stuff", readFromFile(tmpFile, 10)); assertTrue(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(0, bytesRead); assertTrue(decoder.isCompleted()); tmpFile.delete(); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code public void testCodingBeyondContentLimitFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] { "stuff;", "more stuff; and a lot more stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long bytesRead = decoder.transfer(fchannel, 0, 6); assertEquals(6, bytesRead); assertFalse(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel,0 , 10); assertEquals(10, bytesRead); assertTrue(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(-1, bytesRead); assertTrue(decoder.isCompleted()); fileHandle.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConstructors() throws Exception { new ContentLengthOutputStream(new SessionOutputBufferMock(), 10L); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConstructors() throws Exception { final ContentLengthOutputStream in = new ContentLengthOutputStream( new SessionOutputBufferMock(), 10L); in.close(); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected=MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(expected=MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCodingBeyondContentLimitFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] { "stuff;", "more stuff; and a lot more stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long bytesRead = decoder.transfer(fchannel, 0, 6); assertEquals(6, bytesRead); assertFalse(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel,0 , 10); assertEquals(10, bytesRead); assertTrue(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(-1, bytesRead); assertTrue(decoder.isCompleted()); fileHandle.delete(); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code public void testCodingBeyondContentLimitFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] { "stuff;", "more stuff; and a lot more stuff"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 16); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long bytesRead = decoder.transfer(fchannel, 0, 6); assertEquals(6, bytesRead); assertFalse(decoder.isCompleted()); assertEquals(6, metrics.getBytesTransferred()); bytesRead = decoder.transfer(fchannel,0 , 10); assertEquals(10, bytesRead); assertTrue(decoder.isCompleted()); assertEquals(16, metrics.getBytesTransferred()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(-1, bytesRead); assertTrue(decoder.isCompleted()); assertEquals(16, metrics.getBytesTransferred()); fileHandle.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpPostsWithExpectContinue() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testHttpPostsWithExpectContinue() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpPostsContentNotConsumed() throws Exception { HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { // Request content body has not been consumed!!! response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); NStringEntity outgoing = new NStringEntity("Ooopsie"); response.setEntity(outgoing); } }; HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; int connNo = 3; int reqNo = 20; TestJob[] jobs = new TestJob[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new TestJob(); } Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(requestHandler)); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, testjob.getStatusCode()); assertEquals("Ooopsie", testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } } #location 80 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testSimpleHttpPostsContentNotConsumed() throws Exception { HttpRequestHandler requestHandler = new HttpRequestHandler() { public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { // Request content body has not been consumed!!! response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); NStringEntity outgoing = new NStringEntity("Ooopsie"); response.setEntity(outgoing); } }; HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; int connNo = 3; int reqNo = 20; Job[] jobs = new Job[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); } Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(requestHandler)); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, testjob.getStatusCode()); assertEquals("Ooopsie", testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} deleteWithCheck(fileHandle); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} deleteWithCheck(fileHandle); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithMultipleContentLengthSomeWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "1"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithMultipleContentLengthSomeWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "1"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue(instream instanceof ContentLengthInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("IOException should have been thrown"); } catch(IOException expected) { } } finally { testfile.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMalformedChunkTruncatedChunk() throws Exception { String s = "3\r\n12"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); Assert.assertEquals(2, decoder.read(dst)); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMalformedChunkTruncatedChunk() throws Exception { String s = "3\r\n12"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); Assert.assertEquals(2, decoder.read(dst)); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void connected(final IOSession session) { SSLIOSession sslSession = new SSLIOSession( session, this.sslcontext, this.sslHandler); NHttpServerIOTarget conn = createConnection( sslSession); session.setAttribute(NHTTP_CONN, conn); session.setAttribute(SSL_SESSION, sslSession); this.handler.connected(conn); try { sslSession.bind(SSLMode.SERVER, this.params); } catch (SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public void connected(final IOSession session) { SSLIOSession sslSession = createSSLIOSession( session, this.sslcontext, this.sslHandler); NHttpServerIOTarget conn = createConnection( sslSession); session.setAttribute(NHTTP_CONN, conn); session.setAttribute(SSL_SESSION, sslSession); this.handler.connected(conn); try { sslSession.bind(SSLMode.SERVER, this.params); } catch (SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testResponseContentNoEntity() throws Exception { HttpContext context = new HttpExecutionContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void testResponseContentNoEntity() throws Exception { HttpContext context = new BasicHttpContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doShutdown() throws InterruptedIOException { if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) { return; } this.status = IOReactorStatus.SHUTTING_DOWN; try { cancelRequests(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } this.selector.wakeup(); // Close out all channels if (this.selector.isOpen()) { Set<SelectionKey> keys = this.selector.keys(); for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) { try { SelectionKey key = it.next(); Channel channel = key.channel(); if (channel != null) { channel.close(); } } catch (IOException ex) { addExceptionEvent(ex); } } // Stop dispatching I/O events try { this.selector.close(); } catch (IOException ex) { addExceptionEvent(ex); } } // Attempt to shut down I/O dispatchers gracefully for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; dispatcher.gracefulShutdown(); } long gracePeriod = NIOReactorParams.getGracePeriod(this.params); try { // Force shut down I/O dispatchers if they fail to terminate // in time for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) { dispatcher.awaitShutdown(gracePeriod); } if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) { try { dispatcher.hardShutdown(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } } } // Join worker threads for (int i = 0; i < this.workerCount; i++) { Thread t = this.threads[i]; if (t != null) { t.join(gracePeriod); } } } catch (InterruptedException ex) { throw new InterruptedIOException(ex.getMessage()); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void doShutdown() throws InterruptedIOException { synchronized (this.statusLock) { if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) { return; } this.status = IOReactorStatus.SHUTTING_DOWN; } try { cancelRequests(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } this.selector.wakeup(); // Close out all channels if (this.selector.isOpen()) { Set<SelectionKey> keys = this.selector.keys(); for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) { try { SelectionKey key = it.next(); Channel channel = key.channel(); if (channel != null) { channel.close(); } } catch (IOException ex) { addExceptionEvent(ex); } } // Stop dispatching I/O events try { this.selector.close(); } catch (IOException ex) { addExceptionEvent(ex); } } // Attempt to shut down I/O dispatchers gracefully for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; dispatcher.gracefulShutdown(); } long gracePeriod = NIOReactorParams.getGracePeriod(this.params); try { // Force shut down I/O dispatchers if they fail to terminate // in time for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) { dispatcher.awaitShutdown(gracePeriod); } if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) { try { dispatcher.hardShutdown(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } } } // Join worker threads for (int i = 0; i < this.workerCount; i++) { Thread t = this.threads[i]; if (t != null) { t.join(gracePeriod); } } } catch (InterruptedException ex) { throw new InterruptedIOException(ex.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); in.read(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); in.read(); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(4, in.available()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(4, in.available()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(input, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.assertEquals(0, out.size()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(input, CONTENT_CHARSET))); final byte[] buffer = new byte[300]; final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } Assert.assertEquals(0, out.size()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testInputThrottling() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("queue", attachment); } public HttpRequest submitRequest(final HttpContext context) { @SuppressWarnings("unchecked") Queue<TestJob> queue = (Queue<TestJob>) context.getAttribute("queue"); if (queue == null) { throw new IllegalStateException("Queue is null"); } TestJob testjob = queue.poll(); context.setAttribute("job", testjob); if (testjob != null) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); StringEntity entity = null; try { entity = new StringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } else { return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { TestJob testjob = (TestJob) context.removeAttribute("job"); if (testjob == null) { throw new IllegalStateException("TestJob is null"); } int statusCode = response.getStatusLine().getStatusCode(); String content = null; HttpEntity entity = response.getEntity(); if (entity != null) { try { // Simulate slow response handling in order to cause the // internal content buffer to fill up, forcing the // protocol handler to throttle input rate ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = entity.getContent(); byte[] tmp = new byte[2048]; int l; while((l = instream.read(tmp)) != -1) { Thread.sleep(1); outstream.write(tmp, 0, l); } content = new String(outstream.toByteArray(), EntityUtils.getContentCharSet(entity)); } catch (InterruptedException ex) { content = "Interrupted: " + ex.getMessage(); } catch (IOException ex) { content = "I/O exception: " + ex.getMessage(); } } testjob.setResult(statusCode, content); } public void finalizeContext(final HttpContext context) { TestJob testjob = (TestJob) context.removeAttribute("job"); if (testjob != null) { testjob.fail("Request failed"); } } }; int connNo = 3; int reqNo = 20; TestJob[] jobs = new TestJob[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new TestJob(10000); } Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } } #location 127 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testInputThrottling() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("queue", attachment); } public HttpRequest submitRequest(final HttpContext context) { @SuppressWarnings("unchecked") Queue<Job> queue = (Queue<Job>) context.getAttribute("queue"); if (queue == null) { throw new IllegalStateException("Queue is null"); } Job testjob = queue.poll(); context.setAttribute("job", testjob); if (testjob != null) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); StringEntity entity = null; try { entity = new StringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } else { return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob == null) { throw new IllegalStateException("TestJob is null"); } int statusCode = response.getStatusLine().getStatusCode(); String content = null; HttpEntity entity = response.getEntity(); if (entity != null) { try { // Simulate slow response handling in order to cause the // internal content buffer to fill up, forcing the // protocol handler to throttle input rate ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = entity.getContent(); byte[] tmp = new byte[2048]; int l; while((l = instream.read(tmp)) != -1) { Thread.sleep(1); outstream.write(tmp, 0, l); } content = new String(outstream.toByteArray(), EntityUtils.getContentCharSet(entity)); } catch (InterruptedException ex) { content = "Interrupted: " + ex.getMessage(); } catch (IOException ex) { content = "I/O exception: " + ex.getMessage(); } } testjob.setResult(statusCode, content); } public void finalizeContext(final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob != null) { testjob.fail("Request failed"); } } }; int connNo = 3; int reqNo = 20; Job[] jobs = new Job[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(10000); } Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); try { in.read(); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch(final MalformedChunkCodingException e) { /* expected exception */ } in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doShutdown() throws InterruptedIOException { if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) { return; } this.status = IOReactorStatus.SHUTTING_DOWN; try { cancelRequests(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } this.selector.wakeup(); // Close out all channels if (this.selector.isOpen()) { Set<SelectionKey> keys = this.selector.keys(); for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) { try { SelectionKey key = it.next(); Channel channel = key.channel(); if (channel != null) { channel.close(); } } catch (IOException ex) { addExceptionEvent(ex); } } // Stop dispatching I/O events try { this.selector.close(); } catch (IOException ex) { addExceptionEvent(ex); } } // Attempt to shut down I/O dispatchers gracefully for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; dispatcher.gracefulShutdown(); } long gracePeriod = NIOReactorParams.getGracePeriod(this.params); try { // Force shut down I/O dispatchers if they fail to terminate // in time for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) { dispatcher.awaitShutdown(gracePeriod); } if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) { try { dispatcher.hardShutdown(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } } } // Join worker threads for (int i = 0; i < this.workerCount; i++) { Thread t = this.threads[i]; if (t != null) { t.join(gracePeriod); } } } catch (InterruptedException ex) { throw new InterruptedIOException(ex.getMessage()); } finally { synchronized (this.shutdownMutex) { this.status = IOReactorStatus.SHUT_DOWN; this.shutdownMutex.notifyAll(); } } } #location 65 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void doShutdown() throws InterruptedIOException { if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) { return; } this.status = IOReactorStatus.SHUTTING_DOWN; try { cancelRequests(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } this.selector.wakeup(); // Close out all channels if (this.selector.isOpen()) { Set<SelectionKey> keys = this.selector.keys(); for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) { try { SelectionKey key = it.next(); Channel channel = key.channel(); if (channel != null) { channel.close(); } } catch (IOException ex) { addExceptionEvent(ex); } } // Stop dispatching I/O events try { this.selector.close(); } catch (IOException ex) { addExceptionEvent(ex); } } // Attempt to shut down I/O dispatchers gracefully for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; dispatcher.gracefulShutdown(); } long gracePeriod = NIOReactorParams.getGracePeriod(this.params); try { // Force shut down I/O dispatchers if they fail to terminate // in time for (int i = 0; i < this.workerCount; i++) { BaseIOReactor dispatcher = this.dispatchers[i]; if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) { dispatcher.awaitShutdown(gracePeriod); } if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) { try { dispatcher.hardShutdown(); } catch (IOReactorException ex) { if (ex.getCause() != null) { addExceptionEvent(ex.getCause()); } } } } // Join worker threads for (int i = 0; i < this.workerCount; i++) { Thread t = this.threads[i]; if (t != null) { t.join(gracePeriod); } } } catch (InterruptedException ex) { throw new InterruptedIOException(ex.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMalformedFooters() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (IOException ex) { // expected } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMalformedFooters() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (IOException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; HttpEntity entity = this.response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE); response.setEntity(new ContentBufferEntity(entity, this.buf)); } } #location 14 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasics() throws IOException { final String correct = "1234567890123456"; final InputStream in = new ContentLengthInputStream(new SessionInputBufferMock( EncodingUtils.getBytes(correct, CONTENT_CHARSET)), 10L); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[50]; int len = in.read(buffer, 0, 2); out.write(buffer, 0, len); len = in.read(buffer); out.write(buffer, 0, len); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, "1234567890"); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBasics() throws IOException { final String correct = "1234567890123456"; final InputStream in = new ContentLengthInputStream(new SessionInputBufferMock( EncodingUtils.getBytes(correct, CONTENT_CHARSET)), 10L); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[50]; int len = in.read(buffer, 0, 2); out.write(buffer, 0, len); len = in.read(buffer); out.write(buffer, 0, len); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, "1234567890"); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpGets() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("GET", s); } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testSimpleHttpGets() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("GET", s); } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); final byte[] tmp = new byte[2]; Assert.assertEquals(2, instream.read(tmp, 0, tmp.length)); Assert.assertEquals('a', tmp[0]); Assert.assertEquals('b', tmp[1]); Assert.assertEquals('c', instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); final byte[] tmp = new byte[2]; Assert.assertEquals(2, instream.read(tmp, 0, tmp.length)); Assert.assertEquals('a', tmp[0]); Assert.assertEquals('b', tmp[1]); Assert.assertEquals('c', instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); instream.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(s, Consts.ISO_8859_1)); in.read(); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.