instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") @Override public boolean removeAll(Collection<?> c) { boolean success = true; Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element); } return success; }
#vulnerable code @SuppressWarnings("unchecked") @Override public boolean removeAll(Collection<?> c) { boolean success = true; Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element, false); } refreshStorage(true); return success; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int size() { int repoSize = nest.smembers().size(); return repoSize; }
#vulnerable code @Override public int size() { int repoSize = nest.smembers().size(); if (repoSize != elements.size()) { refreshStorage(true); } return repoSize; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element); } return success; }
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code RiakConnection getConnection() throws IOException { return getConnection(true); }
#vulnerable code RiakConnection getConnection() throws IOException { RiakConnection c = connections.get(); if (c == null || !c.endIdleAndCheckValid()) { c = new RiakConnection(addr, port); if (this.clientID != null) { setClientID(clientID); } } else { // we're fine! // } connections.set(null); return c; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RawFetchResponse fetch(String bucket, String key) { return doFetch(bucket, key, null, false); }
#vulnerable code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void receive_code(int code) throws IOException, RiakError { int len = din.readInt(); int get_code = din.read(); if (code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); throw new RiakError(err); } if (len != 1 || code != get_code) { throw new IOException("bad message code"); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean findNext() throws IOException { if (currentPartStream != null) { InputStream is = currentPartStream.branch(); try { while (is.read() != -1) { /* nop */} // advance stream to end of next boundary finishReadingLine(stream); // and consume the rest of the boundary line including the newline } catch (IOException e) { throw new RuntimeException(e); } } if (stream.peek() != -1) { currentPartStream = new BranchableInputStream(new OneTokenInputStream(stream.branch(), boundary)); return true; } return false; }
#vulnerable code private boolean findNext() throws IOException { if (currentPartStream != null && !currentPartStream.done()) { InputStream is = new OneTokenInputStream(stream, boundary); try { while (is.read() != -1) { /* nop */} } catch (IOException e) { throw new RuntimeException(e); } } if (stream.peek() != -1) { currentPartStream = new OneTokenInputStream(stream.branch(), boundary); return true; } return false; } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code byte[] receive(int code) throws IOException { int len = din.readInt(); int get_code = din.read(); byte[] data = null; if (len > 1) { data = new byte[len - 1]; din.readFully(data); } if (get_code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); throw new RiakError(err); } if (code != get_code) { throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); } return data; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setClientID(ByteString id) throws IOException { if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); } this.clientId = id.toByteArray(); }
#vulnerable code public void setClientID(ByteString id) throws IOException { if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); } RpbSetClientIdReq req = RPB.RpbSetClientIdReq.newBuilder().setClientId( id).build(); RiakConnection c = getConnection(false); try { c.send(MSG_SetClientIdReq, req); c.receive_code(MSG_SetClientIdResp); } finally { release(c); } this.clientID = id; } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public WriteBucket addPrecommitHook(NamedFunction preCommitHook) { httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); if(preCommitHook != null) { if(precommitHooks == null) { precommitHooks = new ArrayList<NamedFunction>(); } precommitHooks.add(preCommitHook); } return this; }
#vulnerable code public WriteBucket addPrecommitHook(NamedFunction preCommitHook) { httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); builder.addPrecommitHook(preCommitHook); return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void send(int code) throws IOException { dout.writeInt(1); dout.write(code); dout.flush(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getClientID() throws IOException { RiakConnection c = getConnection(); try { c.send(MSG_GetClientIdReq); byte[] data = c.receive(MSG_GetClientIdResp); if (data == null) return null; RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); clientId = res.getClientId().toByteArray(); return CharsetUtils.asUTF8String(clientId); } finally { release(c); } }
#vulnerable code public String getClientID() throws IOException { RiakConnection c = getConnection(); try { c.send(MSG_GetClientIdReq); byte[] data = c.receive(MSG_GetClientIdResp); if (data == null) return null; RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); clientID = res.getClientId(); return clientID.toStringUtf8(); } finally { release(c); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null, false); }
#vulnerable code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed 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; }
#vulnerable code private Map<String, Set<String>> readIndexFiles() { // checking cache if (entries != null) { return entries; } entries = new HashMap<String, Set<String>>(); List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins(); for (PluginWrapper plugin : startedPlugins) { 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 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void resolveDependencies() throws PluginException { DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins); resolvedPlugins = dependencyResolver.getSortedPlugins(); for (PluginWrapper pluginWrapper : resolvedPlugins) { unresolvedPlugins.remove(pluginWrapper); uberClassLoader.addLoader(pluginWrapper.getPluginClassLoader()); LOG.info("Plugin '" + pluginWrapper.getDescriptor().getPluginId() + "' resolved"); } }
#vulnerable code private void resolveDependencies() { DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins); resolvedPlugins = dependencyResolver.getSortedDependencies(); for (Plugin plugin : resolvedPlugins) { unresolvedPlugins.remove(plugin); uberClassLoader.addLoader(plugin.getWrapper().getPluginClassLoader()); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } } }
#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 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getTitle() { return title; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_mod").toString()); }
#vulnerable code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_mod").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mail").toString()); }
#vulnerable code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_mod").toString()); }
#vulnerable code public boolean isMod() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_mod").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_gold").toString()); }
#vulnerable code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_gold").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int linkKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(getUserInformation().get("link_karma"))); }
#vulnerable code public int linkKarma() throws IOException, ParseException { return Integer.parseInt(Utils.toString(info().get("link_karma"))); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getAuthor() { return author; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String id() throws IOException, ParseException { return getUserInformation().get("id").toString(); }
#vulnerable code public String id() throws IOException, ParseException { return info().get("id").toString(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("is_gold").toString()); }
#vulnerable code public boolean isGold() throws IOException, ParseException { return Boolean.parseBoolean(info().get("is_gold").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created_utc").toString()); }
#vulnerable code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(info().get("created_utc").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mod_mail").toString()); }
#vulnerable code public boolean hasModMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mod_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public double getCreatedUTC() { return createdUTC; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(getUserInformation().get("has_mail").toString()); }
#vulnerable code public boolean hasMail() throws IOException, ParseException { return Boolean.parseBoolean(info().get("has_mail").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } } } }); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } } } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } }
#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 83 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(input, Consts.ISO_8859_1)); 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(); }
#vulnerable code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock(input, Consts.ISO_8859_1)); 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 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; }
#vulnerable code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) this.request).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); ((HttpEntityEnclosingRequest) this.request).setEntity( new ContentBufferEntity(entity, this.buf)); } } } #location 14 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfStreamConditionReadingLastChunk() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345"; 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()); }
#vulnerable code @Test public void testEndOfStreamConditionReadingLastChunk() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345"; 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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void processEvent(final SelectionKey key) { IOSessionImpl session = (IOSessionImpl) key.attachment(); try { if (key.isAcceptable()) { acceptable(key); } if (key.isConnectable()) { connectable(key); } if (key.isReadable()) { session.resetLastRead(); readable(key); } if (key.isWritable()) { session.resetLastWrite(); writable(key); } } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } }
#vulnerable code protected void processEvent(final SelectionKey key) { SessionHandle handle = (SessionHandle) key.attachment(); IOSession session = handle.getSession(); try { if (key.isAcceptable()) { acceptable(key); } if (key.isConnectable()) { connectable(key); } if (key.isReadable()) { handle.resetLastRead(); readable(key); } if (key.isWritable()) { handle.resetLastWrite(); writable(key); } } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\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(); }
#vulnerable code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testChunkedConsistence() throws IOException { final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); final byte[] d = new byte[10]; final ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); in.close(); }
#vulnerable code @Test public void testChunkedConsistence() throws IOException { final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); final byte[] d = new byte[10]; final ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleHttpPostsWithContentLength() 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(false); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
#vulnerable code public void testSimpleHttpPostsWithContentLength() 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(false); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFoldedFooters() 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 fghij\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); int bytesRead = decoder.read(dst); Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Header[] footers = decoder.getFooters(); Assert.assertEquals(1, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde fghij", footers[0].getValue()); }
#vulnerable code @Test public void testFoldedFooters() 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 fghij\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); int bytesRead = decoder.read(dst); Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Header[] footers = decoder.getFooters(); Assert.assertEquals(1, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde fghij", footers[0].getValue()); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAvailable() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); instream.read(); Assert.assertEquals(2, instream.available()); instream.close(); }
#vulnerable code @Test public void testAvailable() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); instream.read(); Assert.assertEquals(2, instream.available()); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public DefaultNHttpClientConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); return new DefaultNHttpClientConnection( ssliosession, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), null, null, null, this.responseParserFactory); }
#vulnerable code public DefaultNHttpClientConnection 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 DefaultNHttpClientConnection( ssliosession, this.config.getBufferSize(), this.config.getFragmentSizeHint(), this.allocator, chardecoder, charencoder, this.config.getMessageConstraints(), null, null, null, this.responseParserFactory); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\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) { } }
#vulnerable code @Test public void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", ".txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); try { encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { // ignore } finally { fchannel.close(); deleteWithCheck(tmpFile); } }
#vulnerable code public void testCodingCompletedFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder( channel, outbuf, metrics, 5); encoder.write(wrap("stuff")); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("more stuff"); wrtout.flush(); wrtout.close(); try { FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 10); fail("IllegalStateException should have been thrown"); } catch (IllegalStateException ex) { // ignore } finally { deleteWithCheck(tmpFile); } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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 58 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void handleRequest( final ServerConnState connState, final HttpContext context) throws HttpException, IOException { HttpRequest request = connState.getRequest(); context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request); 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; } HttpResponse response; if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.getParams().setDefaults(this.params); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { handleException(connState, ex ,context); return; } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met waitForOutput(connState, ServerConnState.READY); connState.setResponse(response); synchronized (connState) { waitForOutput(connState, ServerConnState.RESPONSE_SENT); connState.resetOutput(); } } else { // The request does not meet the server expections context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); connState.setResponse(response); return; } } // Create a wrapper entity instead of the original one if (entityReq.getEntity() != null) { entityReq.setEntity(new ContentBufferEntity( entityReq.getEntity(), connState.getInbuffer())); } } response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.getParams().setDefaults(this.params); context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); try { this.httpProcessor.process(request, context); HttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } if (handler != null) { handler.handle(request, response, context); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } catch (HttpException ex) { handleException(connState, ex ,context); return; } this.httpProcessor.process(response, context); connState.setResponse(response); }
#vulnerable code private void handleRequest( final ServerConnState connState, final HttpContext context) throws HttpException, IOException { HttpRequest request = connState.getRequest(); context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request); 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; } HttpResponse response; if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.getParams().setDefaults(this.params); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { handleException(connState, ex ,context); return; } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met waitForOutput(connState, ServerConnState.READY); connState.setResponse(response); synchronized (connState) { waitForOutput(connState, ServerConnState.RESPONSE_SENT); connState.resetOutput(); } } else { // The request does not meet the server expections context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); connState.setResponse(response); return; } } // Create a wrapper entity instead of the original one if (entityReq.getEntity() != null) { entityReq.setEntity(new BufferedContent( entityReq.getEntity(), connState.getInbuffer())); } } response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.getParams().setDefaults(this.params); context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); try { this.httpProcessor.process(request, context); HttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } if (handler != null) { handler.handle(request, response, context); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } catch (HttpException ex) { handleException(connState, ex ,context); return; } this.httpProcessor.process(response, context); connState.setResponse(response); } #location 55 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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 39 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructors() throws Exception { final ContentLengthInputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {}), 0); in.close(); try { new ContentLengthInputStream(null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
#vulnerable code @Test public void testConstructors() throws Exception { new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), 10); try { new ContentLengthInputStream(null, 10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code 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; } } fchannel.close(); assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); fileHandle.delete(); }
#vulnerable code public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff;", "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 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)); assertFalse(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(0, bytesRead); assertTrue(decoder.isCompleted()); bytesRead = decoder.transfer(fchannel, 0, 1); assertEquals(0, bytesRead); assertTrue(decoder.isCompleted()); tmpFile.delete(); } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInvalidInput() 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); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } }
#vulnerable code @Test public void testInvalidInput() 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); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicDecodingFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII"); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); final File fileHandle = File.createTempFile("testFile", ".txt"); final RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final 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); testfile.close(); }
#vulnerable code @Test public void testBasicDecodingFile() throws Exception { final ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII"); final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII); final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); final IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); final File fileHandle = File.createTempFile("testFile", ".txt"); final RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); final FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { final 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 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testComplexDecoding() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\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); 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)); 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()); }
#vulnerable code @Test public void testComplexDecoding() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\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); 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)); 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 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } ContentType contentType = ContentType.getOrDefault(entity); String charset = contentType.getCharset(); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } }
#vulnerable code public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } String charset = getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadingWitSmallBuffer() throws Exception { String s = "10\r\n1234567890123456\r\n" + "40\r\n12345678901234561234567890123456" + "12345678901234561234567890123456\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); ByteBuffer tmp = ByteBuffer.allocate(10); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(tmp); if (i > 0) { bytesRead += i; tmp.flip(); dst.put(tmp); tmp.compact(); } } Assert.assertEquals(80, bytesRead); Assert.assertEquals("12345678901234561234567890123456" + "12345678901234561234567890123456" + "1234567890123456", convert(dst)); Assert.assertTrue(decoder.isCompleted()); }
#vulnerable code @Test public void testReadingWitSmallBuffer() throws Exception { String s = "10\r\n1234567890123456\r\n" + "40\r\n12345678901234561234567890123456" + "12345678901234561234567890123456\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); ByteBuffer tmp = ByteBuffer.allocate(10); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(tmp); if (i > 0) { bytesRead += i; tmp.flip(); dst.put(tmp); tmp.compact(); } } Assert.assertEquals(80, bytesRead); Assert.assertEquals("12345678901234561234567890123456" + "12345678901234561234567890123456" + "1234567890123456", convert(dst)); Assert.assertTrue(decoder.isCompleted()); } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; }
#vulnerable code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) this.request).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); ((HttpEntityEnclosingRequest) this.request).setEntity( new ContentBufferEntity(entity, this.buf)); } } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEntityWithMultipleContentLengthAllWrong() 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", "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.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); }
#vulnerable code @Test public void testEntityWithMultipleContentLengthAllWrong() 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", "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.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 25 #vulnerability type RESOURCE_LEAK