output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code public void saveConfig(String configString, File file) throws IOException { String configuration = this.prepareConfigString(configString); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); writer.write(configuration); writer.flush(); } catch (IOException e) { throw e; } finally { if (writer != null) writer.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveConfig(String configString, File file) throws IOException { String configuration = this.prepareConfigString(configString); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); writer.write(configuration); writer.flush(); writer.close(); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Deprecated protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt) throws IOException { /* NOTE: MUST call the deprecated method until it is deleted, just so * that override still works as expected, for now. */ return _createGenerator(out, ctxt); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Deprecated protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt) throws IOException { WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt, _generatorFeatures, _objectCodec, out); if (_characterEscapes != null) { gen.setCharacterEscapes(_characterEscapes); } SerializableString rootSep = _rootValueSeparator; if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { gen.setRootValueSeparator(rootSep); } return gen; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void testFieldValueWrites() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartObject(); gen.writeNumberField("long", 3L); gen.writeNumberField("double", 0.25); gen.writeNumberField("float", -0.25f); gen.writeEndObject(); gen.close(); assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testFieldValueWrites() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartObject(); gen.writeNumberField("long", 3L); gen.writeNumberField("double", 0.25); gen.writeNumberField("float", -0.25f); gen.writeEndObject(); gen.close(); assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim()); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public void testConvenienceMethods() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartObject(); final BigDecimal dec = new BigDecimal("0.1"); final String TEXT = "\"some\nString!\""; gen.writeNullField("null"); gen.writeBooleanField("bt", true); gen.writeBooleanField("bf", false); gen.writeNumberField("int", -1289); gen.writeNumberField("dec", dec); gen.writeObjectFieldStart("ob"); gen.writeStringField("str", TEXT); gen.writeEndObject(); gen.writeArrayFieldStart("arr"); gen.writeEndArray(); gen.writeEndObject(); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("null", jp.getText()); assertEquals(JsonToken.VALUE_NULL, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("bt", jp.getText()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("bf", jp.getText()); assertEquals(JsonToken.VALUE_FALSE, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("int", jp.getText()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("dec", jp.getText()); assertEquals(JsonToken.VALUE_NUMBER_FLOAT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("ob", jp.getText()); assertEquals(JsonToken.START_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("str", jp.getText()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals(TEXT, getAndVerifyText(jp)); assertEquals(JsonToken.END_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("arr", jp.getText()); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_OBJECT, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testConvenienceMethods() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartObject(); final BigDecimal dec = new BigDecimal("0.1"); final String TEXT = "\"some\nString!\""; gen.writeNullField("null"); gen.writeBooleanField("bt", true); gen.writeBooleanField("bf", false); gen.writeNumberField("int", -1289); gen.writeNumberField("dec", dec); gen.writeObjectFieldStart("ob"); gen.writeStringField("str", TEXT); gen.writeEndObject(); gen.writeArrayFieldStart("arr"); gen.writeEndArray(); gen.writeEndObject(); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("null", jp.getText()); assertEquals(JsonToken.VALUE_NULL, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("bt", jp.getText()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("bf", jp.getText()); assertEquals(JsonToken.VALUE_FALSE, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("int", jp.getText()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("dec", jp.getText()); assertEquals(JsonToken.VALUE_NUMBER_FLOAT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("ob", jp.getText()); assertEquals(JsonToken.START_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("str", jp.getText()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals(TEXT, getAndVerifyText(jp)); assertEquals(JsonToken.END_OBJECT, jp.nextToken()); assertEquals(JsonToken.FIELD_NAME, jp.nextToken()); assertEquals("arr", jp.getText()); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(JsonToken.END_OBJECT, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); } #location 64 #vulnerability type RESOURCE_LEAK
#fixed code public void testInvalidObjectWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartObject(); // Mismatch: try { gen.writeEndArray(); fail("Expected an exception for mismatched array/object write"); } catch (JsonGenerationException e) { verifyException(e, "Current context not an array"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testInvalidObjectWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartObject(); // Mismatch: try { gen.writeEndArray(); fail("Expected an exception for mismatched array/object write"); } catch (JsonGenerationException e) { verifyException(e, "Current context not an array"); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void run() { logger.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction); try { long usedOldBytes = logOldGenStatus(); if (needTriggerGc(maxOldBytes, usedOldBytes, oldGenOccupancyFraction)) { preGc(); doGc(); postGc(); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { scheduler.reschedule(this); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { log.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction + ", datetime: " + new Date()); try { oldMemoryPool = getOldMemoryPool(); long maxOldBytes = getMemoryPoolMaxOrCommitted(oldMemoryPool); long oldUsedBytes = oldMemoryPool.getUsage().getUsed(); log.info(String.format("max old gen: %.2f MB, used old gen: %.2f MB, available old gen: %.2f MB.", SizeUnit.BYTES.toMegaBytes(maxOldBytes), SizeUnit.BYTES.toMegaBytes(oldUsedBytes), SizeUnit.BYTES.toMegaBytes(maxOldBytes - oldUsedBytes))); if (needTriggerGc(maxOldBytes, oldUsedBytes, oldGenOccupancyFraction)) { preGc(); doGc(); postGc(); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (!scheduler.isShutdown()) { // reschedule this task try { scheduler.reschedule(this); } catch (Exception e) { log.error(e.getMessage(), e); } } } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private void updateGC() { if (perfDataSupport) { ygcCount.update((Long) ygcCountCounter.getValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); fullgcCount.update((Long) fullGcCountCounter.getValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } else if (isJmxStateOk()) { try { ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount()); ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime()); fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount()); fullgcTimeMills.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime()); } catch (Exception e) { handleJmxFetchDataError(e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void updateGC() { if (perfDataSupport) { ygcCount.update((Long) ygcCountCounter.getValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); fullgcCount.update((Long) fullGcCountCounter.getValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } else if (isJmxStateOk()) { try { ygcCount.update(jmxClient.getYoungCollector().getCollectionCount()); ygcTimeMills.update(jmxClient.getYoungCollector().getCollectionTime()); fullgcCount.update(jmxClient.getFullCollector().getCollectionCount()); fullgcTimeMills.update(jmxClient.getFullCollector().getCollectionTime()); } catch (Exception e) { handleJmxFetchDataError(e); } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private void updateGC() { if (perfDataSupport) { ygcCount.update(ygcCountCounter.longValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); if (fullGcCountCounter != null) { fullgcCount.update(fullGcCountCounter.longValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } } else if (isJmxStateOk()) { try { JmxGarbageCollectorManager gcManager = jmxClient.getGarbageCollectorManager(); GarbageCollectorMXBean ygcMXBean = gcManager.getYoungCollector(); ygcStrategy = gcManager.getYgcStrategy(); ygcCount.update(ygcMXBean.getCollectionCount()); ygcTimeMills.update(ygcMXBean.getCollectionTime()); GarbageCollectorMXBean fullgcMXBean = gcManager.getFullCollector(); if (fullgcMXBean != null) { fullgcStrategy = gcManager.getFgcStrategy(); fullgcCount.update(fullgcMXBean.getCollectionCount()); fullgcTimeMills.update(fullgcMXBean.getCollectionTime()); } } catch (Exception e) { handleJmxFetchDataError(e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void updateGC() { if (perfDataSupport) { ygcCount.update(ygcCountCounter.longValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); if (fullGcCountCounter != null) { fullgcCount.update(fullGcCountCounter.longValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } } else if (isJmxStateOk()) { try { ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount()); ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime()); if (jmxClient.getGarbageCollectorManager().getFullCollector() != null) { fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount()); fullgcTimeMills .update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime()); } } catch (Exception e) { handleJmxFetchDataError(e); } } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Double getFGCT() throws Exception { if (fgcCollector == null) { return 0.0; } return Double.parseDouble(getAttribute(fgcCollector, COLLECTION_TIME_ATTRIBUTE).toString()) / 1000; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Double getFGCT() throws Exception { return Double.parseDouble(getAttribute(fgcCollector, COLLECTION_TIME_ATTRIBUTE).toString()) / 1000; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private List<String> readContractList() { return ResourceLoader .newBufferedReader(SLA_CONTRACTS_LIST, getClass()) .lines() .filter(l -> !l.startsWith("#")) .filter(l -> !l.trim().isEmpty()) .collect(toList()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<String> readContractList() { return ResourceLoader .getBufferedReader(getClass(), SLA_CONTRACTS_LIST) .lines() .filter(l -> !l.startsWith("#")) .filter(l -> !l.trim().isEmpty()) .collect(toList()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) { NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet(); if(!(netcl.getCurrentTask() instanceof CloudletExecutionTask)) throw new RuntimeException( "This method has to be called only when the current task of the NetworkCloudlet, inside the given ResCloudlet, is a CloudletExecutionTask"); /** * @todo @author manoelcampos The method updates the execution * length of the task, considering the NetworkCloudlet * has only 1 execution task. */ CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask(); task.process(netcl.getCloudletFinishedSoFar()); if (task.isFinished()) { netcl.getCurrentTask().computeExecutionTime(currentTime); startNextTask(netcl); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) { NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet(); /** * @todo @author manoelcampos updates the execution * length of the task, considering the NetworkCloudlet * has only one execution task. */ CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask(); task.process(netcl.getCloudletFinishedSoFar()); if (task.isFinished()) { netcl.getCurrentTask().computeExecutionTime(currentTime); startNextTask(netcl); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static GoogleTaskEventsTraceReader getInstance( final CloudSim simulation, final String filePath, final Function<TaskEvent, Cloudlet> cloudletCreationFunction) { final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleTaskEventsTraceReader.class); return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static GoogleTaskEventsTraceReader getInstance( final CloudSim simulation, final String filePath, final Function<TaskEvent, Cloudlet> cloudletCreationFunction) { final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleTaskEventsTraceReader.class); return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code private List<String> readContractList() { return ResourceLoader .newBufferedReader(SLA_CONTRACTS_LIST, getClass()) .lines() .map(String::trim) .filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("#")) .collect(toList()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<String> readContractList() { return ResourceLoader .getBufferedReader(getClass(), SLA_CONTRACTS_LIST) .lines() .map(String::trim) .filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("#")) .collect(toList()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public static SlaContract getInstance(final String jsonFilePath) { return getInstanceInternal(ResourceLoader.newInputStream(jsonFilePath, SlaContract.class)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static SlaContract getInstance(final String jsonFilePath) { return getInstanceInternal(ResourceLoader.getInputStream(jsonFilePath, SlaContract.class)); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code @ManagedMetric(description = "Total Disk Space assigned") public long getTotalDiskAssigned() { return convertPotentialLong(parseStorageTotals().get("hdd").get("total")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @ManagedMetric(description = "Total Disk Space assigned") public long getTotalDiskAssigned() { return (Long) parseStorageTotals().get("hdd").get("total"); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMutators() { final CSVFormat format = new CSVFormat('!', '!', null, '!', '!', true, true, CRLF, null); assertEquals('?', format.withDelimiter('?').getDelimiter()); assertEquals('?', format.withQuoteChar('?').getQuoteChar().charValue()); assertEquals('?', format.withCommentStart('?').getCommentStart().charValue()); assertEquals("?", format.withLineSeparator("?").getLineSeparator()); assertEquals('?', format.withEscape('?').getEscape().charValue()); assertFalse(format.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertFalse(format.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertEquals(Quote.ALL, format.withQuotePolicy(Quote.ALL).getQuotePolicy()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMutators() { final CSVFormat format = new CSVFormat('!', '!', null, '!', '!', true, true, CRLF, null); assertEquals('?', format.withDelimiter('?').getDelimiter()); assertEquals('?', format.withEncapsulator('?').getQuoteChar().charValue()); assertEquals('?', format.withCommentStart('?').getCommentStart().charValue()); assertEquals("?", format.withLineSeparator("?").getLineSeparator()); assertEquals('?', format.withEscape('?').getEscape().charValue()); assertFalse(format.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertFalse(format.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertEquals(Quote.ALL, format.withQuotePolicy(Quote.ALL).getQuotePolicy()); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parse(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parseString(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code @Test @Ignore public void testBackslashEscapingOld() throws IOException { String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; String[][] res = { {"one", "two", "three"}, {"on\\\"e", "two"}, {"on\"e", "two"}, {"one", "tw\"o"}, {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") {"one", "two", "th,ree"}, {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") {"a\\", "b"}, // a backslash must be returnd {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") }; CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore public void testBackslashEscapingOld() throws IOException { String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; String[][] res = { {"one", "two", "three"}, {"on\\\"e", "two"}, {"on\"e", "two"}, {"one", "tw\"o"}, {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") {"one", "two", "th,ree"}, {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") {"a\\", "b"}, // a backslash must be returnd {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") }; CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testExcelFormat1() throws IOException { String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat1() throws IOException { String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testIgnoreEmptyLines() throws IOException { final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; //String code = "world\r\n\n"; //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; final CSVParser parser = CSVParser.parseString(code); final List<CSVRecord> records = parser.getRecords(); assertEquals(3, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIgnoreEmptyLines() throws IOException { final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; //String code = "world\r\n\n"; //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(3, records.size()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printComment("This is a comment"); assertEquals("", sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printComment("This is a comment"); assertEquals("", sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyLineBehaviourExcel() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (String code : codes) { CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyLineBehaviourExcel() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (String code : codes) { CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetRecords() throws IOException { final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetRecords() throws IOException { final CSVParser parser = new CSVParser(new StringReader(CSVINPUT), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDefaultFormat() throws IOException { final String code = "" + "a,b#\n" // 1) + "\"\n\",\" \",#\n" // 2) + "#,\"\"\n" // 3) + "# Final comment\n"// 4) ; final String[][] res = { {"a", "b#"}, {"\n", " ", "#"}, {"#", ""}, {"# Final comment"} }; CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isCommentingEnabled()); CSVParser parser = CSVParser.parse(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Failed to parse without comments", res, records); final String[][] res_comments = { {"a", "b#"}, {"\n", " ", "#"}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser.close(); parser = CSVParser.parse(code, format); records = parser.getRecords(); Utils.compare("Failed to parse with comments", res_comments, records); parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDefaultFormat() throws IOException { final String code = "" + "a,b#\n" // 1) + "\"\n\",\" \",#\n" // 2) + "#,\"\"\n" // 3) + "# Final comment\n"// 4) ; final String[][] res = { {"a", "b#"}, {"\n", " ", "#"}, {"#", ""}, {"# Final comment"} }; CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isCommentingEnabled()); CSVParser parser = CSVParser.parse(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Failed to parse without comments", res, records); final String[][] res_comments = { {"a", "b#"}, {"\n", " ", "#"}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = CSVParser.parse(code, format); records = parser.getRecords(); Utils.compare("Failed to parse with comments", res_comments, records); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyLineBehaviourCSV() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyLineBehaviourCSV() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected Function<Publisher<?>, Publisher<?>> lookup(String name) { Function<Publisher<?>, Publisher<?>> function = this.function; if (name != null && this.catalog != null) { @SuppressWarnings("unchecked") Function<Publisher<?>, Publisher<?>> preferred = this.catalog .lookup(Function.class, name); if (preferred != null) { function = preferred; } } if (function != null) { return function; } throw new IllegalStateException("No function defined with name=" + name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Function<Publisher<?>, Publisher<?>> lookup(String name) { Function<Publisher<?>, Publisher<?>> function = this.function; if (name != null && this.catalog != null) { Function<Publisher<?>, Publisher<?>> preferred = this.catalog .lookup(Function.class, name); if (preferred != null) { function = preferred; } } if (function != null) { return function; } throw new IllegalStateException("No function defined"); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int // right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", ""); callback.onSuccess(vResult); ///2016-10-27 华为这版本流程这里,分为两步,这里不便服务器端做验证,注释下面这些 // StringBuilder sb = new StringBuilder(); // sb.append(channel.getCpAppID()).append(ts).append(playerId); // boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); // if(ok){ // // SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); // // callback.onSuccess(vResult); // }else{ // callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); // } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); StringBuilder sb = new StringBuilder(); sb.append(channel.getCpAppID()).append(ts).append(playerId); boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); if(ok){ SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); callback.onSuccess(vResult); }else{ callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code private void writeToLog(String type, String content) { writerThread.execute(()->{ String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeToLog(String type, String content) { String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); if(f==null) { return; } // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void createDefaultAccountPropertiesFile() { Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")..."); final Properties dap = new Properties(); dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD); dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH); dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL); try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) { FileLock lock = accountSettingOut.getChannel().lock(); dap.store(accountSettingOut, "<This is the default kiftd account setting file. >"); lock.release(); Printer.instance.print("初始账户配置文件生成完毕。"); } catch (FileNotFoundException e) { Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。"); } catch (IOException e2) { Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createDefaultAccountPropertiesFile() { Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")..."); final Properties dap = new Properties(); dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD); dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH); dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL); try { dap.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE), "<This is the default kiftd account setting file. >"); Printer.instance.print("初始账户配置文件生成完毕。"); } catch (FileNotFoundException e) { Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。"); } catch (IOException e2) { Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。"); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Override public boolean add(T e) { return internalAdd(e); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean add(T e) { return internalAdd(e, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private boolean internalRemove(T element) { boolean success = false; if (element != null) { success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalRemove(T element) { boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); return success; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalRemove(T element) { boolean success = false; if (element != null) { Integer lrem = nest.cat(JOhmUtils.getId(owner)) .cat(field.getName()).lrem(1, JOhmUtils.getId(element).toString()); unindexValue(element); success = lrem > 0; } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalRemove(T element) { Integer lrem = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .lrem(1, JOhmUtils.getId(element).toString()); unindexValue(element); return lrem > 0; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean add(T element) { return internalAdd(element); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean add(T element) { return internalAdd(element, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void cannotSearchAfterDeletingIndexes() { User user = new User(); user.setAge(88); JOhm.save(user); user.setAge(77); // younger JOhm.save(user); user.setAge(66); // younger still JOhm.save(user); Long id = user.getId(); assertNotNull(JOhm.get(User.class, id)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 66); assertEquals(1, users.size()); JOhm.delete(User.class, id); users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 66); assertEquals(0, users.size()); assertNull(JOhm.get(User.class, id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void cannotSearchAfterDeletingIndexes() { User user = new User(); user.setAge(88); JOhm.save(user); user.setAge(77); // younger JOhm.save(user); user.setAge(66); // younger still JOhm.save(user); int id = user.getId(); assertNotNull(JOhm.get(User.class, id)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 66); assertEquals(1, users.size()); JOhm.delete(User.class, id); users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 66); assertEquals(0, users.size()); assertNull(JOhm.get(User.class, id)); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody() throws ExecutionException, InterruptedException, UnknownHostException { final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true, false); assertEquals(NUMBER_OF_TEST_VALUES, results.size()); verifyResults(results, true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody() throws ExecutionException, InterruptedException, UnknownHostException { final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true); assertEquals(NUMBER_OF_TEST_VALUES, results.size()); for (int i=0; i<NUMBER_OF_TEST_VALUES; ++i) { final String key = "k"+i; assertTrue(results.containsKey(key)); final RiakObject ro = results.get(key); assertNotNull(ro); assertEquals("plain/text", ro.getContentType()); assertFalse(ro.isDeleted()); assertEquals("v"+i, ro.getValue().toStringUtf8()); } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testInterruptedExceptionDealtWith() throws InterruptedException { final Throwable[] ex = {null}; int timeout = 1000; Thread testThread = new Thread(() -> { try { @SuppressWarnings("unchecked") TransferQueue<FakeResponse> fakeQueue = (TransferQueue<FakeResponse>) mock(TransferQueue.class); when(fakeQueue.poll(timeout, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException("foo")); @SuppressWarnings("unchecked") PBStreamingFutureOperation<FakeResponse, Void, Void> coreFuture = (PBStreamingFutureOperation<FakeResponse, Void, Void>) mock(PBStreamingFutureOperation.class); when(coreFuture.getResultsQueue()).thenReturn(fakeQueue); // ChunkedResponseIterator polls the response queue when created, // so we'll use that to simulate a Thread interrupt. new ChunkedResponseIterator<>(coreFuture, timeout, Long::new, FakeResponse::iterator); } catch (RuntimeException rex) { ex[0] = rex; } catch (InterruptedException e) { // Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with // If we actually catch one here we've failed at our jobs. fail(e.getMessage()); } assertTrue(Thread.currentThread().isInterrupted()); }); testThread.start(); testThread.join(); Throwable caughtException = ex[0]; assertNotNull(caughtException); Throwable wrappedException = caughtException.getCause(); assertNotNull(caughtException.getMessage(), wrappedException); assertEquals("foo", wrappedException.getMessage()); assertTrue(wrappedException instanceof InterruptedException); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInterruptedExceptionDealtWith() throws InterruptedException { final boolean[] caught = {false}; final InterruptedException[] ie = {null}; int timeout = 1000; Thread t = new Thread(() -> { try { @SuppressWarnings("unchecked") TransferQueue<FakeResponse> fakeQueue = (TransferQueue<FakeResponse>) mock(TransferQueue.class); when(fakeQueue.poll(timeout, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException( "foo")); @SuppressWarnings("unchecked") PBStreamingFutureOperation<FakeResponse, Void, Void> coreFuture = (PBStreamingFutureOperation<FakeResponse, Void, Void>) mock( PBStreamingFutureOperation.class); when(coreFuture.getResultsQueue()).thenReturn(fakeQueue); // ChunkedResponseIterator polls the response queue when created, // so we'll use that to simulate a Thread interrupt. new ChunkedResponseIterator<>(coreFuture, timeout, Long::new, FakeResponse::iterator); } catch (RuntimeException ex) { caught[0] = true; ie[0] = (InterruptedException) ex.getCause(); } catch (InterruptedException e) { // Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with // If we actually catch one here we've failed at our jobs. caught[0] = false; } assertTrue(Thread.currentThread().isInterrupted()); }); t.start(); t.join(); assertTrue(caught[0]); assertEquals("foo", ie[0].getMessage()); } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(getUserInformation().get("created_utc").toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public double createdUTC() throws IOException, ParseException { return Double.parseDouble(info().get("created_utc").toString()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithInvalidContentLength() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Assert.assertTrue(decoder.isCompleted()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Assert.assertTrue(decoder.isCompleted()); } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code public void testSimpleHttpPostsChunked() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpPostsChunked() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; HttpEntity entity = this.response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len > Integer.MAX_VALUE) { throw new ContentTooLongException("Entity content is too long: " + len); } if (len < 0) { len = 4096; } this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE); response.setEntity(new ContentBufferEntity(entity, this.buf)); } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public void testSimpleHttpHeads() throws Exception { int connNo = 3; int reqNo = 20; Job[] jobs = new Job[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); } Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("HEAD", s); } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener(new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.getFailureMessage() != null) { fail(testjob.getFailureMessage()); } assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertNull(testjob.getResult()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleHttpHeads() throws Exception { int connNo = 3; int reqNo = 20; TestJob[] jobs = new TestJob[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new TestJob(); } Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("HEAD", s); } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener(new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.getFailureMessage() != null) { fail(testjob.getFailureMessage()); } assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertNull(testjob.getResult()); } } #location 61 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testConstructors() throws Exception { final ContentLengthOutputStream in = new ContentLengthOutputStream( new SessionOutputBufferMock(), 10L); in.close(); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConstructors() throws Exception { new ContentLengthOutputStream(new SessionOutputBufferMock(), 10L); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); fail("expected IOException"); } catch(IOException iox) {} deleteWithCheck(fileHandle); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void testResponseContentNoEntity() throws Exception { HttpContext context = new BasicHttpContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testResponseContentNoEntity() throws Exception { HttpContext context = new HttpExecutionContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void testInputThrottling() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("queue", attachment); } public HttpRequest submitRequest(final HttpContext context) { @SuppressWarnings("unchecked") Queue<Job> queue = (Queue<Job>) context.getAttribute("queue"); if (queue == null) { throw new IllegalStateException("Queue is null"); } Job testjob = queue.poll(); context.setAttribute("job", testjob); if (testjob != null) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); StringEntity entity = null; try { entity = new StringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } else { return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob == null) { throw new IllegalStateException("TestJob is null"); } int statusCode = response.getStatusLine().getStatusCode(); String content = null; HttpEntity entity = response.getEntity(); if (entity != null) { try { // Simulate slow response handling in order to cause the // internal content buffer to fill up, forcing the // protocol handler to throttle input rate ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = entity.getContent(); byte[] tmp = new byte[2048]; int l; while((l = instream.read(tmp)) != -1) { Thread.sleep(1); outstream.write(tmp, 0, l); } content = new String(outstream.toByteArray(), EntityUtils.getContentCharSet(entity)); } catch (InterruptedException ex) { content = "Interrupted: " + ex.getMessage(); } catch (IOException ex) { content = "I/O exception: " + ex.getMessage(); } } testjob.setResult(statusCode, content); } public void finalizeContext(final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob != null) { testjob.fail("Request failed"); } } }; int connNo = 3; int reqNo = 20; Job[] jobs = new Job[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(10000); } Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testInputThrottling() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("queue", attachment); } public HttpRequest submitRequest(final HttpContext context) { @SuppressWarnings("unchecked") Queue<TestJob> queue = (Queue<TestJob>) context.getAttribute("queue"); if (queue == null) { throw new IllegalStateException("Queue is null"); } TestJob testjob = queue.poll(); context.setAttribute("job", testjob); if (testjob != null) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); StringEntity entity = null; try { entity = new StringEntity(testjob.getExpected(), "US-ASCII"); entity.setChunked(testjob.getCount() % 2 == 0); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } else { return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { TestJob testjob = (TestJob) context.removeAttribute("job"); if (testjob == null) { throw new IllegalStateException("TestJob is null"); } int statusCode = response.getStatusLine().getStatusCode(); String content = null; HttpEntity entity = response.getEntity(); if (entity != null) { try { // Simulate slow response handling in order to cause the // internal content buffer to fill up, forcing the // protocol handler to throttle input rate ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = entity.getContent(); byte[] tmp = new byte[2048]; int l; while((l = instream.read(tmp)) != -1) { Thread.sleep(1); outstream.write(tmp, 0, l); } content = new String(outstream.toByteArray(), EntityUtils.getContentCharSet(entity)); } catch (InterruptedException ex) { content = "Interrupted: " + ex.getMessage(); } catch (IOException ex) { content = "I/O exception: " + ex.getMessage(); } } testjob.setResult(statusCode, content); } public void finalizeContext(final HttpContext context) { TestJob testjob = (TestJob) context.removeAttribute("job"); if (testjob != null) { testjob.fail("Request failed"); } } }; int connNo = 3; int reqNo = 20; TestJob[] jobs = new TestJob[connNo * reqNo]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new TestJob(10000); } Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>(); for (int i = 0; i < connNo; i++) { SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); connRequests.add(sessionRequest); } while (!connRequests.isEmpty()) { SessionRequest sessionRequest = connRequests.remove(); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); } assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < jobs.length; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(HttpStatus.SC_OK, testjob.getStatusCode()); assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } } #location 127 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } ContentType contentType = ContentType.getOrDefault(entity); String charset = contentType.getCharset(); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } String charset = getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code protected void processEvent(final SelectionKey key) { IOSessionImpl session = (IOSessionImpl) key.attachment(); try { if (key.isAcceptable()) { acceptable(key); } if (key.isConnectable()) { connectable(key); } if (key.isReadable()) { session.resetLastRead(); readable(key); } if (key.isWritable()) { session.resetLastWrite(); writable(key); } } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processEvent(final SelectionKey key) { SessionHandle handle = (SessionHandle) key.attachment(); IOSession session = handle.getSession(); try { if (key.isAcceptable()) { acceptable(key); } if (key.isConnectable()) { connectable(key); } if (key.isReadable()) { handle.resetLastRead(); readable(key); } if (key.isWritable()) { handle.resetLastWrite(); writable(key); } } catch (CancelledKeyException ex) { queueClosedSession(session); key.attach(null); } } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); fileHandle.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 36); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); long pos = 0; while (!decoder.isCompleted()) { long bytesRead = decoder.transfer(fchannel, pos, 10); if (bytesRead > 0) { pos += bytesRead; } } fchannel.close(); assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); fileHandle.delete(); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testFoldedFooters() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\n \r\n fghij\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Header[] footers = decoder.getFooters(); Assert.assertEquals(1, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde fghij", footers[0].getValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFoldedFooters() throws Exception { String s = "10;key=\"value\"\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\n \r\n fghij\r\n\r\n"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(26, bytesRead); Assert.assertEquals("12345678901234561234512345", convert(dst)); Header[] footers = decoder.getFooters(); Assert.assertEquals(1, footers.length); Assert.assertEquals("Footer1", footers[0].getName()); Assert.assertEquals("abcde fghij", footers[0].getValue()); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntityWithMultipleContentLengthAllWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntityWithMultipleContentLengthAllWrong() throws Exception { SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'}); HttpMessage message = new DummyHttpMessage(); // lenient mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false); message.addHeader("Content-Type", "unknown"); message.addHeader("Content-Length", "yyy"); message.addHeader("Content-Length", "xxx"); EntityDeserializer entitygen = new EntityDeserializer( new LaxContentLengthStrategy()); HttpEntity entity = entitygen.deserialize(inbuffer, message); Assert.assertNotNull(entity); Assert.assertEquals(-1, entity.getContentLength()); Assert.assertFalse(entity.isChunked()); InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertFalse(instream instanceof ContentLengthInputStream); Assert.assertTrue(instream instanceof IdentityInputStream); // strict mode message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true); try { entitygen.deserialize(inbuffer, message); Assert.fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code public void testHttpPostsWithExpectationVerification() throws Exception { Job[] jobs = new Job[3]; jobs[0] = new Job("AAAAA", 10); jobs[1] = new Job("AAAAA", 10); jobs[2] = new Job("BBBBB", 20); Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); NByteArrayEntity outgoing = new NByteArrayEntity( EncodingUtils.getAsciiBytes("Expectation failed")); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setExpectationVerifier( expectationVerifier); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < 2; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } Job failedExpectation = jobs[2]; failedExpectation.waitFor(); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpPostsWithExpectationVerification() throws Exception { TestJob[] jobs = new TestJob[3]; jobs[0] = new TestJob("AAAAA", 10); jobs[1] = new TestJob("AAAAA", 10); jobs[2] = new TestJob("BBBBB", 20); Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); NByteArrayEntity outgoing = new NByteArrayEntity( EncodingUtils.getAsciiBytes("Expectation failed")); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setExpectationVerifier( expectationVerifier); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < 2; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } TestJob failedExpectation = jobs[2]; failedExpectation.waitFor(); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode()); } #location 84 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWriteBeyondFileSize() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"a"}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedDecoder decoder = new LengthDelimitedDecoder( channel, inbuf, metrics, 1); File fileHandle = File.createTempFile("testFile", ".txt"); RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw"); FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("expected IOException"); } catch(IOException iox) {} testfile.close(); deleteWithCheck(fileHandle); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public HttpClientConnection create(final HttpHost host) throws IOException { final String scheme = host.getSchemeName(); Socket socket = null; if ("http".equalsIgnoreCase(scheme)) { socket = this.plainfactory != null ? this.plainfactory.createSocket() : new Socket(); } if ("https".equalsIgnoreCase(scheme)) { socket = (this.sslfactory != null ? this.sslfactory : SSLSocketFactory.getDefault()).createSocket(); } if (socket == null) { throw new IOException(scheme + " scheme is not supported"); } final String hostname = host.getHostName(); int port = host.getPort(); if (port == -1) { if (host.getSchemeName().equalsIgnoreCase("http")) { port = 80; } else if (host.getSchemeName().equalsIgnoreCase("https")) { port = 443; } } socket.setSoTimeout(this.sconfig.getSoTimeout()); socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); final int linger = this.sconfig.getSoLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } return this.connFactory.createConnection(socket); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HttpClientConnection create(final HttpHost host) throws IOException { final String scheme = host.getSchemeName(); Socket socket = null; if ("http".equalsIgnoreCase(scheme)) { socket = this.plainfactory != null ? this.plainfactory.createSocket() : new Socket(); } if ("https".equalsIgnoreCase(scheme)) { if (this.sslfactory != null) { socket = this.sslfactory.createSocket(); } } if (socket == null) { throw new IOException(scheme + " scheme is not supported"); } final String hostname = host.getHostName(); int port = host.getPort(); if (port == -1) { if (host.getSchemeName().equalsIgnoreCase("http")) { port = 80; } else if (host.getSchemeName().equalsIgnoreCase("https")) { port = 443; } } socket.setSoTimeout(this.sconfig.getSoTimeout()); socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); final int linger = this.sconfig.getSoLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } return this.connFactory.createConnection(socket); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void testHttpPostsWithExpectationVerification() throws Exception { Job[] jobs = new Job[3]; jobs[0] = new Job("AAAAA", 10); jobs[1] = new Job("AAAAA", 10); jobs[2] = new Job("BBBBB", 20); Queue<Job> queue = new ConcurrentLinkedQueue<Job>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); NByteArrayEntity outgoing = new NByteArrayEntity( EncodingUtils.getAsciiBytes("Expectation failed")); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new RequestHandler())); serviceHandler.setExpectationVerifier( expectationVerifier); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < 2; i++) { Job testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } Job failedExpectation = jobs[2]; failedExpectation.waitFor(); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpPostsWithExpectationVerification() throws Exception { TestJob[] jobs = new TestJob[3]; jobs[0] = new TestJob("AAAAA", 10); jobs[1] = new TestJob("AAAAA", 10); jobs[2] = new TestJob("BBBBB", 20); Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>(); for (int i = 0; i < jobs.length; i++) { queue.add(jobs[i]); } HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() { public void verify( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException { String s = request.getRequestLine().getUri(); if (!s.equals("AAAAAx10")) { response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED); NByteArrayEntity outgoing = new NByteArrayEntity( EncodingUtils.getAsciiBytes("Expectation failed")); response.setEntity(outgoing); } } }; HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler( serverHttpProc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), this.execService, this.server.getParams()); serviceHandler.setHandlerResolver( new SimpleHttpRequestHandlerResolver(new TestRequestHandler())); serviceHandler.setExpectationVerifier( expectationVerifier); serviceHandler.setEventListener( new SimpleEventListener()); HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler( clientHttpProc, requestExecutionHandler, new DefaultConnectionReuseStrategy(), this.execService, this.client.getParams()); clientHandler.setEventListener( new SimpleEventListener()); this.server.start(serviceHandler); this.client.start(clientHandler); ListenerEndpoint endpoint = this.server.getListenerEndpoint(); endpoint.waitFor(); InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress(); assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus()); SessionRequest sessionRequest = this.client.openConnection( new InetSocketAddress("localhost", serverAddress.getPort()), queue); sessionRequest.waitFor(); if (sessionRequest.getException() != null) { throw sessionRequest.getException(); } assertNotNull(sessionRequest.getSession()); assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus()); for (int i = 0; i < 2; i++) { TestJob testjob = jobs[i]; testjob.waitFor(); if (testjob.isSuccessful()) { assertEquals(testjob.getExpected(), testjob.getResult()); } else { fail(testjob.getFailureMessage()); } } TestJob failedExpectation = jobs[2]; failedExpectation.waitFor(); assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode()); } #location 87 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testResponseContentOverwriteHeaders() throws Exception { ResponseContent interceptor = new ResponseContent(true); HttpContext context = new BasicHttpContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10")); response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever")); interceptor.process(response, context); Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testResponseContentOverwriteHeaders() throws Exception { ResponseContent interceptor = new ResponseContent(true); HttpContext context = new BasicHttpContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10")); response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever")); interceptor.process(response, context); Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue()); Assert.assertEquals("whatever", response.getFirstHeader(HTTP.TRANSFER_ENCODING).getValue()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testBlockByAvailabilityOnAllServices() throws Exception { ApolloTestClient apolloTestClient = Common.signupAndLogin(); ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); String availability = "BLOCK-ME-2"; Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability); assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, service, deployableVersion)).isInstanceOf(Exception.class) .hasMessageContaining("Deployment is currently blocked"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBlockByAvailabilityOnAllServices() throws Exception { ApolloTestClient apolloTestClient = Common.signupAndLogin(); ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); String availability = "BLOCK-ME-2"; Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability); DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class) .hasMessageContaining("Deployment is currently blocked"); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void tooDeeplyNestedObjects() throws IOException { Object root = Boolean.TRUE; for (int i = 0; i < MAX_DEPTH + 1; i++) { root = singletonMap("a", root); } JsonReader reader = new JsonValueReader(root); for (int i = 0; i < MAX_DEPTH; i++) { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); } try { reader.beginObject(); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessage("Nesting too deep at $" + repeat(".a", MAX_DEPTH) + "."); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void tooDeeplyNestedObjects() throws IOException { Object root = Boolean.TRUE; for (int i = 0; i < 32; i++) { root = singletonMap("a", root); } JsonReader reader = new JsonValueReader(root); for (int i = 0; i < 31; i++) { reader.beginObject(); assertThat(reader.nextName()).isEqualTo("a"); } try { reader.beginObject(); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessage( "Nesting too deep at $.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a."); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void readerUnquotedDoubleValue() throws Exception { JsonReader reader = factory.newReader("{5:1}"); reader.setLenient(true); reader.beginObject(); reader.promoteNameToValue(); assertThat(reader.nextDouble()).isEqualTo(5d); assertThat(reader.nextInt()).isEqualTo(1); reader.endObject(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void readerUnquotedDoubleValue() throws Exception { JsonReader reader = newReader("{5:1}"); reader.setLenient(true); reader.beginObject(); reader.promoteNameToValue(); assertThat(reader.nextDouble()).isEqualTo(5d); assertThat(reader.nextInt()).isEqualTo(1); reader.endObject(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static JsonWriter of(BufferedSink sink) { return new JsonUtf8Writer(sink); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static JsonWriter of(BufferedSink sink) { return new JsonUt8Writer(sink); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public boolean addOrReplace(byte[] key, V old, V value) { KeyBuffer keyBuffer = keySource(key); byte[] data = value(value); byte[] oldData = value(old); CheckSegment segment = segment(keyBuffer.hash()); return segment.put(keyBuffer, data, false, oldData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean addOrReplace(byte[] key, V old, V value) { KeyBuffer keyBuffer = keySource(key); byte[] data = value(value); byte[] oldData = value(old); if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize) { remove(key); putFailCount++; return false; } CheckSegment segment = segment(keyBuffer.hash()); return segment.put(keyBuffer, data, false, oldData); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean put(byte[] key, V value) { KeyBuffer keyBuffer = keySource(key); byte[] data = value(value); CheckSegment segment = segment(keyBuffer.hash()); return segment.put(keyBuffer, data, false, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean put(byte[] key, V value) { KeyBuffer keyBuffer = keySource(key); byte[] data = value(value); if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize) { remove(key); putFailCount++; return false; } CheckSegment segment = segment(keyBuffer.hash()); return segment.put(keyBuffer, data, false, null); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code Parser(Parser p, String text) { this.logger = p.logger; this.properties = p.properties; this.infoMap = p.infoMap; this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize()); this.lineSeparator = p.lineSeparator; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void parse(File outputFile, Context context, String[] includePath, String ... includes) throws IOException, ParserException { ArrayList<Token> tokenList = new ArrayList<Token>(); for (String include : includes) { File file = null; String filename = include; if (filename.startsWith("<") && filename.endsWith(">")) { filename = filename.substring(1, filename.length() - 1); } else { File f = new File(filename); if (f.exists()) { file = f; } } if (file == null && includePath != null) { for (String path : includePath) { File f = new File(path, filename); if (f.exists()) { file = f; break; } } } if (file == null) { file = new File(filename); } Info info = infoMap.getFirst(file.getName()); if (info != null && info.skip) { continue; } else if (!file.exists()) { throw new FileNotFoundException("Could not parse \"" + file + "\": File does not exist"); } logger.info("Parsing " + file); Token token = new Token(); token.type = Token.COMMENT; token.value = "\n// Parsed from " + include + "\n\n"; tokenList.add(token); Tokenizer tokenizer = new Tokenizer(file); while (!(token = tokenizer.nextToken()).isEmpty()) { if (token.type == -1) { token.type = Token.COMMENT; } tokenList.add(token); } if (lineSeparator == null) { lineSeparator = tokenizer.lineSeparator; } tokenizer.close(); token = new Token(); token.type = Token.COMMENT; token.spacing = "\n"; tokenList.add(token); } tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()])); final String newline = lineSeparator != null ? lineSeparator : "\n"; Writer out = outputFile != null ? new FileWriter(outputFile) { @Override public Writer append(CharSequence text) throws IOException { return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu")); }} : new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }; LinkedList<Info> infoList = leafInfoMap.get(null); for (Info info : infoList) { if (info.javaText != null && !info.javaText.startsWith("import")) { out.append(info.javaText + "\n"); } } out.append(" static { Loader.load(); }\n"); DeclarationList declList = new DeclarationList(); containers(context, declList); declarations(context, declList); for (Declaration d : declList) { out.append(d.text); } out.append("\n}\n").close(); } #location 78 #vulnerability type RESOURCE_LEAK
#fixed code void init(long allocatedAddress, int allocatedCapacity, long ownerAddress, long deallocatorAddress) { address = allocatedAddress; position = 0; limit = allocatedCapacity; capacity = allocatedCapacity; deallocator(new NativeDeallocator(this, ownerAddress, deallocatorAddress)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void init(long allocatedAddress, int allocatedCapacity, long deallocatorAddress) { address = allocatedAddress; position = 0; limit = allocatedCapacity; capacity = allocatedCapacity; deallocator(new NativeDeallocator(this, deallocatorAddress)); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile; try { urlFile = new File(new URI(resourceURL.toString().split("#")[0])); } catch (IllegalArgumentException | URISyntaxException e) { urlFile = new File(resourceURL.getPath()); } String name = urlFile.getName(); boolean reference = false; long size, timestamp; File cacheDir = getCacheDir(); File cacheSubdir = cacheDir.getCanonicalFile(); String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase(); boolean noSubdir = s.equals("true") || s.equals("t") || s.equals(""); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); if (!noSubdir) { String subdirName = jarFileFile.getName(); String parentName = jarEntryFile.getParent(); if (parentName != null) { subdirName = subdirName + File.separator + parentName; } cacheSubdir = new File(cacheSubdir, subdirName); } } else if (urlConnection instanceof HttpURLConnection) { size = urlConnection.getContentLength(); timestamp = urlConnection.getLastModified(); if (!noSubdir) { String path = resourceURL.getHost() + resourceURL.getPath(); cacheSubdir = new File(cacheSubdir, path.substring(0, path.lastIndexOf('/') + 1)); } } else { size = urlFile.length(); timestamp = urlFile.lastModified(); if (!noSubdir) { cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName()); } } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... String newName = resourceURL.getRef(); // ... but create a symbolic link only if the name does not change ... reference = newName.equals(name); name = newName; } File file = new File(cacheSubdir, name); File lockFile = new File(cacheDir, ".lock"); FileChannel lockChannel = null; FileLock lock = null; ReentrantLock threadLock = null; if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... try { Path path = file.toPath(), targetPath = Paths.get(target); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + targetPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, targetPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, targetPath); } } } } catch (IOException | RuntimeException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links, // or other (filesystem?) exception: for example, // "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ... if (logger.isDebugEnabled()) { logger.debug("Failed to create symbolic link " + file + ": " + e); } return null; } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } else { if (urlFile.exists() && reference) { // ... try to create a symbolic link to the existing file, if we can, ... try { Path path = file.toPath(), urlPath = urlFile.toPath(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + urlPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, urlPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, urlPath); } } } return file; } catch (IOException | RuntimeException e) { // ... (let's try to copy the file instead, such as on Windows) ... if (logger.isDebugEnabled()) { logger.debug("Could not create symbolic link " + file + ": " + e); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } // ... check if it has not already been extracted, and if not ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... add lock to avoid two JVMs access cacheDir simultaneously and ... try { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " before extracting"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); // ... check if other JVM has extracted it before this JVM get the lock ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } } return file; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile; try { urlFile = new File(new URI(resourceURL.toString().split("#")[0])); } catch (IllegalArgumentException | URISyntaxException e) { urlFile = new File(resourceURL.getPath()); } String name = urlFile.getName(); boolean reference = false; long size, timestamp; File cacheDir = getCacheDir(); File cacheSubdir = cacheDir.getCanonicalFile(); String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase(); boolean noSubdir = s.equals("true") || s.equals("t") || s.equals(""); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); if (!noSubdir) { String subdirName = jarFileFile.getName(); String parentName = jarEntryFile.getParent(); if (parentName != null) { subdirName = subdirName + File.separator + parentName; } cacheSubdir = new File(cacheSubdir, subdirName); } } else { size = urlFile.length(); timestamp = urlFile.lastModified(); if (!noSubdir) { cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName()); } } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... String newName = resourceURL.getRef(); // ... but create a symbolic link only if the name does not change ... reference = newName.equals(name); name = newName; } File file = new File(cacheSubdir, name); File lockFile = new File(cacheDir, ".lock"); FileChannel lockChannel = null; FileLock lock = null; ReentrantLock threadLock = null; if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... try { Path path = file.toPath(), targetPath = Paths.get(target); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + targetPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, targetPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, targetPath); } } } } catch (IOException | RuntimeException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links, // or other (filesystem?) exception: for example, // "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ... if (logger.isDebugEnabled()) { logger.debug("Failed to create symbolic link " + file + ": " + e); } return null; } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } else { if (urlFile.exists() && reference) { // ... try to create a symbolic link to the existing file, if we can, ... try { Path path = file.toPath(), urlPath = urlFile.toPath(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + urlPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, urlPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, urlPath); } } } return file; } catch (IOException | RuntimeException e) { // ... (let's try to copy the file instead, such as on Windows) ... if (logger.isDebugEnabled()) { logger.debug("Could not create symbolic link " + file + ": " + e); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } // ... check if it has not already been extracted, and if not ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... add lock to avoid two JVMs access cacheDir simultaneously and ... try { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " before extracting"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); // ... check if other JVM has extracted it before this JVM get the lock ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } } return file; } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { throw new ResourceNotFoundException("Unknown ID!"); } routeDTO.setVersion(route.getVersion()); routeDTO.setService(route.getService()); Route newRoute = convertRouteDTOtoRoute(routeDTO, id); routeService.updateRoute(newRoute); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { //TODO Exception } routeDTO.setVersion(route.getVersion()); routeDTO.setService(route.getService()); Route newRoute = convertRouteDTOtoRoute(routeDTO, id); routeService.updateRoute(newRoute); return true; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public AnalysisResult run() throws Exception { long startMs = System.currentTimeMillis(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); long loadEndMs = System.currentTimeMillis(); MBStream<OutlierClassificationResult> ocrs = MBOperatorChain.begin(data) .then(new EWFeatureTransform(conf)) .then(new EWAppxPercentileOutlierClassifier(conf)).executeMiniBatchUntilFixpoint(1000); Summarizer summarizer = new EWStreamingSummarizer(conf); summarizer.consume(ocrs.drain()); Summary result = summarizer.getStream().drain().get(0); final long endMs = System.currentTimeMillis(); final long loadMs = loadEndMs - startMs; final long totalMs = endMs - loadEndMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AnalysisResult run() throws Exception { long startMs = System.currentTimeMillis(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); long loadEndMs = System.currentTimeMillis(); FeatureTransform featureTransform = new EWFeatureTransform(conf); featureTransform.consume(ingester.getStream().drain()); OutlierClassifier outlierClassifier = new EWAppxPercentileOutlierClassifier(conf); outlierClassifier.consume(featureTransform.getStream().drain()); Summarizer summarizer = new EWStreamingSummarizer(conf); summarizer.consume(outlierClassifier.getStream().drain()); Summary result = summarizer.getStream().drain().get(0); final long endMs = System.currentTimeMillis(); final long loadMs = loadEndMs - startMs; final long totalMs = endMs - loadEndMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile) && destFile.setReadOnly(); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { jsonSupport.writeValue(out, values); } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { if (binary) { // handling websocket encoding bug ByteBuf b = allocateBuffer(allocator); try { ByteBufOutputStream os = new ByteBufOutputStream(b); jsonSupport.writeValue(os, values); CharsetEncoder enc = CharsetUtil.ISO_8859_1.newEncoder(); String str = b.toString(CharsetUtil.ISO_8859_1); if (enc.canEncode(str)) { buf.writeBytes(str.getBytes(CharsetUtil.UTF_8)); } else { buf.writeBytes(b); } } finally { b.release(); } } else { jsonSupport.writeValue(out, values); } } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } } #location 64 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canUpsertWithWriteConcern() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().concern(WriteConcern.SAFE).with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); assertThat(writeResult.getLastConcern()).isEqualTo(WriteConcern.SAFE); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canUpsertWithWriteConcern() throws Exception { WriteConcern writeConcern = spy(WriteConcern.SAFE); /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}", writeConcern); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); verify(writeConcern).callGetLastError(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Party party = collection.findOne().as(Party.class); assertThat(party.friends).onProperty("name").containsExactly("Robert", "John"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Friends friends = collection.findOne().as(Friends.class); assertThat(friends.friends).onProperty("name").containsExactly("Robert", "John"); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), is("Hello, world!")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); final byte[] bytes = new byte[(int) response.getEntity().getContentLength()]; new DataInputStream(response.getEntity().getContent()).readFully(bytes); assertThat(new String(bytes, UTF_8), is("Hello, world!")); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public static void start(List<GraphvizEngine> engines) throws IOException { final String executable = SystemUtils.executableName("java"); final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void start(List<GraphvizEngine> engines) throws IOException { final boolean windows = System.getProperty("os.name").contains("windows"); final String executable = windows ? "java.exe" : "java"; final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (threadNum <= 1) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (executorService == null) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); Page page = null; page.getJson().jsonPath("$.name").get(); page.getJson().removePadding("callback").jsonPath("$.name").get(); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (exhausted) return false; LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; Object p = current; E e = null; lock.lock(); try { if ((p != null && p != getNextNode(p)) || (p = getQueueFirst(q)) != null) { e = getNodeItem(p); p = getNextNode(p); } } finally { lock.unlock(); } exhausted = ((current = p) == null); if (e == null) return false; action.accept(e); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; if (!exhausted) { E e = null; lock.lock(); try { if (current == null) { current = getQueueFirst(q); } while (current != null) { e = getNodeItem(current); current = getNextNode(current); if (e != null) { break; } } } finally { lock.unlock(); } if (current == null) { exhausted = true; } if (e != null) { action.accept(e); return true; } } return false; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int hi = getFence(); Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) { action.accept((E) a[i]); } if (getModCount(list) != expectedModCount) { throw new ConcurrentModificationException(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int i, hi; // hoist accesses and checks from loop Vector<E> lst = list; Object[] a; if ((hi = fence) < 0) { synchronized (lst) { expectedModCount = getModCount(lst); a = array = getData(lst); hi = fence = getSize(lst); } } else { a = array; } if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) { action.accept((E) a[i++]); } if (expectedModCount == getModCount(lst)) { return; } } throw new ConcurrentModificationException(); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { String[] strings = line.trim().split("\\s+"); if (strings.length < 1) { continue; } int pid = Integer.parseInt(strings[0]); if (pid == currentPid) { continue; } if (strings.length >= 2 && strings[1].equals("Jps")) { // skip jps continue; } result.put(pid, line); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } return result; } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader, new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { process.write(new String(cbuf, off, len)); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } } #location 51 #vulnerability type RESOURCE_LEAK
#fixed code public static void write(String content, File output) throws IOException { try (final FileOutputStream out = new FileOutputStream(output); final OutputStreamWriter w = new OutputStreamWriter(out)) { w.write(content); w.flush(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void write(String content, File output) throws IOException { FileOutputStream out = new FileOutputStream(output); OutputStreamWriter w = new OutputStreamWriter(out); try { w.write(content); w.flush(); } finally { out.close(); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void close(IotHubConnectionStatusChangeReason reason, Throwable cause) throws DeviceClientException { if (reason == null) { //Codes_SRS_IOTHUBTRANSPORT_34_026: [If the supplied reason is null, this function shall throw an // IllegalArgumentException.] throw new IllegalArgumentException("reason cannot be null"); } this.cancelPendingPackets(); //Codes_SRS_IOTHUBTRANSPORT_34_023: [This function shall invoke all callbacks.] this.invokeCallbacks(); if (this.taskScheduler != null) { this.taskScheduler.shutdown(); } if (this.scheduledExecutorService != null) { this.scheduledExecutorService.shutdownNow(); this.scheduledExecutorService = null; } //Codes_SRS_IOTHUBTRANSPORT_34_024: [This function shall close the connection.] if (this.iotHubTransportConnection != null) { this.iotHubTransportConnection.close(); } //Codes_SRS_IOTHUBTRANSPORT_34_025: [This function shall invoke updateStatus with status DISCONNECTED and the // supplied reason and cause.] this.updateStatus(IotHubConnectionStatus.DISCONNECTED, reason, cause); // Notify send thread to finish up so it doesn't survive this close synchronized (this.sendThreadLock) { this.sendThreadLock.notifyAll(); } // Notify receive thread to finish up so it doesn't survive this close synchronized (this.receiveThreadLock) { this.receiveThreadLock.notifyAll(); } log.info("Client connection closed successfully"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void close(IotHubConnectionStatusChangeReason reason, Throwable cause) throws DeviceClientException { if (reason == null) { //Codes_SRS_IOTHUBTRANSPORT_34_026: [If the supplied reason is null, this function shall throw an // IllegalArgumentException.] throw new IllegalArgumentException("reason cannot be null"); } this.cancelPendingPackets(); //Codes_SRS_IOTHUBTRANSPORT_34_023: [This function shall invoke all callbacks.] this.invokeCallbacks(); if (this.taskScheduler != null) { this.taskScheduler.shutdown(); } if (this.scheduledExecutorService != null) { this.scheduledExecutorService.shutdownNow(); this.scheduledExecutorService = null; } //Codes_SRS_IOTHUBTRANSPORT_34_024: [This function shall close the connection.] if (this.iotHubTransportConnection != null) { this.iotHubTransportConnection.close(); } //Codes_SRS_IOTHUBTRANSPORT_34_025: [This function shall invoke updateStatus with status DISCONNECTED and the // supplied reason and cause.] this.updateStatus(IotHubConnectionStatus.DISCONNECTED, reason, cause); log.info("Client connection closed successfully"); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public MojoExecutionService getMojoExecutionService() { return mojoExecutionService; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MojoExecutionService getMojoExecutionService() { checkBaseInitialization(); return mojoExecutionService; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testFromSettingsSimple() throws MojoExecutionException { setupServers(); AuthConfig config = factory.createAuthConfig(isPush, null, settings, "roland", "test.org"); assertNotNull(config); verifyAuthConfig(config, "roland", "secret", "[email protected]"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFromSettingsSimple() throws MojoExecutionException { setupServers(); AuthConfig config = factory.createAuthConfig(null,settings, "roland", "test.org"); assertNotNull(config); verifyAuthConfig(config, "roland", "secret", "[email protected]"); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private void execute() throws IOException, TransformerException, JAXBException { final CFLint cflint = new CFLint(loadConfig(configfile)); cflint.setVerbose(verbose); cflint.setLogError(logerror); cflint.setQuiet(quiet); cflint.setShowProgress(showprogress); cflint.setProgressUsesThread(progressUsesThread); if(extensions != null && extensions.trim().length() > 0){ try{ cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(","))); }catch(Exception e){ System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage()); } } CFLintFilter filter = CFLintFilter.createFilter(verbose); if(filterFile != null){ File ffile = new File(filterFile); if(ffile.exists()){ FileInputStream fis = new FileInputStream(ffile); byte b[] = new byte[fis.available()]; fis.read(b); filter = CFLintFilter.createFilter(new String(b),verbose); } } if (excludeCodes != null && excludeCodes.length > 0) { filter.excludeCode(excludeCodes); } if (includeCodes != null && includeCodes.length > 0) { filter.includeCode(includeCodes); } cflint.getBugs().setFilter(filter); for (final String scanfolder : folder) { cflint.scan(scanfolder); } if (stdIn) { StringBuilder source = new StringBuilder(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String nextLine = scanner.nextLine(); source.append(nextLine); source.append(System.lineSeparator()); } scanner.close(); cflint.process(source.toString(), stdInFile); } if (xmlOutput) { Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile); if ("findbugs".equalsIgnoreCase(xmlstyle)) { if(verbose) { display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile)); } new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter); } else { if(verbose) { display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile)); } new XMLOutput().output(cflint.getBugs(), xmlwriter); } } if (textOutput) { if(textOutFile != null){ if(verbose) { display("Writing text" + (stdOut ? "." : " to " + textOutFile)); } } Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile); new TextOutput().output(cflint.getBugs(), textwriter); } if (htmlOutput) { try { if(verbose) { display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile)); } Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile); new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter); } catch (final TransformerException e) { throw new IOException(e); } } if (jsonOutput) { if(verbose) { display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile)); } Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile); new JSONOutput().output(cflint.getBugs(), jsonwriter); } if (includeCodes != null) { cflint.getBugs().getFilter().includeCode(includeCodes); } if (excludeCodes != null) { cflint.getBugs().getFilter().excludeCode(excludeCodes); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void execute() throws IOException, TransformerException, JAXBException { CFLintConfig config = null; if(configfile != null){ if(configfile.toLowerCase().endsWith(".xml")){ config = ConfigUtils.unmarshal(new FileInputStream(configfile), CFLintConfig.class); }else{ config = ConfigUtils.unmarshalJson(new FileInputStream(configfile), CFLintConfig.class); } } final CFLint cflint = new CFLint(config); cflint.setVerbose(verbose); cflint.setLogError(logerror); cflint.setQuiet(quiet); cflint.setShowProgress(showprogress); cflint.setProgressUsesThread(progressUsesThread); if(extensions != null && extensions.trim().length() > 0){ try{ cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(","))); }catch(Exception e){ System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage()); } } CFLintFilter filter = CFLintFilter.createFilter(verbose); if(filterFile != null){ File ffile = new File(filterFile); if(ffile.exists()){ FileInputStream fis = new FileInputStream(ffile); byte b[] = new byte[fis.available()]; fis.read(b); filter = CFLintFilter.createFilter(new String(b),verbose); } } if (excludeCodes != null && excludeCodes.length > 0) { filter.excludeCode(excludeCodes); } if (includeCodes != null && includeCodes.length > 0) { filter.includeCode(includeCodes); } cflint.getBugs().setFilter(filter); for (final String scanfolder : folder) { cflint.scan(scanfolder); } if (stdIn) { StringBuilder source = new StringBuilder(); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String nextLine = scanner.nextLine(); source.append(nextLine); source.append(System.lineSeparator()); } scanner.close(); cflint.process(source.toString(), stdInFile); } if (xmlOutput) { Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile); if ("findbugs".equalsIgnoreCase(xmlstyle)) { if(verbose) { display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile)); } new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter); } else { if(verbose) { display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile)); } new XMLOutput().output(cflint.getBugs(), xmlwriter); } } if (textOutput) { if(textOutFile != null){ if(verbose) { display("Writing text" + (stdOut ? "." : " to " + textOutFile)); } } Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile); new TextOutput().output(cflint.getBugs(), textwriter); } if (htmlOutput) { try { if(verbose) { display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile)); } Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile); new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter); } catch (final TransformerException e) { throw new IOException(e); } } if (jsonOutput) { if(verbose) { display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile)); } Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile); new JSONOutput().output(cflint.getBugs(), jsonwriter); } if (includeCodes != null) { cflint.getBugs().getFilter().includeCode(includeCodes); } if (excludeCodes != null) { cflint.getBugs().getFilter().excludeCode(excludeCodes); } } #location 41 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void dispose() { if (!disposed.compareAndSet(false, true)) { return; } LOG.debug("Disposing GStreamer device"); close(); source.dispose(); filter.dispose(); jpegdec.dispose(); caps.dispose(); sink.dispose(); pipe.dispose(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void dispose() { if (!disposed.compareAndSet(false, true)) { return; } LOG.debug("Disposing GStreamer device"); close(); source.dispose(); filter.dispose(); jpegparse.dispose(); jpegdec.dispose(); caps.dispose(); sink.dispose(); pipe.dispose(); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void close() { if (!open.compareAndSet(true, false)) { return; } LOG.debug("Closing GStreamer device"); pipelineStop(); image = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void close() { if (!open.compareAndSet(true, false)) { return; } LOG.debug("Closing GStreamer device"); image = null; LOG.debug("Unlink elements"); pipe.setState(State.NULL); Element.unlinkMany(source, filter, sink); pipe.removeMany(source, filter, sink); } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION