output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code @Test public void testGarbageCollectorExports() { assertEquals( 100L, registry.getSampleValue( "jvm_gc_collection_seconds_count", new String[]{"gc"}, new String[]{"MyGC1"}), .0000001); assertEquals( 10d, registry.getSampleValue( "jvm_gc_collection_seconds_sum", new String[]{"gc"}, new String[]{"MyGC1"}), .0000001); assertEquals( 200L, registry.getSampleValue( "jvm_gc_collection_seconds_count", new String[]{"gc"}, new String[]{"MyGC2"}), .0000001); assertEquals( 20d, registry.getSampleValue( "jvm_gc_collection_seconds_sum", new String[]{"gc"}, new String[]{"MyGC2"}), .0000001); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGarbageCollectorExports() { assertEquals( 100L, registry.getSampleValue( GarbageCollectorExports.COLLECTIONS_COUNT_METRIC, new String[]{"gc"}, new String[]{"MyGC1"}), .0000001); assertEquals( 10d, registry.getSampleValue( GarbageCollectorExports.COLLECTIONS_TIME_METRIC, new String[]{"gc"}, new String[]{"MyGC1"}), .0000001); assertEquals( 200L, registry.getSampleValue( GarbageCollectorExports.COLLECTIONS_COUNT_METRIC, new String[]{"gc"}, new String[]{"MyGC2"}), .0000001); assertEquals( 20d, registry.getSampleValue( GarbageCollectorExports.COLLECTIONS_TIME_METRIC, new String[]{"gc"}, new String[]{"MyGC2"}), .0000001); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private static void main(Config config, boolean taq) throws IOException { NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface"); InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group"); int multicastPort = Configs.getPort(config, "market-data.multicast-port"); InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address"); int requestPort = Configs.getPort(config, "market-data.request-port"); List<String> instruments = config.getStringList("instruments"); MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments); Market market = new Market(listener); for (String instrument : instruments) market.open(encodeLong(instrument)); MarketDataProcessor processor = new MarketDataProcessor(market, listener); MoldUDP64.receive(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort), new InetSocketAddress(requestAddress, requestPort), new PMDParser(processor)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void main(Config config, boolean taq) throws IOException { NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface"); InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group"); int multicastPort = Configs.getPort(config, "market-data.multicast-port"); InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address"); int requestPort = Configs.getPort(config, "market-data.request-port"); List<String> instruments = config.getStringList("instruments"); MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments); Market market = new Market(listener); for (String instrument : instruments) market.open(encodeLong(instrument)); MarketDataProcessor processor = new MarketDataProcessor(market, listener); MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort), new InetSocketAddress(requestAddress, requestPort), new PMDParser(processor)); transport.run(); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code private static void main(Config config, boolean taq) throws IOException { NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface"); InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group"); int multicastPort = Configs.getPort(config, "market-data.multicast-port"); InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address"); int requestPort = Configs.getPort(config, "market-data.request-port"); List<String> instruments = config.getStringList("instruments"); MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments); Market market = new Market(listener); for (String instrument : instruments) market.open(encodeLong(instrument)); MarketDataProcessor processor = new MarketDataProcessor(market, listener); MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort), new InetSocketAddress(requestAddress, requestPort), new PMDParser(processor)); while (true) transport.receive(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void main(Config config, boolean taq) throws IOException { NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface"); InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group"); int multicastPort = Configs.getPort(config, "market-data.multicast-port"); InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address"); int requestPort = Configs.getPort(config, "market-data.request-port"); List<String> instruments = config.getStringList("instruments"); MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments); MarketDataClient client = MarketDataClient.open(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort), new InetSocketAddress(requestAddress, requestPort), instruments, listener); while (true) client.receive(); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void run() throws IOException { LineReader reader = LineReaderBuilder.builder() .completer(new StringsCompleter(Commands.names().castToList())) .build(); printf("Type 'help' for help.\n"); while (!closed) { String line = reader.readLine("> "); if (line == null) break; Scanner scanner = scan(line); if (!scanner.hasNext()) continue; Command command = Commands.find(scanner.next()); if (command == null) { printf("error: Unknown command\n"); continue; } try { command.execute(this, scanner); } catch (CommandException e) { printf("Usage: %s\n", command.getUsage()); } catch (ClosedChannelException e) { printf("error: Connection closed\n"); } } close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() throws IOException { ConsoleReader reader = new ConsoleReader(); reader.addCompleter(new StringsCompleter(Commands.names().castToList())); printf("Type 'help' for help.\n"); while (!closed) { String line = reader.readLine("> "); if (line == null) break; Scanner scanner = scan(line); if (!scanner.hasNext()) continue; Command command = Commands.find(scanner.next()); if (command == null) { printf("error: Unknown command\n"); continue; } try { command.execute(this, scanner); } catch (CommandException e) { printf("Usage: %s\n", command.getUsage()); } catch (ClosedChannelException e) { printf("error: Connection closed\n"); } } close(); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { return loadPlugin(file, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { JavaPlugin result = null; PluginDescriptionFile description = null; if (!file.exists()) { throw new InvalidPluginException(new FileNotFoundException(String.format("%s does not exist", file.getPath()))); } try { JarFile jar = new JarFile(file); JarEntry entry = jar.getJarEntry("plugin.yml"); if (entry == null) { throw new InvalidPluginException(new FileNotFoundException("Jar does not contain plugin.yml")); } InputStream stream = jar.getInputStream(entry); description = new PluginDescriptionFile(stream); stream.close(); jar.close(); } catch (IOException ex) { throw new InvalidPluginException(ex); } catch (YAMLException ex) { throw new InvalidPluginException(ex); } File dataFolder = new File(file.getParentFile(), description.getName()); File oldDataFolder = getDataFolder(file); // Found old data folder if (dataFolder.equals(oldDataFolder)) { // They are equal -- nothing needs to be done! } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) { server.getLogger().log( Level.INFO, String.format( "While loading %s (%s) found old-data folder: %s next to the new one: %s", description.getName(), file, oldDataFolder, dataFolder )); } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) { if (!oldDataFolder.renameTo(dataFolder)) { throw new InvalidPluginException(new Exception("Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'")); } server.getLogger().log( Level.INFO, String.format( "While loading %s (%s) renamed data folder: '%s' to '%s'", description.getName(), file, oldDataFolder, dataFolder )); } if (dataFolder.exists() && !dataFolder.isDirectory()) { throw new InvalidPluginException(new Exception(String.format( "Projected datafolder: '%s' for %s (%s) exists and is not a directory", dataFolder, description.getName(), file ))); } ArrayList<String> depend; try { depend = (ArrayList)description.getDepend(); if(depend == null) { depend = new ArrayList<String>(); } } catch (ClassCastException ex) { throw new InvalidPluginException(ex); } for(String pluginName : depend) { if(loaders == null) { throw new UnknownDependencyException(pluginName); } PluginClassLoader current = loaders.get(pluginName); if(current == null) { throw new UnknownDependencyException(pluginName); } } PluginClassLoader loader = null; try { URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); loader = new PluginClassLoader(this, urls, getClass().getClassLoader()); Class<?> jarClass = Class.forName(description.getMain(), true, loader); Class<? extends JavaPlugin> plugin = jarClass.asSubclass(JavaPlugin.class); Constructor<? extends JavaPlugin> constructor = plugin.getConstructor(); result = constructor.newInstance(); result.initialize(this, server, description, dataFolder, file, loader); } catch (Throwable ex) { throw new InvalidPluginException(ex); } loaders.put(description.getName(), (PluginClassLoader)loader); return (Plugin)result; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code int shared_cache(boolean enable) throws SQLException { // The shared cache is per-process, so it is useless as // each nested connection is its own process. return -1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code int enable_load_extension(boolean enable) throws SQLException { return call("sqlite3_enable_load_extension", handle, enable ? 1 : 0); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { osArch = resolveArmArchType(); } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getArchName() { String osArch = System.getProperty("os.arch"); if(osArch.startsWith("arm")) { // Java 1.8 introduces a system property to determine armel or armhf if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) { return translateArchNameToFolderName("armhf"); } // For java7, we stil need to if run some shell commands to determine ABI of JVM if(System.getProperty("os.name").contains("Linux")) { String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI int exitCode = Runtime.getRuntime().exec("which readelf").waitFor(); if(exitCode == 0) { String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return translateArchNameToFolderName("armhf"); } } else { System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " + "armel architecture will be presumed."); } } catch(IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch(InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } } else { String lc = osArch.toLowerCase(Locale.US); if(archMapping.containsKey(lc)) return archMapping.get(lc); } return translateArchNameToFolderName(osArch); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean execute(String sql) throws SQLException { internalClose(); SQLExtension ext = ExtendedCommand.parse(sql); if (ext != null) { ext.execute(db); return false; } this.sql = sql; db.prepare(this); return exec(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean execute(String sql) throws SQLException { internalClose(); SQLExtension ext = ExtendedCommand.parse(sql); if (ext != null) { ext.execute(db); return false; } this.sql = sql; boolean success = false; try { db.prepare(this); final boolean result = exec(); success = true; return result; } finally { if (!success) { internalClose(); } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void TestEscSlashLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestEscSlashLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140))); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void TestGeomFirst() throws Exception { Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestGeomFirst() throws IOException { Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54))); Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54))); Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true)); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void TestEscPoints() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestEscPoints() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true)); Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true)); Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true)); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void TestArbitrarySplitLocations() throws Exception { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestArbitrarySplitLocations() throws IOException { //int totalSize = 415; //int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41))); Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123))); Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123))); Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123))); Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415))); Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415))); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void TestEscAposLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestEscAposLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void TestNullGeom() throws Exception { ArrayList<Object> stuff = new ArrayList<Object>(); Properties proptab = new Properties(); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "shape"); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "binary"); SerDe jserde = mkSerDe(proptab); StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector(); //value.set("{\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[15.0,5.0]}}"); addWritable(stuff, new Point(15.0, 5.0)); Object row = runSerDe(stuff, jserde, rowOI); Object fieldData = getField("shape", row, rowOI); ckPoint(new Point(15.0, 5.0), (BytesWritable)fieldData); //value.set("{\"properties\":{},\"coordinates\":null}"); stuff.set(0, null); row = runSerDe(stuff, jserde, rowOI); fieldData = getField("shape", row, rowOI); Assert.assertNull(fieldData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestNullGeom() throws Exception { Configuration config = new Configuration(); Text value = new Text(); SerDe jserde = new GeoJsonSerDe(); Properties proptab = new Properties(); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "shape"); proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "binary"); jserde.initialize(config, proptab); StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector(); value.set("{\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[15.0,5.0]}}"); Object row = jserde.deserialize(value); StructField f0 = rowOI.getStructFieldRef("shape"); Object fieldData = rowOI.getStructFieldData(row, f0); ckPoint(new Point(15.0, 5.0), (BytesWritable)fieldData); value.set("{\"properties\":{},\"coordinates\":null}"); row = jserde.deserialize(value); f0 = rowOI.getStructFieldRef("shape"); fieldData = rowOI.getStructFieldData(row, f0); Assert.assertEquals(null, fieldData); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void TestEscOpenLast() throws Exception { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 44, 140))); Assert.assertArrayEquals(new int[] { 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 268, 280))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void TestEscOpenLast() throws IOException { //int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , }; Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 44))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 45))); Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 0, 46))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 19, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 26, 140))); Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 44, 140))); Assert.assertArrayEquals(new int[] { 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc5.json", 268, 280))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public SmsAlphabet getAlphabet() { switch (getGroup()) { case GENERAL_DATA_CODING: // General Data Coding Indication if (dcs_ == 0x00) { return SmsAlphabet.ASCII; } switch (dcs_ & 0x0C) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; case 0x08: return SmsAlphabet.UCS2; case 0x0C: return SmsAlphabet.RESERVED; default: return SmsAlphabet.UCS2; } case MESSAGE_WAITING_STORE_GSM: return SmsAlphabet.ASCII; case MESSAGE_WAITING_STORE_UCS2: return SmsAlphabet.UCS2; case DATA_CODING_MESSAGE: switch (dcs_ & 0x04) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; default: return SmsAlphabet.UCS2; } default: return SmsAlphabet.UCS2; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SmsAlphabet getAlphabet() { switch (getGroup()) { case GENERAL_DATA_CODING: // General Data Coding Indication if (dcs_ == 0x00) { return SmsAlphabet.ASCII; } switch (dcs_ & 0x0C) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; case 0x08: return SmsAlphabet.UCS2; case 0x0C: return SmsAlphabet.RESERVED; default: return null; } case MESSAGE_WAITING_STORE_GSM: return SmsAlphabet.ASCII; case MESSAGE_WAITING_STORE_UCS2: return SmsAlphabet.UCS2; case DATA_CODING_MESSAGE: switch (dcs_ & 0x04) { case 0x00: return SmsAlphabet.ASCII; case 0x04: return SmsAlphabet.LATIN1; default: return null; } default: return null; } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code void startRebalancingTimer(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting timer at period " + period); if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); } _rebalanceTimer = new Timer(true); _timerPeriod = period; _rebalanceTimer .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); } else { logger.info("Controller already has timer at period " + _timerPeriod); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void stopRebalancingTimer() { if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); _rebalanceTimer = null; } _timerPeriod = Integer.MAX_VALUE; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { validateCurrentThread(); Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); LOG.debug("Waiting for keeper state " + keeperState); acquireEventLock(); try { boolean stillWaiting = true; while (_currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); } LOG.debug("State is " + (_currentState == null ? "CLOSED" : _currentState)); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); } Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); LOG.debug("Waiting for keeper state " + keeperState); acquireEventLock(); try { boolean stillWaiting = true; while (_currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); } LOG.debug("State is " + (_currentState == null ? "CLOSED" : _currentState)); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void disconnect() { if (!isConnected()) { logger.error("ClusterManager " + _instanceName + " already disconnected"); return; } disconnectInternal(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void disconnect() { if (!isConnected()) { logger.warn("ClusterManager " + _instanceName + " already disconnected"); return; } logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutDown(); resetHandlers(); _helixAccessor.shutdown(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } if (_participantHealthCheckInfoCollector != null) { _participantHealthCheckInfoCollector.stop(); } if (_timer != null) { _timer.cancel(); _timer = null; } if (_instanceType == InstanceType.CONTROLLER) { stopTimerTasks(); } // unsubscribe accessor from controllerChange _zkClient.unsubscribeAll(); _zkClient.close(); // HACK seems that zkClient is not sending DISCONNECT event _zkStateChangeListener.disconnect(); logger.info("Cluster manager: " + _instanceName + " disconnected"); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void handleChildChange(String parentPath, List<String> currentChilds) { if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) { return; } // Resubscribe _zkClientForRoutingDataListener.unsubscribeAll(); _zkClientForRoutingDataListener.subscribeRoutingDataChanges(this, this); resetZkResources(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handleChildChange(String parentPath, List<String> currentChilds) { if (_zkClientForListener == null || _zkClientForListener.isClosed()) { return; } // Resubscribe _zkClientForListener.unsubscribeAll(); _zkClientForListener.subscribeRoutingDataChanges(this, this); resetZkResources(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected static Set<String> getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext) { Set<String> expiredJobs = new HashSet<String>(); if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); if (jobConfig == null) { LOG.error(String.format("Job %s exists in JobDAG but JobConfig is missing!", job)); continue; } long expiry = jobConfig.getExpiry(); if (expiry == workflowConfig.DEFAULT_EXPIRY || expiry < 0) { expiry = workflowConfig.getExpiry(); } if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } } return expiredJobs; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected static Set<String> getExpiredJobs(HelixDataAccessor dataAccessor, HelixPropertyStore propertyStore, WorkflowConfig workflowConfig, WorkflowContext workflowContext) { Set<String> expiredJobs = new HashSet<String>(); if (workflowContext != null) { Map<String, TaskState> jobStates = workflowContext.getJobStates(); for (String job : workflowConfig.getJobDag().getAllNodes()) { JobConfig jobConfig = TaskUtil.getJobConfig(dataAccessor, job); JobContext jobContext = TaskUtil.getJobContext(propertyStore, job); long expiry = jobConfig.getExpiry(); if (expiry == workflowConfig.DEFAULT_EXPIRY || expiry < 0) { expiry = workflowConfig.getExpiry(); } if (jobContext != null && jobStates.get(job) == TaskState.COMPLETED) { if (System.currentTimeMillis() >= jobContext.getFinishTime() + expiry) { expiredJobs.add(job); } } } } return expiredJobs; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code void addControllerMessageListener(MessageListener listener) { addListener(listener, new Builder(_clusterName).controllerMessages(), ChangeType.MESSAGES_CONTROLLER, new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void disconnectInternal() { // This function can be called when the connection are in bad state(e.g. flapping), // in which isConnected() could be false and we want to disconnect from cluster. logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); /** * shutdown thread pool first to avoid reset() being invoked in the middle of state * transition */ _messagingService.getExecutor().shutdown(); resetHandlers(); _helixAccessor.shutdown(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(); } if (_participantHealthCheckInfoCollector != null) { _participantHealthCheckInfoCollector.stop(); } if (_timer != null) { _timer.cancel(); _timer = null; } if (_instanceType == InstanceType.CONTROLLER) { stopTimerTasks(); } // unsubscribe accessor from controllerChange _zkClient.unsubscribeAll(); _zkClient.close(); // HACK seems that zkClient is not sending DISCONNECT event _zkStateChangeListener.disconnect(); logger.info("Cluster manager: " + _instanceName + " disconnected"); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void handleNewSession(String sessionId) { if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) { return; } // Resubscribe _zkClientForRoutingDataListener.unsubscribeAll(); _zkClientForRoutingDataListener.subscribeRoutingDataChanges(this, this); resetZkResources(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handleNewSession(String sessionId) { if (_zkClientForListener == null || _zkClientForListener.isClosed()) { return; } // Resubscribe _zkClientForListener.unsubscribeAll(); _zkClientForListener.subscribeRoutingDataChanges(this, this); resetZkResources(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testConsumerStartWithInterval() { int msgSize = 100; String originMsgDCName = RandomUtils.getStringByUUID(); String msgBodyDCName = RandomUtils.getStringByUUID(); RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag, new RMQNormalListner(originMsgDCName, msgBodyDCName)); producer.send(tag, msgSize, 100); TestUtils.waitForMoment(5); getConsumer(nsAddr, consumer1.getConsumerGroup(), tag, new RMQNormalListner(originMsgDCName, msgBodyDCName)); TestUtils.waitForMoment(5); consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime); assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(), consumer1.getListner().getAllMsgBody())) .containsExactlyElementsIn(producer.getAllMsgBody()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConsumerStartWithInterval() { String tag = "jueyin"; int msgSize = 100; String originMsgDCName = RandomUtils.getStringByUUID(); String msgBodyDCName = RandomUtils.getStringByUUID(); RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag, new RMQNormalListner(originMsgDCName, msgBodyDCName)); producer.send(tag, msgSize, 100); TestUtils.waitForMoment(5); RMQNormalConsumer consumer2 = getConsumer(nsAddr, consumer1.getConsumerGroup(), tag, new RMQNormalListner(originMsgDCName, msgBodyDCName)); TestUtils.waitForMoment(5); consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime); assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(), consumer1.getListner().getAllMsgBody())) .containsExactlyElementsIn(producer.getAllMsgBody()); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code public void executeSendMessageHookBefore(final ChannelHandlerContext ctx, final RemotingCommand request, SendMessageContext context) { if (hasSendMessageHook()) { for (SendMessageHook hook : this.sendMessageHookList) { try { final SendMessageRequestHeader requestHeader = parseRequestHeader(request); if (null != requestHeader) { context.setProducerGroup(requestHeader.getProducerGroup()); context.setTopic(requestHeader.getTopic()); context.setBodyLength(request.getBody().length); context.setMsgProps(requestHeader.getProperties()); context.setBornHost(RemotingHelper.parseChannelRemoteAddr(ctx.channel())); context.setBrokerAddr(this.brokerController.getBrokerAddr()); context.setQueueId(requestHeader.getQueueId()); } hook.sendMessageBefore(context); if (requestHeader != null) { requestHeader.setProperties(context.getMsgProps()); } } catch (Throwable e) { // Ignore } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void executeSendMessageHookBefore(final ChannelHandlerContext ctx, final RemotingCommand request, SendMessageContext context) { if (hasSendMessageHook()) { for (SendMessageHook hook : this.sendMessageHookList) { try { final SendMessageRequestHeader requestHeader = parseRequestHeader(request); if (null != requestHeader) { context.setProducerGroup(requestHeader.getProducerGroup()); context.setTopic(requestHeader.getTopic()); context.setBodyLength(request.getBody().length); context.setMsgProps(requestHeader.getProperties()); context.setBornHost(RemotingHelper.parseChannelRemoteAddr(ctx.channel())); context.setBrokerAddr(this.brokerController.getBrokerAddr()); context.setQueueId(requestHeader.getQueueId()); } hook.sendMessageBefore(context); requestHeader.setProperties(context.getMsgProps()); } catch (Throwable e) { } } } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testIPv6Check() throws UnknownHostException { InetAddress nonInternal = InetAddress.getByName("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A"); InetAddress internal = InetAddress.getByName("FE80:0000:0000:0000:0000:0000:0000:FFFF"); assertThat(UtilAll.isInternalV6IP(nonInternal)).isFalse(); assertThat(UtilAll.isInternalV6IP(internal)).isTrue(); assertThat(UtilAll.ipToIPv6Str(nonInternal.getAddress()).toUpperCase()).isEqualTo("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIPv6Check() { byte[] nonInternalIp = UtilAll.string2bytes("24084004018081003FAA1DDE2B3F898A"); byte[] internalIp = UtilAll.string2bytes("FEC0000000000000000000000000FFFF"); assertThat(UtilAll.isInternalV6IP(nonInternalIp)).isFalse(); assertThat(UtilAll.isInternalV6IP(internalIp)).isTrue(); assertThat(UtilAll.ipToIPv6Str(nonInternalIp).toUpperCase()).isEqualTo("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A"); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void threadDumpIfNeed(String reasonMsg) { if (!enable) { return; } synchronized (this) { if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) { return; } else { lastThreadDumpTime = System.currentTimeMillis(); } } logger.info("Thread dump by ThreadDumpper" + (reasonMsg != null ? (" for " + reasonMsg) : "")); Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); // 两条日志间的时间间隔,是VM被thread dump堵塞的时间. logger.info("Finish the threads snapshot"); StringBuilder sb = new StringBuilder(8192 * 20).append("\n"); for (Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) { dumpThreadInfo(entry.getKey(), entry.getValue(), sb); } logger.info(sb.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void threadDumpIfNeed(String reasonMsg) { if (!enable) { return; } synchronized (this) { if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) { return; } else { lastThreadDumpTime = System.currentTimeMillis(); } } logger.info("Thread dump by ThreadDumpper" + reasonMsg != null ? (" for " + reasonMsg) : ""); // 参数均为false, 避免输出lockedMonitors和lockedSynchronizers导致的JVM缓慢 ThreadInfo[] threadInfos = threadMBean.dumpAllThreads(false, false); StringBuilder b = new StringBuilder(8192); b.append('['); for (int i = 0; i < threadInfos.length; i++) { b.append(dumpThreadInfo(threadInfos[i])).append(", "); } // 两条日志间的时间间隔,是VM被thread dump堵塞的时间. logger.info(b.toString()); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void printCounter(CounterMetric counter) { output.printf(" last count = %d%n", counter.lastCount); output.printf(" total count = %d%n", counter.totalCount); output.printf(" last rate = %d%n", counter.lastRate); output.printf(" mean rate = %d%n", counter.meanRate); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void printCounter(CounterMetric counter) { output.printf(" last count = %d%n", counter.lastCount); output.printf(" total count = %d%n", counter.totalCount); output.printf(" last rate = %2.2f/s%n", counter.lastRate); output.printf(" mean rate = %2.2f/s%n", counter.meanRate); } #location 5 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public OutputStream writeBoolean(boolean value) throws IOException { write(value ? booleanTrue : booleanFalse); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public OutputStream writeBoolean(boolean value) throws IOException { write(getIsoBytes(String.valueOf(value))); return this; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void outlinesTest() throws IOException, PdfException { PdfReader reader = new PdfReader(new FileInputStream(sourceFolder+"iphone_user_guide.pdf")); PdfDocument pdfDoc = new PdfDocument(reader); PdfOutline outlines = pdfDoc.getOutlines(false); List<PdfOutline> children = outlines.getAllChildren().get(0).getAllChildren(); Assert.assertEquals(outlines.getTitle(), "Outlines"); Assert.assertEquals(children.size(), 13); Assert.assertTrue(children.get(0).getDestination() instanceof PdfStringDestination); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void outlinesTest() throws IOException, PdfException { PdfReader reader = new PdfReader(new FileInputStream(sourceFolder+"iphone_user_guide.pdf")); PdfDocument pdfDoc = new PdfDocument(reader); PdfOutline outlines = pdfDoc.getCatalog().getOutlines(); List<PdfOutline> children = outlines.getAllChildren().get(0).getAllChildren(); Assert.assertEquals(outlines.getTitle(), "Outlines"); Assert.assertEquals(children.size(), 13); Assert.assertTrue(children.get(0).getDestination() instanceof PdfStringDestination); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void imageTest05() throws IOException, InterruptedException { String outFileName = destinationFolder + "imageTest05.pdf"; String cmpFileName = sourceFolder + "cmp_imageTest05.pdf"; FileOutputStream file = new FileOutputStream(outFileName); PdfWriter writer = new PdfWriter(file); PdfDocument pdfDoc = new PdfDocument(writer); Document doc = new Document(pdfDoc); PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); Image image = new Image(xObject, 100); doc.add(new Paragraph(new Text("First Line"))); Paragraph p = new Paragraph(); p.add(image); image.scale(1, 0.5f); doc.add(p); doc.add(new Paragraph(new Text("Second Line"))); doc.close(); Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void imageTest05() throws IOException, InterruptedException { String outFileName = destinationFolder + "imageTest05.pdf"; String cmpFileName = sourceFolder + "cmp_imageTest05.pdf"; FileOutputStream file = new FileOutputStream(outFileName); PdfWriter writer = new PdfWriter(file); PdfDocument pdfDoc = new PdfDocument(writer); Document doc = new Document(pdfDoc); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg"); nRead = is.read(); while (nRead != -1){ buffer.write(nRead); nRead = is.read(); } PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray())); Image image = new Image(xObject, 100); doc.add(new Paragraph(new Text("First Line"))); Paragraph p = new Paragraph(); p.add(image); image.scale(1, 0.5f); doc.add(p); doc.add(new Paragraph(new Text("Second Line"))); doc.close(); Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code @Override public LayoutResult layout(LayoutContext layoutContext) { LayoutArea area = layoutContext.getArea(); Rectangle layoutBox = area.getBBox(); occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0)); width = getPropertyAsFloat(Property.WIDTH); Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE); PdfXObject xObject = ((Image) (getModelElement())).getXObject(); imageWidth = xObject.getWidth(); imageHeight = xObject.getHeight(); width = width == null ? imageWidth : width; height = width / imageWidth * imageHeight; fixedXPosition = getPropertyAsFloat(Property.X); fixedYPosition = getPropertyAsFloat(Property.Y); Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING); Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING); AffineTransform t = new AffineTransform(); if (xObject instanceof PdfFormXObject && width != imageWidth) { horizontalScaling *= width / imageWidth; verticalScaling *= height / imageHeight; } if (horizontalScaling != 1) { if (xObject instanceof PdfFormXObject) { t.scale(horizontalScaling, 1); } width *= horizontalScaling; } if (verticalScaling != 1) { if (xObject instanceof PdfFormXObject) { t.scale(1, verticalScaling); } height *= verticalScaling; } float imageItselfScaledWidth = width; float imageItselfScaledHeight = height; if (angle != null) { t.rotate(angle); adjustPositionAfterRotation(angle); } getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); if (width > layoutBox.getWidth()){ return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); } if (height > layoutBox.getHeight()){ return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); } occupiedArea.getBBox().moveDown(height); occupiedArea.getBBox().setHeight(height); occupiedArea.getBBox().setWidth(width); Float mx = getProperty(Property.X_DISTANCE); Float my = getProperty(Property.Y_DISTANCE); if (mx != null && my != null) { translateImage(mx, my, t); getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); } if (fixedXPosition != null && fixedYPosition != null) { occupiedArea.getBBox().setWidth(0); occupiedArea.getBBox().setHeight(0); } return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public LayoutResult layout(LayoutContext layoutContext) { LayoutArea area = layoutContext.getArea(); Rectangle layoutBox = area.getBBox(); occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0)); width = getPropertyAsFloat(Property.WIDTH); Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE); PdfXObject xObject = ((Image) (getModelElement())).getXObject(); if (xObject instanceof PdfImageXObject) { imageWidth = ((PdfImageXObject)xObject).getWidth(); imageHeight = ((PdfImageXObject)xObject).getHeight(); } else { imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2); imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3); } width = width == null ? imageWidth : width; height = width / imageWidth * imageHeight; fixedXPosition = getPropertyAsFloat(Property.X); fixedYPosition = getPropertyAsFloat(Property.Y); Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING); Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING); AffineTransform t = new AffineTransform(); if (xObject instanceof PdfFormXObject && width != imageWidth) { horizontalScaling *= width / imageWidth; verticalScaling *= height / imageHeight; } if (horizontalScaling != 1) { if (xObject instanceof PdfFormXObject) { t.scale(horizontalScaling, 1); } width *= horizontalScaling; } if (verticalScaling != 1) { if (xObject instanceof PdfFormXObject) { t.scale(1, verticalScaling); } height *= verticalScaling; } float imageItselfScaledWidth = width; float imageItselfScaledHeight = height; if (angle != null) { t.rotate(angle); adjustPositionAfterRotation(angle); } getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); if (width > layoutBox.getWidth()){ return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); } if (height > layoutBox.getHeight()){ return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this); } occupiedArea.getBBox().moveDown(height); occupiedArea.getBBox().setHeight(height); occupiedArea.getBBox().setWidth(width); Float mx = getProperty(Property.X_DISTANCE); Float my = getProperty(Property.Y_DISTANCE); if (mx != null && my != null) { translateImage(mx, my, t); getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight); } if (fixedXPosition != null && fixedYPosition != null) { occupiedArea.getBBox().setWidth(0); occupiedArea.getBBox().setHeight(0); } return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code protected int writeXRefTable() throws IOException, PdfException { int strtxref = currentPos; if (fullCompression) { PdfStream stream = new PdfStream(pdfDocument); stream.put(PdfName.Type, PdfName.XRef); stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1)); stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{ add(new PdfNumber(1)); add(new PdfNumber(4)); add(new PdfNumber(2)); }})); stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo()); stream.put(PdfName.Root, pdfDocument.trailer.getCatalog()); stream.getOutputStream().write(0); stream.getOutputStream().write(intToBytes(0)); stream.getOutputStream().write(shortToBytes(0xFFFF)); for (PdfIndirectReference indirect : pdfDocument.getIndirects()) { if (indirect.getObjectStreamNumber() == 0) { stream.getOutputStream().write(1); stream.getOutputStream().write(intToBytes(indirect.getOffset())); stream.getOutputStream().write(shortToBytes(0)); } else { stream.getOutputStream().write(2); stream.getOutputStream().write(intToBytes(indirect.getObjectStreamNumber())); stream.getOutputStream().write(shortToBytes(indirect.getIndex())); } } stream.flush(); } else { writeString("xref\n"). writeString("0 "). writeInteger(pdfDocument.getIndirects().size() + 1). writeString("\n0000000000 65535 f \n"); for (PdfIndirectReference indirect : pdfDocument.getIndirects()) { writeString(objectOffsetFormatter.format(indirect.getOffset())). writeBytes(endXRefEntry); } } return strtxref; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected int writeXRefTable() throws IOException, PdfException { int strtxref = currentPos; if (fullCompression) { PdfStream stream = new PdfStream(pdfDocument); stream.put(PdfName.Type, PdfName.XRef); stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1)); stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{ add(new PdfNumber(1)); add(new PdfNumber(4)); add(new PdfNumber(2)); }})); stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo()); stream.put(PdfName.Root, pdfDocument.trailer.getCatalog()); stream.getOutputStream().write(0); stream.getOutputStream().write(intToBytes(0)); stream.getOutputStream().write(shortToBytes(0xFFFF)); for (PdfIndirectReference indirect : pdfDocument.getIndirects()) { if (indirect.getObjectStream() != null) { stream.getOutputStream().write(2); stream.getOutputStream().write(intToBytes(indirect.getObjectStream().getIndirectReference().getObjNr())); stream.getOutputStream().write(shortToBytes(indirect.getOffset())); } else { stream.getOutputStream().write(1); stream.getOutputStream().write(intToBytes(indirect.getOffset())); stream.getOutputStream().write(shortToBytes(0)); } } stream.flush(); } else { writeString("xref\n"). writeString("0 "). writeInteger(pdfDocument.getIndirects().size() + 1). writeString("\n0000000000 65535 f \n"); for (PdfIndirectReference indirect : pdfDocument.getIndirects()) { writeString(objectOffsetFormatter.format(indirect.getOffset())). writeBytes(endXRefEntry); } } return strtxref; } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void imageTest04() throws IOException, InterruptedException { String outFileName = destinationFolder + "imageTest04.pdf"; String cmpFileName = sourceFolder + "cmp_imageTest04.pdf"; FileOutputStream file = new FileOutputStream(outFileName); PdfWriter writer = new PdfWriter(file); PdfDocument pdfDoc = new PdfDocument(writer); Document doc = new Document(pdfDoc); PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL())); Image image = new Image(xObject, 100); Paragraph p = new Paragraph(); p.add(new Text("before image")); p.add(image); image.setRotateAngle(Math.PI/6); p.add(new Text("after image")); doc.add(p); doc.close(); Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void imageTest04() throws IOException, InterruptedException { String outFileName = destinationFolder + "imageTest04.pdf"; String cmpFileName = sourceFolder + "cmp_imageTest04.pdf"; FileOutputStream file = new FileOutputStream(outFileName); PdfWriter writer = new PdfWriter(file); PdfDocument pdfDoc = new PdfDocument(writer); Document doc = new Document(pdfDoc); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg"); nRead = is.read(); while (nRead != -1){ buffer.write(nRead); nRead = is.read(); } PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray())); Image image = new Image(xObject, 100); Paragraph p = new Paragraph(); p.add(new Text("before image")); p.add(image); image.setRotateAngle(Math.PI/6); p.add(new Text("after image")); doc.add(p); doc.close(); Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff")); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public OutputStream writeInteger(int value) throws IOException { writeInteger(value, 8); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public OutputStream writeInteger(int value) throws IOException { write(getIsoBytes(String.valueOf(value))); return this; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static NSObject parse(File f) throws Exception { FileInputStream fis = new FileInputStream(f); return parse(fis); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static NSObject parse(File f) throws Exception { FileInputStream fis = new FileInputStream(f); byte[] magic = new byte[8]; fis.read(magic); String magic_string = new String(magic); fis.close(); if (magic_string.startsWith("bplist00")) { return BinaryPropertyListParser.parse(f); } else if (magic_string.startsWith("<?xml")) { return XMLPropertyListParser.parse(f); } else { throw new UnsupportedOperationException("The given file is neither a binary nor a XML property list. ASCII property lists are not supported."); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void runTagger() throws IOException, ClassNotFoundException { tagger = new Tagger(); if (!justTokenize) { tagger.loadModel(modelFilename); } if (inputFormat.equals("conll")) { runTaggerInEvalMode(); return; } assert (inputFormat.equals("json") || inputFormat.equals("text")); JsonTweetReader jsonTweetReader = new JsonTweetReader(); LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename)); String line; long currenttime = System.currentTimeMillis(); int numtoks = 0; while ( (line = reader.readLine()) != null) { String[] parts = line.split("\t"); String tweetData = parts[inputField-1]; if (reader.getLineNumber()==1) { if (inputFormat.equals("auto")) { detectAndSetInputFormat(tweetData); } } String text; if (inputFormat.equals("json")) { text = jsonTweetReader.getText(tweetData); if (text==null) { System.err.println("Warning, null text (JSON parse error?), using blank string instead"); text = ""; } } else { text = tweetData; } Sentence sentence = new Sentence(); sentence.tokens = Twokenize.tokenizeRawTweetText(text); ModelSentence modelSentence = null; if (sentence.T() > 0 && !justTokenize) { modelSentence = new ModelSentence(sentence.T()); tagger.featureExtractor.computeFeatures(sentence, modelSentence); goDecode(modelSentence); } if (outputFormat.equals("conll")) { outputJustTagging(sentence, modelSentence); } else { outputPrependedTagging(sentence, modelSentence, justTokenize, line); } numtoks += sentence.T(); } long finishtime = System.currentTimeMillis(); System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n", justTokenize ? "" : " and tagged", reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0, reader.getLineNumber() / ((finishtime-currenttime)/1000.0), numtoks / ((finishtime-currenttime)/1000.0) ); reader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void runTagger() throws IOException, ClassNotFoundException { tagger = new Tagger(); if (!justTokenize) { tagger.loadModel(modelFilename); } if (inputFormat.equals("conll")) { runTaggerInEvalMode(); return; } assert (inputFormat.equals("json") || inputFormat.equals("text")); JsonTweetReader jsonTweetReader = new JsonTweetReader(); LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename)); String line; long currenttime = System.currentTimeMillis(); int numtoks = 0; while ( (line = reader.readLine()) != null) { String[] parts = line.split("\t"); String tweetData = parts[inputField-1]; String text; if (inputFormat.equals("json")) { text = jsonTweetReader.getText(tweetData); } else { text = tweetData; } Sentence sentence = new Sentence(); sentence.tokens = Twokenize.tokenizeRawTweetText(text); ModelSentence modelSentence = null; if (sentence.T() > 0 && !justTokenize) { modelSentence = new ModelSentence(sentence.T()); tagger.featureExtractor.computeFeatures(sentence, modelSentence); goDecode(modelSentence); } if (outputFormat.equals("conll")) { outputJustTagging(sentence, modelSentence); } else { outputPrependedTagging(sentence, modelSentence, justTokenize, tweetData); } numtoks += sentence.T(); } long finishtime = System.currentTimeMillis(); System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n", justTokenize ? "" : " and tagged", reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0, reader.getLineNumber() / ((finishtime-currenttime)/1000.0), numtoks / ((finishtime-currenttime)/1000.0) ); reader.close(); } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code public static ArrayList<Sentence> readFile(String filename) throws IOException { BufferedReader reader = BasicFileIO.openFileToReadUTF8(filename); ArrayList sentences = new ArrayList<String>(); ArrayList<String> curLines = new ArrayList<String>(); String line; while ( (line = reader.readLine()) != null ) { if (line.matches("^\\s*$")) { if (curLines.size() > 0) { // Flush sentences.add(sentenceFromLines(curLines)); curLines.clear(); } } else { curLines.add(line); } } if (curLines.size() > 0) { sentences.add(sentenceFromLines(curLines)); } return sentences; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ArrayList<Sentence> readFile(String filename) throws IOException { BufferedReader reader = BasicFileIO.openFileToRead(filename); ArrayList sentences = new ArrayList<String>(); ArrayList<String> curLines = new ArrayList<String>(); String line; while ( (line = reader.readLine()) != null ) { if (line.matches("^\\s*$")) { if (curLines.size() > 0) { // Flush sentences.add(sentenceFromLines(curLines)); curLines.clear(); } } else { curLines.add(line); } } if (curLines.size() > 0) { sentences.add(sentenceFromLines(curLines)); } return sentences; } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) { RedissonClient redisson = (RedissonClient) BeanManager.getBean(RedissonClient.class); RequestContext context = RequestContext.getCurrentContext(); if (shouldCache(context, headers, queryParams)) { RBucket<ApiResponse> rBucket = redisson.getBucket(createCacheKey(context, cacheName, headers, queryParams)); if (rBucket.get() == null) { context.put(CACHE_BUCKET, rBucket); context.put(CACHE_TIME_TO_LIVE, timeToLive); } else { ApiResponse response = rBucket.get(); helper.call().response().header().addAll(response.getHeaders()); helper.call().response().setBody(response.getBody()); helper.call().response().setStatus(response.getStatus()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) { Helper helper = new HelperImpl(); RedissonClient redisson = (RedissonClient) BeanManager.getBean(RedissonClient.class); RequestContext context = RequestContext.getCurrentContext(); if (shouldCache(context, headers, queryParams)) { RBucket<ApiResponse> rBucket = redisson.getBucket(createCacheKey(context, cacheName, headers, queryParams)); if (rBucket.get() == null) { context.put(CACHE_BUCKET, rBucket); context.put(CACHE_TIME_TO_LIVE, timeToLive); } else { ApiResponse response = rBucket.get(); helper.call().response().header().addAll(response.getHeaders()); helper.call().response().setBody(response.getBody()); helper.call().response().setStatus(response.getStatus()); } } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code private void load() throws IOException { if ( !knownHosts.exists() ) { return; } assertKnownHostFileReadable(); try ( BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ) ) { String line; while ( (line = reader.readLine()) != null ) { if ( (!line.trim().startsWith( "#" )) ) { String[] strings = line.split( " " ); if ( strings[0].trim().equals( serverId ) ) { // load the certificate fingerprint = strings[1].trim(); return; } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void load() throws IOException { if ( !knownHosts.exists() ) { return; } assertKnownHostFileReadable(); BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ); String line; while ( (line = reader.readLine()) != null ) { if ( (!line.trim().startsWith( "#" )) ) { String[] strings = line.split( " " ); if ( strings[0].trim().equals( serverId ) ) { // load the certificate fingerprint = strings[1].trim(); return; } } } reader.close(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test void shouldSaveNewCert() throws Throwable { // Given int newPort = 200; BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort ); Logger logger = mock(Logger.class); TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger ); String fingerprint = fingerprint( knownCertificate ); // When manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null ); // Then no exception should've been thrown, and we should've logged that we now trust this certificate verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" ); // And the file should contain the right info try ( Scanner reader = new Scanner( knownCertsFile ) ) { String line1 = nextLine( reader ); assertEquals( knownServer + " " + fingerprint, line1 ); assertTrue( reader.hasNextLine() ); String line2 = nextLine( reader ); assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line2 ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void shouldSaveNewCert() throws Throwable { // Given int newPort = 200; BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort ); Logger logger = mock(Logger.class); TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger ); String fingerprint = fingerprint( knownCertificate ); // When manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null ); // Then no exception should've been thrown, and we should've logged that we now trust this certificate verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" ); // And the file should contain the right info Scanner reader = new Scanner( knownCertsFile ); String line; line = nextLine( reader ); assertEquals( knownServer + " " + fingerprint, line ); assertTrue( reader.hasNextLine() ); line = nextLine( reader ); assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line ); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings( "ConstantConditions" ) @Test public void shouldHandleNullAuthToken() throws Throwable { // Given AuthToken token = null; try ( Driver driver = GraphDatabase.driver( neo4j.address(), token ) ) { Session session = driver.session(); // When session.close(); // Then assertFalse( session.isOpen() ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings( "ConstantConditions" ) @Test public void shouldHandleNullAuthToken() throws Throwable { // Given AuthToken token = null; Driver driver = GraphDatabase.driver( neo4j.address(), token); Session session = driver.session(); // When session.close(); // Then assertFalse( session.isOpen() ); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException { try ( BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ) ) { CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" ); int certCount = 0; // The file might contain multiple certs while ( inputStream.available() > 0 ) { try { Certificate cert = certFactory.generateCertificate( inputStream ); certCount++; loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore ); } catch ( CertificateException e ) { if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) ) { // This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a // second cert, at which point we fail return; } throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e ); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException { BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ); CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" ); int certCount = 0; // The file might contain multiple certs while ( inputStream.available() > 0 ) { try { Certificate cert = certFactory.generateCertificate( inputStream ); certCount++; loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore ); } catch ( CertificateException e ) { if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) ) { // This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a // second cert, at which point we fail return; } throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e ); } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test void shouldNotSendWriteAccessModeInStatementMetadata() throws Exception { StubServer server = StubServer.start( "hello_run_exit.script", 9001 ); try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", INSECURE_CONFIG ); Session session = driver.session( AccessMode.WRITE ) ) { List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() ); assertEquals( asList( "Foo", "Bar" ), names ); } finally { assertEquals( 0, server.exitStatus() ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void shouldNotSendWriteAccessModeInStatementMetadata() throws Exception { StubServer server = StubServer.start( "hello_run_exit.script", 9001 ); Config config = Config.builder() .withoutEncryption() .build(); try ( Driver driver = GraphDatabase.driver( "bolt://localhost:9001", config ); Session session = driver.session( AccessMode.WRITE ) ) { List<String> names = session.run( "MATCH (n) RETURN n.name" ).list( record -> record.get( 0 ).asString() ); assertEquals( asList( "Foo", "Bar" ), names ); } finally { assertEquals( 0, server.exitStatus() ); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public static String read(File file) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String ret = new String(new byte[0], "UTF-8"); String line; while ((line = in.readLine()) != null) { ret += line; } in.close(); return ret; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String read(File file) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); InputStream inStream = new FileInputStream(file); BufferedReader in = new BufferedReader(inputStreamToReader(inStream)); StringBuilder ret = new StringBuilder(); String line; while ((line = in.readLine()) != null) { ret.append(line); } in.close(); return ret.toString(); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code void findTarget(final String patFilename, final Location initOffset) { Thread thread = new Thread(new Runnable() { @Override public void run() { Region screenUnion = Region.create(0, 0, 1, 1); Finder f = new Finder(_simg, screenUnion); try { f.find(patFilename); if (f.hasNext()) { //TODO rewrite completely for ScreenUnion Screen s = (Screen) screenUnion.getScreen(); s.setAsScreenUnion(); _match = f.next(); s.setAsScreen(); if (initOffset != null) { setTarget(initOffset.x, initOffset.y); } else { setTarget(0, 0); } } _img = ImageIO.read(new File(patFilename)); } catch (IOException e) { Debug.error(me + "Can't load " + patFilename); } synchronized (PatternPaneTargetOffset.this) { _finding = false; } repaint(); } }); thread.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void paintLoading(Graphics2D g2d) { int w = getWidth(), h = getHeight(); g2d.setColor(new Color(0, 0, 0, 200)); g2d.fillRect(0, 0, w, h); BufferedImage spinner = _loading.getFrame(); g2d.drawImage(spinner, null, w / 2 - spinner.getWidth() / 2, h / 2 - spinner.getHeight() / 2); repaint(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed { lastMatches = null; Image img = null; String targetStr = target.toString(); if (target instanceof String) { targetStr = targetStr.trim(); } while (true) { try { if (autoWaitTimeout > 0) { RepeatableFindAll rf = new RepeatableFindAll(target); rf.repeat(autoWaitTimeout); lastMatches = rf.getMatches(); } else { lastMatches = doFindAll(target, null); } } catch (Exception ex) { if (ex instanceof IOException) { if (handleImageMissing(img, false)) { continue; } } throw new FindFailed(ex.getMessage()); } if (lastMatches != null) { return lastMatches; } if (!handleFindFailed(target, img)) { return null; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <PSI> Iterator<Match> findAll(PSI target) throws FindFailed { lastMatches = null; Image img = null; String targetStr = target.toString(); if (target instanceof String) { targetStr = targetStr.trim(); } while (true) { try { if (autoWaitTimeout > 0) { RepeatableFindAll rf = new RepeatableFindAll(target); rf.repeat(autoWaitTimeout); lastMatches = rf.getMatches(); } else { lastMatches = doFindAll(target, null); } } catch (Exception ex) { if (ex instanceof IOException) { if (handleImageMissing(img, false)) { continue; } } throw new FindFailed(ex.getMessage()); } if (lastMatches != null) { return lastMatches; } if (!handleFindFailed(img)) { return null; } } } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws FindFailed { System.out.println("********** Running Sikulix.main"); if (args.length > 1 && args[0].toLowerCase().startsWith("runserver")) { if (args[1].toLowerCase().contains("start")) { RunServer.run(null); System.exit(0); } else { File fRunServer = new File(RunTime.get().fSikulixStore, "RunServer"); String theServer = ""; if (fRunServer.exists()) { theServer = FileManager.readFileToString(fRunServer).trim(); if (!theServer.isEmpty()) { String[] parts = theServer.split(" "); RunClient runner = new RunClient(parts[0].trim(), parts[1].trim()); runner.close(true); fRunServer.delete(); System.exit(0); } } } } int dl = RunTime.checkArgs(args, RunTime.Type.API); if (dl > -1 && dl < 999) { testNumber = dl; Debug.on(3); } else { testNumber = -1; } testNumber = rt.getOptionNumber("testing.test", testNumber); if (dl == 999) { int exitCode = Runner.runScripts(args); cleanUp(exitCode); System.exit(exitCode); } else if (testNumber > -1) { if (!rt.testing) { rt.show(); rt.testing = true; } Tests.runTest(testNumber); System.exit(1); } else { rt = RunTime.get(); if (rt.fSxBaseJar.getName().contains("setup")) { Sikulix.popError("Not useable!\nRun setup first!"); System.exit(0); } Debug.on(3); Settings.InfoLogs = false; Settings.ActionLogs = false; Screen s = new Screen(); RunClient runner = new RunClient("192.168.2.122", "50001"); runner.close(true); System.exit(1); if (rt.runningWinApp) { popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName()); try { Screen scr = new Screen(); scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3); } catch (Exception ex) { popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName()); } popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName()); System.exit(1); } String version = String.format("(%s-%s)", rt.getVersionShort(), rt.sxBuildStamp); File lastSession = new File(rt.fSikulixStore, "LastAPIJavaScript.js"); String runSomeJS = ""; if (lastSession.exists()) { runSomeJS = FileManager.readFileToString(lastSession); } runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)" + "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub" + "\nWhat you enter now will be shown the next time.", "API::JavaScriptRunner " + version, 10, 60, runSomeJS); if (runSomeJS.isEmpty()) { popup("Nothing to do!", version); } else { FileManager.writeStringToFile(runSomeJS, lastSession); Runner.runjs(null, null, runSomeJS, null); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws FindFailed { System.out.println("********** Running Sikulix.main"); int dl = RunTime.checkArgs(args, RunTime.Type.API); if (dl > -1 && dl < 999) { testNumber = dl; Debug.on(3); } else { testNumber = -1; } testNumber = rt.getOptionNumber("testing.test", testNumber); if (dl == 999) { int exitCode = Runner.runScripts(args); cleanUp(exitCode); System.exit(exitCode); } else if (testNumber > -1) { if (!rt.testing) { rt.show(); rt.testing = true; } Tests.runTest(testNumber); System.exit(1); } else { rt = RunTime.get(); if (rt.fSxBaseJar.getName().contains("setup")) { Sikulix.popError("Not useable!\nRun setup first!"); System.exit(0); } Debug.on(3); Settings.InfoLogs = false; Settings.ActionLogs = false; Screen s = new Screen(); RunClient runner = new RunClient("192.168.2.114", "50001"); runner.send("START"); runner.send("SDIR /Volumes/HD6/rhocke-plus/SikuliX-2014/StuffContainer/testScripts/testJavaScript"); runner.send("RUN testRunServer"); runner.close(true); System.exit(1); if (rt.runningWinApp) { popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName()); try { Screen scr = new Screen(); scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3); } catch (Exception ex) { popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName()); } popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName()); System.exit(1); } String version = String.format("(%s-%s)", rt.getVersionShort(), rt.sxBuildStamp); File lastSession = new File(rt.fSikulixStore, "LastAPIJavaScript.js"); String runSomeJS = ""; if (lastSession.exists()) { runSomeJS = FileManager.readFileToString(lastSession); } runSomeJS = inputText("enter some JavaScript (know what you do - may silently die ;-)" + "\nexample: run(\"git*\") will run the JavaScript showcase from GitHub" + "\nWhat you enter now will be shown the next time.", "API::JavaScriptRunner " + version, 10, 60, runSomeJS); if (runSomeJS.isEmpty()) { popup("Nothing to do!", version); } else { FileManager.writeStringToFile(runSomeJS, lastSession); Runner.runjs(null, null, runSomeJS, null); } } } #location 39 #vulnerability type NULL_DEREFERENCE
#fixed code @Deprecated public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) { return Key.addHotkey(key, modifiers, listener); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Deprecated public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) { return HotkeyManager.getInstance().addHotkey(key, modifiers, listener); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public static List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) { List<Object[]> returnList = null; try { ArrayListHandler resultSetHandler = new ArrayListHandler(); // returnList = new QueryRunner().query(con, sql, resultSetHandler, params); returnList = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) { List<Object[]> returnList = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); ArrayListHandler resultSetHandler = new ArrayListHandler(); returnList = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e1) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e1); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnList; } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private ClassLoader getDriverClassLoader() { File localDriverPath = getCustomDriverPath(); if (driverClassLoader != null) { return driverClassLoader; } else if (localDriverPath.exists()) { try { List<URL> urlList = new ArrayList<>(); File[] files = localDriverPath.listFiles(); if (files != null) { for (File file : files) { String filename = file.getCanonicalPath(); if (!filename.startsWith("/")) { filename = "/" + filename; } urlList.add(new URL("jar:file:" + filename + "!/")); urlList.add(new URL("file:" + filename)); } } URL[] urls = urlList.toArray(new URL[0]); return new URLClassLoader(urls); } catch (Exception e) { throw new MigrationException("Error creating a driver ClassLoader. Cause: " + e, e); } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ClassLoader getDriverClassLoader() { File localDriverPath = getCustomDriverPath(); if (driverClassLoader != null) { return driverClassLoader; } else if (localDriverPath.exists()) { try { List<URL> urlList = new ArrayList<URL>(); for (File file : localDriverPath.listFiles()) { String filename = file.getCanonicalPath(); if (!filename.startsWith("/")) { filename = "/" + filename; } urlList.add(new URL("jar:file:" + filename + "!/")); urlList.add(new URL("file:" + filename)); } URL[] urls = urlList.toArray(new URL[urlList.size()]); return new URLClassLoader(urls); } catch (Exception e) { throw new MigrationException("Error creating a driver ClassLoader. Cause: " + e, e); } } return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private void verifyNode(Node node) { if (node == null) return; // Pre-order traversal. verifyNodes(node.children()); if (node instanceof Call) { Call call = (Call) node; // Skip resolving property derefs. if (call.isJavaStatic() || call.isPostfix()) return; verifyNode(call.args()); FunctionDecl targetFunction = resolveCall(call.name); if (targetFunction == null) addError("Cannot resolve function: " + call.name, call.sourceLine, call.sourceColumn); else { // Check that the args are correct. int targetArgs = targetFunction.arguments().children().size(); int calledArgs = call.args().children().size(); if (calledArgs != targetArgs) addError("Incorrect number of arguments to: " + targetFunction.name() + " (expected " + targetArgs + ", found " + calledArgs + ")", call.sourceLine, call.sourceColumn); } } else if (node instanceof PatternRule) { PatternRule patternRule = (PatternRule) node; verifyNode(patternRule.rhs); // Some sanity checking of pattern rules. FunctionDecl function = functionStack.peek().function; int argsSize = function.arguments().children().size(); int patternsSize = patternRule.patterns.size(); if (patternsSize != argsSize) addError("Incorrect number of patterns in: '" + function.name() + "' (expected " + argsSize + " found " + patternsSize + ")", patternRule.sourceLine, patternRule.sourceColumn); } else if (node instanceof Guard) { Guard guard = (Guard) node; verifyNode(guard.expression); verifyNode(guard.line); } else if (node instanceof Variable) { Variable var = (Variable) node; if (!resolveVar(var.name)) addError("Cannot resolve symbol: " + var.name, var.sourceLine, var.sourceColumn); } else if (node instanceof ConstructorCall) { ConstructorCall call = (ConstructorCall) node; if (!resolveType(call)) addError("Cannot resolve type (either as loop or Java): " + (call.modulePart == null ? "" : call.modulePart) + call.name, call.sourceLine, call.sourceColumn); } else if (node instanceof Assignment) { // Make sure that you cannot reassign function arguments. Assignment assignment = (Assignment) node; if (assignment.lhs() instanceof Variable) { Variable lhs = (Variable) assignment.lhs(); FunctionContext functionContext = functionStack.peek(); for (Node argument : functionContext.function.arguments().children()) { ArgDeclList.Argument arg = (ArgDeclList.Argument) argument; if (arg.name().equals(lhs.name)) addError("Illegal argument reassignment (declare a local variable instead)", lhs.sourceLine, lhs.sourceColumn); } // verifyNode(assignment.rhs()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void verifyNode(Node node) { if (node == null) return; // Pre-order traversal. verifyNodes(node.children()); if (node instanceof Call) { Call call = (Call) node; // Skip resolving property derefs. if (call.isJavaStatic() || call.isPostfix()) return; verifyNode(call.args()); FunctionDecl targetFunction = resolveCall(call.name); if (targetFunction == null) addError("Cannot resolve function: " + call.name, call.sourceLine, call.sourceColumn); else { // Check that the args are correct. int targetArgs = targetFunction.arguments().children().size(); int calledArgs = call.args().children().size(); if (calledArgs != targetArgs) addError("Incorrect number of arguments to: " + targetFunction.name() + " (expected " + targetArgs + ", found " + calledArgs + ")", call.sourceLine, call.sourceColumn); } } else if (node instanceof PatternRule) { PatternRule patternRule = (PatternRule) node; verifyNode(patternRule.rhs); // Some sanity checking of pattern rules. FunctionDecl function = functionStack.peek().function; int argsSize = function.arguments().children().size(); int patternsSize = patternRule.patterns.size(); if (patternsSize != argsSize) addError("Incorrect number of patterns in: '" + function.name() + "' (expected " + argsSize + " found " + patternsSize + ")", patternRule.sourceLine, patternRule.sourceColumn); } else if (node instanceof Guard) { Guard guard = (Guard) node; verifyNode(guard.expression); verifyNode(guard.line); } else if (node instanceof Variable) { Variable var = (Variable) node; if (!resolveVar(var.name)) addError("Cannot resolve symbol: " + var.name, var.sourceLine, var.sourceColumn); } else if (node instanceof ConstructorCall) { ConstructorCall call = (ConstructorCall) node; if (!resolveType(call)) addError("Cannot resolve type (either as loop or Java): " + (call.modulePart == null ? "" : call.modulePart) + call.name, call.sourceLine, call.sourceColumn); } } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code public void testToArray() throws SQLException { Object[] a = null; assertTrue(this.rs.next()); a = processor.toArray(this.rs); assertEquals(COLS, a.length); assertEquals("1", a[0]); assertEquals("2", a[1]); assertEquals("3", a[2]); assertTrue(this.rs.next()); a = processor.toArray(this.rs); assertEquals(COLS, a.length); assertEquals("4", a[0]); assertEquals("5", a[1]); assertEquals("6", a[2]); assertFalse(this.rs.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testToArray() throws SQLException { int rowCount = 0; Object[] a = null; while (this.rs.next()) { a = processor.toArray(this.rs); assertEquals(COLS, a.length); rowCount++; } assertEquals(ROWS, rowCount); assertEquals("4", a[0]); assertEquals("5", a[1]); assertEquals("6", a[2]); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); pod = client.pods().inNamespace(namespace).create(pod); LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); TaskListener runListener = template.getListener(); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); LOGGER.log(Level.FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); pod = client.pods().inNamespace(namespace).create(pod); LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); TaskListener runListener = template.getListener(); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } catch (InvalidPodTemplateException e) { LOGGER.info("Caught invalid pod template exception"); switch (e.getReason()) { case "ImagePullBackOff": runListener.getLogger().printf(e.getMessage()); PodUtils.cancelInvalidPodTemplateJob(pod, "ImagePullBackOff"); break; default: LOGGER.warning("Unknown reason for InvalidPodTemplateException : " + e.getReason()); break; } } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } } #location 51 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.image); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl())); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd = cmd == null ? new ArrayList<String>(2) : cmd; cmd.add(slave.getComputer().getJnlpMac()); // secret cmd.add(slave.getComputer().getName()); // name container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); return podTemplate; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Pod getPodTemplate(KubernetesSlave slave, Label label) { DockerTemplate template = getTemplate(label); String id = getIdForLabel(label); Pod podTemplate = new Pod(); podTemplate.setId(slave.getNodeName()); // labels podTemplate.setLabels(getLabelsFor(id)); Container container = new Container(); container.setName(CONTAINER_NAME); container.setImage(template.image); // environment // List<EnvironmentVariable> env = new // ArrayList<EnvironmentVariable>(template.environment.length + 3); List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3); // always add some env vars env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac())); env.add(new EnvironmentVariable("JENKINS_URL", JenkinsLocationConfiguration.get().getUrl())); String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl; url = url.endsWith("/") ? url : url + "/"; env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp")); if (!StringUtils.isBlank(jenkinsTunnel)) { env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel)); } // for (int i = 0; i < template.environment.length; i++) { // String[] split = template.environment[i].split("="); // env.add(new EnvironmentVariable(split[0], split[1])); // } container.setEnv(env); // ports // TODO open ports defined in template // container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) + // 49152)); // command: SECRET SLAVE_NAME List<String> cmd = parseDockerCommand(template.dockerCommand); cmd.addAll(ImmutableList.of(slave.getComputer().getJnlpMac(), slave.getComputer().getName())); container.setCommand(cmd); Manifest manifest = new Manifest(Collections.singletonList(container), null); podTemplate.setDesiredState(new State(manifest)); return podTemplate; } #location 40 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); TaskListener runListener = template.getListener(); LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); try { pod = client.pods().inNamespace(namespace).create(pod); } catch (KubernetesClientException e) { int httpCode = e.getCode(); if (400 <= httpCode && httpCode < 500) { // 4xx runListener.getLogger().printf("ERROR: Unable to create pod %s/%s.%n%s%n", namespace, pod.getMetadata().getName(), e.getMessage()); PodUtils.cancelQueueItemFor(pod, e.getMessage()); } else if (500 <= httpCode && httpCode < 600) { // 5xx LOGGER.log(FINE,"Kubernetes returned HTTP code {0} {1}. Retrying...", new Object[] {e.getCode(), e.getStatus()}); } else { LOGGER.log(WARNING, "Kubernetes returned unhandled HTTP code {0} {1}", new Object[] {e.getCode(), e.getStatus()}); } throw e; } LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine") public synchronized void launch(SlaveComputer computer, TaskListener listener) { if (!(computer instanceof KubernetesComputer)) { throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer"); } KubernetesComputer kubernetesComputer = (KubernetesComputer) computer; computer.setAcceptingTasks(false); KubernetesSlave slave = kubernetesComputer.getNode(); if (slave == null) { throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName()); } if (launched) { LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName()); computer.setAcceptingTasks(true); return; } final PodTemplate template = slave.getTemplate(); try { KubernetesClient client = slave.getKubernetesCloud().connect(); Pod pod = template.build(slave); slave.assignPod(pod); String podName = pod.getMetadata().getName(); String namespace = Arrays.asList( // pod.getMetadata().getNamespace(), template.getNamespace(), client.getNamespace()) // .stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null); slave.setNamespace(namespace); TaskListener runListener = template.getListener(); LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName }); try { pod = client.pods().inNamespace(namespace).create(pod); } catch (KubernetesClientException e) { int k8sCode = e.getCode(); if (k8sCode >= 400 && k8sCode < 500) { // 4xx runListener.getLogger().printf("ERROR: Unable to create pod. " + e.getMessage()); PodUtils.cancelQueueItemFor(pod, e.getMessage()); } else if (k8sCode >= 500 && k8sCode < 600) { // 5xx LOGGER.log(FINE,"Kubernetes code {0}. Retrying...", e.getCode()); } else { LOGGER.log(WARNING, "Unknown Kubernetes code {0}", e.getCode()); } throw e; } LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName }); listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName); template.getWorkspaceVolume().createVolume(client, pod.getMetadata()); watcher = new AllContainersRunningPodWatcher(client, pod, runListener); try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher); Watch w2 = eventWatch(client, podName, namespace, runListener)) { assert watcher != null; // assigned 3 lines above watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS); } LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName }); // We need the pod to be running and connected before returning // otherwise this method keeps being called multiple times List<String> validStates = ImmutableList.of("Running"); int waitForSlaveToConnect = template.getSlaveConnectTimeout(); int waitedForSlave; // now wait for agent to be online SlaveComputer slaveComputer = null; String status = null; List<ContainerStatus> containerStatuses = null; long lastReportTimestamp = System.currentTimeMillis(); for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) { slaveComputer = slave.getComputer(); if (slaveComputer == null) { throw new IllegalStateException("Node was deleted, computer is null"); } if (slaveComputer.isOnline()) { break; } // Check that the pod hasn't failed already pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { throw new IllegalStateException("Pod no longer exists: " + podName); } status = pod.getStatus().getPhase(); if (!validStates.contains(status)) { break; } containerStatuses = pod.getStatus().getContainerStatuses(); List<ContainerStatus> terminatedContainers = new ArrayList<>(); for (ContainerStatus info : containerStatuses) { if (info != null) { if (info.getState().getTerminated() != null) { // Container has errored LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}", new Object[] { podName, info.getState().getTerminated(), info.getName() }); listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName, info.getState().getTerminated(), info.getName()); terminatedContainers.add(info); } } } checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client); if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) { LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[]{podName, waitedForSlave, waitForSlaveToConnect}); listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave, waitForSlaveToConnect); lastReportTimestamp = System.currentTimeMillis(); } Thread.sleep(1000); } if (slaveComputer == null || slaveComputer.isOffline()) { logLastLines(containerStatuses, podName, namespace, slave, null, client); throw new IllegalStateException( "Agent is not connected after " + waitedForSlave + " seconds, status: " + status); } computer.setAcceptingTasks(true); launched = true; try { // We need to persist the "launched" setting... slave.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e); } } catch (Throwable ex) { setProblem(ex); LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex); LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName()); try { slave.terminate(); } catch (IOException | InterruptedException e) { LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e); } throw Throwables.propagate(ex); } } #location 42 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code private static boolean userHasAdministerPermission() { return Jenkins.get().hasPermission(Jenkins.ADMINISTER); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static boolean userHasAdministerPermission() { return Jenkins.getInstance().getACL().hasPermission(Jenkins.ADMINISTER); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean start() throws Exception { Cloud cloud = Jenkins.get().getCloud(cloudName); if (cloud == null) { throw new AbortException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; Run<?, ?> run = getContext().get(Run.class); if (kubernetesCloud.isUsageRestricted()) { checkAccess(run, kubernetesCloud); } PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class); String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null; String label = step.getLabel(); if (label == null) { label = labelify(run.getExternalizableId()); } //Let's generate a random name based on the user specified to make sure that we don't have //issues with concurrent builds, or messing with pre-existing configuration String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); String stepName = step.getName(); if (stepName == null) { stepName = label; } String name = String.format(NAME_FORMAT, stepName, randString); String namespace = checkNamespace(kubernetesCloud, podTemplateContext); newTemplate = new PodTemplate(); newTemplate.setName(name); newTemplate.setNamespace(namespace); if (step.getInheritFrom() == null) { newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates)); } else { newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom())); } newTemplate.setInstanceCap(step.getInstanceCap()); newTemplate.setIdleMinutes(step.getIdleMinutes()); newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout()); newTemplate.setLabel(label); newTemplate.setEnvVars(step.getEnvVars()); newTemplate.setVolumes(step.getVolumes()); if (step.getWorkspaceVolume() != null) { newTemplate.setWorkspaceVolume(step.getWorkspaceVolume()); } newTemplate.setContainers(step.getContainers()); newTemplate.setNodeSelector(step.getNodeSelector()); newTemplate.setNodeUsageMode(step.getNodeUsageMode()); newTemplate.setServiceAccount(step.getServiceAccount()); newTemplate.setAnnotations(step.getAnnotations()); newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy()); if(run!=null) { String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull(); if(url != null) { newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl())); } } newTemplate.setImagePullSecrets( step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList())); newTemplate.setYaml(step.getYaml()); if (step.isShowRawYamlSet()) { newTemplate.setShowRawYaml(step.isShowRawYaml()); } newTemplate.setPodRetention(step.getPodRetention()); if(step.getActiveDeadlineSeconds() != 0) { newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds()); } for (ContainerTemplate container : newTemplate.getContainers()) { if (!PodTemplateUtils.validateContainerName(container.getName())) { throw new AbortException(Messages.RFC1123_error(container.getName())); } } Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls()); if (!errors.isEmpty()) { throw new AbortException(Messages.RFC1123_error(String.join(", ", errors))); } // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally. if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) { throw new AbortException(Messages.label_error(newTemplate.getLabel())); } kubernetesCloud.addDynamicTemplate(newTemplate); BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate)); if (step.getLabel() == null) { invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label)))); } invoker.start(); return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean start() throws Exception { Cloud cloud = Jenkins.getInstance().getCloud(cloudName); if (cloud == null) { throw new AbortException(String.format("Cloud does not exist: %s", cloudName)); } if (!(cloud instanceof KubernetesCloud)) { throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName, cloud.getClass().getName())); } KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; Run<?, ?> run = getContext().get(Run.class); if (kubernetesCloud.isUsageRestricted()) { checkAccess(run, kubernetesCloud); } PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class); String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null; String label = step.getLabel(); if (label == null) { label = labelify(run.getExternalizableId()); } //Let's generate a random name based on the user specified to make sure that we don't have //issues with concurrent builds, or messing with pre-existing configuration String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); String stepName = step.getName(); if (stepName == null) { stepName = label; } String name = String.format(NAME_FORMAT, stepName, randString); String namespace = checkNamespace(kubernetesCloud, podTemplateContext); newTemplate = new PodTemplate(); newTemplate.setName(name); newTemplate.setNamespace(namespace); if (step.getInheritFrom() == null) { newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates)); } else { newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom())); } newTemplate.setInstanceCap(step.getInstanceCap()); newTemplate.setIdleMinutes(step.getIdleMinutes()); newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout()); newTemplate.setLabel(label); newTemplate.setEnvVars(step.getEnvVars()); newTemplate.setVolumes(step.getVolumes()); if (step.getWorkspaceVolume() != null) { newTemplate.setWorkspaceVolume(step.getWorkspaceVolume()); } newTemplate.setContainers(step.getContainers()); newTemplate.setNodeSelector(step.getNodeSelector()); newTemplate.setNodeUsageMode(step.getNodeUsageMode()); newTemplate.setServiceAccount(step.getServiceAccount()); newTemplate.setAnnotations(step.getAnnotations()); newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy()); if(run!=null) { String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull(); if(url != null) { newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl())); } } newTemplate.setImagePullSecrets( step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList())); newTemplate.setYaml(step.getYaml()); if (step.isShowRawYamlSet()) { newTemplate.setShowRawYaml(step.isShowRawYaml()); } newTemplate.setPodRetention(step.getPodRetention()); if(step.getActiveDeadlineSeconds() != 0) { newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds()); } for (ContainerTemplate container : newTemplate.getContainers()) { if (!PodTemplateUtils.validateContainerName(container.getName())) { throw new AbortException(Messages.RFC1123_error(container.getName())); } } Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls()); if (!errors.isEmpty()) { throw new AbortException(Messages.RFC1123_error(String.join(", ", errors))); } // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally. if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) { throw new AbortException(Messages.label_error(newTemplate.getLabel())); } kubernetesCloud.addDynamicTemplate(newTemplate); BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate)); if (step.getLabel() == null) { invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label)))); } invoker.start(); return false; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code protected void deleteNode(Handle handle) throws IOException { if (cachesize != 0) { Node n = (Node) cache.get(handle); if (n != null) synchronized (cache) { cacheScore.deleteScore(handle); cache.remove(handle); } } dispose(handle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void deleteNode(Handle handle) throws IOException { if (cachesize != 0) { Node n = (Node) cache.get(handle); if (n != null) { cacheScore.deleteScore(handle); cache.remove(handle); } } dispose(handle); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void respondError(OutputStream respond, String origerror, int errorcase, String url) { FileInputStream fis = null; try { // set rewrite values serverObjects tp = new serverObjects(); tp.put("errormessage", errorcase); tp.put("httperror", origerror); tp.put("url", url); // rewrite the file File file = new File(htRootPath, "/proxymsg/error.html"); byte[] result; ByteArrayOutputStream o = new ByteArrayOutputStream(); fis = new FileInputStream(file); httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); o.close(); result = o.toByteArray(); // return header httpHeader header = new httpHeader(); header.put("Date", httpc.dateString(httpc.nowDate())); header.put("Content-type", "text/html"); header.put("Content-length", "" + o.size()); header.put("Pragma", "no-cache"); // write the array to the client respondHeader(respond, origerror, header); serverFileUtils.write(result, respond); respond.flush(); } catch (IOException e) { } finally { if (fis != null) try { fis.close(); } catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void respondError(OutputStream respond, String origerror, int errorcase, String url) { try { // set rewrite values serverObjects tp = new serverObjects(); tp.put("errormessage", errorcase); tp.put("httperror", origerror); tp.put("url", url); // rewrite the file File file = new File(htRootPath, "/proxymsg/error.html"); byte[] result; ByteArrayOutputStream o = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(file); httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); o.close(); result = o.toByteArray(); // return header httpHeader header = new httpHeader(); header.put("Date", httpc.dateString(httpc.nowDate())); header.put("Content-type", "text/html"); header.put("Content-length", "" + o.size()); header.put("Pragma", "no-cache"); // write the array to the client respondHeader(respond, origerror, header); serverFileUtils.write(result, respond); respond.flush(); } catch (IOException e) { } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public static void copy(File source, OutputStream dest) throws IOException { InputStream fis = null; try { fis = new FileInputStream(source); copy(fis, dest); } finally { if (fis != null) try { fis.close(); } catch (Exception e) {} } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void copy(File source, OutputStream dest) throws IOException { InputStream fis = new FileInputStream(source); copy(fis, dest); fis.close(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { Biz biz = DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager); if (biz == null) { continue; } if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "failed"); } else { builder.withDetail(String.format("Biz: %s health check", biz.getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Health health() { boolean allPassed = true; Health.Builder builder = new Health.Builder(); for (SofaRuntimeManager sofaRuntimeManager : SofaFramework.getRuntimeSet()) { if (!sofaRuntimeManager.isLivenessHealth()) { allPassed = false; builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "failed"); } else { builder.withDetail( String.format("Biz: %s health check", DynamicJvmServiceProxyFinder.getBiz(sofaRuntimeManager).getIdentity()), "passed"); } } if (allPassed) { return builder.up().build(); } else { return builder.down().build(); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testReadinessCheckFailedHttpCode() { ResponseEntity<String> response = restTemplate.getForEntity("/health/readiness", String.class); Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE, response.getStatusCode()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadinessCheckFailedHttpCode() throws IOException { HttpURLConnection huc = (HttpURLConnection) (new URL( "http://localhost:8080/health/readiness").openConnection()); huc.setRequestMethod("HEAD"); huc.connect(); int respCode = huc.getResponseCode(); System.out.println(huc.getResponseMessage()); Assert.assertEquals(503, respCode); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = readClusterConf(); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = readClusterConf(); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } writeClusterConf(sb.toString()); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = readClusterConf(); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/updateClusterConf") public JSONObject updateClusterConf(HttpServletRequest request) throws IOException { JSONObject result = new JSONObject(); String ipSpliter = ","; String ips = BaseServlet.optional(request, "ips", ""); String action = BaseServlet.required(request, "action"); if (SwitchEntry.ACTION_ADD.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8")); StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_REPLACE.equals(action)) { StringBuilder sb = new StringBuilder(); for (String ip : ips.split(ipSpliter)) { sb.append(ip).append("\r\n"); } Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString()); IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_DELETE.equals(action)) { Set<String> removeIps = new HashSet<>(); for (String ip : ips.split(ipSpliter)) { removeIps.add(ip); } List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); Iterator<String> iterator = oldList.iterator(); while (iterator.hasNext()) { String ip = iterator.next(); if (removeIps.contains(ip)) { iterator.remove(); } } StringBuilder sb = new StringBuilder(); for (String ip : oldList) { sb.append(ip).append("\r\n"); } IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8"); return result; } if (SwitchEntry.ACTION_VIEW.equals(action)) { List<String> oldList = IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8")); result.put("list", oldList); return result; } throw new InvalidParameterException("action is not qualified, action: " + action); } #location 47 #vulnerability type RESOURCE_LEAK
#fixed code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5Utils.md5Hex(content, Constants.ENCODE); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkLocalConfig(CacheData cacheData) { final String dataId = cacheData.dataId; final String group = cacheData.group; final String tenant = cacheData.tenant; File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant); // 没有 -> 有 if (!cacheData.isUseLocalConfigInfo() && path.exists()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); return; } // 有 -> 没有。不通知业务监听器,从server拿到配置后通知。 if (cacheData.isUseLocalConfigInfo() && !path.exists()) { cacheData.setUseLocalConfigInfo(false); LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant); return; } // 有变更 if (cacheData.isUseLocalConfigInfo() && path.exists() && cacheData.getLocalConfigInfoVersion() != path.lastModified()) { String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant); String md5 = MD5.getInstance().getMD5String(content); cacheData.setUseLocalConfigInfo(true); cacheData.setLocalConfigInfoVersion(path.lastModified()); cacheData.setContent(content); LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}", agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content)); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertIntEquals(1, f.getHourOffset()); assertIntEquals(0, f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedProperties("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedProperties("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void lotusNotesVCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V3_0, vcard.getVersion()); //PRODID { ProdIdType f = vcard.getProdId(); assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); } //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("Doe", f.getFamily()); assertEquals("John", f.getGiven()); assertEquals(Arrays.asList("Johny"), f.getAdditional()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("I"), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Doe John I Johny", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("Generic Accountant", f.getValue()); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertTrue(types.contains(EmailTypeParameter.PREF)); f = it.next(); assertEquals("[email protected]", f.getValue()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertTrue(types.contains(new EmailTypeParameter("WORK"))); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("+1 (212) 204-34456", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); assertTrue(types.contains(TelephoneTypeParameter.PREF)); f = it.next(); assertEquals("00-1-212-555-7777", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals("item1", f.getGroup()); assertEquals(null, f.getPoBox()); assertEquals(null, f.getExtendedAddress()); assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("New York", f.getRegion()); assertEquals("NYC887", f.getPostalCode()); assertEquals("U.S.A.", f.getCountry()); assertNull(f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); assertFalse(it.hasNext()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("item2", f.getGroup()); assertEquals("http://www.sun.com", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("pref")); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1980); c.set(Calendar.MONTH, Calendar.MAY); c.set(Calendar.DAY_OF_MONTH, 21); assertEquals(c.getTime(), f.getDate()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(7957, f.getData().length); assertFalse(it.hasNext()); } //UID { UidType f = vcard.getUid(); assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); } //GEO { GeoType f = vcard.getGeo(); assertEquals(-2.6, f.getLatitude(), .01); assertEquals(3.4, f.getLongitude(), .01); } //CLASS { ClassificationType f = vcard.getClassification(); assertEquals("Public", f.getValue()); } //PROFILE { ProfileType f = vcard.getProfile(); assertEquals("VCard", f.getValue()); } //TZ { TimezoneType f = vcard.getTimezone(); assertIntEquals(1, f.getHourOffset()); assertIntEquals(0, f.getMinuteOffset()); } //LABEL { Iterator<LabelType> it = vcard.getOrphanedLabels().iterator(); LabelType f = it.next(); assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(3, types.size()); assertTrue(types.contains(AddressTypeParameter.HOME)); assertTrue(types.contains(AddressTypeParameter.PARCEL)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //SORT-STRING { SortStringType f = vcard.getSortString(); assertEquals("JOHN", f.getValue()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("Counting Money", f.getValue()); assertFalse(it.hasNext()); } //SOURCE { Iterator<SourceType> it = vcard.getSources().iterator(); SourceType f = it.next(); assertEquals("Whatever", f.getValue()); assertFalse(it.hasNext()); } //MAILER { MailerType f = vcard.getMailer(); assertEquals("Mozilla Thunderbird", f.getValue()); } //NAME { SourceDisplayTextType f = vcard.getSourceDisplayText(); assertEquals("VCard for John Doe", f.getValue()); } //extended types { assertEquals(4, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); assertEquals("item2", f.getGroup()); assertEquals("X-ABLabel", f.getTypeName()); assertEquals("_$!<HomePage>!$_", f.getValue()); f = vcard.getExtendedProperties("X-ABUID").get(0); assertEquals("X-ABUID", f.getTypeName()); assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); f = vcard.getExtendedProperties("X-GENERATOR").get(0); assertEquals("X-GENERATOR", f.getTypeName()); assertEquals("Cardme Generator", f.getValue()); f = vcard.getExtendedProperties("X-LONG-STRING").get(0); assertEquals("X-LONG-STRING", f.getTypeName()); assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { if (subTypes.getValue() != null) { setUrl(VCardStringUtils.unescape(value)); } else { //instruct the marshaller to look for an embedded vCard throw new EmbeddedVCardException(new EmbeddedVCardException.InjectionCallback() { public void injectVCard(VCard vcard) { setVcard(vcard); } }); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) { value = VCardStringUtils.unescape(value); if (subTypes.getValue() != null) { url = value; } else { VCardReader reader = new VCardReader(new StringReader(value)); reader.setCompatibilityMode(compatibilityMode); try { vcard = reader.readNext(); } catch (IOException e) { //reading from a string } for (String w : reader.getWarnings()) { warnings.add("AGENT unmarshal warning: " + w); } } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void outlook2007VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Angstadt", f.getFamily()); assertEquals("Michael", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Jr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Michael Angstadt Jr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Mike"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue()); assertEquals("us-ascii", f.getSubTypes().getCharset()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(111) 555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-4444", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-3333", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("222 Broadway", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("99999", f.getPostalCode()); assertEquals("USA", f.getCountry()); assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("HOME")); f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1922); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(514, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(2324, f.getData().length); assertFalse(it.hasNext()); } //FBURL { //a 4.0 property in a 2.1 vCard... Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); FbUrlType f = it.next(); assertEquals("http://website.com/mycal", f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.AUGUST); c.set(Calendar.DAY_OF_MONTH, 1); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 46); c.set(Calendar.SECOND, 31); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(8, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0); assertEquals("X-MS-TEL", f.getTypeName()); assertEquals("(111) 555-4444", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(2, types.size()); assertTrue(types.contains("VOICE")); assertTrue(types.contains("CALLBACK")); f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0); assertEquals("X-MS-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); } assertWarnings(0, reader.getWarnings()); assertNull(reader.readNext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void outlook2007VCard() throws Exception { VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf")); VCard vcard = reader.readNext(); //VERSION assertEquals(VCardVersion.V2_1, vcard.getVersion()); //N { StructuredNameType f = vcard.getStructuredName(); assertEquals("en-us", f.getSubTypes().getLanguage()); assertEquals("Angstadt", f.getFamily()); assertEquals("Michael", f.getGiven()); assertTrue(f.getAdditional().isEmpty()); assertEquals(Arrays.asList("Mr."), f.getPrefixes()); assertEquals(Arrays.asList("Jr."), f.getSuffixes()); } //FN { FormattedNameType f = vcard.getFormattedName(); assertEquals("Mr. Michael Angstadt Jr.", f.getValue()); } //NICKNAME { NicknameType f = vcard.getNickname(); assertEquals(Arrays.asList("Mike"), f.getValues()); } //ORG { OrganizationType f = vcard.getOrganization(); assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues()); } //TITLE { Iterator<TitleType> it = vcard.getTitles().iterator(); TitleType f = it.next(); assertEquals("TheJobTitle", f.getValue()); assertFalse(it.hasNext()); } //NOTE { Iterator<NoteType> it = vcard.getNotes().iterator(); NoteType f = it.next(); assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue()); assertEquals("us-ascii", f.getSubTypes().getCharset()); assertFalse(it.hasNext()); } //TEL { Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator(); TelephoneType f = it.next(); assertEquals("(111) 555-1111", f.getText()); Set<TelephoneTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-2222", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.HOME)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-4444", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.CELL)); assertTrue(types.contains(TelephoneTypeParameter.VOICE)); f = it.next(); assertEquals("(111) 555-3333", f.getText()); types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(TelephoneTypeParameter.FAX)); assertTrue(types.contains(TelephoneTypeParameter.WORK)); assertFalse(it.hasNext()); } //ADR { Iterator<AddressType> it = vcard.getAddresses().iterator(); AddressType f = it.next(); assertEquals(null, f.getPoBox()); assertEquals("TheOffice", f.getExtendedAddress()); assertEquals("222 Broadway", f.getStreetAddress()); assertEquals("New York", f.getLocality()); assertEquals("NY", f.getRegion()); assertEquals("99999", f.getPostalCode()); assertEquals("USA", f.getCountry()); assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel()); Set<AddressTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(AddressTypeParameter.WORK)); assertTrue(types.contains(AddressTypeParameter.PREF)); assertFalse(it.hasNext()); } //LABEL { assertTrue(vcard.getOrphanedLabels().isEmpty()); } //URL { Iterator<UrlType> it = vcard.getUrls().iterator(); UrlType f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("HOME")); f = it.next(); assertEquals("http://mikeangstadt.name", f.getValue()); types = f.getSubTypes().getTypes(); assertEquals(1, types.size()); assertTrue(types.contains("WORK")); assertFalse(it.hasNext()); } //ROLE { Iterator<RoleType> it = vcard.getRoles().iterator(); RoleType f = it.next(); assertEquals("TheProfession", f.getValue()); assertFalse(it.hasNext()); } //BDAY { BirthdayType f = vcard.getBirthday(); Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR, 1922); c.set(Calendar.MONTH, Calendar.MARCH); c.set(Calendar.DAY_OF_MONTH, 10); assertEquals(c.getTime(), f.getDate()); } //KEY { Iterator<KeyType> it = vcard.getKeys().iterator(); KeyType f = it.next(); assertEquals(KeyTypeParameter.X509, f.getContentType()); assertEquals(514, f.getData().length); assertFalse(it.hasNext()); } //EMAIL { Iterator<EmailType> it = vcard.getEmails().iterator(); EmailType f = it.next(); assertEquals("[email protected]", f.getValue()); Set<EmailTypeParameter> types = f.getTypes(); assertEquals(2, types.size()); assertTrue(types.contains(EmailTypeParameter.PREF)); assertTrue(types.contains(EmailTypeParameter.INTERNET)); assertFalse(it.hasNext()); } //PHOTO { Iterator<PhotoType> it = vcard.getPhotos().iterator(); PhotoType f = it.next(); assertEquals(ImageTypeParameter.JPEG, f.getContentType()); assertEquals(2324, f.getData().length); assertFalse(it.hasNext()); } //FBURL { //a 4.0 property in a 2.1 vCard... Iterator<FbUrlType> it = vcard.getFbUrls().iterator(); FbUrlType f = it.next(); assertEquals("http://website.com/mycal", f.getValue()); assertFalse(it.hasNext()); } //REV { RevisionType f = vcard.getRevision(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(Calendar.YEAR, 2012); c.set(Calendar.MONTH, Calendar.AUGUST); c.set(Calendar.DAY_OF_MONTH, 1); c.set(Calendar.HOUR_OF_DAY, 18); c.set(Calendar.MINUTE, 46); c.set(Calendar.SECOND, 31); assertEquals(c.getTime(), f.getTimestamp()); } //extended types { assertEquals(8, countExtTypes(vcard)); RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0); assertEquals("X-MS-TEL", f.getTypeName()); assertEquals("(111) 555-4444", f.getValue()); Set<String> types = f.getSubTypes().getTypes(); assertEquals(2, types.size()); assertTrue(types.contains("VOICE")); assertTrue(types.contains("CALLBACK")); f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); assertEquals("2", f.getValue()); f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); assertEquals("20120801", f.getValue()); f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); assertEquals("X-MS-IMADDRESS", f.getTypeName()); assertEquals("[email protected]", f.getValue()); f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); assertEquals("X-MS-OL-DESIGN", f.getTypeName()); assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue()); assertEquals("utf-8", f.getSubTypes().getCharset()); f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); assertEquals("X-MS-MANAGER", f.getTypeName()); assertEquals("TheManagerName", f.getValue()); f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); assertEquals("X-MS-ASSISTANT", f.getTypeName()); assertEquals("TheAssistantName", f.getValue()); f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0); assertEquals("X-MS-SPOUSE", f.getTypeName()); assertEquals("TheSpouse", f.getValue()); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) { LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); // Timeout is specified per file, not per batch (which can vary a lot) // so multiply it up this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs); return getFileContent(tslintOutputFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) { LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); // Timeout is specified per file, not per batch (which can vary a lot) // so multiply it up this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs); StringBuilder outputBuilder = new StringBuilder(); try { BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile); String str; while ((str = reader.readLine()) != null) { outputBuilder.append(str); } reader.close(); return outputBuilder.toString(); } catch (IOException ex) { LOG.error("Failed to re-read TsLint output", ex); } return ""; } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); FileOutputStream fileOutputStream = new FileOutputStream(destination); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); // Use copyLarge (over 2GB) try { IOUtils.copyLarge(inputStream, bufferedOutputStream); bufferedOutputStream.flush(); fileOutputStream.flush(); } finally { inputStream.close(); bufferedOutputStream.close(); fileOutputStream.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); // Use copyLarge (over 2GB) try { IOUtils.copyLarge(inputStream, new BufferedOutputStream(new FileOutputStream(destination))); } finally { inputStream.close(); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) { try { client.get(domainId, key, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException { client.get(domainId, key, resultHandler); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code Host getHost() { return host; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean isAvailable() { return state != HostConnectionState.STANDBY; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void addCompleteTask(GetTask task) { synchronized (getTasksComplete) { getTasksComplete.addLast(task); } //dispatcherThread.interrupt(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void addCompleteTask(GetTask task) { synchronized (getTasksComplete) { getTasksComplete.addLast(task); } dispatcherThread.interrupt(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void start() { disruptor.handleEventsWith(eventHandler); disruptor.start(); RingBuffer<ServerEvent> ringBuffer = disruptor.getRingBuffer(); requestConsumer.startConsumers(ringBuffer); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { consumerWorkers = new ArrayList<>(consumerThreads); CountDownLatch startupLatch = new CountDownLatch(consumerThreads); for (int i = 0; i < consumerThreads; i++) { KafkaConsumer<String, Request> consumer = new KafkaConsumer<>(consumerProps); RequestConsumerWorker worker = new RequestConsumerWorker(topic, consumer, messageDispatcher, startupLatch); consumerExecutor.submit(worker); } try { startupLatch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.error("Error while waiting for server consumers to subscribe", e); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Override public User getWithNetworksById(long id) { User user = find(id); Set<Long> networkIds = userNetworkDao.findNetworksForUser(id); if (networkIds == null) { return user; } Set<Network> networks = new HashSet<>(); for (Long networkId : networkIds) { Network network = networkDao.find(networkId); networks.add(network); } user.setNetworks(networks); return user; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public User getWithNetworksById(long id) { User user = find(id); Set<Long> networkIds = userNetworkDao.findNetworksForUser(id); Set<Network> networks = new HashSet<>(); for (Long networkId : networkIds) { Network network = networkDao.find(networkId); networks.add(network); } user.setNetworks(networks); return user; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public RpcData doHandle(RpcData data) throws Exception { Object input = null; Object[] param; Object ret; if (data.getData() != null && parseFromMethod != null) { input = parseFromMethod.invoke(getInputClass(), new ByteArrayInputStream(data.getData()));; param = new Object[] {input}; } else { param = new Object[0]; } RpcData retData = new RpcData(); // process attachment if (getAttachmentHandler() != null) { byte[] responseAttachment = getAttachmentHandler().handleAttachement(data.getAttachment(), getServiceName(), getMethodName(), param); retData.setAttachment(responseAttachment); } ret = getMethod().invoke(getService(), param); if (ret == null) { return retData; } if (ret != null && ret instanceof GeneratedMessage) { byte[] response = ((GeneratedMessage) ret).toByteArray(); retData.setData(response); } return retData; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RpcData doHandle(RpcData data) throws Exception { Object input = null; Object[] param; Object ret; if (data.getData() != null && parseFromMethod != null) { input = parseFromMethod.invoke(getInputClass(), new ByteArrayInputStream(data.getData()));; param = new Object[] {input}; } else { param = new Object[0]; } RpcData retData = new RpcData(); // process attachment if (getAttachmentHandler() != null) { byte[] responseAttachment = getAttachmentHandler().handleAttachement(data.getAttachment(), getServiceName(), getMethodName(), param); retData.setAttachment(responseAttachment); } ret = getMethod().invoke(getService(), param); if (ret == null) { return retData; } if (ret != null && ret instanceof GeneratedMessage) { byte[] response = ((GeneratedMessage) input).toByteArray(); retData.setData(response); } return retData; } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code public void close() { Collection<List<ProtobufRpcProxy<T>>> values = protobufRpcProxyListMap.values(); for (List<ProtobufRpcProxy<T>> list : values) { doClose(null, list); } Collection<LoadBalanceProxyFactoryBean> lbs = lbMap.values(); for (LoadBalanceProxyFactoryBean loadBalanceProxyFactoryBean : lbs) { doClose(loadBalanceProxyFactoryBean, null); } super.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void close() { doClose(lbProxyBean, protobufRpcProxyList); super.close(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testExecuteAndFetchWithNulls(){ String sql = "create table testExecWithNullsTbl (" + "id int identity primary key, " + "text varchar(255), " + "aNumber int, " + "aLongNumber bigint)"; try (Connection con = sql2o.open()) { con.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate(); Connection connection = sql2o.beginTransaction(); Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)"); insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", (Integer) null).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", (String) null).addParameter("number", 21).addParameter("lnum", (Long) null).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate(); connection.commit(); List<Entity> fetched = con.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class); assertTrue(fetched.size() == 5); assertNull(fetched.get(2).text); assertNotNull(fetched.get(3).text); assertNull(fetched.get(1).aNumber); assertNotNull(fetched.get(2).aNumber); assertNull(fetched.get(2).aLongNumber); assertNotNull(fetched.get(3).aLongNumber); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExecuteAndFetchWithNulls(){ String sql = "create table testExecWithNullsTbl (" + "id int identity primary key, " + "text varchar(255), " + "aNumber int, " + "aLongNumber bigint)"; sql2o.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate(); Connection connection = sql2o.beginTransaction(); Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)"); insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", (Integer)null).addParameter("lnum", 10L).executeUpdate(); insQuery.addParameter("text", (String)null).addParameter("number", 21).addParameter("lnum", (Long)null).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate(); insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate(); connection.commit(); List<Entity> fetched = sql2o.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class); assertTrue(fetched.size() == 5); assertNull(fetched.get(2).text); assertNotNull(fetched.get(3).text); assertNull(fetched.get(1).aNumber); assertNotNull(fetched.get(2).aNumber); assertNull(fetched.get(2).aLongNumber); assertNotNull(fetched.get(3).aLongNumber); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExecuteAndFetch(){ createAndFillUserTable(); try (Connection con = sql2o.open()) { Date before = new Date(); List<User> allUsers = con.createQuery("select * from User").executeAndFetch(User.class); assertNotNull(allUsers); Date after = new Date(); long span = after.getTime() - before.getTime(); System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span)); // repeat this before = new Date(); allUsers = con.createQuery("select * from User").executeAndFetch(User.class); after = new Date(); span = after.getTime() - before.getTime(); System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span)); assertTrue(allUsers.size() == insertIntoUsers); } deleteUserTable(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExecuteAndFetch(){ createAndFillUserTable(); Date before = new Date(); List<User> allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class); Date after = new Date(); long span = after.getTime() - before.getTime(); System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span)); // repeat this before = new Date(); allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class); after = new Date(); span = after.getTime() - before.getTime(); System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span)); assertTrue(allUsers.size() == insertIntoUsers); deleteUserTable(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSelectTransactedGetAs() { try (Database db = db()) { db // .select("select name from person") // .transacted() // .getAs(String.class) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValueCount(4) // .assertComplete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSelectTransactedGetAs() { db() // .select("select name from person") // .transacted() // .getAs(String.class) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValueCount(4) // .assertComplete(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSelectTransactedChained() throws Exception { try (Database db = db()) { db // .select("select score from person where name=?") // .parameters("FRED", "JOSEPH") // .transacted() // .transactedValuesOnly() // .getAs(Integer.class) // .doOnNext(tx -> log .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// .flatMap(tx -> tx // .select("select name from person where score = ?") // .parameter(tx.value()) // .valuesOnly() // .getAs(String.class)) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoErrors() // .assertValues("FRED", "JOSEPH") // .assertComplete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSelectTransactedChained() throws Exception { Database db = db(); db // .select("select score from person where name=?") // .parameters("FRED", "JOSEPH") // .transacted() // .transactedValuesOnly() // .getAs(Integer.class) // .doOnNext( tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// .flatMap(tx -> tx // .select("select name from person where score = ?") // .parameter(tx.value()) // .valuesOnly() // .getAs(String.class)) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoErrors() // .assertValues("FRED", "JOSEPH") // .assertComplete(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test @Ignore // TODO fix test public void testMaxIdleTime() throws InterruptedException { TestScheduler s = new TestScheduler(); AtomicInteger count = new AtomicInteger(); AtomicInteger disposed = new AtomicInteger(); MemberFactory<Integer, NonBlockingPool<Integer>> memberFactory = pool -> new NonBlockingMember<Integer>(pool, null); Pool<Integer> pool = NonBlockingPool.factory(() -> count.incrementAndGet()) // .healthy(n -> true) // .disposer(n -> { }) // .maxSize(3) // .maxIdleTime(1, TimeUnit.MINUTES) // .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // .disposer(n -> disposed.incrementAndGet()) // .memberFactory(memberFactory) // .scheduler(s) // .build(); TestSubscriber<Member<Integer>> ts = pool // .member() // .repeat() // .doOnNext(m -> m.checkin()) // .doOnNext(System.out::println) // .doOnRequest(t -> System.out.println("test request=" + t)) // .test(1); s.triggerActions(); ts.assertValueCount(1); assertEquals(0, disposed.get()); s.advanceTimeBy(1, TimeUnit.MINUTES); s.triggerActions(); assertEquals(1, disposed.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore // TODO fix test public void testMaxIdleTime() throws InterruptedException { TestScheduler s = new TestScheduler(); AtomicInteger count = new AtomicInteger(); AtomicInteger disposed = new AtomicInteger(); MemberFactory2<Integer, NonBlockingPool2<Integer>> memberFactory = pool -> new NonBlockingMember2<Integer>(pool, null); Pool2<Integer> pool = NonBlockingPool2.factory(() -> count.incrementAndGet()) // .healthy(n -> true) // .disposer(n -> { }) // .maxSize(3) // .maxIdleTime(1, TimeUnit.MINUTES) // .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // .disposer(n -> disposed.incrementAndGet()) // .memberFactory(memberFactory) // .scheduler(s) // .build(); TestSubscriber<Member2<Integer>> ts = pool // .member() // .repeat() // .doOnNext(m -> m.checkin()) // .doOnNext(System.out::println) // .doOnRequest(t -> System.out.println("test request=" + t)) // .test(1); s.triggerActions(); ts.assertValueCount(1); assertEquals(0, disposed.get()); s.advanceTimeBy(1, TimeUnit.MINUTES); s.triggerActions(); assertEquals(1, disposed.get()); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException { TestScheduler scheduler = new TestScheduler(); NonBlockingConnectionPool2 pool = Pools // .nonBlocking() // .connectionProvider(DatabaseCreator.connectionProvider()) // .maxIdleTime(10, TimeUnit.MINUTES) // .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // .healthy(healthy) // .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // .scheduler(scheduler) // .maxPoolSize(1) // .build(); try (Database db = Database.from(pool)) { TestSubscriber<Integer> ts0 = db.select( // "select score from person where name=?") // .parameter("FRED") // .getAs(Integer.class) // .test(); ts0.assertValueCount(0) // .assertNotComplete(); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); ts0.assertValueCount(1) // .assertComplete(); TestSubscriber<Integer> ts = db.select( // "select score from person where name=?") // .parameter("FRED") // .getAs(Integer.class) // .test() // .assertValueCount(0); System.out.println("done2"); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); Thread.sleep(200); ts.assertValueCount(1); Thread.sleep(200); ts.assertValue(21) // .assertComplete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException { TestScheduler scheduler = new TestScheduler(); NonBlockingConnectionPool pool = Pools // .nonBlocking() // .connectionProvider(DatabaseCreator.connectionProvider()) // .maxIdleTime(10, TimeUnit.MINUTES) // .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // .healthy(healthy) // .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // .scheduler(scheduler) // .maxPoolSize(1) // .build(); try (Database db = Database.from(pool)) { TestSubscriber<Integer> ts0 = db.select( // "select score from person where name=?") // .parameter("FRED") // .getAs(Integer.class) // .test(); ts0.assertValueCount(0) // .assertNotComplete(); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); ts0.assertValueCount(1) // .assertComplete(); TestSubscriber<Integer> ts = db.select( // "select score from person where name=?") // .parameter("FRED") // .getAs(Integer.class) // .test() // .assertValueCount(0); System.out.println("done2"); scheduler.advanceTimeBy(1, TimeUnit.MINUTES); Thread.sleep(200); ts.assertValueCount(1); Thread.sleep(200); ts.assertValue(21) // .assertComplete(); } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testUpdateClobWithNull() { try (Database db = db()) { insertNullClob(db); db // .update("update person_clob set document = :doc") // .parameter("doc", Database.NULL_CLOB) // .counts() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1) // .assertComplete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUpdateClobWithNull() { Database db = db(); insertNullClob(db); db // .update("update person_clob set document = :doc") // .parameter("doc", Database.NULL_CLOB) // .counts() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(1) // .assertComplete(); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testAutoMapToInterfaceWithIndexTooSmall() { try (Database db = db()) { db // .select("select name, score from person order by name") // .autoMap(Person7.class) // .firstOrError() // .map(Person7::examScore) // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoValues() // .assertError(ColumnIndexOutOfRangeException.class); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAutoMapToInterfaceWithIndexTooSmall() { db() // .select("select name, score from person order by name") // .autoMap(Person7.class) // .firstOrError() // .map(Person7::examScore) // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoValues() // .assertError(ColumnIndexOutOfRangeException.class); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static Database test(int maxPoolSize) { Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0"); return Database.from( // Pools.nonBlocking() // .connectionProvider(testConnectionProvider()) // .maxPoolSize(maxPoolSize) // .build()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Database test(int maxPoolSize) { Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0"); return Database.from( // Pools.nonBlocking() // .connectionProvider(testConnectionProvider()) // .maxPoolSize(maxPoolSize) // .scheduler(Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))) // .build()); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSelectWithFetchSizeZero() { try (Database db = db()) { db.select("select score from person order by name") // .fetchSize(0) // .getAs(Integer.class) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoErrors() // .assertValues(21, 34, 25) // .assertComplete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSelectWithFetchSizeZero() { db().select("select score from person order by name") // .fetchSize(0) // .getAs(Integer.class) // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertNoErrors() // .assertValues(21, 34, 25) // .assertComplete(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void sendMessage(CommandIssuer issuer, MessageType type, MessageKeyProvider key, String... replacements) { String message = formatMessage(issuer, type, key, replacements); for (String msg : ACFPatterns.NEWLINE.split(message)) { issuer.sendMessageInternal(ACFUtil.rtrim(msg)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void sendMessage(CommandIssuer issuer, MessageType type, MessageKeyProvider key, String... replacements) { String message = getLocales().getMessage(issuer, key.getMessageKey()); if (replacements.length > 0) { message = ACFUtil.replaceStrings(message, replacements); } message = getCommandReplacements().replace(message); MessageFormatter formatter = formatters.getOrDefault(type, defaultFormatter); if (formatter != null) { message = formatter.format(message); } for (String msg : ACFPatterns.NEWLINE.split(message)) { issuer.sendMessageInternal(msg); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public List<String> tabComplete(CommandIssuer issuer, String commandLabel, String[] args) { return tabComplete(issuer, commandLabel, args, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> tabComplete(CommandIssuer issuer, String commandLabel, String[] args) throws IllegalArgumentException { commandLabel = commandLabel.toLowerCase(); try { CommandOperationContext commandOperationContext = preCommandOperation(issuer, commandLabel, args); final CommandSearch search = findSubCommand(args, true); String argString = ApacheCommonsLangUtil.join(args, " ").toLowerCase(); final List<String> cmds = new ArrayList<>(); if (search != null) { cmds.addAll(completeCommand(commandOperationContext, issuer, search.cmd, Arrays.copyOfRange(args, search.argIndex, args.length), commandLabel)); } else if (subCommands.get(UNKNOWN).size() == 1) { cmds.addAll(completeCommand(commandOperationContext, issuer, Iterables.getOnlyElement(subCommands.get(UNKNOWN)), args, commandLabel)); } for (Map.Entry<String, RegisteredCommand> entry : subCommands.entries()) { final String key = entry.getKey(); if (key.startsWith(argString) && !UNKNOWN.equals(key) && !DEFAULT.equals(key)) { final RegisteredCommand value = entry.getValue(); if (!value.hasPermission(issuer)) { continue; } String prefCommand = value.prefSubCommand; final String[] psplit = ACFPatterns.SPACE.split(prefCommand); cmds.add(psplit[args.length - 1]); } } return filterTabComplete(args[args.length - 1], cmds); } finally { postCommandOperation(); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean hasLink(final String pid, final String rel, final String href) throws IOException { this.checkExist(pid); try (final Item item = this.item()) { return !new Xocument(item.path()).nodes( String.format( // @checkstyle LineLength (1 line) "/catalog/project[@id='%s' and links/link[@rel='%s' and @href='%s']]", pid, rel, href ) ).isEmpty(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean hasLink(final String pid, final String rel, final String href) throws IOException { if (!this.exists(pid)) { throw new IllegalArgumentException( new Par( "Project %s doesn't exist, can't check link" ).say(pid) ); } try (final Item item = this.item()) { return !new Xocument(item.path()).nodes( String.format( // @checkstyle LineLength (1 line) "/catalog/project[@id='%s' and links/link[@rel='%s' and @href='%s']]", pid, rel, href ) ).isEmpty(); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rejectsIfAlreadyApplied() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String uid = "yegor256"; people.touch(uid); people.apply(uid, Instant.now()); final RqWithUser req = new RqWithUser( farm, new RqFake("POST", "/join-post") ); people.breakup(uid); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( req, "personality=INTJ-A&stackoverflow=187241" ) ), new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2)) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rejectsIfAlreadyApplied() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String uid = "yegor256"; people.touch(uid); people.apply(uid, new Date()); final RqWithUser req = new RqWithUser( farm, new RqFake("POST", "/join-post") ); people.breakup(uid); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( req, "personality=INTJ-A&stackoverflow=187241" ) ), new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2)) ); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rendersAgendaPage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithUser( farm, new RqFake("GET", "/u/Yegor256/agenda") ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:body") ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rendersAgendaPage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String uid = "yegor256"; final People people = new People(farm).bootstrap(); people.touch(uid); people.invite(uid, "mentor"); final Take take = new TkApp(farm); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( take.act( new RqWithHeaders( new RqFake("GET", "/u/Yegor256/agenda"), // @checkstyle LineLength (1 line) "Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE" ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:body") ); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rendersReport() throws Exception { final Farm farm = new FtFarm(new PropsFarm(new FkFarm())); final String uid = "yegor256"; new ClaimOut() .type("Order was given") .param("login", uid) .postTo(farm.find("@id='C00000000'").iterator().next()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new View( farm, "/report/C00000000?report=orders-given-by-week" ).xml() ), XhtmlMatchers.hasXPaths("/page/rows/row[week]") ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rendersReport() throws Exception { final Farm farm = new FtFarm(new PropsFarm(new FkFarm())); final String uid = "yegor256"; new ClaimOut() .type("Order was given") .param("login", uid) .postTo(farm.find("@id='C00000000'").iterator().next()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithHeaders( new RqWithUser( farm, new RqFake( "GET", // @checkstyle LineLength (1 line) "/report/C00000000?report=orders-given-by-week" ) ), "Accept: application/vnd.zerocracy+xml" ) ) ).printBody() ), XhtmlMatchers.hasXPaths("/page/rows/row[week]") ); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public Collection<String> links(final String pid) throws IOException { this.checkExist(pid); try (final Item item = this.item()) { return new SolidList<>( new Mapped<>( xml -> String.format( "%s:%s", xml.xpath("@rel").get(0), xml.xpath("@href").get(0) ), new Xocument(item).nodes( String.format( "/catalog/project[@id='%s']/links/link", pid ) ) ) ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Collection<String> links(final String pid) throws IOException { if (!this.exists(pid)) { throw new IllegalArgumentException( new Par( "Project %s doesn't exist, can't get links" ).say(pid) ); } try (final Item item = this.item()) { return new SolidList<>( new Mapped<>( xml -> String.format( "%s:%s", xml.xpath("@rel").get(0), xml.xpath("@href").get(0) ), new Xocument(item).nodes( String.format( "/catalog/project[@id='%s']/links/link", pid ) ) ) ); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rendersProfilePageWithRateInFirefox() throws Exception { final Farm farm = FkFarm.props(); final double rate = 99.99; final People people = new People(farm).bootstrap(); people.rate( "yegor256", new Cash.S(String.format("USD %f", rate)) ); MatcherAssert.assertThat( new View(farm, "/u/yegor256").html(), Matchers.containsString( String.format( "rate</a> is <span style=\"color:darkgreen\">$%.2f</span>", rate ) ) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rendersProfilePageWithRateInFirefox() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final double rate = 99.99; final People people = new People(farm).bootstrap(); people.rate( "yegor256", new Cash.S(String.format("USD %f", rate)) ); MatcherAssert.assertThat( new View(farm, "/u/yegor256").html(), Matchers.containsString( String.format( "rate</a> is <span style=\"color:darkgreen\">$%.2f</span>", rate ) ) ); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rendersSingleArtifact() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithUser( farm, new RqFake( "GET", "/xml/C00000000?file=roles.xml" ) ) ) ).printBody() ), XhtmlMatchers.hasXPaths("/roles") ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rendersSingleArtifact() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final Catalog catalog = new Catalog(new Pmo(farm)).bootstrap(); final String pid = "A1B2C3D4F"; catalog.add(pid, String.format("2017/07/%s/", pid)); final Roles roles = new Roles( farm.find(String.format("@id='%s'", pid)).iterator().next() ).bootstrap(); final String uid = "yegor256"; roles.assign(uid, "PO"); new People(new Pmo(farm)).bootstrap().invite(uid, "mentor"); final Take take = new TkApp(farm); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( take.act( new RqWithHeaders( new RqFake( "GET", String.format( "/xml/%s?file=roles.xml", pid ) ), // @checkstyle LineLength (1 line) "Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE" ) ) ).printBody() ), XhtmlMatchers.hasXPaths("/roles") ); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void acceptIfNeverApplied() throws Exception { final Farm farm = FkFarm.props(); final People people = new People(farm).bootstrap(); final String uid = "yegor256"; people.touch(uid); final Request req = new RqWithUser( farm, new RqFake("POST", "/join-post"), uid ); people.breakup(uid); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( req, // @checkstyle LineLength (1 line) "personality=INTJ-A&stackoverflow=187241&telegram=123&about=txt" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/") ) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void acceptIfNeverApplied() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String uid = "yegor256"; people.touch(uid); final Request req = new RqWithUser( farm, new RqFake("POST", "/join-post"), uid ); people.breakup(uid); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( req, // @checkstyle LineLength (1 line) "personality=INTJ-A&stackoverflow=187241&telegram=123&about=txt" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/") ) ); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code public void title(final String pid, final String title) throws IOException { this.checkExist(pid); try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives() .xpath(String.format("/catalog/project[@id = '%s']", pid)) .strict(1) .addIf(Catalog.PRJ_TITLE) .set(title) ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void title(final String pid, final String title) throws IOException { if (!this.exists(pid)) { throw new IllegalArgumentException( new Par( "Project %s doesn't exist, can't change title" ).say(pid) ); } try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives() .xpath(String.format("/catalog/project[@id = '%s']", pid)) .strict(1) .addIf(Catalog.PRJ_TITLE) .set(title) ); } } #location 7 #vulnerability type RESOURCE_LEAK